我正在用python设计一个tic-tac-toe游戏,它计算用户打败三个关卡所需的时间,然后将这个分数保存到一个名为“Player”的文件中时代.txt'. 我想对每个玩家从低到高的时间进行排名。你知道吗
print('You beaten all three levels and reached the end of the game!')
.windll.user32.MessageBoxW(0, "Hooray you've won the game.","Victory", 1)
ctypes.windll.user32.MessageBoxW(0, str(sum1), "Your Score", 1)
#top_score=str(input('Would you like to see the leaderbooard?'))
MyfileWrite = open('Player Times.txt','a')
MyfileWrite.write(file_info + "'s time is " + str(sum1) + '.' + '\n')
MyfileWrite.close()
print('--------------------')
top_score=str(input('Would you like to see the leaderbooard?'))
print('--------------------')
if (top_score=='yes'):
MyfileWrite = open('Player Times.txt', 'r')
file_contents = MyfileWrite.read()
print(file_contents)
MyfileWrite.close()
所以这就是当你打败三个关卡时会发生的事情。你可以看看排行榜,但它只是打印出所有的时间,已写入文件。我能做些什么来排列这些时间?你知道吗
幸运的是,您正在编写一个好的、整洁的文件,以便于解析。它看起来像这样:
这意味着我们可以做到:
首先,我们使用score作为排序键对打开的文件进行排序(这是一个iterable,所以我们可以直接进行排序)。我们将使用} 将使用这个数字来确定正确的顺序。你知道吗
lambda
定义一个内联函数,该函数接受一个参数,该参数将是文件中的每一行。分数在字符串"'s time is "
之后,在最后两个字符".\n"
之前,所以我们剪掉最后两个字符,在"'s time is "
上拆分剩余的字符串,并将其转换为float
。^{这给了我们一些与原始文件对象非常相似的东西:一个
list
的字符串,只是这次它们被正确地排序了。很好地打印字符串列表的一种快速方法是用*
展开列表,因为每行末尾都有一个换行符,所以我们将告诉print()
使用空字符串作为分隔符,而不是通常的空格。你知道吗结果:
sorted()
使用的默认升序在这里起作用,但是如果您想从高到低排序(例如,有点数的游戏),可以传递关键字参数reverse=True
,例如sorted(['a', 'bbb', 'cc'], key=len, reverse=True)
来生成['bbb', 'cc', 'a']
。你知道吗相关问题 更多 >
编程相关推荐