Game” section of this hour, you learned how to use events and event types to exit a game. You can
also use events to control the interaction in your game.
One popular method is to use the mouse and a collide point (a particular event occurring on top of a
Surface object). First, you need to set up the mouse in your game script. Several event types
concern the mouse. An easy one is MOUSEBUTTONDOWN, which simply indicates that one of the
buttons on the mouse has been pressed. To trap this event, you use the following Python statements:
Click here to view code image
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
If event.type matches pygame.MOUSEBUTTONDOWN, then you can test for a collide point. The
.collidepoint method helps here. You simply pass the method the position of the other object to
test for a collision. If it returns True, then the additional actions can be taken.
The following example tests the current image’s location on the game screen and determines whether
the mouse pointer has collided with the game image. In other words, it tests whether the mouse
pointer clicked the image:
Click here to view code image
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if GameImageLocation.collidepoint(pygame.mouse.get_pos()):
sys.exit()
If the mouse clicked the image, then the game is exited. Of course, you can set up any kind of desired
action for a collide point. It doesn’t have to be “exit the game.”
Reading about all this is one thing, but trying it is another. This is especially true when it comes to
understanding moving images on your game screen. In the following Try It Yourself section, you’ll
play a little bit with moving an image around the screen and trying out different “speeds.”
Try It Yourself: Create Game Images and Move Them About the Screen
In the following steps, you are going to load an image, move the image about the screen
at different speeds, learn how to keep an image on the screen, create a collide point for
action, and resize an image. Fasten your safety belt and please keep your hands and
legs inside the cart for the duration of this ride:
- If you have not already done so, power up your Raspberry Pi and log in to the
system. - If you do not have the LXDE GUI started automatically at boot, start it now by typing
startx and pressing Enter. - Open a script editor, such as nano or the IDLE 3 text editor, and create the script
py3prog/script1902.py. - Type all the information for script1902.py shown below. Take your time and
avoid any typographical errors:
Click here to view code image
#script1902.py - Move Game Image
#Written by