Python游戏得分展示、存档、读档功能实现问题咨询
问题修复方案
你提供的代码核心问题为读档函数逻辑错误,同时存在几处不符合需求的细节,修复后可完全实现所有要求的功能:
已解决的问题点
- 修复了读档函数逻辑错误,可正确读取本地存档并恢复玩家得分列表
- 修正了回合上限错误,现在最多可玩18轮,符合需求
- 优化了得分展示功能,除了显示当前获胜者,同时展示两位玩家的各轮得分和总得分
- 增加了异常捕获,避免用户输入非数字、找不到存档文件时程序崩溃
修复后完整代码
Player_1 = [] Player_2 = [] def main(): choice = 0 while choice != "6" : print("1: 新游戏") print("2: 进行回合") print("3: 查看得分") print("4: 存档游戏") print("5: 读取存档") print("6: 退出游戏") choice = input("请选择操作: ") if choice == "1": print("新游戏 // 重置游戏") ResetGame() elif choice == "2": print("开始游玩回合") PlayRound() elif choice == "3": print("查看得分情况") ShowScores() elif choice == "4": print("保存游戏存档") SaveGame() elif choice == "5": print("读取本地存档") LoadGame() elif choice == "6": print("感谢游玩!") else: print("无效选择,请重新输入") def PlayRound(): holes = 0 endRound = 0 # 最多18轮,循环条件调整为holes < 18 while holes < 18 and endRound != 1: try: Player_1Score = int(input("玩家1杆数: ")) Player_2Score = int(input("玩家2杆数: ")) endRound = int(input("是否继续游玩?0=继续 1=结束: ")) except ValueError: print("输入无效,请输入数字") continue if Player_1Score > 5: Player_1Score = 5 if Player_2Score > 5: Player_2Score = 5 Player_1.append(Player_1Score) Player_2.append(Player_2Score) holes += 1 print(f"玩家1当前得分列表:{Player_1}") print(f"玩家2当前得分列表:{Player_2}") def ShowScores(): total1 = sum(Player_1) total2 = sum(Player_2) print(f"玩家1各轮得分:{Player_1},总得分:{total1}") print(f"玩家2各轮得分:{Player_2},总得分:{total2}") if total1 < total2: print("当前获胜者是玩家1") elif total1 > total2: print("当前获胜者是玩家2") else: print("当前双方平局") def SaveGame(): # 优化存档写入逻辑,更简洁高效 with open("score1.txt","w") as P1: P1.write(' '.join(map(str, Player_1))) with open("score2.txt", "w") as P2: P2.write(' '.join(map(str, Player_2))) print('得分已成功存档') def LoadGame(): global Player_1, Player_2 Player_1.clear() Player_2.clear() try: with open("score1.txt", "r") as P1: content1 = P1.read().strip() if content1: Player_1 = [int(s) for s in content1.split(' ') if s] with open("score2.txt", "r") as P2: content2 = P2.read().strip() if content2: Player_2 = [int(s) for s in content2.split(' ') if s] print(f'存档已加载,玩家1得分:{Player_1},玩家2得分:{Player_2}') except FileNotFoundError: print('未找到本地存档文件,请先创建存档后再读取') def ResetGame(): Player_1.clear() Player_2.clear() print(f'游戏已重置,当前得分:玩家1{Player_1},玩家2{Player_2}') if __name__ == "__main__": main()
功能使用说明
- 选择菜单
1: 新游戏:清空所有得分记录,重置游戏状态 - 选择菜单
2: 进行回合:录入每轮两位玩家的杆数,杆数超过5自动按5计算,最多支持18轮游玩 - 选择菜单
3: 查看得分:展示两位玩家各轮得分、总得分,以及当前获胜方 - 选择菜单
4: 存档游戏:将当前得分存入本地score1.txt、score2.txt文件完成存档 - 选择菜单
5: 读取存档:读取本地存档文件,自动恢复之前的得分数据,无存档时会给出提示 - 选择菜单
6: 退出游戏:关闭程序
内容的提问来源于stack exchange,提问作者Mello Ferguson
相关产品推荐
相关产品推荐

