我创建了一个小游戏。我想将3个最高分保存在一个文本文件中,并在赛后显示。我创建了一个文本文件,其内容如下:0 0 0
(应代表您第一次玩游戏之前的状态)。我创建了两个函数update_highscores()
和display_highscores()
,但是在完成游戏后没有任何反应。比赛结束后,获得的分数不会存储在文本文件中,也不会显示高分。如何保存和显示高分?
def update_highscores():
global score, scores
file = "C:\Programmieren\Eigene Spiele\Catch The Bananas\highscores.txt"
scores=[]
with open(filename, "r") as file:
line = file.readline()
high_scores = line.split()
for high_score in high_scores:
if (score > int(high_score)):
scores.append(str(score) + " ")
score = int(high_score)
else:
scores.append(str(high_score) + " ")
with open (filename, "w") as file:
for high_score in scores:
file.write(high_score)
def display_highscores():
screen.draw.text("HIGHSCORES", (350,150), fontsize=40, color = "black")
y = 200
position = 1
for high_score in scores:
screen.draw.text(str(position) + ". " + high_score, (350, y), color = "black")
y = y + 25
position = position + 1
答案 0 :(得分:2)
如果您进行更改,update_highscores
代码应该可以正常工作
file = "C:\Programmieren\Eigene Spiele\Catch The Bananas\highscores.txt"
到
filename = r"C:\Programmieren\Eigene Spiele\Catch The Bananas\highscores.txt"
更改的两件事是:将file
更改为filename
,否则此代码将引发异常,因为未定义filename
。我以为是这种方式。我更改的第二件事是在字符串之前添加r
,以便反斜杠按字面意义进行解释。另外两个可行的选择是:
"C:\\Programmieren\\Eigene Spiele\\Catch The Bananas\\highscores.txt"
或
"C:/Programmieren/Eigene Spiele/Catch The Bananas/highscores.txt"
请记住,非原始字符串中的单个反斜杠通常会尝试转义下一个字符。
除此之外,只需确保文件存在,并且包含0 0 0
或任何用空格分隔的字符序列即可。如果文件未正确初始化,则不会替换任何分数。
此代码对我有用,因此,如果仍然有问题,仅显示分数即可。他们在文件中更新就好了。但是我不知道您在screen
中使用哪个库,因此我无法对其进行测试。
哦,还要:确保您实际上在调用该函数。我认为它在您代码的其他位置,您只是省略了它。显然,如果不调用该函数,您的代码将无法正常工作。
这是我的代码有效。只需替换highscores.txt
的路径,然后单独运行此代码即可。如果可行,则问题出在您代码中的其他地方,除非您给我们更多代码,否则我们将无法为您提供帮助。
score = int(input("Enter new score: "))
scores = []
def update_highscores():
global score, scores
filename = r"path\to\highscores.txt"
scores=[]
with open(filename, "r") as file:
line = file.readline()
high_scores = line.split()
for high_score in high_scores:
if (score > int(high_score)):
scores.append(str(score) + " ")
score = int(high_score)
else:
scores.append(str(high_score) + " ")
with open (filename, "w") as file:
for high_score in scores:
print(high_score)
file.write(high_score)
update_highscores()
input()