My First Game – Part 5: Pong – Paddle Movement

In order to move the Paddle, we need to do the following things:

  1. Make the paddle into a class variable so that it can be accessed in other functions.
  2. Check for player UP and DOWN key inputs and move the paddle.
  3. Prevent the paddle from moving outside the screen.

Now we will need to modify our code a little:

Step 1 is shown in lines 15-16 and 25-26 — The paddle  variable is now a class variable, so that the update()  function can later access it.

Step 2 is shown in lines 45-54 — Notice that to move the paddle up, we subtract the y-position, and vice versa. Remember, the origin of the screen begins from the top-left of the screen.

ss3

The same top-left origin applies for all objects (in this case, the paddle), unless you offset its origin — but for now we don’t need to worry about it.

Let’s now write some code to make sure the paddle doesn’t go out of the screen:

In lines 57-60, we make sure the paddle’s y-position does not exceed the screen’s top.

In lines 62-65, the code is a little longer. Remember that the y-position of the paddle is on its top-left, so to make sure that the paddle’s bottom doesn’t go out of the screen’s bottom, we need to add the paddle’s height into the equation.

ss4

Now go ahead and test your game again, back at the command prompt/terminal:

And if everything was done right so far, you’ll be able to move your paddle with the UP and DOWN keys, and they won’t move out of the screen.

In the next post, we shall run through some code to create the second paddle.

One thought on “My First Game – Part 5: Pong – Paddle Movement

Leave a Reply

Your email address will not be published. Required fields are marked *