Breakout Tutorial using Pygame: Adding the Paddle

break-out-gameThis tutorial is the second tutorial in a series of five Pygame tutorials:

Learning Objectives


In this second tutorial on how to create the retro arcade game Breakout using PyGame, we are looking at creating our first sprite.
definition-sprite

Consider a sprite as an object. An object can have different properties (e.g. width, height, colour, etc.) and methods (e.g. jump(), hide(), moveForward(), etc.). Like in the industry an object is built from a mould. In computing the mould/template is called a Class.

So, by creating our first sprite we will implement OOP (Object Orientated Programming). We will create our first Class called Paddle and derive our first object from this class.

Our first Class


So let’s look at the code for our Paddle Class:
To start with the first method we will need in our class is the __init__() method. It’s called a constructor. It is used when the object is first created to initalise the main properties of the object (e.g. its x and y position, dimensions, colour, etc.)

Later on we will add more properties and methods to this class. But before doing so we will look at how we can use it to create our first object: the pladdle.

So let’s save our class as a python file called paddle.py.

Our first Object


Now that we have a Class we can create/instantiate an object from this Class. (Remember a Class is like a mould. It enables you to create as many objects as you need using the same mould.)

Let’s go back to our main.py file (from previous tutorial) to edit its content.

First let’s add at the top of the code an import statement to import our Paddle class.

Then we need to create and position our paddle in our main program using the following lines of code:

Let’s reuse the code from the first tutorial.

On lines 3/4 notice how we are using the import command to link to our Paddle Class python file (paddle.py).

On line 25 we are declaring a list called all_sprites_list that will store all the sprites we will create in our game. (For now just one sprite, the paddle)

On lines 27 to 30, we are instantiating an paddle object using the Paddle class. Notice how when declaring our first object we use the parameters from its constructor (__init__()), in this case, the colour, width and height of the paddle we want to create.

Now that we have created our first sprite we need to add it to our list of spites: all_sprites_list. This is what happens on line 33.

Finally, within the main program loop, on line 64 we are refreshing the screen and drawing all the sprites from our list: all_sprites_list.

Here is the full code:

That’s it… You are now ready to move to our third tutorial to learn how to control your sprites using the arrow keys.
Breakout Tutorial using PygameControlling the paddle

Share Button
Tagged with: