Breakout Tutorial using Pygame: Controlling the Paddle

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

For this third tutorial we will complete the code from the previous tutorial:

Remember the aim is to create a game of Breakout. In the first tutorial we looked at how to create the background for our game. In the second tutorial we added our first sprite called paddle which is an instance of the Paddle class.

In this third tutorial we will add methods to our Paddle class to move the paddle left and right when player uses the left and right arrow keys.

We will then add event handlers to the main program loop to respond to keystroke events. When the players use the relevant keys on the keyboard we will call our methods to move their paddle on the screen.

Step 1: Adding Methods to the Paddle class.

Open the file and add the lines 23 to 33 as follows:

As you can see we have added two methods to our class. In OOP (Object Orientated Programming) a method is a procedure or function associated to a class. Let’s look at the moveLeft() method.

The moveLeft() method takes two arguments. The first one is implicit and is called self. It refers to the current object. The second one is called pixels and refers to the number of pixels we will use to move the paddle.

Step 2: Responding to keystroke events

arrowKeysLet’s look at the code for our main program. You may remember that in the first tutorial we talked about the main program loop. The first section of this loop is to respond to events such as user interactions when the user uses the mouse or the keyboard.

So let’s add four event handlers, to move the paddle up or down when the user presses the the left and right arrow keys. Each event handler will call the relevant method from the Paddle class. Check the code below with the new event handlers from line 47 to 52.

All done… Save your files and try your code. You should now be able to control the paddle using the left arrow and right arrow keys!

Next Step?

It’s now time to add a bouncing ball to our game:
Breakout Tutorial using Pygame:Adding a Bouncing Ball
Tagged with: