[Tutor] Timed While Loops and Threads

bhaaluu bhaaluu at gmail.com
Sun Dec 9 16:30:04 CET 2007


On Dec 8, 2007 11:11 PM, Michael H. Goldwasser <goldwamh at slu.edu> wrote:
>
> Hi everyone,
>
> I'm having some fun combining two recent topics: the "Timed While
> Loops" game and that of communication between threads.  Here is an
> example that allows a person to gather points in a while loop, but
> only for a fixed period of time.  It relies on a few shared variables
> to coordinate the activity of the main thread and the secondary
> thread.
>
>
> import threading
>
> def playGame():
>     global score, inPlay     # shared with main thread
>     while inPlay:
>         raw_input('Press return to score a point! ')
>         if inPlay:
>             score += 1
>             print 'Score =', score
>
> score = 0
> inPlay = True
> numSeconds = 5       # I didn't have patience for the 30 second version
> T = threading.Thread(target=playGame)
> T.start()
> T.join(numSeconds)
> inPlay = False       # signal to secondary thread that game is over
> print
> print 'After', numSeconds, 'seconds, you scored', score, 'points.'
>

WOW! That is awesome! 8^D

Here's my best score:
After 5 seconds, you scored 106 points.
Heheheh.

It shouldn't take much to convert that into any kind of timed gaming event.
It is easy to read and understand.
It is elegant!
Thank you!

Although I'm not the OP, I'm interested in all things related to gaming in
Python. This code is trully excellent! 8^D

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m

>
>
>
>
>        +-----------------------------------------------
>        | Michael Goldwasser
>        | Associate Professor
>        | Dept. Mathematics and Computer Science
>        | Saint Louis University
>        | 220 North Grand Blvd.
>        | St. Louis, MO 63103-2007
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list