[英]How to make a timer run concurrently in python
I am going through Zed Shaw's Learn Python the Hard Way and as one of the exercise we are asked to create a game. 我正在阅读Zed Shaw的《学习Python的艰难方法》,作为一项练习,我们被要求创建一个游戏。 I wanted to create a rhyming game that would print out a word and the player had 5 seconds to guess a word that rhymed with the word printed out. 我想创建一个押韵游戏,该押韵游戏会打印出一个单词,而玩家有5秒钟的时间来猜测一个与押记单词押韵的单词。
I was able to get the game to work without a timer. 我能够在没有计时器的情况下使游戏正常运行。 However, I can't figure out how to make the timer run concurrently with the game. 但是,我不知道如何使计时器与游戏同时运行。 Below is the code: 下面是代码:
#libraries
libs = [about, cake, chart, score]
#points
p = 0
#timer
class countdown(object):
def __init__(self, timer):
self.timer = timer
while timer != 0:
print "timer: %i" % timer
sleep(1)
timer -= 1
else:
exit("You ran out of time!")
class engine(object):
# randomly select a library
i = randint(0, len(libs)-1)
randlib = libs[i].words.split(' ')
rhymeword = sample(randlib, 1)
print rhymeword
guess = raw_input("> ")
while guess not in randlib:
print rhymeword
guess = raw_input("> ")
else:
# to reset the timer
timer = 5
# points assignment
if guess in libs[i].onesyl.split(' '):
p += 1
print "Points: %s" % p
elif guess in libs[i].twosyl.split(' '):
p += 2
print "Points: %s" % p
elif guess in libs[i].threesyl.split(' '):
p += + 3
print "Points: %s" % p
t = countdown(5)
e = engine()
t.start()
e.start()
What I would like to do is have the timer counting down while the user tries to guess and then have the timer restart once a correct answer is enter. 我想做的是在用户尝试猜测时让计时器倒数,然后在输入正确答案后重新启动计时器。
I looked into multiprocessing in the python documentation, but I wasn't sure how to make that work. 我在python文档中研究了多处理,但是不确定如何使它工作。
really this is bad design if you want a timer like this you should look into a gui or at least curses ... your output likely wont look how you hope 真的,这是一个糟糕的设计,如果您想要这样的计时器,您应该查看gui或至少curses ...您的输出可能不会看起来像您希望的那样
all that said I guess this is roughly the behaviour you want 所有这些我想这大概是您想要的行为
import sys,time,threading
def wait_for_secs(N):
for i in range(N):
print N-i
time.sleep(1)
print "OUT OF TIME!!!"
sys.exit(1)
threading.Thread(target=wait_for_secs,args=(15,)).start()
answer = raw_input("5+6*3=? >")
print "You Answered:",answer
sys.exit(0)
You can use the standard module signal to make a simple timer. 您可以使用标准模块信号制作一个简单的计时器。 Here is an example : 这是一个例子:
import signal, sys
def handler(signum, frame):
#print 'Signal handler called with signal', signum
print "You ran out of time!"
sys.exit()
def engine():
guess = raw_input("> ")
print "fast enough to input",guess
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)
engine()
signal.alarm(0) # Disable the alarm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.