如何将计时器设置为一个功能

2024-07-02 11:48:52 发布

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

def choosePath():
    path = ""
    while path != "e" and path !="n":
        print('\nWhich way do you go (n, s, e, w):\n')
        t = Timer(1 * 1, timeout)
        t.start()
        answer = input(path)
        path = path.lower()
        if path =="e":
            station()
        elif path =="n":
            estate()
        elif path =="s":
            building()
        else:
            print("\nYou return the way you came are but are soon caught by Mansons and assimilated.\n")
        return path

我已经收到了这个代码,并希望添加一个计时器,如果答案没有在一定的时间内完成,它说gameover。你知道吗


Tags: andpathyougoreturndefdoare
3条回答

你需要在while循环外启动计时器。还有几种方法可以实现计时器,但这应该是可行的(我简化了它,您需要根据业务逻辑调整它)

import time

start_time = datetime.now()
max_time_allowed = 45
while path != "e" and path !="n":
    #Business logic here
    current_time= datetime.now()
    if current_time-start_time > max_time_allowed:
        return

您需要线程模块中的Timer类。你知道吗

import threading

t = threading.Timer(<delay in secs>, <callback>, [<function args>])
t.start()

如果用户在time中选择了一个选项,则调用t.cancel()

尝试创建另一个线程来跟踪时间,然后更新全局布尔值:

from threading import Thread 
from time import sleep

timeIsUp = False

threadKill = False
def answerTime(self):
    sleep(self)
    if threadKill = True:
         self._is_running = False
    else:
        timeIsUp = True
        self._is_running = False

thread = Thread(target = answerTime,      args = (10)

现在您可以让主代码在while循环中有一个附加语句:

while path != "e" and path !="n" and timeIsUp==False:
  ...
 if path =="e": 
      station()
      threadKill=True
 elif path =="n": 
      estate()
      threadKill=True
 elif path =="s": 
      building()
      threadKill=True
else:
    print("Time is up")

相关问题 更多 >