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)
Community
  • 1
  • 1
rpassza
  • 226
  • 1
  • 2
  • 8
  • Are you on linux or windows? have you looked at: http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python – Astrom Apr 18 '17 at 16:29
  • and here http://stackoverflow.com/questions/492519/timeout-on-a-function-call – Astrom Apr 18 '17 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. – ForceBru Apr 18 '17 at 17:24

0 Answers0