Pygame贪吃蛇游戏重启异常:蛇位置未重置
Pygame贪吃蛇重启后蛇位置未重置的修复方案
问题根源
在gameOver函数中点击重试按钮时,你重置蛇位置和身体的代码只是创建了局部变量,并没有修改全局作用域中的snakePosition和snakeSegments,导致回到游戏后蛇还是保持死亡时的状态,直接触发失败。
修复步骤
- 在
gameOver函数内使用global关键字声明要修改的全局变量,确保修改的是全局作用域中的数据。 - 除了蛇的位置和身体,还要重置分数、方向等其他游戏状态,保证重启后完全回到初始状态。
修改后的gameOver函数代码
def gameOver(): """creates splash screen""" done = False # 声明要修改的全局变量 global snakePosition, snakeSegments, score, direction, changeDirection pygame.display.set_caption('You Lose') splash_background_image = pygame.image.load("black_hole.jpg").convert() screen.blit(splash_background_image, [0, 0]) pygame.draw.rect(display, (255,0,0,0),(270,50,100,50)) font = pygame.font.Font(None, 25) text = font.render ("Retry?", 1, (0,0,255)) display.blit(text, (290,70)) pygame.draw.rect(display, (255,255,255,255),(550,440,150,150)) font = pygame.font.Font(None, 25) text = font.render ("Quit Game", 1, (0,0,0)) display.blit(text, (550,450)) splashScreenFont = pygame.font.Font('freesansbold.ttf',50) splashScreenSurf = splashScreenFont.render('...Game Over...',True,red) splashScreenRect = splashScreenSurf.get_rect() splashScreenRect.midtop = (330,200) screen.blit(splashScreenSurf, splashScreenRect) pygame.display.flip() print('Game Over') while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.MOUSEBUTTONDOWN: mouseX = event.pos[0] mouseY = event.pos[1] print(mouseX,mouseY) if (mouseX >= 270) and (mouseX < 270 + 100) and (mouseY >= 50) and (mouseY < 50 + 50): print('Game Restart') done = True # 重置所有游戏状态到初始值 snakePosition = [100,100] snakeSegments = [[100,100],[80,100],[60,100]] score = 0 direction = 'right' changeDirection = direction splash_screen() elif (mouseX >= 550) and (mouseX < 550 + 150) and (mouseY >= 440) and (mouseY < 440+150): exit() else: print('Click Retry')
额外优化提示
- 可以把游戏初始状态的变量封装成一个函数(比如
reset_game()),这样重置时直接调用函数,代码更简洁易维护。 - 注意
pygame.QUIT事件的拼写,原代码里有一处小写的pygame.quit,建议统一规范。
内容的提问来源于stack exchange,提问作者Bryce Jones
相关产品推荐
相关产品推荐

