Pygame modules for interactive programs
In Raspberry Pi Geek issue 03 [1], I introduced you to the graphics functions of the Pygame library [2]. 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.
Pygame Events
The main module for dealing with user input is the pygame.event
module. Once you start your program, initialize variables, and draw your opening graphics, you probably need to respond to user input to make things happen. That's where the Pygame event loop comes in. Its job is to watch all the different inputs (keyboard, mouse, joysticks, etc.) and process them as they occur. You can also create your own events based on time, game logic, or anything else in your program. More on that a little later.
Listing 1 shows a basic event loop that's about as simple as you can get. The only thing it does is watch for the Pygame window to be closed and exit the program. In line 8, pygame.event.get()
returns a list of all pending events. Each returned event
has a type
that tells me what generated this event. In line 9, I compare the event type to a constant provided by the Pygame module. If it's a pygame.QUIT
event, then call sys.exit
.
[...]
Buy this article as PDF
Pages: 2
(incl. VAT)