Pong Tutorial using Pygame – Adding a Bouncing Ball

pong-gameThis tutorial is the third tutorial in a series of five Pygame tutorials:

Our aim is to add the bouncing ball to our Pong game. To do so we will create a new class called Ball.

Bouncing Algorithm


To understand how to implement a bouncing algorithm, it is essential to understand how the computer controls the trajectory of a sprite (e.g. ball) on the screen. Arcade games are based on a frame based animation where the screen is refreshed every x milliseconds. Moving sprites are positionned using (x,y) coordinates and have a velocity vector (Vx,Vy) which specifies the delta in pixels to apply to the (x,y) coordinates of a sprite between two frames:

  • frame n: Sprite Coordinates: (x,y)
  • frame n+1: Sprite Coordinates: (x+Vx,y+Vy)

velocity-vector

As the sprite moves across the screen, it may need to bounce against another sprite or against the edge of the screen.

Let’s investigate how the velocity vector is affected when the sprite bounces against vertical and horizontal walls/edges.

Right Wall/EdgeLeft Wall/EdgeTop Wall/EdgeBottom Wall/Edge
bouncing-algorithm-right
bouncing-algorithm-left
bouncing-algorithm-top
bouncing-algorithm-bottom

Ball Class


Below is the code for the Ball class. You will need to copy this code in a new Python file called ball.py. The update() method of this class will be called for each frame of the main program loop. It moves (changes the (x,y) coordinates of) the ball using its velocity vector.

Adding the ball to the game


In the main.py file, we will first import the Ball class. (See line 4) We will then create an object called ball using the Ball class. (See lines 25 to 27) We will add this object to the all_sprites_list group of sprites. (See line 35)

We will also apply the bouncing algorithm to check if it needs to bounce against any of the four walls. (See lines 67 to 75)

Collision Detection


The next addition to our game is to detect when the ball hits/collides with one the two paddles. If it does, we will make it bounce using a random new direction.

So first, let’s add a new method called bounce() to our Ball class.

Then, in the main program loop, let’s add some code to detect if the ball sprite collides with the paddleA or paddleB sprites. If it does we will call the bounce() method of the Ball class.

ball.pymain.py
We have added the bounce() method on lines 30 to 32.
We have added on lines 77 to 79 the code to detect a collision between the ball and the paddles.

Next Step?


The final touch consists of adding a scoring system:
Pong Tutorial using Pygame:Adding a Scoring System
Share Button
Tagged with: