0

` # 1 (code introduction) import random

print("Welcome to Response Time Tester!")
print("You will be asked to press Enter after random amounts of time.")
print("How close can you get? ")
print()
while True:
    try:
        rounds = int(input("Enter desired number of rounds: "))
        if rounds <= 0:
            print("Number of rounds must be greater than zero. Try again.")
        else:
            break
    except ValueError:
        print("Invalid input. Enter a number.")

num = random.randint(2, 8)    

for i in range(rounds): 
    print("round 1 of",i+1)
    print(f'Press Enter in', num, 'seconds')

#Difference Rating
#<= 0.25 Excellent!
#<= 0.5 Great!
#<= 1 Good!
#<= 2 OK!
#> 2 Miss

so in my code i want to ask the user to press Enter in a certain amount of seconds and that data gets recorded and put in a variable or something for the result. I will then compile all the results and tell the user how quick he was based on this scale.

2 Answers2

0

There is a number of ways to do this in python, but here is what i would do.

To detect the enter key being press the most standard way would be to install and use the python keyboard module. Then you can use keyboard.wait("\n") which will wait until the user hits the enter key.

For detecting the time your best bet is probably pref_counter time.perf_counter() (needs the time module to be imported import time). time.pref_counter() returns the time in seconds, so you can use it to measure the difference in time

here is a start on how you would use both of them

for i in range(rounds): 
    print("round 1 of",i+1)
    print(f'Press Enter in', num, 'seconds')
    start_time = time.pref_counter()
    keyboard.wait("\n")
    stop_time = time.pref_counter()
    lapsed_time = stop_time - start_time # time taken to hit enter
Zachary N
  • 1
  • 1
  • are you able to impliment this into my existing code please, because i have no idea how to do that. Thanks –  Mar 12 '23 at 08:24
0

You can get the time immediately before starting the go using:

import time

...
....
start = time.time()

Then read from the keyboard with a timeout of timeToGuess + 2, see here.

Then measure the elapsed time with:

elapsed = time.time() - start
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432