[Tutor] How to only give the user so much time to enter response?

Kent Johnson kent37 at tds.net
Sun Mar 15 14:28:39 CET 2009


On Sun, Mar 15, 2009 at 4:22 AM, james carnell <jimcarnell at yahoo.com> wrote:
> Trying to use Timer in console based game that gives the user so much time
> to act. If they do not act then it just passes the turn back to the program
> to do the next thing. I have Python 2.5 and Windows XP.

> so... this kind is where I am:
>
> t=Timer(10.0)
>
> def waitFunction(timerObj):
>    newMove = 5 #5 = player will stay in same position on 2d array
>    newMove = int(raw_input("Move 1-9 / 0 to
>  quit:"))
>    timerObj.start()
>    while timerObj.isAlive():
>       pass
>    print newMove
>
> It works, but I am guessing it isn't a very good way to do it.

I am surprised that this works. The raw_input() call should block
until the user enters a move.

One way to do this would be to poll for user input using kbhit(). If a
key is not hit in your required interval, exit the loop and continue
processing. You don't need a threaded timer for this, just use
time.time() to measure duration.

On Windows use msvcrt.kbhit() and msvcrt.getch(). On Linux (or Mac?)
use this recipe:
http://code.activestate.com/recipes/572182/

Kent


More information about the Tutor mailing list