Lab 7a: Sprites and pygame (part I)

In this lab we'll focus on a special pygame class to handle moving and interactive objects in our games: Sprites.

First, as always, move into your games directory, create a directory for this week's lab, and move into that. E.g.


   cd games
   mkdir lab7
   cd lab7
Next, copy across some files for this week's lab: backdrop.gif, ship.gif, star.gif.

Today we'll be creating our python files from scratch, e.g.
gedit lab7a.py &

Once the file has been created, you'll need to make it executable, e.g.
chmod u+x *.py


Pre-amble: clean program structure

Sprites for in-game objects

Part of our previous lab looked at reorganizing our game code to use Python classes to hold information about the various types of objects in our game.

There is also a special PyGame class called Sprites that have a variety of builtin properties and routines that we will look at today.

We will create a GameObject class, based on the PyGame Sprites class, that allows us to do some cleanly automated updating of objects.

Our game object class will have two routines (or methods) associated with it:

Updating our in-game objects

The class definition above defines how a "GameObject" works, but we still need to add code to our main routine to create the actual game objects we want to see, and to provide specific initial values for their speed, facing, position, etc.

We'll revise our main routine to:

Updating the display

We're getting closer, but the game display hasn't been told how/when to redraw the portions of the screen that need to change based on the movement of our game objects.

This involves two steps:

Complete version

Hopefully we can now see three ships moving towards the center of the screen. (A copy of the complete code is included below.)