I need a timed input for python 3 on both Mac and Windows which, if the user runs out of time, automatically chooses one of the options. Every other answer for a question I've seen only terminates after user presses 'Enter'. I need it to terminate regardless of any 'Enter' pressed or not.
For example, in my chess program, if no input is given after 5 seconds, I need it to automatically choose "Q". Also if the input is not in ["Q", "R", "B", "N"] then I also need it to choose "Q".
The following code doesn't work. It'll ask for the input then wait forever; the timer doesn't work at all.
def countdown():
global timer
timer = 5
for x in range(timer):
timer -= 1
time.sleep(1)
countdownThread = threading.Thread(target=countdown)
countdownThread.start()
while timer > 0:
promotedPiece = input("Promote to Q, R, B or N? > ").upper()
if timer == 0:
break
if timer == 0:
if promotedPiece not in ["Q", "R", "B", "N"]: # If not valid input, choose Queen
promotedPiece = "Q"
print("Queen auto selected")
from Timed input in python 3 for Mac and Windows
No comments:
Post a Comment