2017-04-09 37 views
1

我在Python中很新。製作我在python中製作的遊戲的高分列表

所以我目前正在使用tkinter和python製作遊戲的高分榜。到目前爲止,我有代碼:

from operator import itemgetter 
import pickle 

playerName = input("what is your name? ") 
playerScore = int(input('Give me a score? ')) 

highscores = [ 
    ('Luke', 0), 
    ('Dalip', 0), 
    ('Andrew', 0), 
] 

highscores.append((playerName, playerScore)) 
highscores = sorted(highscores, key = itemgetter(1), reverse = True)[:10] 

with open('highscore.txt', 'wb') as f: 
    pickle.dump(highscores, f) 

highscores = [] 

with open('highscore.txt', 'rb') as f: 
    highscores = pickle.load(f) 

的問題是,它把這個到文件:

€] Q(X lukeqK†QX LukeqK†QX DalipqK†QX And​​rewqK†QE (和是的,這正是它看起來像)

我不知道什麼是錯了,任何人都可以幫助,請

+1

爲什麼這是一個問題嗎?通過使用'pickle',您可以將數據序列化並反序列化爲二進制格式。您正嘗試讀取不包含unicode的文件的文件內容,這就是爲什麼它看起來很奇怪。裝載後的「高分」是否包含正確的信息?如果是這樣,沒有錯。 – Ede

+0

這裏沒有什麼錯:'pickle'產生一個數據的二進制表示 - 所以它不應該是人類可讀的。當你加載你的醃製文件時,你會得到你的數據。如果你想要一個人類可讀的文件,你可以使用'json'。請參閱https://docs.python.org/3/library/pickle.html#comparison-with-json –

回答

1

pickle產生數據的二進制表示 - 所以它不應該是人類可讀。

當你加載你的醃製文件時,你得到你的數據,所以一切工作正常。

如果你想要一個人類可讀的文件,一個常見的解決方案是使用json。請參閱http://docs.python.org/3/library/pickle.html#comparison-with-json進行比較。特別是:

默認情況下,JSON只能表示Python內置的 類型的一個子集,並且沒有自定義類; pickle可以代表一個非常大的Python類型數量(其中很多是自動的,通過靈巧地使用 Python的內省設施;複雜的情況可以通過執行特定對象API的 來解決)。

您只需要使用json,而不是pickle在你的代碼:

from operator import itemgetter 
import json 

try: 
    with open('highscore.txt', 'r') as f: 
     highscores = json.load(f) 
except FileNotFoundError: 
    # If the file doesn't exist, use your default values 
    highscores = [ 
     ('Luke', 0), 
     ('Dalip', 0), 
     ('Andrew', 0), 
     ] 

playerName = input("what is your name? ") 
playerScore = int(input('Give me a score? ')) 

highscores.append((playerName, playerScore)) 
highscores = sorted(highscores, key = itemgetter(1), reverse = True)[:10] 

with open('highscore.txt', 'w') as f: 
    json.dump(highscores, f) 

highscores = [] 

highscore.txt內容將是這樣的:

[["thierry", 100], ["Luke", 0], ["Dalip", 0], ["Andrew", 0]] 
+0

感謝Thierry它的工作!我如何獲得它,以便一旦它將名稱添加到文件中,它就停留在那裏?因爲當我重新運行代碼之前,它就擺脫了分數。 –

+0

您應該在輸入新分數前閱讀高分檔案。我更新了我的答案。 –