Добавить новую функцию, которая рисует змею:
def drawSnake():
for p in snake_parts:
screen.blit(shake, p.topleft)
Конечно, вы можете нарисовать изображение вместо recatangl.snake
- это изображение типа pygame.Surface
:
def drawSnake():
for p in snake_parts:
pygame.draw.rect(screen, RED, p)
Добавить голову в список snake_parts
перед основным циклом (перед while True:
):
snake_parts.append(pygame.Rect(x,y,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
Используйте drawSnake
, чтобы нарисовать змею и обновить позиции частей прямо перед:
slither( (x, y) )
if ap:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if x == ax and y == ay:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
sa += 1
snake_parts.append(pygame.Rect(x, y, tilesize, tilesize))
drawSnake()
pygame.display.update()
В slither
есть опечатка.Это должно быть snake_parts[0].center
, а не snake_parts[0].centre
.Но в любом случае, в вашем случае происхождение пар змеи составляет topleft
, а не center
.Измените функцию slither
:
def slither( new_head_coord ):
for i in range( len(snake_parts)-1, 0, -1 ):
snake_parts[i] = snake_parts[i-1].copy()
snake_parts[0].topleft = new_head_coord
Выполните только 1 цикл событий в основном цикле:
например
run = True
while run:
sx, sy = x, y
for row in range(sizex):
for column in range(sizey):
screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
run = False
if event.type == KEYDOWN:
if event.key == K_UP:
vel_y = -25
vel_x = 0
# [...]
Демо
import pygame, sys, random
from pygame.locals import *
pygame.init()
movement_x = movement_y = 0
RED = (240, 0, 0)
GREEN = (0, 255, 0)
ran = [0,25,50,75,100,125,150,175,200,225,250,275,300,325,350,375,400,425,450,475]
sizex, sizey = 500, 500
tilesize = 25
screen = pygame.display.set_mode((sizex,sizey))
pygame.display.set_caption('Snake')
tile = pygame.Surface((tilesize, tilesize))
tile.fill((0, 0, 64))
tile = pygame.transform.scale(tile, (tilesize, tilesize))
x2 = 0
pag = 0
clock = pygame.time.Clock()
sx, sy = 0, 0
vel_x, vel_y = 0, 0
x, y = 0, 0
sa = 0
ap = True
snake_parts = [] # /N/ Pygame rects
def slither( new_head_coord ):
for i in range( len(snake_parts)-1, 0, -1 ):
snake_parts[i] = snake_parts[i-1].copy()
snake_parts[0].topleft = new_head_coord
def drawSnake():
for p in snake_parts:
pygame.draw.rect(screen, GREEN, p)
snake_parts.append(pygame.Rect(x,y,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
run = True
while run:
sx, sy = x, y
for row in range(sizex):
for column in range(sizey):
screen.blit(tile,(column*tilesize, row*tilesize,tilesize,tilesize))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
run = False
if event.type == KEYDOWN:
if event.key == K_UP:
vel_x, vel_y = 0, -25
elif event.key == K_DOWN:
vel_x, vel_y = 0, 25
elif event.key == K_LEFT:
vel_x, vel_y = -25, 0
elif event.key == K_RIGHT:
vel_x, vel_y = 25, 0
elif event.key == K_y:
pag = 1
elif event.key == K_n:
pag = 2
inBounds = pygame.Rect(0, 0, sizex, sizey).collidepoint(x+vel_x, y+vel_y)
if inBounds:
y += vel_y
x += vel_x
else:
basicFont = pygame.font.SysFont(None, 48)
text = basicFont.render('Game Over! Play again? y/n', True, GREEN, RED)
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery
pygame.draw.rect(screen, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
screen.blit(text, textRect)
ax, ay = -25, -25
x, y = -25, -25
if pag == 1:
pag = 0
inBounds = True
x, y = 0, 0
vel_x, vel_y = 0, 0
ax, ay = random.choice(ran), random.choice(ran)
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if pag == 2:
pygame.quit()
sys.exit()
slither( (x, y) )
if ap:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
if x == ax and y == ay:
pygame.draw.rect(screen, RED, pygame.Rect(ax,ay,tilesize,tilesize))
ax, ay = random.choice(ran), random.choice(ran)
sa += 1
snake_parts.append(pygame.Rect(x, y, tilesize, tilesize))
drawSnake()
pygame.display.update()
clock.tick(100)