[英]How to run a background timer in Python
我目前正在制作一個數學游戲,用戶有 60 秒的時間回答盡可能多的問題。 到目前為止,除了計時器應該倒數到 0 或數到 60 然后停止游戲之外,我已經完成了所有工作。 現在,我將計時器設置為 time.clock() 以計數到 60,而當計時器小於該計時器時,游戲將繼續運行。 然而,由於某種原因, time.clock() 沒有像我預期的那樣工作。 我還嘗試同時運行兩個 while 循環,但也沒有用。 任何人都可以在這里幫助我嗎? 只是尋找一種在后台運行計時器的方法。
這是我的代碼:
score = 0
timer = time.clock()
lives = 3
while timer < 60 and lives > 0:
if score >= 25:
x = random.randint(-100,100)
y = random.randint(-100,100)
answer = int(raw_input("What is %d + %d? " % (x,y)))
if answer == x + y:
print "Correct!"
score += 1
else:
print "Wrong!"
lives -= 1
elif score >= 20:
x = random.randint(-75,75)
y = random.randint(-75,75)
answer = int(raw_input("What is %d + %d? " % (x,y)))
if answer == x + y:
print "Correct!"
score += 1
else:
print "Wrong!"
lives -= 1
elif score >= 15:
x = random.randint(-50,50)
y = random.randint(-50,50)
answer = int(raw_input("What is %d + %d? " % (x,y)))
if answer == x + y:
print "Correct!"
score += 1
else:
print "Wrong!"
lives -= 1
elif score >= 10:
x = random.randint(-25,25)
y = random.randint(-25,25)
answer = int(raw_input("What is %d + %d? " % (x,y)))
if answer == x + y:
print "Correct!"
score += 1
else:
print "Wrong!"
lives -= 1
elif score >= 5:
x = random.randint(-10,10)
y = random.randint(-10,10)
answer = int(raw_input("What is %d + %d? " % (x,y)))
if answer == x + y:
print "Correct!"
score += 1
else:
print "Wrong!"
lives -= 1
elif score >= 0:
x = random.randint(-5,5)
y = random.randint(-5,5)
answer = int(raw_input("What is %d + %d? " % (x,y)))
if answer == x + y:
print "Correct!"
score += 1
else:
print "Wrong!"
lives -= 1
if lives == 0:
print "Oh no! You ran out of lives! Your score was %d." % score
elif timer == 60:
print "Time's up! Your score is %d." % score
else:
print "Goodbye!"
使用time.time()
,它返回紀元時間(即自1970年1月1日UNIX Time以來的秒數)。 您可以將其與開始時間進行比較,以獲取秒數:
start = time.time()
while time.time() - start < 60:
# stuff
您可以在任何時候(即使用戶正在輸入信息)使用帶信號的計時器來將您從代碼中拉出來,但這要復雜一些。 一種方法是使用信號庫:
import signal
def timeout_handler(signal, frame):
raise Exception('Time is up!')
signal.signal(signal.SIGALRM, timeout_handler)
這定義了引發異常的函數,並在發生超時時調用。 現在,您可以將while循環放入try catch塊中並設置計時器:
signal.alarm.timeout(60)
try:
while lives > 0
# stuff
except:
# print score
一種更簡單的方法是創建一個變量來確定計時器應該運行多長時間。 這是一個例子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.