python - 将高分保存在游戏的文本文件中
问题描述
我创建了一个小游戏。我想将 3 个最高分保存在一个文本文件中,并在游戏结束后显示它们。我创建了一个包含以下内容的文本文件:(0 0 0
应该代表你第一次玩游戏之前的状态)。我创建了 2 个函数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
解决方案
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()
推荐阅读
- angularjs - AngularJS过滤器检查数组参数是否包含值
- python - 使用python从字符串中查找和替换标记的单词?
- javascript - 使用javascript将月-日-年转换为日-月-年
- javascript - Stripe 和 React,react-stripe-element 自定义卡片元素,没有 zip 字段
- amazon-web-services - 如何在没有 ngnix 的情况下使用 Elasticbeanstalk(仅使用应用程序负载均衡器)
- javascript - 关于 PhpStorm 中可选链接和空值合并 JavaScript 运算符支持的问题
- python - Python 将命令及其输出写入文件
- c++ - 为什么显式弃用寄存器存储类
- android - 验证在 firebase 回收器适配器中不起作用
- c# - 如果可以更改 VisualParent,如何在 UserControl 中处理订阅