Certain Amount of Time to Input in Python?
Question: I'm making a simple Python Text Adventure Game, and I want to know a way how
to make a simple function that asks for a user input; however, I want the
program to ONLY accept the input before a certain duration (in my program I'm
using 3 seconds). Furthermore, I want the function to check the correctness of
the input before accepting it as right. My attempt is as follows:

    
    
    lvl1 = [
     'Hi', 'Friend', 'Say', 'Smelly',
     'Made', 'Tree', 'Python', 'Freak'
    ]
    
    one = raw_input("You have 3 seconds to type: " + random.choice(lvl1))
    endtime = time.time() + 3
    while time.time() <= endtime and lvl1[0:]: 
      print("Wrong!")
      one = raw_input("Try again: ")
    print("Correct")
    

Basically what I want this code to do is to get an input from the user in
(less than or equal to) a 3 second time duration, but before congratulating
the user, make sure that their input is the same as one of the strings in the
'lvl1' array.

Thanks!


Answer: You were very close. One thing that you missed was that you need to start the
timer before you prompt the user for input. If you do not do this, the program
will wait for the users input before starting the timer, which will always
cause the "in less than 3 seconds" condition to be true. Another change I made
was storing the value of the randomly selected word so that you can display it
and, later in the program, verify that the user's input matches later.

    
    
    import random
    import time
    
    lvl1 = [
     'Hi', 'Friend', 'Say', 'Smelly',
     'Made', 'Tree', 'Python', 'Freak'
    ]
    
    word = random.choice(lvl1)
    start_time = time.time()
    one = raw_input("You have 3 seconds to type: {}\n".format(word))
    
    while time.time() - start_time > 3 or one != word:
        print("Wrong!")
        start_time = time.time()
        one = raw_input("Try again: ")
    print("Correct")
    

Hope this helps!

