Write a Raspberry Pi game in Python

If you’re the proud owner of a Raspberry Pi, the visual Scratch language is a great way to start creating your first game. But to unlock more of the power and potential of the hardware, take a look at Python.

If you’d prefer more of a low-tech project, why not check out our guide on how to turn a Raspberry Pi into an XBMC media center?

Python is the default educational programming language for the Raspberry Pi. It’s used around the world as an introductory language for many platforms, thanks to its uncluttered style and easy-to-understand syntax. It isn’t only for beginners, though: according to the TIOBE Programming Community index, Python is the eighth most popular programming language among professional engineers, ahead of Perl, JavaScript and Visual Basic .NET. It’s also free, so it’s easy to see why so many people choose Python as their first scripting language.

In this feature we’ll introduce the key concepts of Python, and show you how to get started with the language by walking you through a sample game written in Python. Then it’s over to you to create your own masterpiece.

Getting to know Python

There are two major versions of Python in use. Python 3 is the future, but Python 2 enjoys wider compatibility with existing resources, and it’s this version that’s currently bundled with Raspberry Pi. For this tutorial, we’ll use Python 2.7, the final stable release in the 2.x series: this means we can use the majority of online examples and pre-written code unchanged. When the time comes, moving up to version 3 will be straightforward.

When you look at Python code, the first thing you may notice is how neat it looks. Those used to PHP, JavaScript or other modern languages will also spot the absence of curly braces, as conventionally used to enclose sections of code. This is because Python uses indentation to organise code. This is good practice in most languages, because it makes code more readable: in Python it’s mandatory. If you don’t get your spacing right, your code won’t work. While this can be a shift for experienced programmers, it becomes natural quickly and leads to clear, intelligible code by default.

Python also makes a good first language because it represents a simple implementation of object-oriented programming – a concept any aspiring coder must understand – and is relaxed about how variables are created and managed. The net result is a particularly productive programming environment.

Python code is usually run through an interpreter rather than being compiled, but despite this, end results are pretty fast. Python applications can run on all major operating systems, so it’s possible to create a Python game on a Windows PC and have it run on a Mac or Linux box – or, indeed, a Raspberry Pi.

The Pygame module includes all sorts of helpful functions and methods for creating action games in Python

A final great strength of Python is the availability of a wide range of add-on modules that bring extra functionality. One such module is Pygame. As its name suggests, Pygame helps you create games using Python: for example, it greatly improves image handling through its Sprite class, makes it easy to control in-game audio, and even allows your game to work with joysticks. Games such as Call of Duty might be beyond its capabilities, but an Angry Birds clone certainly isn’t.

Native and cross-platform development

If you’re running the recommended Debian Squeeze Linux distribution on your Raspberry Pi, Python and Pygame come preinstalled, so you can start programming right away. You can write Python scripts in a text editor, but we suggest you take advantage of the free Geany integrated development environment (IDE) that’s also installed as part of the operating system. This software offers numerous helpful features for programmers, such as automatic syntax colouring, to make your code simpler to read and debug, and a symbol browser to help keep track of all the classes and variables in your code.

As we’ve mentioned, however, Python works across many platforms, so if you prefer you can write your code on a Windows PC and then move it across to the Raspberry Pi when you’re finished. To do this, you’ll need to install Python 2.7 on your PC: you can get the installer from the official Python website. Even if you’re running 64-bit Windows, choose the regular Windows installer, not the x86-64 one, since the standard Pygame installation is 32-bit only.

The Geany development environment is ideal for coding in Python

Once you’ve installed Python (accepting the installation defaults), the next thing to do is install Pygame for Windows, again with default settings. If you already have a preferred IDE, it will almost certainly support Python “out of the box”; if not, you can download Geany for Windows for free. To configure it for testing and running Python scripts, launch Geany, then go to the Build menu and click Set Build Commands. Find the Execute field and replace the current contents with C:Python27python %f (assuming you installed Python to the default directory).

Designing a game

Our first Python project will be a simple shooting game called Raspberry Pie (ahem). In this game, three different types of fruit will fall from the top of the game area, but only the raspberries should reach the bottom and go into the pie. The player controls a movable turret, and wins points by shooting cherries and strawberries: points are deducted if a raspberry is destroyed accidentally, or if one of the other fruits ends up in the pie.

Let’s start by collecting together the assets. The Open Clip Art Library is a great place to find free clip-art; we can get our fruit images from here. We’ll create our own images for the turret and the bullets. We could collect together sounds for our game, too, but for now we’ll keep things simple and silent.

Now let’s think about how we’re going to structure our program. The basic structure of an arcade game is the same whether you’re planning to use Scratch, Python or any other tool. We begin by setting up the execution loop environment, and create the objects that will be used in the game. We then initialise everything – for example, setting the score to zero. Then there’s a main loop that handles the gameplay. Once the game ends, the score is displayed.

Objects

Object-oriented programming (OOP) underpins most modern programming languages, and it isn’t too difficult to understand. Think about the visible objects in our game: the only aspects that vary from one tumbling fruit to another are their position and genus (that is, whether they’re raspberries, strawberries or cherries). We can therefore represent them all very simply by creating a single fruit class with properties that indicate genus and position. We can then create fruits as independent instances of the class (these instances are the “objects” of OOP), each of which contains information about what sort of fruit it is and its location.

As well as properties, classes can have methods – built-in actions that we can invoke whenever we want. In the case of fruit, the major thing each object does is fall. So we might build a method into our class that says “take my current vertical position and move it down by 3 pixels”.

Since all the code relating to the fruit sits within the fruit class, bugs are easy to find and, once fixed, apply to all instances across the entire program. You can even base one class on another, giving you a hierarchy of subclasses. For now, however, let’s stick to a simple implementation. Remember that, while classes are written as part of the code, objects are created only when the program runs, and don’t exist beyond the duration of the game.

The program code

Click here for the program code for Raspberry Pie, along with a running commentary on how we wrote it (PDF). The commentary will walk you through the various sections of the program: if anything seems unclear, your first stop should be the official Python documentation. The program also draws heavily on the methods and properties provided by Pygame.

You can also download a copy of the code as a ready-to-run Python project – simply unzip the files to a convenient location – so you can play the game yourself right away, and use it as a starting point to learn more by modifying and updating it yourself. Can you add a high-score table? Or make different types of fruit move in different ways? Once you’ve mastered the basics of writing games in Python, you can create your own original game.

Disclaimer: Some pages on this site may include an affiliate link. This does not effect our editorial in any way.