is one in every of the earliest and most iconic games within the history of digital entertainment. In its classic form, the sport simulates a table tennis match with two paddles that move vertically across the screen to hit a bouncing ball. Each of the player controls a paddle and has to bounce the ball back to the opposite player, or else they offer some extent to the alternative player.
The history of the sport is somewhat interesting. The Pong game was created and written by Allan Alcom as a test when he was recruited by Atari. This game then became an enormous success, selling a great deal of machines internationally’s pubs and bars, and it so happened that the machines would choke with the masses of cash people would put in, in order that eventually the bars and pubs’ owners needed to call Atari to repair their machines!
On this tutorial, we’ll use Python’s Object Oriented Programming approach to code the Pong game. That is an intermediate-level Python programming tutorial that requires one to have a preliminary knowledge of Python fundamentals: list, …
Understanding the Project
There are various ways we will code this game. We are able to use the easy method and do each task step-by-step with the needed repetitions, or we will use Python’s Object Oriented Programming approach to escapre the repetition and have a neat and arranged code. We’ll opt the second option as this is able to make the sport’s program more systematic and fewer messy!
We’ll use Python’s Turtle module for the visual game development. The turtle module is a built-in functionality that permits one to visulalize code in a simple manner. It mainly consists of a turtle that’s drawing shapes and contours because it moves across the screen in accordance with the coder’s instructions. It’s a robust tool to create beginner-level games, and get easy feedback through a visible screen.
The next are the important thing tasks that we are going to approach in an orderly manner:
- Creating the Game Screen – that is the screen on which the Pong game shall be displayed
- Creating the Paddle & Paddle Class – that is the code that can create a paddle on screen, and configure its movements, which we’ll convert to a category as a blueprint to create 2 paddles, one on the left side and the opposite on the best side
- Creating the Ball Class and Objects – continuing with the OOP approach, we’ll create a generic ball class after which create the ball that can move across the screen, we will even define its relevant methods
- Detecting Collision of Ball with Top/Bottom Wall -this is the piece of code that can detect collision with the upper and lower partitions, and if collision occurs, it’s going to make the ball bounce across the y-axis
- Detecting Collision with Paddle – that is the piece of code that can detect whether the ball collides with the paddle. If yes, it’s going to make the ball bounce; else, if the paddles misses the ball, it’s going to give a rating to the alternative player and restart the sport with the ball on the centre.
- Creating the Scoreboard Class and Object – that is the piece of code that features the creation of the Scoreboard class in a separate Python file and the creation of its object within the predominant game file.
Creating the Game Screen
The primary task is to create the sport screen. This screen shall be rectangular in shape, as in the actual game. We’ll first import the turtle module in or code and use its Screen class to create the screen object and customize it to have a width of 800px and a height of 600px using the Screen class setup() method. We’ll set the background color to black using the bgcolor() method, and name the screen as “Pong Game” using the title() method. Below is the code, where we’ve created the screen object:
from turtle import Turtle, Screen
#Establishing the Game Screen
screen = Screen()
screen.setup(width=800, height=600)
screen.bgcolor("black")
screen.title("Pong Game")
screen.exitonclick()
Notice that we’ve written the last line where we’ve used the screen’s exitonclick() method in order to make sure the screen will remain there until we click on it.
When you find any confusion within the above methods, be happy to ascertain out the official documentation of the Turtle Module from here.
Following is the output as we run this system:
Creating the Paddle & Paddle Class
The following task is to create a paddle, which is a rectangular-shaped object at either side of the Game Screen. We’ll create this paddle using the turtle module’s shape() function, and customize it to be white in color using the color() method, and use the shapesize() method to customize it to have a width of 20px and a height of 100px. Notice that we’ve passed 5 and 1 because the arguments to the shapesize() method. It’s because the shapesize() just isn’t in pixels, but in reference to a base of 20px. So to get a length of 100px, we’ll pass 5 (as 20px x 5 = 100px). Furthermore, we’ll position it such that at first of the sport it’s in the midst of the best side, that’s, a y coordinate of 0 and an x coordinate of 350 (remember our screen is 800px wide). We’ll use the penup() method to remove the turtle’s trace and make it move to the specified location using the goto() method.
#Creating the Paddle
paddle = Turtle()
paddle.shape("square")
paddle.color("white")
paddle.shapesize(5,1)
paddle.penup()
paddle.goto(350,0)
The next is the output of the above code. We are able to see a paddle created on the Game Screen at the best side, with none turtle trace.

Running the above code will create the paddle. Nonetheless, we will see that the paddle is first created, after which it goes to its location. In an effort to turn off the animation, we’ll add the screen’s class tracer() method in our code. This will even require us to update the screen manually:
#Retain the Original Code
screen.tracer(0)
screen.update()
screen.exitonclick()
Calling the tracer() method and passing it a price of 0 will turn off the animation.
Once we’ve created the paddle and updated the screen by turning off the animations, next is to configure the paddle movements. To do that, we’ll use screen listeners. The screen’s class listen() method allows us to hearken to keyboard events, and the onkey() method allows us to call an outlined function each time a selected key’s pressed. We’ll thus define the go_up and go_down functions that can make the paddle move up and down along the y-axis.
def go_up():
new_y = paddle.ycor() + 40
paddle.goto(paddle.xcor(), new_y)
def go_down():
new_y = paddle.ycor() - 40
paddle.goto(paddle.xcor(),new_y)
As will be seen, we’ve defined the paddle’s up and down movement function by making it move 40px vertically from its original position. Next, we’ll use the screen listeners capability to permit these functions to be called on pressing keyboard keys.
screen.listen()
screen.onkey(paddle.go_up, "Up")
screen.onkey(paddle.go_down, "Down")

Now that we’ve created the paddle and configured the mechanism of its movement, allow us to now shift our code to Object Oriented Programming Approach. It’s because we’ll need 2 paddles for the sport, and having a generic blueprint that creates paddles immediately will make our task easier. We’ll refactor our code to create one other paddle easily. We’ll move all of the paddle related code to a different file and create the padlle class in it.
For the reason that paddles we’re creating are in essence turtle objects, we’ll make this paddle class inherit from the Turtle class. So we’ll create a brand new python file in our PyCharm IDE and again import the turtle module’s Turtle class on this separate Python file. Next, we’ll use the category creation syntax and def __inti__() to define the Paddle class. As each the left and right paddles could have different positions across the sport screen, we’ll add the x and y coordinates as attributes to the category.
Now we’ll use the concept of inheritance in OOP and make the Turtle class the super class, and the paddle class will inherit its attributes and methods. Next, we’ll just replace the word “paddle” in our former code where we created the paddle with the “self” keyword.
from turtle import Turtle, Screen
class Paddle(Turtle):
def __init__(self,x,y):
# Creating the Paddle Objects
super().__init__()
self.shape("square")
self.color("white")
self.shapesize(5, 1)
self.penup()
self.x = x
self.y = y
self.goto(x,y)
# Configure Paddle Movement
def go_up(self):
new_y = self.ycor() + 40
self.goto(self.xcor(), new_y)
def go_down(self):
new_y = self.ycor() - 40
self.goto(self.xcor(),new_y)
As will be seen above, we’ve also defined the 2 methods of Paddle class. One is the upward movement and the second is the downward movement that we’ve already defined earlier. Once the Paddle class is defined, we’ll create the paddle objects and configure the up and down movements of each paddles:
from paddle import Paddle
# Creating Paddle Objects
left_paddle = Paddle(-350, 0)
right_paddle = Paddle(350, 0)
# Configuring Paddles' Movement
screen.listen()
screen.onkey(right_paddle.go_up, "Up")
screen.onkey(right_paddle.go_down, "Down")
screen.onkey(left_paddle.go_up, "w")
screen.onkey(left_paddle.go_down, "s")
Running the Game
In an effort to run the sport and update it using the Screen’s update() method, we’ll define some time loop that can proceed to run until externally stopped, or when the condition of the loop turns to False.
#Game is ON:
game_is_on = True
while game_is_on:
screen.update()
Now, if you run the predominant file, you will notice the sport screen and paddles created, and the flexibility of the paddles to maneuver.
Create the Ball Class & Objects
Now continuing on our OOP approach to code this game, we’ll create the Ball class because the generic blueprint and create the ball object from it in our predominant Python file. We’ll create the ball as a turtle object, by making the Ball class inherit from the super class Turtle. We’ll use the turtle class’s methods color() and shape() to initialize a ball of white color in a circular shape. As before, we’ll use the penup() approach to turtle to cover the turtle’s trace.
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.shape("circle")
self.penup()
Now that our ball’s attributes are defined, we will even create the ball’s methods of moving as soon as the sport starts. The sport will start with the ball being on the centre of the sport screen, and when the screen refreshes, it’s going to be moving in the best direction first. In our predominant while loop we’ll call this method so the ball will proceed to maneuver throughout when the sport is on, that’s, its x and y coordinates will change at every refresh of the sport screen.
The option to make the ball move is by changing each its x and y coordinates by a certain number, allow us to say 10 in the interim. We’ll define the move() approach to the ball and code the above scenario:
class Ball(Turtle):
#Retain previous code
def move(self):
new_x = self.xcor() + 10
new_y = self.ycor() + 10
self.goto(new_x, new_y)
We’ll add this approach to the ball object to be called contained in the game’s while loop:
#Game is ON:
game_is_on = True
while game_is_on:
screen.update()
ball.move()
On running the code, we see that the ball vanishes quickly, and what we’re left with is just the two paddles.

We are able to resume the animation by commenting out the screen.tracer() lines and rerunning the code. We’ll now see the two paddles and the ball being created and moved.

One other option to visualise that is using the time module and bringing a delay within the predominant while loop of the sport. This will be done as follows (without commenting out the tracer() function):
import time
#Retain the Original Code
#Game is ON:
game_is_on = True
while game_is_on:
time.sleep(0.1)
screen.update()
ball.move()
Now you possibly can see that the ball moves at a slower pace and we will catch it with a paddle.
Detecting Collision of Ball with Top/Bottom Wall
Now that our ball is created and running, we’d like to design a mechanism to make the ball bounce when it hits the highest and bottom partitions, as for the left and right partitions, the ball ought to be caught by the left and right paddles. If the ball just isn’t caught, it could mean the opposite player scores some extent.
So, considering that our ball is moving from the centre of the screen to the highest right corner, and it reaches the corner, it must bounce now. In easy words, bouncing would simply be a change of direction within the y-axis, because the ball would still be going forward within the x-axis. We’ll now define a brand new approach to the Ball class called bounce() and call it within the predominant game loop when the ball reaches the boundary:
from turtle import Turtle
class Ball(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.shape("circle")
self.penup()
self.x_move = 10
self.y_move = 10
def move(self):
new_x = self.xcor() + self.x_move
new_y = self.ycor() + self.y_move
self.goto(new_x, new_y)
def bounce(self):
self.y_move *= -1
Notice that within the above, we’ve defined 2 recent attributes of the Ball class, the x_move and the y_move, and have made them equal to 10. Then, within the move() method, we’ve replaced the figure of 10 with these attributes. As will be seen, this is useful for our bounce() method. Now, each time the ball bounces, it’s going to move in the other way to its previous y position. This simply signifies that if the ball goes up, and collides with the wall, the y_move would change from +10 to -10, and the ball will move downwards, because the negative number would mean the ball is moving down. Consequently, a collision with the underside wall would change this y_move from -10 to +10, and the ball will then move upwards.
Now, allow us to add this condition within the predominant while loop:
while game_is_on:
#Retain Original Code
#Detect Collision with Top and Bottom Partitions
if ball.ycor() > 275 or ball.ycor() < -275:
ball.bounce_y()
Within the code above, we've added the condition of the collision with the partitions to be detected, after which the bounce() method to be called. You should utilize any value for the boundaries, but through repeated tries, the worth of 275 is nice enough!

Detecting Collision with Paddle
Now that we all know the right way to make the ball bounce from the highest and bottom partitions, the subsequent step is to detect a collision with the paddle and make the ball bounce from the paddle. We'll employ a similiar method as before, except that now we're talking in regards to the x-axis.
The conventional option to detect a collision between the ball and the wall is to make use of the space method. If the space between the 2 is lower than a certain quantity, we will conclude that the two have touched/collided. Nonetheless, know that the distance() function works by calculating the space between the centers of the 2 turtle objects. In our case, one is a 20x20px ball, and the opposite is a 20×200 rectangular paddle. The gap between them would vary along the length of the paddle. If the ball hits the paddle on its edge, the space() method would fail to conclude that each of them have made contact.
We are able to add one other condition which might check if the ball has gone past a certain point on the x-axis, over to the best (within the case of the best paddle), and it's inside a 50px distance from the paddle, then the ball will need to have made contact. We'll add this condition to the predominant while loop. Once the collision is detected, we could have the ball bounce, but this time within the x-direction. Allow us to redefine our bounce functions so we've each bounce functions, one for the x-axis when colliding with pthe addle, and the opposite on the y-axis when colliding with the wall:
def bounce_y(self):
self.y_move *= -1
def bounce_x(self):
self.x_move *= -1
while game_is_on:
...
# Detect Collision of the Ball with the Right Paddle
if ball.distance(right_paddle) < 50 and ball.xcor() > 320:
ball.bounce_x()
# Detect Collision of the Ball with the Left Paddle
elif ball.distance(left_paddle) < 50 and ball.xcor() < -320:
ball.bounce_x()
Note, we've added a price of 320 after some hit and trial and visualizations of the ball colliding with the paddle.

If one in every of the paddles misses the ball, then the opposite player gets some extent, and the sport restarts with the ball within the centre. In an effort to check if the ball is missed by the paddle, we will visualize this by considering the ball going beyond a certain point on the horizontal axis. We all know that the width of the screen is 800 and the paddle is at 350 along the x-axis, so the paddle actually goes from 340 to 360 because it has a width of 20px, so if the ball goes beyond the 360 x axs, it means the paddles has missed the ball. This may mean we'll reset the ball to the starting position on the centre value (0,0). We'll define a reset_position() approach to the ball that shall be called when the above condition is met. Furthermore, we will even add a feature that can reverse the ball’s direction, so as an alternative of going to the best, it's going to go to the left.
Class Ball(Turtle):
...
def reset_position(self):
self.goto(0, 0)
self.bounce_x()
The bounce_x() method will cause the ball to reverse direction because it did when it could bounce off a paddle. Putting these conditions in the sport’s predominant while loop:
while game_is_on:
...
# Detect Right Paddle Missing the Ball
if ball.xcor() > 380:
ball.reset_position()
# Detect Left Paddle Missing the Ball
if ball.xcor() < -380:
ball.reset_position()
Running the code above will show us what happens when a paddle misses the ball; the ball would reverse its direction and would go to the opposite padlle. Now all that’s left is to create a scoreboard to store and display the rating for every player.
Creating the Scoreboard
In an effort to display and update the rating for every player, we'll define a scoreboard class in a brand new python file. We'll create the Scoreboard class inheriting from the turtle class, and can define the attributes that can help the turtle object to put in writing. First we'll initialize the 2 attributes, l_score and r_score and set them to 0 at first of the sport. We'll define two methods, l_point and r_point which shall be called each time a player misses the ball, and can increase the points of the opposite user. We will even define a technique called update_scoreboard(), and call it when a player scores a further point. This method, when called will simply update the scoreboard.
Following is the Scoreboard Class creation:
from turtle import Turtle
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.penup()
self.hideturtle()
self.l_score = 0
self.r_score = 0
self.update_scoreboard()
def update_scoreboard(self):
self.clear()
self.goto(-100, 200)
self.write(self.l_score, align="center", font=("Arial", 40, "normal"))
self.goto(100, 200)
self.write(self.r_score, align="center", font=("Arial", 40, "normal"))
def l_point(self):
self.l_score += 1
self.update_scoreboard()
def r_point(self):
self.r_score += 1
self.update_scoreboard()
The update_scoreboard() method creates a turtle that writes the rating of each players on the predominant screen. Notice that we've used the Turtle module’s write() function in here.
Next we'll import and create a scoreboard object within the predominant file, and we'll use this object to access its methods, satisfying the 2 conditions: each time a player’s paddle misses the ball, the opposite player would get some extent.
from scoreboard import Scoreboard
#Initializing Scoreboard Object
scoreboard = Scoreboard()
while game_is_on:
...
# Detect Right Paddle Missing the Ball
if ball.xcor() > 380:
ball.reset_position()
scoreboard.l_point()
# Detect Left Paddle Missing the Ball
if ball.xcor() < -380:
ball.reset_position()
scoreboard.r_point()
That is where the sport designing and coding involves its end. Runing the predominant python file will generate the sport screen and its components, with the ball moving as the sport starts. Now you only have to fins a player to play this game with!
You may also change the speed of the sport through some changes within the code (that’s so that you can work out!)
Conclusion
In this text, we've developed the classic Pong game with the assistance of the Python Turtle module. We've used the concept of Object Oriented Programming to create classes, initialize attributes and methods, and from these classes create objects within the predominant game file. That is an intermediate-level Python project, and when you stumbled upon some a part of the code, ensure to either consult with the Python official documentation or revise your basic concepts, particularly OOP on this case.
