2012-12-16 108 views
0

我在這裏有一些使用「pickle」模塊的python 3代碼。它應該存儲遊戲的高分。當我再次打開程序時,它會給我默認的「A:100 ...」高分。Python酸洗問題

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) 

這只是代碼中我認爲存在問題的部分。如果需要,我會發布更多信息。我會很樂意回答你的問題。謝謝。

+0

如果您要使用完整的絕對路徑名稱,那麼它是否有效? –

+0

正如「C:\ Users \ Bobby \ Dropbox \ LD25 \ highscores.dat」一樣?我只是測試它,它也有同樣的問題。 – user1149589

+0

您可能希望在'__init__'中插入一個print語句來查看那裏的'.isfile()'測試發生了什麼。該文件是否創建? –

回答

1

您需要重新打開每次寫入的文件。目前,您每次在您的文件中都會一個接一個地更改分數時正在寫入新記錄。你的文件現在包含幾個泡菜,但只有第一個被讀取。與addScore不變

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) 

更改您的代碼。

每次評分改變時,高分檔案現在都會從零開始寫

+0

我可以問一個完全不同的東西嗎?你有多少年的Python經驗? – NlightNFotis

+0

查看http://careers.stackoverflow.com/zopatista,14年。 –

+0

我不得不承認我有點嫉妒:P – NlightNFotis