我如何制作一个代码来保存这个猜测数字游戏的前5名分数


from random import *
tries = 0
guessNum = randint(1,1000)
while True:
guess = int(input("Guess a number between 1-1000: "))
print("You have",29-tries,"tries left.")    
if guess >= guessNum+1:
print("Too high")
tries += 1
elif guess <= guessNum-1:
print("Too low")
tries += 1
if guess == guessNum:
print("You got it right!!")
tries += 1
print("It took you",tries,"tries.")
f = open("scoreBoard.txt","a")
f.write("%-s,%-sn" %(tries,guessNum))
f.close()
break
if tries == 30:
print("You failed, the number was:",guessNum,".")
break

我需要帮助把它放进一个记分板,如果有新的高分,记分板会更新。我知道如何将这些东西附加到txt文件中,但我应该如何对其进行编码,使其只有前五名的分数?

将您的分数添加到名为numbers的列表中,然后添加

numbers.append(yourNumber)
numbers.sort(reverse = True)
del numbers[5:]

则存储列表CCD_ 2

您首先需要将分数放入内存。你可以用一个清单很容易地做到这一点。

highscores = [0]*5

现在,当你得到一个新的分数时,你想把它放在列表的正确位置。假设列表中的第一项是最低的,最后一项是最高的。现在我们可以编写一个函数,将高分附加到列表中,对其进行排序,然后返回5个最高分。

def place_highscores(score: int, highscore_list: list):
size = len(highscore_list)
highscore_list.append(score)
highscore_list.sort()
highscore_list = highscore_list[-size:]
return highscore_list

现在,您可以通过调用以下函数将新的高分放入记分板:

>>>highscores = [1, 2, 3, 5, 5]
>>>highscores = place_highscores(4, highscores)
>>>print(highscores)
[2, 3, 4, 5, 5]

一旦您想保存数据,就可以将其写入文件。你可以直接用你自己的格式来做,你可以使用pickle,或者json,我更喜欢它,因为这个扩展附带了python,而且非常容易使用:

import json
dict = {
"highscores": highscores
}
with open("path/to/file", w) as file:
json.dump(dict, file, indent=4)

以下是json的一些文档:https://www.geeksforgeeks.org/json-dump-in-python/

最新更新