我使用了来自https://stackoverflow.com/a/53299137/11001876的代码,到目前为止它还可以工作,但是我不确定如何将高分限制为只有5分,而只有高分保留在高分文本文件中。我编辑了链接中的代码以适合我的程序:
# Winning Code
elif U1Score > U2Score:
print(username1, "Won")
highscores = open("highscores.txt", "r")
highscores.close()
with open('highscores.txt', 'w') as f:
for username1, U1Score in scores:
f.write('Username: {0}, Score: {1}\n'.format(username1, U1Score))
highscores.close()
highscores = open("highscores.txt", "r")
print(highscores.read())
highscores.close()
else:
print(username2, "Won")
highscores = open("highscores.txt", "r")
highscores.close()
with open('highscores.txt', 'w') as f:
for username2, U2Score in scores:
f.write('Username: {0}, Score: {1}\n'.format(username2, U2Score))
highscores.close()
highscores = open("highscores.txt", "r")
print(highscores.read())
highscores.close()
然而,我仍然不知道如何将分数限制为5个不同的分数,以及如何从最高到最低排序。谢谢我是新来的:)
简单的解决方案是不打印文件。read()逐行读取文件(因为您使用的分隔符是line),然后只打印5行
可能是这样的:
如果你想按降序排序和打印,你可以使用一些排序算法,按每行的数字排序,然后再打印
排序参考-https://www.programiz.com/python-programming/methods/list/sort#targetText=The%20sort()%20method%20sorts,()%20for%20the%20same%20purpose
相关问题 更多 >
编程相关推荐