在Flappy Bird克隆版中使用JSON保存高分的技术求助
解决Pygame中Flappy Bird高分保存与显示问题
核心排查与修复方向
- 路径问题:很多时候是JSON文件读写路径错误,直接写文件名可能会存在Python运行的工作目录,而非游戏脚本所在目录。
- 数据类型不匹配:游戏分数是整数,读取JSON后必须转成整数,否则会出现字符串与整数比较的错误。
- 读写时机错误:应在游戏结束(小鸟碰撞)时判断是否刷新高分,启动游戏时先读取高分,不要在游戏过程中频繁读写文件。
修正后的代码示例
1. 高分读取函数
import json import os import pygame def load_high_score(): # 基于脚本所在目录生成文件路径,避免路径混乱 script_dir = os.path.dirname(os.path.abspath(__file__)) high_score_path = os.path.join(script_dir, "high_score.json") if os.path.exists(high_score_path): with open(high_score_path, "r") as f: # 强制转成整数,防止JSON存储的是字符串类型 return int(json.load(f)) # 文件不存在时初始化高分为0 return 0
2. 高分保存函数
def save_high_score(score): script_dir = os.path.dirname(os.path.abspath(__file__)) high_score_path = os.path.join(script_dir, "high_score.json") with open(high_score_path, "w") as f: json.dump(score, f)
3. 游戏内调用逻辑
# 游戏启动时加载高分 high_score = load_high_score() current_score = 0 screen = pygame.display.set_mode((400, 600)) font = pygame.font.SysFont(None, 40) # 主游戏循环 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 此处省略小鸟移动、碰撞检测、分数增加等逻辑 # 假设collision变量为True时表示游戏结束 if collision: # 比较当前分数与高分,更新并保存 if current_score > high_score: high_score = current_score save_high_score(high_score) # 处理游戏结束逻辑(如显示结束界面) # 绘制分数与高分 screen.fill((0,0,0)) score_surf = font.render(f"Score: {current_score}", True, (255,255,255)) high_score_surf = font.render(f"High Score: {high_score}", True, (255,255,255)) screen.blit(score_surf, (20, 20)) screen.blit(high_score_surf, (20, 60)) pygame.display.flip() pygame.quit()
额外注意事项
- 不要在每次分数变化时都保存高分,仅在游戏结束时判断后保存,减少IO操作并避免出错。
- 若之前照搬的点击类游戏教程,其分数更新逻辑与Flappy Bird不同(点击类可能实时加分),需先确保Flappy Bird的过管道加分逻辑正确,再处理高分功能。
- 测试时可手动删除
high_score.json文件,验证程序是否会自动生成文件并初始化高分为0,以此确认路径是否正确。
内容的提问来源于stack exchange,提问作者Josh Smith
相关产品推荐
相关产品推荐

