【发布时间】:2021-02-08 00:12:02
【问题描述】:
我是一名编程新手,我正在尝试创建一个基于文本的小型游戏,具有高分功能。游戏很好,但是如果玩家在游戏结束时获得更高的分数,我在尝试替换文件中的最高分时会遇到问题。
如果文件不存在,我创建了一个函数来生成文件:
def createhighscore():
hs = os.listdir()
highscore = None
if "highscore.txt" not in hs:
highscore = open("highscore.txt", 'w')
a = ["normal null 0\n", "expert null 0\n"]
highscore.writelines(a)
return highscore
所以现在 highscore.txt 文件有两行:
normal null 0
expert null 0
- 正常/专家 = 玩家选择的游戏模式,我将游戏模式放在变量“模式”中
- null = 替换为玩家名称,我将玩家名称放入变量“玩家”中
- 0 = 替换为新的高分,我把分数放在变量“score”中
我尝试创建一个代码,使用 split() 将每行中的每个单词拆分为一个列表,然后检查是否存在玩家获得的分数高于任一模式的当前分数的情况。我的代码:
checkline = open("highscore.txt", "r+")
for line in checkline:
x = line.split()
if x[0] == mode.lower() and int(x[2]) < score:
line.replace(x[1], player)
line.replace(x[2], str(score))
print("NEW HIGHSCORE")
checkline.close()
checkline = open("highscore.txt", "r+")
for line in checkline:
x = line.split()
if x[0] == mode.lower() and int(x[2]) < score:
x[1] = player
x[2] = score
print("NEW HIGHSCORE")
checkline.close()
因此,如果名为“Raka”的玩家在专家模式中获得 20 分,highscore.txt 文件应更改为:
normal null 0
expert Raka 20
遗憾的是,我的代码没有执行任何操作,highscore.txt 的内容保持不变。我尝试调整我的代码,直到现在我还没有找到解决方案。我认为我的代码确实检测到玩家是否获得了新的高分,因为“NEW HIGHSCORE”被打印出来,但文本没有被替换。我希望你们能帮助我。另外,很抱歉我的英语不好,因为它不是我的第一语言。谢谢!
【问题讨论】:
-
你永远不会向文件中写入内容,这就是它不会改变的原因。
标签: python if-statement text replace