如何在python中创建一个倒计时计时器,以便与我的游戏一起运行?

如何在python中创建一个倒计时计时器,以便与我的游戏一起运行?,python,timer,countdown,Python,Timer,Countdown,我对Python相当陌生,并创建了一个小测试,链接到txt文件以获取问题/答案并存储高分 编辑我没有使用PYGAME 我想为要回答的问题设定一个时间限制,例如1分钟。我设法让计时器倒计时,但它倒计时,然后继续我的游戏 有没有办法让它并行运行?我想了一个循环,但它只是把它搞砸了,所以我猜我做错了 这是我的代码(好的,在顶部): 如果愿意,可以使用threading.Thread来实现此功能 请注意以下代码: import threading import time def countd

我对Python相当陌生,并创建了一个小测试,链接到txt文件以获取问题/答案并存储高分

编辑我没有使用PYGAME

我想为要回答的问题设定一个时间限制,例如1分钟。我设法让计时器倒计时,但它倒计时,然后继续我的游戏

有没有办法让它并行运行?我想了一个循环,但它只是把它搞砸了,所以我猜我做错了

这是我的代码(好的,在顶部):


如果愿意,可以使用
threading.Thread
来实现此功能

请注意以下代码:

import threading
import time     

def countdown():
    t = 60
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        t -= 1
    print("You're out of time!\n")
    # add some function which stops the game, for example by changing a variable to false (which the main thread always checks) 
    # or some other method like by checking count_thread.is_alive()

def main_game():
    count_thread = threading.Thread(None, countdown)
    # do game things

在本例中,
打印(“您没时间了”)
将在
main_game()
启动60秒后进行,但同时
#do game things
处的代码将运行。你所需要实现的只是一种方法,让计数线程本身杀死游戏,或者让游戏检查线程是否仍处于活动状态,如果没有,则退出。

你可以使用
线程
模块如何工作?我想它在后台运行一个过程,但我不太确定。我没怎么用过它。可能是@agtoever no的复制品,因为OP没有使用pygame
import threading
import time     

def countdown():
    t = 60
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print(timeformat, end='\r')
        time.sleep(1)
        t -= 1
    print("You're out of time!\n")
    # add some function which stops the game, for example by changing a variable to false (which the main thread always checks) 
    # or some other method like by checking count_thread.is_alive()

def main_game():
    count_thread = threading.Thread(None, countdown)
    # do game things