我如何使计时器与我在Python的游戏一起运行



我是Python的新手,并且创建了一个琐事测验,链接到TXT文件以获取问题/答案并存储高分。

编辑我不使用pygame

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

有没有办法将其与之一起运行?我考虑了一段时间的循环,但它把它弄乱了,所以我猜我做错了...

这是我的代码(最高位):

import linecache
import sys
import pickle
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')
def travel():
    i = 0
    countdown()
    name = input("What is your name: ")
    q1 = linecache.getline("travel.txt", 1)
    a1 = linecache.getline("travel.txt", 2)
    b1 = linecache.getline("travel.txt", 3)
    c1 = linecache.getline("travel.txt", 4)
    print("n", q1, a1, b1, c1)
    q = input("Answer: ")
    if q == "b":
        print("Correct! You've scored 1 point.")
        i += 1
    else:
        print("Wrong answer buddy, 0 points.")

如果愿意,可以使用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

在此示例中,print("You're out of time")将在启动main_game()后60秒发生,但同时将运行# do game things的代码。您需要实现的所有方法是count_thread本身杀死游戏的方法,或者使游戏检查线程是否还活着,如果没有,则退出。

最新更新