0

I need to know how i can enter user input while this while loop counting time is running. I know my program is not efficient nor organized as I am new to python. A simple but longer fix is better than a short fix that I would not understand.

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!'
Luke
  • 3
  • 1
  • possible duplicate of [Keyboard input with timeout in Python](http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) – Falko Sep 17 '14 at 14:13
  • You might want to try [this solution](http://stackoverflow.com/a/2904057/3419103). – Falko Sep 17 '14 at 14:14

1 Answers1

0

There is no easy way to do this in Python - a single process is running at a time, so without e.g. threading (see https://stackoverflow.com/a/2933423/3001761) you can't overlap user input with counting. An easier approach might be:

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

Then call e.g.:

>>> 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
Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437