Python游戏高分榜功能故障求助:重复写入与排序未实现
问题修复方案
先看你代码里的两个核心问题,直接导致重复记录和排序失效:
1. 主循环的条件判断错误
你写的if score_one or score_two > high_score:逻辑完全不对,这个条件等价于if (score_one非零) 或者 (score_two > high_score),只要score_one不是0,不管分数高低都会触发add_high_score,这就是为什么会写入几百条重复记录。
改成正确的逻辑:
if score_one > high_score or score_two > high_score:
2. 高分存储函数add_high_score的问题
这个函数的逻辑完全偏离了需求,现在的写法只会不断追加当前会话里的最高分,根本没读取历史数据,也没做真正的高分判断。重构一下这个函数:
重构后的函数功能:
- 读取已有高分文件,加载历史记录
- 判断新分数是否能进入高分榜(比如只保留前N名,或者只要比现有最低分高就加入)
- 对所有高分排序后重新写入文件
def add_high_score(new_score, player_name): high_scores = [] # 先读取已有高分记录 try: with open("high_score.txt", "r") as f: for line in f: line = line.strip() if not line: continue name, score_str = line.split(maxsplit=1) high_scores.append( (-int(score_str), name) ) # 用负分实现降序排序 except FileNotFoundError: # 文件不存在就新建 pass # 加入新分数 high_scores.append( (-new_score, player_name) ) # 去重+排序(按分数降序,分数相同保留最早的记录) unique_scores = list( dict.fromkeys(high_scores) ) unique_scores.sort() # 因为存的是负分,升序就是原分数降序 # 只保留前10条高分,可自定义数量 top_scores = unique_scores[:10] # 重新写入文件 try: with open("high_score.txt", "w") as f: for neg_score, name in top_scores: f.write(f"{name} {-neg_score}\n") except IOError: print("Unable to save the high score.")
3. 主循环里的其他小问题
- 你现在的
high_score变量初始是0,但没从文件读取历史最高分,所以第一次运行没问题,之后应该从文件里获取当前最高分来判断:
# 程序启动时读取历史最高分 def get_current_high_score(): try: with open("high_score.txt", "r") as f: highest = 0 for line in f: line = line.strip() if not line: continue _, score_str = line.split(maxsplit=1) score = int(score_str) if score > highest: highest = score return highest except FileNotFoundError: return 0 high_score = get_current_high_score()
- 主循环里的分数比较可以优化,避免重复判断:
if score_one > high_score or score_two > high_score: if score_one > score_two: score_m, player_n = score_one, 'Player one' else: score_m, player_n = score_two, 'Player two' add_high_score(score_m, player_n) # 更新当前最高分 high_score = max(high_score, score_m) else: print("Better luck next time.")
为什么之前会写几百条重复记录?
- 主循环的条件判断错误,导致每帧都调用
add_high_score add_high_score里每次都写当前会话的max,而不是只在新分数超过历史分时写入- 用了追加模式打开文件,每次调用都在末尾加一行,重复调用就会重复写入
现在按上面的改完,就能解决重复记录和排序问题了,高分榜会按分数从高到低保存,还能控制显示的条数。
内容的提问来源于stack exchange,提问作者gevorg
相关产品推荐
相关产品推荐

