3

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)
3
  • Are you on linux or windows? have you looked at: stackoverflow.com/questions/1335507/… Commented Apr 18, 2017 at 16:29
  • and here stackoverflow.com/questions/492519/timeout-on-a-function-call Commented Apr 18, 2017 at 16:31
  • This is very platform-specific, I think. I've seen many such questions upvoted and answered seemingly well, but none of the answers actually worked, because it seems like input doesn't care much about any signals or attempts to terminate the thread: it still sits and blocks until a newline is received. Commented Apr 18, 2017 at 17:24

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.