我正在製作一個數學遊戲,用戶有60秒的時間來回答儘可能多的問題。到目前爲止,除了計時器應該倒數到0或者數到60以外,停止遊戲之後,我就可以開始工作了。現在,我將計時器設置爲time.clock()以計數到60,而計時器小於此時,遊戲將繼續運行。但是,由於某些原因,time.clock()並不像我預期的那樣工作。我也嘗試在同一時間運行兩個while循環,這兩個循環都不起作用。任何人都可以幫助我在這裏?只需尋找一種讓計時器在後臺運行的方法。如何在Python中運行後臺計時器
這裏是我的代碼:
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!"
http://stackoverflow.com/questions/2223157/how-to-execute-a-function-asynchronously-every-60 -python – jcfollower 2014-09-23 18:50:33
你需要'time.clock()'每次你想檢查。另外,time.clock()不會做你認爲它的作用。 – fredtantini 2014-09-23 18:55:50
這個問題有很好的答案:http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish – 2014-09-23 20:01:00