为我用python制作的游戏制作了一个高分列表

2024-05-13 23:24:39 发布

您现在位置: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卢克克†克卢克†克朗†达利普克†安德鲁克†量化宽松。 (是的,这正是它看起来的样子)

我不知道怎么了谁能帮忙吗?在


Tags: 文件importtxtinputtkinteraswithopen
1条回答
网友
1楼 · 发布于 2024-05-13 23:24:39

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

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

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

JSON, by default, can only represent a subset of the Python built-in types, and no custom classes; pickle can represent an extremely large number of Python types (many of them automatically, by clever usage of Python’s introspection facilities; complex cases can be tackled by implementing specific object APIs).

您只需在代码中使用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的内容如下:

^{pr2}$

相关问题 更多 >