0

How would I show some message/error for when enter is pressed before stated 'GO!!'?, as currently when enter is pressed before stated, 'diff' or 'reaction time' is 0.0002 or next to 0?

import random
import time

print("Reaction Time\nPress Enter when stated 'GO' ")

time.sleep(random.randint(1, 4))
then = time.time()
input("GO!! ")
now = time.time()

diff = now-then
print("\nYou took " + str(diff) + " long")
Jamesik01
  • 5
  • 2

1 Answers1

0

One way to do this, is to create a separate thread with the standard threading library. You create a thread, that waits for an input and if it is received, then a variable is modified in the main thread. The flow goes like:

  1. Start a thread that waits for input
  2. Wait the time
  3. Check if variable in main thread has been modified (pressed too early)
  4. start the timer and print GO!
  5. End timer when the variable in main thread is modified (aka input is provided)

This has the downside, that the message Pressed too early. is only printed when the wait timer is up.

Here is your modified code:

import random
import time
import threading

print("Reaction Time\nPress Enter when stated 'GO' ")

def get_input(l):
    """This function runs in a new thread and waits for the user to press enter"""
    data = input()
    l.append(data)
    return
inp = []
input_thread = threading.Thread(target=get_input,args=(inp,))
input_thread.start()
print("Wait...")
time.sleep(random.randint(1, 4))
if inp: #Check if list is still empty
    print("Pressed too early.")
    exit(0)
start = time.time()
print("GO!")
while not inp: #While the list is still empty, run the timer
    pass
end = time.time()
diff = end - start
print("\nYou took " + str(diff) + " long")

There is dicussion of a similar problem/tools to solve such problems here: Python: wait for user input, and if no input after 10 minutes, continue with program and Key Listeners in python?

Ilmard
  • 86
  • 4