How do I disable user input for turn based play?

I am trying to create a basic math game on the command line in Python 3. The game shows the user a basic add problem, the system waits for the user to hit enter, then displays the answer and then the next problem.

I want to put pressure on the player by including a timeout per turn. If the player hasn't pressed the enter button within 3 seconds, the game is stopped and a message is displayed.

Problem: How to interrupt input()

after 3 seconds.

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)

      

+3


source to share





All Articles