如何基于条件更新游戏高分CSV文件?
问题分析与修改方案
核心问题
你的代码存在三个关键问题,导致低分也会覆盖最高分:
- 初始化时未从CSV文件读取已保存的最高分,每次启动游戏
self.new_score都重置为0,只要当前分数大于0就会更新文件。 highest_score方法中,异常处理部分直接写入整数self.score会报错,且file.write返回的是写入字符数,不是分数值,导致显示错误。game_over方法错误地显示当前分数而非最高分,且highest_score末尾的重复写入会导致界面文字叠加。
修改步骤
- 初始化时读取已存最高分:在
__init__方法中添加读取score.csv的逻辑,若文件存在则读取并赋值给self.new_score,不存在则设为0。 - 修正
highest_score方法逻辑:- 仅当当前分数大于已存最高分才更新文件。
- 写入文件时确保是字符串类型,移除错误的
data变量使用。 - 移除末尾的重复写入语句,避免界面文字叠加。
- 修正
game_over的显示内容:将显示的最高分改为self.new_score,而非当前分数。
修改后的完整代码
from turtle import Turtle class ScoreBoard: def __init__(self): self.score = 0 # 初始化时读取已保存的最高分 self.new_score = self.load_high_score() self.text_score = Turtle() self.text_score.hideturtle() self.text_score.penup() self.text_score.goto(200, 260) self.text_score.color("white") self.update_score() def load_high_score(self): """从CSV文件读取最高分,文件不存在则返回0""" try: with open("score.csv", "r") as file: # 读取内容并转为整数,处理空文件情况 content = file.read().strip() return int(content) if content else 0 except FileNotFoundError: return 0 def update_score(self): self.text_score.clear() self.text_score.write(f"Score: {self.score}", align="center", font=("Arial", 20, 'normal')) def increase_score(self): self.score += 1 self.update_score() def game_over(self): self.highest_score() self.text_score.goto(0, 0) self.text_score.color("red") self.text_score.write(f"Game over!\nYour highest score is: {self.new_score}", align="center", font=("Arial", 20, "normal")) def highest_score(self): if self.score > self.new_score: self.new_score = self.score # 写入新的最高分,无需区分文件是否存在,"w"模式会自动创建 with open("score.csv", "w") as file: file.write(str(self.new_score))
说明
load_high_score方法负责读取已有的最高分,处理文件不存在和空文件的情况。- 移除了冗余的异常处理,因为
open的"w"模式会自动创建不存在的文件。 game_over现在正确显示存储的最高分,而非当前游戏的分数。- 每次游戏启动时,都会加载之前保存的最高分,确保只有当前分数超过历史最高分才会更新文件。
内容的提问来源于stack exchange,提问作者DAVE
相关产品推荐
相关产品推荐

