I'm trying to make a basic command-line math game in Python 3. The game shows a user a basic addition problem, the system waits for the user to hit enter, then it displays the answer and then the next problem.
I want to introduce pressure on the player by including a time-out per turn. If the player doesn't hit enter before 3 seconds are up, the game is stopped and a message is displayed.
Problem: How to interrupt the input()
after 3 seconds have passed.
Research so far:
Illustrative code snippet:
import signal
import sys
def ask_question():
input("3 + 4 = ?")
def print_answer():
print("7")
def timeout_handler(signum, frame):
print("sorry you ran out of time")
sys.exit()
MAX_TURN_TIME = 3
ask_question()
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(MAX_TURN_TIME)
print_answer()
signal.alarm(0)