Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

module.


You learned about events in Hour 18, “GUI Programming.” The PyGame library provides the
pygame.event module to monitor these events and event objects to handle them. The following is
an example of a typical game loop:


Click here to view code image


1: while True:
2: for event in pygame.event.get():
3: if event.type in (QUIT,KEYDOWN):
4: sys.exit()

The main loop is a while loop on line 1, and it will continue to run until the sys.exit()
operation exits the loop on line 4. (Note that to use this operation, you need to import the sys module
into your game scripts.) In order to reach sys.exit(), the main loop captures any events. If an
event occurs, Python handles it in the for loop on line 2 by assigning the event to the variable
event. Python checks the event’s type in line 3, using the .type method. If the event is either a quit
(QUIT) or a key being pressed on the keyboard (KEYDOWN), then sys.exit() runs, and the game
exits.


In simple terms, if you press a key on the keyboard while the game is running, the game quits
gracefully. Thus, to keep your game running, until a QUIT event occurs, you need to put all the screen
drawing and updating within a main game loop. Some of the PyGame event types you can check for
include the following:


QUIT
KEYDOWN
KEYUP
MOUSEMOTION
MOUSEBUTTONUP
MOUSEBUTTONDOWN
USEREVENT

Drawing Images and Shapes


Almost all games include some sort of graphic game pieces. These game pieces can be either
imported images or shapes you design yourself.


Creating shapes is easy, thanks to the PyGame module pygame.draw. You can use this module to
draw circles, squares, hearts, and so on. Table 19.4 shows a few of the methods available in the
pygame.draw module.

Free download pdf