我有一个问题,该函数只是覆盖.txt文件中已经存在的行。该功能应该在游戏退出时向文件写入高分(我通过遵循youtube教程制作了蛇游戏)。我不太清楚为什么它不会重新开始,任何人都可以解释它背后的逻辑,以及我如何解决它?我在某处读到,而不是f.open()中的“ w”,我应该键入“ rb”或其他内容。由于我对这种“写到文件”的东西还有些陌生,所以我发现这很困难。
另外,我想将文件中的高分从高到低排序(换句话说,将finalScore从高到低排序)。我不知道该如何继续编写代码,所以我需要一些帮助。您会看到,我想将当前的高分打印到控制台(以便进行评分)
这是代码:
import random
import time
name = "Andreas"
finalScore = random.randint(1,10)
def scoreToFile(finalScore):
#Has to be generated here, since we need the exact current time
currentTime = time.strftime("%c")
print("Sucsessfully logged score (finalScore) to highscores.txt")
f = open("highscores.txt", "w")
#fileOutput = [(currentTime, ":", name, "-", finalScore)]
fileOutput = [(finalScore, "-", name, currentTime)]
for t in fileOutput:
line = ' '.join(str(x) for x in t)
f.write(line + "\n")
f.close()
scoreToFile(finalScore)
无论如何,圣诞快乐,我的蟒蛇怪人!:D
模式会w
覆盖现有文件;模式'a'附加到它。另外,处理文件的最佳方法通常是使用with
语句,以确保代表您关闭文件。所以:
fileOutput = [(finalScore, "-", name, currentTime)]
with open("highscores.txt", "a") as f:
for t in fileOutput:
line = ' '.join(str(x) for x in t)
f.write(line + "\n")
为了进行排序,您需要能够从一行中提取最终分数作为数字:
def minus_score(line):
return -int(line.split()[0])
那么总工作将完成为:
def sorted_by_score():
with open("highscores.txt", "r") as f:
result = list(f)
return sorted(result, key=minus_score)
这将为您提供一个按分数升序排序的列表行(后者的原因score
是否定数字,尽管也可以选择让它仅返回数字并反转排序),以便您继续循环并进一步处理。
补充:因此,在OP的要求下,这就是整个程序的方式(假设存在一个功能,该功能可以玩游戏并返回玩家名称和最终得分,或者None
在不再玩游戏且必须退出程序时返回)。
import time
def play_game():
""" play a game and return name, finalscore;
return None to mean no more games, program finished.
THIS function you'd better code yourself!-)
"""
def scoreToFile(name, finalScore):
""" Add a name and score to the high-scores file. """
currentTime = time.strftime("%c")
fileOutput = finalScore, "-", name, currentTime
line = ' '.join(str(x) for x in fileOutput)
with open("highscores.txt", "a") as f:
f.write(line + "\n")
def minus_score(line):
""" just for sorting purposes, not called directly. """
return -int(line.split()[0])
def sorted_by_score():
""" return list of score lines sorted in descending order of score. """
with open("highscores.txt", "r") as f:
return sorted(f, key=minus_score)
def main():
while True:
game_result = play_game()
if game_result is None: break
scoreToFile(*game_result)
for line in sorted_by_score:
print(line.strip())
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句