Page 84 - Programming the Raspberry Pi Getting Started with Python
P. 84
The basic structure of our Hello World program is still there, but you have some new things to
examine. First of all, there are some more imports. The import for pygame.locals provides us access
to useful constants such as QUIT, which we will use to detect when the game is about to exit. The
import of exit from sys allows us to quit the program gracefully.
We have added two variables (spoon_x and spoon_y) to hold the position of the spoon. Because the
spoon is only going to move left to right, spoon_y will never change.
At the end of the program is a while loop. Each time around the loop, we first check for a QUIT
event coming from the pygame system. Events occur every time the player moves the mouse or
presses or releases a key. In this case, we are only interested in a QUIT event, which is caused by
someone clicking the window close icon in the top-right corner of the game window. We could chose
not to exit immediately here, but rather prompt the player to see whether they indeed want to exit. The
next line clears the screen by filling it with the color white.
Next comes an assignment in which we set spoon_x to the value of the x position of the mouse.
Note that although this is a double assignment, we do not care about the y position of the mouse, so we
ignore the second return value by assigning it to a variable called ignore that we then ignore. We then
draw the spoon on the screen and update the display.
Run the program. You should see the spoon following the mouse.
One Raspberry
The next step in building the game is to add a raspberry. Later on we will expand this so that there are
three raspberries falling at a time, but starting with one is easier. The code listing for this can be found
in the file 08_03_rasp_game_one.py.
Here are the changes from the previous version:
• Add global variables for the position of the raspberry (raspberry_x and raspberry_y).
• Load and convert the image raspberry.jpg.
• Separate updating the spoon into its own function.
• Add a new function called update_raspberry.
• Update the main loop to use the new functions.