# 开发日期: 2024/4/26 import pickle class GameStats(): """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" self.ai_settings = ai_settings self.reset_stats() # 游戏刚启动的时候处于活动状态 self.game_active = False # 在任何情况下都不应该重置最高分 self.high_score = 0 def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" self.ships_left = self.ai_settings.ship_limit self.score = 0 self.level = 1 def save_high_score(self): # 以二进制写入模式打开名为"high_score.pk1"的文件 f = open("high_score.pk1", 'wb') # 使用pickle模块将high_score的字符串表现形式写入文件 pickle.dump(str(self.high_score), f, 0) f.close() def load_high_score(self): # 以二进制读取模式打开名为"high_score.pk1"的文件 f = open("high_score.pk1", 'rb') try: # 从文件中加载(反序列化)数据 str_high_score = pickle.load(f) self.high_score = int(str_high_score) except EOFError: # 如果文件意外结束(EOFError)或没有文件可加载,则设置 self.high_score 为 0 self.high_score = 0 finally: f.close()