1

I am trying to make a simple python game to train my skills,it's something like a dungeon with traps and things like that here's a part of the game code:

from sys import exit

def trap():
    print "You've fallen into a trap,you have 10 seconds to type the word \"Get me out\""

    user_input = raw_input("> ")

    right_choice = "Get me out"

    if *SOME CODE*:
        *MORE CODE*
    else:
        die("you died,you were too slow")

def die(why):
    print why , "Try again"
    exit(0)

as u can see i want to end the python script after 10 seconds if the user_input wasn't equal to right_choice by replacing SOME CODE,MORE CODE in the code example above,how to do that?

Cœur
  • 32,421
  • 21
  • 173
  • 232
KendoClaw
  • 37
  • 2
  • `raw_input` is going to cause the system to wait until you enter something before it executes any more code. You can check the time after they enter something and see if its greater than 10 seconds and tell them they died, but that means the input will show forever until they enter something. If you're not OK with that, then you'll have to kick off some parallel process that can kill your input thread. – Hoopdady Mar 15 '17 at 20:52
  • Possible duplicate of [Keyboard input with timeout in Python](http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) – Charlie G Mar 15 '17 at 20:52
  • http://stackoverflow.com/questions/14029548/input-with-time-limit-countdown – roganjosh Mar 15 '17 at 20:52
  • 1
    http://stackoverflow.com/a/14920854/4180176 - create a thread timer then check to the timer after input has been made – Joshua Nixon Mar 15 '17 at 20:53

2 Answers2

0

What your looking to accomplish can be done with signals: https://stackoverflow.com/a/2282656/2896976

Unfortunately there isn't really a friendly way to handle this. Normally for a game you would call this every frame, but a call like raw_input is what's known as blocking. That is, the program can't do anything until it finishes (but if the user never says anything it won't finish).

Community
  • 1
  • 1
Jesse
  • 1,745
  • 12
  • 27
  • http://stackoverflow.com/a/3911477/7136668 actually this one looks good for me but the thing is iam new to python so i couldn't find a way to merge this with my trap() function. – KendoClaw Mar 15 '17 at 21:31
0

Try this. It uses signal to send a signal back within 10 seconds from the print statement. If you want it to be after the first input, move the signal calls.

import signal
from sys import exit

def trap():
    print "You've fallen into a trap,you have 10 seconds to type the word \"Get me out\""
    signal.signal(signal.SIGALRM, die)
    signal.alarm(10)

    user_input = raw_input("> ")
    right_choice = "Get me out"

    if *SOME CODE*:
        *MORE CODE*
        signal.alarm(0)

def die(signum, frame):
    print "Try again"
    signal.alarm(0)
    exit(0)
cmeadows
  • 170
  • 2
  • 12