Python Pong Game with Source Code
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
Have you ever tried playing the Pong game with your sibling or friend? If not, develop this fun pong game with us in Python and compete! So, without waiting let’s get started with some introduction.
What is a Pong Game?
Pong is one of the famous computer games that resembles table tennis. In this game, the two players control the two paddles on either side of the game window.
They move the paddles up or down to hit the moving ball. The score of a player increases either when he/she hits the ball or when the opponent misses the hit.
Python Pong Game – Project Details
We will be using the turtle module to build this game in Python. In this game, we will be using the up, down, left, and right keys to move the left and the right paddles. Also, the speed of the ball increases, along with the score, as a player hits the ball to predefined speed level.
Once a player misses the hit, the ball again starts from center towards the other player along with the increase in the score of the opponent.
Download the Source Code for Python Pong Game
Please download the source code for the Pong Game in Python using the link: Pong Game Project
Project Prerequisites
It is advised for the developer to have prior knowledge in Python and the Turtle module. Also, install the Turtle module using the below command, if not installed.
pip install turtle
Steps to Build the Pong Game in Python
Done with the prerequisites, let’s start discussing the steps to follow for developing this Pong game in Python.
1. First, we start by importing the modules.
2. Now we create the main screen.
3. Then we create the two paddles, ball, and score board and set their properties.
4. Next, we create the functions to move the paddles and match the keyboard buttons to the respective functions.
5. Finally, we write the game code, included in an infinite loop. In this we
a. Move the ball
b. Check the collision of the ball with walls, i.e., the player missed the ball
c. Check the collision of ball with the paddle
d. Change the direction of the ball based on the above two situations
1. Importing the modules
The first step is to import the turtle module. We will use this module to build the whole game.
# Import the turtle library import turtle
2. Creating main screen
Next, we create the main screen for the game titled “DataFlair Pong game”. And then we set its size.
# Creating the screen with name and size screen = turtle.Screen() screen.title("DataFlair Pong game") screen.setup(width=1000 , height=600)
3. Creating left and right paddles
The next step is to create the left and right paddles. The paddles have the following properties
a. They are of square shape and are centered vertically on left or right ends.
b. Their speed is zero. They move only when keyboard keys are pressed.
# Creating the left paddle paddle1 = turtle.Turtle() #Setting its speed as zero, it moves only when key is pressed paddle1.speed(0) #Setting shape, color, and size paddle1.shape("square") paddle1.color("blue") paddle1.shapesize(stretch_wid=6, stretch_len=2) paddle1.penup() #The paddle is left-centered initially paddle1.goto(-400, 0)
# Creating the right paddle paddle2 = turtle.Turtle() #Setting its speed as zero, it moves only when key is pressed paddle2.speed(0) #Setting shape, color, and size paddle2.shape("square") paddle2.color("red") paddle2.shapesize(stretch_wid=6, stretch_len=2) paddle2.penup() #The paddle is right-centered initially paddle2.goto(400, 0)
4. Creating ball and setting its properties
Now it’s the time to create the ball. It is in circle shape and initially located at the centre of the screen. Even it’s speed is 0 and it moves based on the values dx and dy.
Everytime the main game loop runs, the location of the ball is updated by dx and dy which gives the sense of motion.
# Ball of circle shape ball = turtle.Turtle() #Setting the speed of ball to 0, it moves based on the dx and dy values ball.speed(0) #Setting shape, color, and size ball.shape("circle") ball.color("green") ball.penup() #Ball starts from the centre of the screen ball.goto(0, 0) #Setting dx and dy that decide the speed of the ball ball.dx = 2 ball.dy = -2
5. Initializing scores and creating scoreboard
Next, we initialize the scores to zero. And then create a scoreboard on top of the screen to show the current scores. In this, the write() function is used to show the text on the window.
# Initializing the score of the two players player1 = 0 player2 = 0 # Displaying the score score = turtle.Turtle() score.speed(0) score.penup() #Hiding the turtle to show text score.hideturtle() #Locating the scoreboard on top of the screen score.goto(0, 260) #Showing the score score.write("Player1 : 0 Player2: 0", align="center", font=("Courier", 20, "bold"))
6. Writing functions to move paddles and matching with keys
Now we write the functions to move the paddles vertically. For giving the movement, we are changing the y-coordinate of the paddle by 15 units. They work in the following way:
1. On clicking the left arrow button on the keyboard, movePad1Up() function executes and the left paddle moves up.
2. On clicking the right arrow button on the keyboard, movePad1Down() function executes and the left paddle moves down.
3. On clicking the up arrow button on the keyboard, movePad2Up() function executes and the right paddle moves up.
4. On clicking the down arrow button on the keyboard, movePad2Down() function executes and the right paddle moves down.
# Function to move the left paddle up def movePad1Up(): y = paddle1.ycor() #Getting the current y-coordinated of the left paddle y += 15 paddle1.sety(y) #Updating the y-coordinated of the paddle # Function to move the left paddle down def movePad1Down(): y = paddle1.ycor()#Getting the current y-coordinated of the left paddle y -= 15 paddle1.sety(y)#Updating the y-coordinated of the paddle # Function to move the right paddle up def movePad2Up(): y = paddle2.ycor()#Getting the current y-coordinated of the right paddle y += 15 paddle2.sety(y)#Updating the y-coordinated of the paddle # Function to move the right paddle down def movePad2Down(): y = paddle2.ycor()#Getting the current y-coordinated of the right paddle y -= 15 paddle2.sety(y)#Updating the y-coordinated of the paddle # Matching the Keyboard buttons to the above functions= screen.listen() screen.onkeypress(movePad1Up, "Left") screen.onkeypress(movePad1Down, "Right") screen.onkeypress(movePad2Up, "Up") screen.onkeypress(movePad2Down, "Down")
7. Writing the main game
At last, we are here to write the code for the main game. We write it in an infinite while loop that runs till the window is closed.
a. First we update the screen.
b. Then we move the ball by updating the coordinates dx and dy.
c. We check if the ball hits top and bottom walls and bounce the ball by changing the sign of dy.
d. We know that if any of the players miss the hit, then the ball touches the left or right walls. So, we check if the ball hits the left or right walls and
- Change the score of opponent and update score board
- Start the ball again from center of the screen in opposite direction
e. Finally, we check if any of the paddles hit the ball and we
- Increase the score and update score board
- Increase the speed making sure it does not cross the limit 7
- Change sign of dx of ball, making it move towards the opposite player
#The main game while True: #Updating the screen every time with the new changes screen.update() #Moving the ball by updating the coordinates ball.setx(ball.xcor()+ball.dx) ball.sety(ball.ycor()+ball.dy) # Checking if ball hits the top of the screen if ball.ycor() > 280: ball.sety(280) ball.dy *= -1 #Bouncing the ball # Checking if ball hits the bottom of the screen if ball.ycor() < -280: ball.sety(-280) ball.dy *= -1#Bouncing the ball #Checking if the ball hits the left or right walls, the player missed the hit if ball.xcor() > 480 or ball.xcor() < -480: if(ball.xcor() <-480): player2 += 1 #Increasing the score of right player if left player missed else: player1 += 1 #Increasing the score of left player if right player missed #Starting ball again from center towards the opposite direction ball.goto(0, 0) ball.dx *= -1 ball.dy *= -1 #Updating score in the scoreboard score.clear() score.write("Player1 : {} Player2: {}".format(player1, player2), align="center", font=("Courier", 20, "bold")) #Checking if the left player hit the ball if (ball.xcor() < -360 and ball.xcor() > -370) and (paddle1.ycor() + 50 > ball.ycor() > paddle1.ycor() - 50): #Increasing score of left player and updating score board player1 += 1 score.clear() score.write("Player A: {} Player B: {}".format(player1, player2), align="center", font=("Courier", 20, "bold")) ball.setx(-360) #Increasing speed of the ball with the limit 7 if(ball.dy>0 and ball.dy<5): #If dy is positive increasing dy ball.dy+=0.5 elif(ball.dy<0 and ball.dy>-5): #else if dy is negative decreasing dy ball.dy-=0.5 if(ball.dx>0 and ball.dx<5):#If dx is positive increasing dx ball.dx+=0.5 elif(ball.dx<0 and ball.dx>-5): #else if dx is negative decreasing dx ball.dx-=0.5 #Changing the direction of ball towards the right player ball.dx *=-1 #Checking if the right player hit the ball if (ball.xcor() > 360 and ball.xcor() < 370) and (paddle2.ycor() + 50 > ball.ycor() > paddle2.ycor() - 50): #Increasing score of right player and updating scoreboard player2 += 1 score.clear() score.write("Player A: {} Player B: {}".format(player1, player2), align="center", font=("Courier", 20, "bold")) ball.setx(360) #Increasing speed of the ball with the limit 7 if(ball.dy>0 and ball.dy<7):#If dy is positive increasing dy ball.dy+=1 elif(ball.dy<0 and ball.dy>-7):#else if dy is negative decreasing dy ball.dy-=1 if(ball.dx>0 and ball.dx<7):#If dx is positive increasing dx ball.dx+=1 elif(ball.dx<0 and ball.dx>-7): #else if dx is negative decreasing dx ball.dx-=1 #Changing the direction of ball towards the left player ball.dx*=-1
Output of Python Pong Game
Summary
With this Python project, we have successfully built the Pong game. For this, we used the turtle module. We learned how to create shapes for blocks, balls, change the speed and update the screen. Hoping that you enjoyed developing this game!
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google