簡體   English   中英

如何為功能設定計時器

[英]how to make a timer to a function

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

我已收到此代碼,並想添加一個計時器,如果在一定時間內未完成回答,它將顯示游戲結束。

您需要在線程模塊中使用Timer類。

import threading

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

如果用戶及時選擇了一個選項,則調用t.cancel()

您需要在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

嘗試創建另一個線程來跟蹤時間,然后更新全局布爾值:

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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM