You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.4 KiB

6 months ago
# 开发日期: 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):
6 months ago
# 以二进制写入模式打开名为"high_score.pk1"的文件
6 months ago
f = open("high_score.pk1", 'wb')
6 months ago
# 使用pickle模块将high_score的字符串表现形式写入文件
6 months ago
pickle.dump(str(self.high_score), f, 0)
f.close()
def load_high_score(self):
6 months ago
# 以二进制读取模式打开名为"high_score.pk1"的文件
6 months ago
f = open("high_score.pk1", 'rb')
try:
6 months ago
# 从文件中加载(反序列化)数据
6 months ago
str_high_score = pickle.load(f)
self.high_score = int(str_high_score)
except EOFError:
6 months ago
# 如果文件意外结束EOFError或没有文件可加载则设置 self.high_score 为 0
6 months ago
self.high_score = 0
finally:
f.close()