0

我这里有一些使用“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)

这只是我认为问题所在的代码部分。如果需要,我会发布更多。我很乐意回答您的问题。谢谢你。

4

1 回答 1

1

您每次都需要重新打开文件进行写入。目前,每次分数更改时,您都会在文件中一个接一个地写入新记录。您的文件现在包含几个泡菜,但只读取第一个。

将您的代码更改为:

def __init__(self):
    self.filename = "highscores.dat"
    self.numScores = 5

    if not os.path.isfile(self.filename):
        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)]
    else:
        with open(self.filename, "rb") as f:
            self.highscores = pickle.load(f)
        self.names = [highscore[0] for highscore in self.highscores]
        self.scores = [highscore[1] for highscore in self.highscores]

def updateFile(self):
    with open(self.filename, 'wb') as f:
        pickle.dump(self.highscores, f)

addScore不变。

现在,每次分数更改时,都会从头开始写入高分文件。

于 2012-12-16T17:27:57.243 回答