Pong Tutorial using Pygame – Controlling the Paddles

pong-gameThis tutorial is the third 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 two-player game of Pong. In the first tutorial we looked at how to create the background for our game. In the second tutorial we added our first sprites called paddleA and paddleB which are instances of the Paddle class.

In this third tutorial we will add methods to our Paddle class to move the paddles up and down when player A uses the W (up) and S (down) keys and player B uses the up and down 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 paddle.py 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 moveUp() method.

The moveUp() 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 players press the W or S keys (Paddle A) or the up and down arrow keys (paddle B). 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 56.

All done… Save your files and try your code. You should now be able to control each paddle using the W, S, Up arrow and Down arrow keys!

Next Step?

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