Notice: Undefined index: order_next_posts in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 194

Notice: Undefined index: post_link_target in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 195

Notice: Undefined index: posts_featured_size in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 196

Create Space Invaders on Raspberry Pi part one

Write your own RasPi shooter in 300 lines of Python

When you’re learning to program in a new language or trying to master a new module, experimenting with a familiar and relatively simply project is a very useful exercise to help expand your understanding of the tools you’re using. Our Space Invaders clone is one such example that lends itself perfectly to Python and the Pygame module – it’s a simple game with almost universally understood rules and logic. While the Invaders meander their way down the screen towards you, it’s your job to pick them off while dodging their random fire. When one wave is conquered, another faster, more aggressive wave appears. We’ve tried to use many features of Pygame, which is designed to make the creation of games and interactive applications easier. We’ve extensively used the Sprite class, which saves dozens of lines of extra code in making collision detection simple and updating the screen and its many actors a single-line command.

We hope you agree that this is an exciting game to play and a great tool to learn more about Python and Pygame, but our sensory system is far from overloaded here. Stay tuned, then, because next month we’ll be adding animation and sound effects to our game to give it the spit and polish any self-respecting Space Invaders- inspired shooter demands…

Pivaders as we like to call it
Pivaders as we like to call it

What you’ll need



Step 01 Setting up dependencies

If you’re looking to get a better understanding of programming games with Python and Pygame, we strongly recommend you copy the Pivaders code in this tutorial into your own program. It’s great practice and gives you a chance to tweak elements of the game to suit you, be it a different ship image, changing the difficulty or the ways the alien waves behave. If you just want to play the game, that’s easily achieved too, though. Either way, the game’s only dependency is Pygame, which (if it isn’t already) can be installed from the terminal by typing:

$ sudo apt-get install python-pygame

Step 02 Downloading the project

For Pivaders we’ve used Git, a brilliant form of version control used to safely store the game files and retain historical versions of your code. Git should already be installed on your Pi; if not, you can acquire it by typing:

$ sudo apt-get install git

As well as acting as caretaker for your code, Git enables you to clone copies of other people’s projects so you can work on them, or just use them. To clone Pivaders, go to your home folder in the terminal (cd ~), make a directory for the project (mkdir pivaders), enter the directory (cd pivaders) and type:

git pull

Step 03 Testing Pivaders

With Pygame installed and the project cloned to your machine (you can also find the .zip on this issue’s cover DVD – simply unpack it and copy it to your home directory to use it), you can take it for a quick test drive to make sure everything’s set up properly. All you need to do is type python from within the pivaders directory in the terminal to get started. You can start the game with the space bar, shoot with the same button and simply use the left and right arrows on your keyboard to move your ship left and right.

Step 04 Creating your own clone

Once you’ve racked up a good high score (anything over 2,000 points is respectable) and got to know our simple implementation, you’ll get more from following along with and exploring the code and our brief explanations of what’s going on. For those who want to make their own project, create a new project folder and use either IDLE or Leafpad (or perhaps install Geany) to create and save a .py file of your own.

Step 05 Global variables & tuples

Once we’ve imported the modules we need for the project, there’s quite a long list of variables in block capitals. The capitals denote that these variables are constants (or global variables). These are important numbers that never change – they represent things referred to regularly in the code, like colours, block sizes and resolution. You’ll also notice that colours and sizes hold multiple numbers in braces – these are tuples. You could use square brackets (to make them lists), but we use tuples here since they’re immutable, which means you can’t reassign individual items within them. Perfect for constants, which aren’t designed to change anyway.

Step 06 Classes – part 1

A class is essentially a blueprint for an object you’d like to make. In the case of our player, it contains all the required info, from which you can make multiple copies (we create a player instance in the make_player() method halfway through the project). The great thing about the classes in Pivaders is that they inherit lots of capabilities and shortcuts from Pygame’s Sprite class, as denoted by the pygame.sprite.Sprite found within the braces of the first line of the class. You can read the docs to learn more about the Sprite class via

Step 07 Classes – part 2

In Pivader’s classes, besides creating the required attributes – these are simply variables in classes – for the object (be it a player, an alien, some ammo or a block), you’ll also notice all the classes have an update() method apart from the Block class (a method is a function within a class). The update() method is called in every loop through the main game (we’ve called ours main_loop()) and simply asks the iteration of the class we’ve created to move. In the case of a bullet from the Ammo class, we’re asking it to move down the screen. If it goes off either the top or bottom of the screen, we destroy it (since we don’t need it any more).

Step 08 Ammo

What’s most interesting about classes, though, is that you can use one class to create lots of different things. You could, for example, have a pet class. From that class you could create a cat (that meows) and a dog (that barks). They’re different in many ways, but they’re both furry and have four legs, so can be created from the same parent class. We’ve done exactly that with our Ammo class, using it to create both the player bullets and the alien missiles. They’re different colours and they shoot in opposite directions, but they’re fundamentally one and the same. This saves us creating extra unnecessary code and ensures consistent behaviour between objects we create.

Step 09 The game

Our final class is called Game. This is where all the main functionality of the game itself comes in, but remember, so far this is still just a list of ingredients – nothing can actually happen until a ‘Game’ object is created (right at the bottom of the code). The Game class is where the central mass of the game resides, so we initialise Pygame, set the imagery for our protagonist and extraterrestrial antagonist and create some GameState attributes that we use to control key aspects of external classes, like changing the player’s vector (direction) and deciding if we need to return to the start screen, among other things.

Step 10 The main loop

There are a lot of methods (class functions) in the Game class, and each is designed to control a particular aspect of either setting up the game or the gameplay itself. The actual logic that dictates what happens within any one round of the game is actually contained in the main_loop() method right at the bottom of the script and is the key to unlocking exactly what variables and functions you need for your game. Starting at the top of main_loop() and working line-by-line down to its last line, you can see exactly what’s being evaluated 20 times every second when you’re playing the game.

Step 11 Main loop key logic – part 1

Firstly the game checks that the end_game attribute is false – if it’s true, the entire loop in main_loop() is skipped and we go straight to pygame.quit(), exiting the game. This flag is set to true only if the player closes the game window or presses the Esc key when on the start_screen. Assuming end_game and start_screen are false, the main loop can start proper, with the control() method, which checks to see if the location of the player needs to change. Next we attempt to make an enemy missile and we use the random module to limit the number of missiles that can be created. Next we call the update() method for each and every actor on the screen using a simple for loop. This makes sure everyone’s up to date and moved before we check collisions in calc_collisions().

Step 12 Main loop key logic – part 2

Once collisions have been calculated, we need to see if the game is still meant to continue. We do so with is_dead() and defenses_breached() – if either of these methods returns true, we know we need to return to the start screen. On the other hand, we also need to check to see if we’ve killed all the aliens, from within win_round(). Assuming we’re not dead, but the aliens are, we know we can call the next_round() method, which creates a fresh batch of aliens and increases their speed around the screen. Finally, we refresh the screen so everything that’s been moved, shot or killed can be updated or removed from the screen. Remember, the main loop happens 20 times a second – so the fact we don’t call for the screen to update right at the end of the loop is of no consequence.

The full code listing can be downloaded from our tutorials page

This tutorial originally appeared in Linux User & Developer 136, which you can easily get digitally at