Miki Miki - 1 month ago 18
Python Question

Python time limit

I have a homework assignment to do and I really need a solution. I have been trying to do this since yesterday but I do not know how.

Program has to generate and print a letter or a number and then a user has to type it as quickly as possible and press ENTER. The game is over after 30 secs.

Well I do not know how to put time limit to a game. I was searching through stackoverflow and I did not find anything useful. Please help me.

**Here it is what I have done so far. I tried code from the answer by SYSS.STDER, but it does not quite work because when the 30 secs are over, the game should also be over, but here in this code the game is over when I type last character.

LOOP WILL NOT STOP UNTIL IT FINISHES AND WE DISCOVER THAT WE ARE PAST OUR DEADLINE. THE TASK NEEDS TO BE INTERRUPTED IN PROGRESS AS SOON AS THE TIME ELAPSES.

max_time =30
start_time = time.time() # remember when we started
while (time.time() - start_time) < max_time:

response = "a" # the variable that will hold the user's response
c = "b" #the variable that will hold the character the user should type
score = 0
number = 0

c = random.choice(string.ascii_lowercase + string.digits)
print(c)
number = number + 1

response = input("Type a letter or a number: ") #get the user's response

if response == c and (time.time() - start_time) < max_time:
# if the response from the previous loop matches the character
# from the previous loop, increase the score.
score = score + 1

Answer

Here's my way to do it:

import string
import random 
import time   

response = "a"              # the variable that will hold the user's response
c = "b"                     #the variable that will hold the character the user should type
score = 0                   #the variable that will hold the user's score
start = time.time()         #the variable that holds the starting time
elapsed = 0                 #the variable that holds the number of seconds elapsed.
while elapsed < 30:         #while less than 30 seconds have elapsed  

    if response == c:       #if the response from the previous loop matches the character
        score += 1          #from the previous loop, increase the score.

    #c is a random character
    c = random.choice(string.ascii_lowercase + string.digits)
    print(c)               

    response = input("Type a letter or a number: ") #get the user's response

    elapsed = time.time() - start #update the time elapsed