[Tutor] Using time module to count off seconds before an event

Michael Janssen Janssen@rz.uni-frankfurt.de
Thu Jun 19 12:33:24 2003


On Thu, 19 Jun 2003, Magnus Lyck=E5 wrote:

> At 20:18 2003-06-18 +0100, valhalla wrote:
> >I am wanting to modify a guessing game script I have so that the player =
is
> >given x number of seconds (e.g. 60 seconds) during which to guess the an=
swer
> >before time's up and game is over.
>
> You might want to look at the threading module and Timer
> objects. See
> http://starship.python.net/crew/aahz/OSCON2001/index.html
>
> This isn't trivial though...
>
> If some piece of your code is waiting at a "answer =3D raw_input()",
> I don't think there is any way in Python to interrupt that.

I havn't thought of this problem ... Solution could be in the signal
module (Unix):

import sys, signal, time

def alarm_handler(signum, frame):
    pass

def cd():
 for n in range(60, 0, -1):
    print "sec remaining: %2i  - type in your guess: " % (n),
    k =3D signal.signal(signal.SIGALRM, alarm_handler)
    k =3D signal.alarm(1)
    # readline can't be interrupted cleanly by alarm (raw_input can't be
    # interupted at all).
    try:
        answer =3D sys.stdin.readline()
        print "Your answere was -%s-" % (answer),
        break
    except IOError:
        pass
    print "\033[A"


---> both countdown and readline ;-) You must be confident and type in
your answere while the countdown string will overwrite it ([enter] at
the end is importent)

Perhaps the curses modules helps to do both printing and reading in one
term without puzzling the user (OTOH curses isn't much easier against GUI
Programming).


Michael

>
> Obviously, it's easy to see after the answer was given if it
> was supplied within 60 seconds or not...
>
> If you use a GUI you have different possibilities to for
> instance disable a text box or close a window when a certain
> amount of time has passed.
>
>
> --
> Magnus Lycka (It's really Lyckå), magnus@thinkware.se
> Thinkware AB, Sweden, www.thinkware.se
> I code Python ~ The Agile Programming Language
>
>
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>