我这里有一些使用“pickle”模块的python 3代码。它应该存储游戏的高分。当我再次打开程序时,它反而给了我默认的“A:100 ...”高分。
def __init__(self):
self.filename = "highscores.dat"
self.numScores = 5
if not os.path.isfile(self.filename):
self.file = open(self.filename, "wb")
self.scores = [100 for i in range(self.numScores)]
self.names = ["A", "B", "C", "D", "E"]
self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
self.updateFile()
else:
file = open(self.filename, "rb")
self.highscores = pickle.load(file)
file.close()
self.file = open(self.filename, "wb")
self.names = [highscore[0] for highscore in self.highscores]
self.scores = [highscore[1] for highscore in self.highscores]
def addScore(self, name, score):
self.scores.append(score) #Add new score
self.scores.sort(reverse = True) #Sort
self.names.insert(self.scores.index(score), name)
self.names = self.names[:self.numScores] # Top 5
self.scores = self.scores[:self.numScores]
self.highscores = [(self.names[i], self.scores[i]) for i in range(self.numScores)]
self.updateFile()
def updateFile(self):
pickle.dump(self.highscores, self.file)
这只是我认为问题所在的代码部分。如果需要,我会发布更多。我很乐意回答您的问题。谢谢你。