0

I am trying to code a chess timer in which there are two timers counting down alternatingly. Only one timer runs at a time, and when a certain input is given by the user, which I am using keyboard.is_pressed("some_key") for, one timer pauses and the other begins counting down and vice versa. My problem is that to countdown by intervals of 1 second, I am using time.sleep(1) and the program will not receive user input during this time, so unless the user gives input on exactly the 1 second mark, nothing happens. How can I make the countdown process and the checking for user input process run at the same time?

Here is the code:

import time
import keyboard


def timers(t1, t2):
    pause = True
    while t1 or t2:
        if pause:
            while pause:
                mins1 = t1 // 60
                secs1 = t1 % 60
                timer1 = '{:02d}:{:02d}'.format(mins1, secs1)
                print("Timer1: ", timer1)
                time.sleep(1)
                t1 -= 1
                if keyboard.is_pressed("w"):
                    pause = False
                    break
                else:
                    continue
        else:
            while not pause:
                mins2 = t2 // 60
                secs2 = t2 % 60
                timer2 = '{:02d}:{:02d}'.format(mins2, secs2)
                print("Timer2: ", timer2)
                time.sleep(1)
                t2 -= 1
                if keyboard.is_pressed("w"):
                    pause = True
                    break

    print("Beep")


tWhite = int(input("Enter the time in seconds for White: "))
tBlack = int(input("Enter the time in seconds for Black: "))

timers(tWhite, tBlack)

0 Answers0