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
我收到了这段代码,并希望添加一个计时器,如果在一段时间内没有完成答案,那就说游戏结束。
答案 0 :(得分:3)
你想在线程模块中使用Timer类。
import threading
t = threading.Timer(<delay in secs>, <callback>, [<function args>])
t.start()
如果用户在时间调用t.cancel()
答案 1 :(得分:0)
您需要在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
答案 2 :(得分:0)
尝试创建另一个线程来跟踪时间,然后更新全局布尔值:
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")