为我在python中制作的游戏制作高分榜

时间:2017-04-09 10:53:12

标签: 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 个答案:

答案 0 :(得分:1)

pickle生成数据的二进制表示 - 因此它不应该是人类可读的。

当你加载你的pickle文件时,你会得到你的数据,所以一切正常。

如果你想要一个人类可读的文件,一个常见的解决方案是使用json。请参阅http://docs.python.org/3/library/pickle.html#comparison-with-json进行比较。特别是:

  

默认情况下,JSON只能代表Python内置的子集   类型,没有自定义类;泡菜可以代表一个非常大的   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]]
相关问题