如何在python中使用messagebox显示时间

2024-10-01 19:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用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()

所以这就是当你打败三个关卡时会发生的事情。你可以看看排行榜,但它只是打印出所有的时间,已写入文件。我能做些什么来排列这些时间?你知道吗


Tags: 文件thetxtyougametop时间file
1条回答
网友
1楼 · 发布于 2024-10-01 19:31:39

幸运的是,您正在编写一个好的、整洁的文件,以便于解析。它看起来像这样:

Alice's time is 3.2.
Bob's time is 4.6.
Charlie's time is 4.1.
(empty line)

这意味着我们可以做到:

if top_score.lower().startswith('y'):
    with open('Player Times.txt', 'r') as f:
        print(*sorted(f, key=lambda x: float(x[:-2].split("'s time is ")[1])), sep='')

首先,我们使用score作为排序键对打开的文件进行排序(这是一个iterable,所以我们可以直接进行排序)。我们将使用lambda定义一个内联函数,该函数接受一个参数,该参数将是文件中的每一行。分数在字符串"'s time is "之后,在最后两个字符".\n"之前,所以我们剪掉最后两个字符,在"'s time is "上拆分剩余的字符串,并将其转换为float^{}将使用这个数字来确定正确的顺序。你知道吗

这给了我们一些与原始文件对象非常相似的东西:一个list的字符串,只是这次它们被正确地排序了。很好地打印字符串列表的一种快速方法是用*展开列表,因为每行末尾都有一个换行符,所以我们将告诉print()使用空字符串作为分隔符,而不是通常的空格。你知道吗

结果:

Alice's time is 3.2.
Charlie's time is 4.1.
Bob's time is 4.6.

sorted()使用的默认升序在这里起作用,但是如果您想从高到低排序(例如,有点数的游戏),可以传递关键字参数reverse=True,例如sorted(['a', 'bbb', 'cc'], key=len, reverse=True)来生成['bbb', 'cc', 'a']。你知道吗

相关问题 更多 >

    热门问题