Page 81 - Programming the Raspberry Pi Getting Started with Python
P. 81
8
Games Programming
Clearly a single chapter is not going to make you an expert in game programming. A number of good
books are devoted specifically to game programming in Python, such as Beginning Game Development
with Python and Pygame, by Will McGugan. This chapter introduces you to a very handy library
called pygame and gets you started using it to build a simple game.
What Is Pygame?
Pygame is a library that makes it easier to write games for the Raspberry Pi—or more generally for
any computer running Python. The reason why a library is useful is that most games have certain
elements in common, and you’ll encounter some of the same difficulties when writing them. A library
such as pygame takes away some of this pain because someone really good at Python and game
programming has created a nice little package to make it easier for us to write games. In particular,
pygame helps us in the following ways:
• We can draw graphics that don’t flicker.
• We can control the animation so that it runs at the same speed regardless of whether we run it on a
Raspberry Pi or a top-of-the-range gaming PC.
• We can catch keyboard and mouse events to control the game play.
The Raspbian Wheezy distribution comes with two versions of Python: Python 2 and Python 3. That
is why two shortcuts to IDLE appear on the desktop. So far in this book, we have been using IDLE 3
and thus Python 3. In Raspbian Wheezy, the Python 3 installation does not include pygame, whereas
the Python 2 installation has it preinstalled.
Rather than install pygame into Python 3 (which is a bit involved), we will use Python 2 in this
chapter. Don’t worry, all the code that we write should still work on Python 3 should you prefer (or
find that in a later distribution pygame is there waiting for you). You just have to remember to start
IDLE instead of IDLE 3.
Hello Pygame
You may also have a shortcut on your desktop called Python Games. This shortcut runs a launcher
program that allows you to run some Python games. However, if you use the File Explorer, you will
also find a directory in your root directory called python_games. If you look in here, you will see the
.py files for the games, and you can open these files in IDLE to have a look at how others have written
their games.
Figure 8-1 shows what a Hello World–type application looks like in pygame, and here is the code
listing for it: