问题描述
我是编程方面的新手,我正在尝试创建一款具有高分功能的小型基于文本的游戏。这款游戏很好用,但是如果玩家在游戏结束时获得更高的分数,那么尝试替换文件中的高分会遇到问题。
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
normal null 0
expert null 0
我尝试创建一个代码,使用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”被打印以来玩家是否获得了新的高分,但是文本并没有被替换。我希望你们能帮助我。另外,对我的英语不好,也很抱歉,因为它不是我的母语。谢谢!
解决方法
即使没有任何更改,我也编写了一个简单的脚本来将更改写入highscores.txt中。
score = 30
mode = "normal"
player = "Raka"
f = open("highscore.txt","r")
lines = f.read().split("\n")
#remove empty lines in the lines list
lines = [line for line in lines if line.strip() != ""]
for x in range(0,len(lines)):
words = lines[x].split(" ")
if words[0] == mode and score > int(words[2]):
lines[x] = mode +" "+player+" "+str(score)
#Write the changes in highscore.txt
outF = open("highscore.txt","w")
for line in lines:
outF.write(line)
outF.write("\n")
outF.close()
,
尝试使用以下代码:
check_high_score = open("highscore.txt","r")
list_high_scores = check_high_score.readlines()
check_high_score.close()
to_write = []
for score in list_high_scores:
if mode.lower() == "normal":
if int(list_high_scores[0][2]) < score:
to_write.append("normal " + player + " " + str(score))
else:
to_write.append(list_high_scores[0])
elif mode.lower() == "expert":
if int(list_high_scores[1][2]) < score:
to_write.append("expert " + player + " " + str(score))
else:
to_write.append(list_high_scores[1])
write_score = open("highscore.txt","w")
write_score.writelines(to_write)
write_score.close()
我建议在打开文件后将数据存储在新变量中,而不是直接访问它,这样可以更轻松地对其进行逻辑处理并提高代码的可读性。另外,每次创建文件处理程序时,请尝试使用不同的变量名。至于为什么代码无法正常工作,我认为这是因为替换内容后,您尚未使用checkline.close()
关闭文件。除非关闭文件,否则程序将不会将数据从缓存推送到磁盘,并且内容将保持不变。另外,您也可以使用flush(在您的情况下为checkline.flush()
)将数据推送到文件中,但请记住,这样做时,文件处理程序将继续在后台运行并在关闭时占用内存函数将终止它。内存现在可能不是问题,但在较大的项目中可能很重要,这是一个好习惯。