If true, 1 second has elapsed, so I increment the seconds counter and print the number of seconds.Įach round of the event loop also checks to see whether the s key has been pressed. Line 14 checks whether the event is my timer event (I provided pygame.USEREVENT when I set the timer). Line 7 in Listing 3 sets a timer for every 1,000 milliseconds, or once a second. When the amount of time passes, the event ID provided will appear on the event queue. To set up a timer, call _timer(), which takes two arguments, the event ID and the amount of time in milliseconds for the event to recur. If it's a pygame.QUIT event, then call sys.exit.Ġ5 screen = _mode ( ( 320, 240 ) )Ġ7 _timer ( pygame.USEREVENT, 1000 )ġ6 print " seconds have elapsed since you started this program".format ( seconds )ġ8 if event.key = ord ( "s" ): _timer ( pygame.USEREVENT, 0 ) In line 9, I compare the event type to a constant provided by the Pygame module. Each returned event has a type that tells me what generated this event. In line 8, () returns a list of all pending events. The only thing it does is watch for the Pygame window to be closed and exit the program. Listing 1 shows a basic event loop that's about as simple as you can get.
You can also create your own events based on time, game logic, or anything else in your program. Its job is to watch all the different inputs (keyboard, mouse, joysticks, etc.) and process them as they occur. That's where the Pygame event loop comes in. Once you start your program, initialize variables, and draw your opening graphics, you probably need to respond to user input to make things happen.
The main module for dealing with user input is the pygame.event module. In this article, I'll follow up with the Pygame event, input, and sound modules, which you can use to create games, puzzles, or other interactive programs. In Raspberry Pi Geek issue 03, I introduced you to the graphics functions of the Pygame library.