我怎样才能使程序进展,而'while循环'运行一个计时器(python)

时间:2014-09-17 13:32:41

标签: python-2.7 while-loop

我需要知道在循环计数时间运行时我如何输入用户输入。我知道我的程序不高效也没有组织,因为我是python的新手。一个简单但更长的修复比一个我不理解的简短修复要好。

import time
print 'Welcome To the Speedy Type Game!'
time.sleep(1)
print "You're objective is to win the game by typing the specific word before the time runs out"
print "Don't forget to press 'enter' after typing the word!!!!"
print "For round 1 you will have 5 seconds"
null = raw_input('Press enter when you are ready to start')
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
print 'GO'
C = 'poop'
x = 5
while C in ['poop']:
    x = x - 1
    time.sleep(1) #This is where my program comes to a halt.
C = raw_input("Print the word 'Calfornia': ") #I dont know how to make the program progress to here without stopping the timer above.
if x < 0:
    print 'You have failed, game over!'
else:
    print 'Good Job! let us move to the next round!'

1 个答案:

答案 0 :(得分:0)

在Python中没有简单的方法 - 一次运行一个进程,所以没有例如线程(请参阅https://stackoverflow.com/a/2933423/3001761)您不能将用户输入与计数重叠。更简单的方法可能是:

def test(word, limit=5):
    started = time.time()
    while True:
        result = raw_input("Type {0!r}: ".format(word))
        finished = time.time()
        if result == word and finished <= started + limit:
            print 'Good Job! let us move to the next round!'
            return True
        elif finished > started + limit:
            break
        print 'Wrong, try again.'
    print 'You have failed, game over!'
    return False

然后拨打例如:

>>> test("California")
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly but quickly
Wrong, try again.
Type 'California': California # typed quickly
Good Job! let us move to the next round!
True
>>> test("California")
Type 'California': foo # typed wrongly and slowly
You have failed, game over!
False
>>> test("California")
Type 'California': California # typed slowly
You have failed, game over!
False