我正在制作一个数学游戏,用户有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