CatsInSpace CatsInSpace - 1 month ago 9
Python Question

Python Countdown while other code running

I want it so that the player only has a 500-600 milisecond frame to type 1 or 2. I don't know how to do this and the only timers I found only do

time.sleep(1)


Here is my code:

game = 1
while game == 1:
play = input(print("'display picture in other window' [1] for right [2] for wrong "))
if '1' in play:
print("You shot the Criminal! + 1 point")
point = point + 1
row = row + 1
if row == 3:
unlock2 = 1
print ("You gained 2 bonus points!")
point = point + 2
row = 0
if unlock2 == 1:
point = point + (point/2)
print ("You gained bonus points!")

elif '2' in play:
print("You shot an innocent! Game Over!")
break

game = 0

Answer

The easiest way to do what you want would be to measure the time the user takes for a response, like this:

import time

def respond_in_time(msg, s):
    start = time.time()
    response = input(msg)
    end = time.time()
    print(end-start)
    if end - start > s:
        return False
    else:
        return response

Usage:

>>> respond_in_time("What is 2+2? ", 0.5) # User responds in time
'4'
>>> respond_in_time("What is 2+2? ", 0.5) # User is too slow
False
Comments