Create and Play Pong Game using Python

Rahul Patodi
Wiki Flood
Published in
5 min readAug 17, 2024

Pong is one of the first video games to appear in arcades. It is a basic two-dimensional sports game that aims to emulate real table tennis. The players control two paddles on their respective sides of the screen, and the goal is to hit a ball to and fro. The objective is for a team to get as many points as possible by making the rival fail to ‘strike’ the ball.

Need for a Python Pong Game:

The advantages of playing a Pong game are improved response time of the hands due to the quick movements required when playing the game, coordination of hand and eye as one needs to move the paddles while focusing on the ball, and enhancement of concentration since one has to keep following the ball and being aware of the ball’s trajectory. The game relieves stress and brings relaxation; thus, it is entertaining in a way.

About the Python Pong Game

In this project, the user has to create a Pong game using Python and the Pygame library. Pygame is a library that contains Python modules for writing applications in the category of video games.

The general aspects of the project are as follows:

  • Two paddles which will be controlled by the players will be located on the screen
  • A ball that rolls over the paddles
Python Pong Game Project

Prerequisites for Python Pong Game

To run this project, the following prerequisites must be met:

  • Python: The user must have Python installed in their system.
  • Pygame Library: This library is used to make games.

Explanation of the Python Pong Game code:

The following is the explanation of the code for the project:

Initialization

import pygame
import sys
pygame.init()
screenWidth, screenHeight = 800, 600
Screen_Object_1=pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption('Pong Game')
colourWhite = (255, 255, 255)
colourBlack = (0, 0, 0)

The first step is to import the “pygame” library for game development and “sys” for system-specific parameters and functions. The “pygame.init()” function initializes all the modules in Pygame. The game window is set to 800x600 pixels, and colors are defined using RGB values.

Game Elements

paddle_b, paddle_l = 10, 100
paddle_speed = 10
ballRadius = 10
X_ballSpeed, Y_ballSpeed = 5, 5
leftPaddle=pygame.Rect(50, screenHeight // 2 - paddle_l // 2, paddle_b, paddle_l)
rightPaddle=pygame.Rect(screenWidth - 50 - paddle_b, screenHeight // 2 - paddle_l // 2, paddle_b, paddle_l)
Ball_Object_2=pygame.Rect(screenWidth // 2 - ballRadius, screenHeight // 2 - ballRadius, ballRadius * 2, ballRadius * 2)
score_player1, score_player2 = 0, 0
font = pygame.font.Font(None, 36)

Variables for paddle dimensions, paddle speed, ball radius, and ball speed are defined. Paddle Rectangles and a ball is created. Two variables are made to track the scores. The `font` object is used to render text on the screen.

Drawing Function

def draw():
Screen_Object_1.fill(colourBlack)
pygame.draw.rect(Screen_Object_1, colourWhite, leftPaddle)
pygame.draw.rect(Screen_Object_1, colourWhite, rightPaddle)
pygame.draw.ellipse(Screen_Object_1, colourWhite, Ball_Object_2)
pygame.draw.aaline(Screen_Object_1, colourWhite, (screenWidth // 2, 0), (screenWidth // 2, screenHeight))
left_text = font.render(str(score_player1), True, colourWhite)
right_text = font.render(str(score_player2), True, colourWhite)
Screen_Object_1.blit(left_text, (screenWidth // 4, 20))
Screen_Object_1.blit(right_text, (screenWidth * 3 // 4, 20))
pygame.display.flip()

The screen is set to black. Two paddles, the ball and the centre dividing line, are created. The scores are shown as text on the top of each side.

Ball Reset and Winner Check Functions

def ball_reset():
global X_ballSpeed, Y_ballSpeed
Ball_Object_2.center = (screenWidth // 2, screenHeight // 2)
X_ballSpeed *= -1
def winner_check():
if score_player1 >= 20:
return "Player 1"
elif score_player2 >= 20:
return "Player 2"
return None
def win_display(winner):
win_text = font.render(f"{winner} Wins! Game Over!", True, colourWhite)
Screen_Object_1.fill(colourBlack)
Screen_Object_1.blit(win_text, (screenWidth // 2 - win_text.get_width() // 2, screenHeight // 2 - win_text.get_height() // 2))
pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()
sys.exit()

The “ball_reset()” function brings the ball to the centre, and the “winner_check()” function checks if any player has reached a score of 20 and returns the winner’s name.

Main Game Loop

def main():
global X_ballSpeed, Y_ballSpeed, score_player1, score_player2
time_interval = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
var = pygame.key.get_pressed()
if var[pygame.K_w] and leftPaddle.top > 0:
leftPaddle.y -= paddle_speed
if var[pygame.K_s] and leftPaddle.bottom < screenHeight:
leftPaddle.y += paddle_speed
if var[pygame.K_UP] and rightPaddle.top > 0:
rightPaddle.y -= paddle_speed
if var[pygame.K_DOWN] and rightPaddle.bottom < screenHeight:
rightPaddle.y += paddle_speed
Ball_Object_2.x += X_ballSpeed
Ball_Object_2.y += Y_ballSpeed
if Ball_Object_2.top <= 0 or Ball_Object_2.bottom >= screenHeight:
Y_ballSpeed *= -1
if Ball_Object_2.left <= 0:
score_player2 += 1
ball_reset()
if Ball_Object_2.right >= screenWidth:
score_player1 += 1
ball_reset()
if Ball_Object_2.colliderect(leftPaddle) or Ball_Object_2.colliderect(rightPaddle):
X_ballSpeed *= -1
draw()
winner = winner_check()
if winner:
win_display(winner)


time_interval.tick(60)
if __name__ == '__main__':
main()

The “main()” function modifies global variables for ball speed and player scores. The loop checks for key presses (‘W’, ‘S’, ‘UP’, ‘DOWN’) to move the paddles. The ball’s position is updated. If the ball crosses the left or right edge, the respective player’s score is increased, and the ball is reset. The game ends when one player reaches a score of 20, displaying the winner and closing the game.

Python Pong Game Output

  1. The image shows the application's launch page, where we can see two paddles and one ball along with the scores of both players. The players will control these two paddles to hit the ball and score.
Python Pong Game Output

2. Here, we can see the game is midway, and the players are trying to win according to the rules.

Pong Game Output

3. This is the last screen for the game, where player 2 wins by scoring 20 points and defeating the first player.

Pong Game Output Project

Conclusion

The project involves creating a simplified Pong game that can be successfully used to explain programmed notions, game mechanics, and the usage of Pygame. By completing this Python project, you will gain practical experience that can be used in larger projects in the future.

--

--