Python Pygame贪吃蛇游戏添加Highscore功能失败求助
贪吃蛇游戏最高分功能修复及优化建议
核心问题分析
你的代码里导致最高分功能失效的几个关键问题:
- 函数与变量重名:定义了
High_score函数,又在gameLoop里用同名变量,逻辑完全混乱。 - 最高分未持久化:
Score_high变量在gameLoop内部,每次重启游戏都会重置为0,无法保留历史记录。 - 显示位置冲突:当前得分和最高分都渲染在
[0,0]位置,互相覆盖看不到效果。 - 游戏结束逻辑错误:
game_close循环里的最高分更新判断和函数调用逻辑错误,且没有持续展示最高分。
修复方案
1. 区分函数与变量名
重命名显示最高分的函数,避免和变量冲突,同时调整显示位置避免重叠:
def draw_high_score(score): value = score_font.render("Highscore: " + str(score), True, yellow) dis.blit(value, [dis_width - 150, 0]) # 移到右上角,避免和当前得分重叠
2. 持久化存储最高分
用文本文件保存最高分,关闭游戏后不会丢失:
# 读取/保存最高分的工具函数 def load_high_score(): try: with open("highscore.txt", "r") as f: return int(f.read()) except FileNotFoundError: return 0 def save_high_score(score): with open("highscore.txt", "w") as f: f.write(str(score)) # 在全局初始化最高分 high_score = load_high_score()
3. 修正游戏结束时的最高分更新逻辑
在game_close循环里正确更新并显示最高分:
while game_close == True: dis.blit(screenUpdate, (0, 0)) # 先清屏,避免残留画面 message("You Lost! Press C-Play Again or Q-Quit", white) current_score = Length_of_snake - 1 Your_score(current_score) # 更新并保存最高分 global high_score if current_score > high_score: high_score = current_score save_high_score(high_score) draw_high_score(high_score) pygame.display.update() # 事件处理放在显示之后 for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_over = True game_close = False if event.key == pygame.K_c: gameLoop()
4. 游戏过程中持续显示最高分
在主游戏循环的渲染部分添加最高分显示:
our_snake(snake_block, snake_List) Your_score(Length_of_snake - 1) draw_high_score(high_score) # 新增这行 pygame.display.update()
额外优化建议
- 避免食物生成在蛇身上:修改食物生成逻辑,检查食物坐标是否在蛇身列表中,若存在则重新生成:
def generate_food(snake_list): while True: foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 if [foodx, foody] not in snake_list: return foodx, foody - 替换递归重启为循环:递归调用
gameLoop会导致栈溢出,改为重置游戏状态的循环结构。 - 难度递增:随着得分增加,提高
snake_speed的值,比如每得5分速度加1。 - 代码模块化:把游戏初始化、事件处理、渲染等逻辑拆分到单独函数中,提升可读性。
内容的提问来源于stack exchange,提问作者E_stkvs
相关产品推荐
相关产品推荐

