如何在不丢失变量值的情况下刷新变量



最近我开始在python中做Snake。我想到了这个动作,蛇记得它最后的位置。我必须刷新一个名为body的变量才能使其工作,因为我在主循环开始之前就调用了它。当蛇吃苹果时,身体变量应该扩展,我不想失去它的扩展值。你能帮帮我吗?这是我的代码:

import pygame, math, random
pygame.init()
screen = pygame.display.set_mode((640,640))
pygame.display.set_caption('Snake')

score = 0

x, y = 320,320
dirUp, dirDown = False, False
dirLeft, dirRight = False, False
body = [(x, y)]
snakeImg = [pygame.image.load('snakeblock.png') for i in range(len(body))]


squares = []
for i in range(640):
if i % 32 == 0:
squares.append(i)
food = pygame.image.load('fruit.png')
foodx,foody = random.choice(squares), random.choice(squares)
def isCollision(obsX, obsY, x, y):
return math.sqrt(math.pow(obsX - x, 2) + math.pow(obsY - y, 2)) <= 0
def show_text():
score_font = pygame.font.Font('freesansbold.ttf',32)
score_text = score_font.render('Score: {}'.format(score), True, (255,255,255))
screen.blit(score_text, (0,0))
running = True
i = 0
while running:
i += 1
body = body
pygame.time.Clock().tick(10)
screen.fill((0,128,0))
if x > 608 or x < 0:
running = False
elif y > 608 or y < 0:
running = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
dirUp = True
dirLeft, dirDown, dirRight = False, False, False
if event.key == pygame.K_DOWN:
dirDown = True
dirUp, dirLeft, dirRight = False, False, False
if event.key == pygame.K_RIGHT:
dirRight = True
dirUp, dirDown, dirLeft = False, False, False
if event.key == pygame.K_LEFT:
dirLeft = True
dirUp, dirDown, dirRight = False, False, False
if dirUp:
y -= 32
elif dirDown:
y += 32
elif dirRight:
x += 32
elif dirLeft:
x -= 32
for i in range(len(body)):
if isCollision(foodx,foody,x,y):
foodx, foody = random.choice(squares), random.choice(squares)
score += 1
print( body)
screen.blit(food, (foodx, foody))
screen.blit(snakeImg[i], (x, y))
show_text()
pygame.display.update()

我意识到我不能一次修改整个列表。相反,我做了这样的事情:

while running:
last_pos = (body[-1][0], body[-1][1])
body[0] = (x,y)
for i in range(1,len(body)):
body[i] = last_pos

最新更新