0

I want to make a stopwatch for rubik's cube timing, where you press enter to start it and press spacebar to make it stop. Here is what I have so far:

import time
running = True
second = 0
minute = 0
mill = 0 #by the way this is for millisecond
while running:
    print('Rubik\'s cube timer: press enter to start, space bar to stop')
    print('Note: you won\'t be able to see the time until you end it')
    input()
    if mill == 100:
        mill = 0
        second += 1
    if second == 60:
        second = 0
        minute += 1
    time.sleep(.01)
    mill += 1

But all that does is go on and on without ending. It is supposed to not stop the timer or show you ho w long it was until you press space bar. I don't know how to make it stop when space bar is pressed.

1
  • why don't you save current time, wait until a keypress (there are tons of solutions on SO for this), read the current time again and subtract the saved one? These time.sleep are really unnecessary Commented Nov 6, 2020 at 19:11

1 Answer 1

1

There are a couple of design considerations you might want to think about here. First, your method of time tracking is very imprecise and will result in losses to due how long python takes to perform operations. Instead of even using a loop you could just use two inputs and note the time difference between when the first one happened and when the second one happened. Second, you should also consider using a library to handle key input (as it is different for each platform). Here I use pynput:

from pynput import keyboard
import datetime
print('Rubik\'s cube timer: press enter to start, space bar to stop')
print('Note: you won\'t be able to see the time until you end it')
input()
start = datetime.datetime.now()
with keyboard.Listener(
    on_press=lambda key: key != keyboard.Key.space) as listener:
    listener.join()
end = datetime.datetime.now()
print(f"It took you {end - start} to finish")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.