Making a Class

To do this tutorial, you first should do the Space Game tutorial here.  Or, you can start with the completed Space Game tutorial.  Download that here.

In this tutorial, we’ll make the enemy ships fall at different speeds.  Right now, each enemy is a pygame.Rect object.  This object has a position (x and y) and a size (w and h).  We’d like it also to have a speed, but the pygame.Rect object doesn’t have a speed.  To solve this we’ll make a new type of object, called an Enemy.  An Enemy will have everything a pygame.Rect object has, and also a speed.  At the top of your program, add the new class.  You could also make a new file for the new class, and import it into your game.  For now though, just add this after the import statements in your python file.

The Enemy class

This code creates a new type.  The init function is special, and has two underscores before the word init, and two after.   Putting pygame.Rect in the parenthesis means that Enemy IS a pygame.Rect, but also can have more stuff, like speed.

To add these new Enemies instead of pygame.Rect objects replace the code that adds enemies with this:

Adding Enemy Objects

We can also add functions to the Enemy class.  For instance, to move the enemies we can make a fall() function inside the class.  Functions that are inside a class are also called methods.  Put this code inside the Enemy class.

The fall method.

Now, to move the enemies we can use this method.  Replace the code that made the enemies fall with this:

Making the enemies fall.

 

Now when you run the game, each enemy will fall at its own speed.  This is just a taste of what you can do by making your own classes in Python.

Challenge

Try using this reference to rotate your ship instead of moving it.   Then when you shoot bullets, have them go in the direction the ship is currently pointing.   To do this make a Bullet class (always capitalize class names) that keeps track of which way the bullet is moving and has a move() function to move the bullets.  You might need some math trig functions to do this.