我一直在完成本书中的练习,但遇到了一些障碍。挑战在于:
“改进 Trivia Challenge 游戏,使其在文件中维护高分列表。程序应记录玩家的姓名和分数。使用腌制对象存储高分。”
我设法将分数保存到列表中,然后将此列表附加到 dat 文件中。但是,当我尝试查看分数/读取文件时,它似乎只显示输入的第一个分数。我查看了 bat 文件,它似乎正确地转储了列表,所以我想知道我是否搞砸了检索部分?
谢谢阅读
这是代码(之前):
def high_score():
"""Records a player's score"""
high_scores = []
#add a score
name = input("What is your name? ")
player_score = int(input("What is your score? "))
entry = (name, player_score)
high_scores.append(entry)
high_scores.sort(reverse=True)
high_scores = high_scores[:5] # keep only top five
# Open a new file to store the pickled list
f = open("pickles1.dat", "ab")
pickle.dump(high_scores, f)
f.close()
choice = None
while choice !="0":
print(
"""
0 - Quit
1 - Show high scores
"""
)
choice = input("choice: ")
print()
# exit
if choice == "0":
print("Goodbye")
# show a score
if choice == "1":
f = open("pickles1.dat", "rb")
show_scores = pickle.load(f)
print(show_scores)
f.close()
input("\n\nPress enter to exit.")
解决方案(之后):
def high_score():
"""Records a player's score"""
# no previous high score file
try:
with open("pickles1.dat", "rb") as f:
high_scores = pickle.load(f)
except EOFError:
high_scores = []
#add a score // Do current stuff for adding a new score...
name = input("What is your name? ")
player_score = int(input("What is your score? "))
entry = (name, player_score)
high_scores.append(entry)
high_scores.sort(reverse=True)
high_scores = high_scores[:5] # keep only top five
# dump scores
with open("pickles1.dat", "wb") as f:
pickle.dump(high_scores, f)