我正在通过Zed Shaw的艰苦学习Python,并且作为练习之一,我们被要求创建一个游戏。我想创建一个押韵的游戏,打印出一个单词,玩家有5秒的时间猜出一个与打印出来的单词押韵的单词。
我能够在没有计时器的情况下让游戏工作。但是,我无法弄清楚如何使计时器与游戏同时运行。以下是代码:
#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()
我想做的是在用户尝试猜测时让计时器倒计时,然后在输入正确的答案后重新启动计时器。
我在python文档中研究了多处理,但我不确定如何使用它。
答案 0 :(得分:2)
真的这是糟糕的设计,如果你想要这样的计时器,你应该看看gui或至少诅咒...你的输出可能不会看起来你希望
所有这些说我猜这大致是你想要的行为
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)
答案 1 :(得分:1)
您可以使用标准模块信号制作一个简单的计时器。 这是一个例子:
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