Classic Pong Game Using Python and Pygame

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to create a Pong game using Python and the Pygame library. Pong is a classic two-player arcade game where players control paddles to hit a ball past each other.

To complete this project, you will need to follow the steps below. We will start by creating the project files and setting up the game window. Then, we will define the colors and set up the paddles and ball. Finally, we will move the paddles and ball, handle collisions, and draw the game elements.

👀 Preview

Alt text

🎯 Tasks

In this project, you will learn:

  • How to create the project files
  • How to set up the game window
  • How to set up the paddles and ball
  • How to set up the game variables
  • How to set up the game loop
  • How to move the paddles
  • How to move the ball
  • How to handle ball collisions
  • How to update scores and reset the ball
  • How to handle power-up collisions and movement
  • How to draw the game elements
  • How to draw the score
  • How to update the display
  • How to set the frames per second (FPS)
  • How to quit the game

🏆 Achievements

After completing this project, you will be able to:

  • Use the Pygame library to create a game window
  • Set up and move game objects like paddles and a ball
  • Handle collisions between game objects
  • Update and display game scores
  • Set the frames per second (FPS) for the game
  • Quit the game properly

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FileHandlingGroup(["`File Handling`"]) pygame(("`Pygame`")) -.-> pygame/CoreConceptsGroup(["`Core Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FileHandlingGroup -.-> python/with_statement("`Using with Statement`") pygame/CoreConceptsGroup -.-> pygame/display("`Display Management`") pygame/CoreConceptsGroup -.-> pygame/draw("`Drawing Utilities`") pygame/CoreConceptsGroup -.-> pygame/event("`Event Handling`") pygame/CoreConceptsGroup -.-> pygame/font("`Font Styling`") pygame/CoreConceptsGroup -.-> pygame/key("`Keyboard Interaction`") pygame/CoreConceptsGroup -.-> pygame/time("`Timing Functions`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/while_loops("`While Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") subgraph Lab Skills python/comments -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/with_statement -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} pygame/display -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} pygame/draw -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} pygame/event -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} pygame/font -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} pygame/key -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} pygame/time -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/booleans -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/conditional_statements -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/for_loops -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/while_loops -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/lists -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/tuples -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/sets -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/importing_modules -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/standard_libraries -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} python/math_random -.-> lab-298856{{"`Classic Pong Game Using Python and Pygame`"}} end

Create the Project Files

Create a file named pong_game.py in your preferred code editor or IDE. This will be the main file where you write the code for the Pong game.

cd ~/project
touch pong_game.py
sudo pip install pygame

Set up the Game Window

Inside the pong_game.py file, import the required libraries at the beginning of the code:

import pygame
import random

Then, initialize Pygame by calling pygame.init():

## Initialize Pygame
pygame.init()

Next, set up the game window by defining the width, height, and frames per second (FPS):

## Set up the game window
WIDTH = 800
HEIGHT = 400
FPS = 60

Define the colors used in the game:

## Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
ORANGE = (255, 165, 0)
BACKGROUND_COLOR = (50, 50, 50)

Create the game window, set the window title, and create a clock object to control the frame rate:

## Set up the game window
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Game")
clock = pygame.time.Clock()

Set up the Paddles and Ball

Define the properties of the paddles, such as width, height, speed, and color:

## Set up the paddles
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 60
PADDLE_SPEED = 5
PADDLE_COLOR = WHITE

Create two paddle objects using the pygame.Rect() constructor and position them at the center of each side of the game window:

paddle1 = pygame.Rect(0, HEIGHT / 2 - PADDLE_HEIGHT / 2, PADDLE_WIDTH, PADDLE_HEIGHT)
paddle2 = pygame.Rect(
    WIDTH - PADDLE_WIDTH, HEIGHT / 2 - PADDLE_HEIGHT / 2, PADDLE_WIDTH, PADDLE_HEIGHT
)

Set up the properties of the ball, such as width, height, speed, and color:

## Set up the ball
BALL_WIDTH = 10
BALL_HEIGHT = 10
BALL_SPEED_X = 3
BALL_SPEED_Y = 3
BALL_COLOR = WHITE

Create a ball object using the pygame.Rect() constructor and position it at the center of the game window:

ball = pygame.Rect(
    WIDTH / 2 - BALL_WIDTH / 2, HEIGHT / 2 - BALL_HEIGHT / 2, BALL_WIDTH, BALL_HEIGHT
)

Set the initial speed of the ball in both x and y directions randomly:

ball_speed_x = BALL_SPEED_X * random.choice((1, -1))
ball_speed_y = BALL_SPEED_Y * random.choice((1, -1))

Set up the Game Variables

Set up the variables to keep track of the player scores, create a game font object, and define the color for the score display:

## Set up the game variables
score1 = 0
score2 = 0
game_font = pygame.font.SysFont(None, 48)
SCORE_COLOR = WHITE

Set up the Game Loop

Create a boolean variable running and set it to True to start the game loop:

## Set up the game loop
running = True
while running:

Inside the game loop, handle the events by iterating through the events that have occurred:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

Move the Paddles

Inside the game loop, check for keyboard input to move the paddles:

    ## Move the paddles
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w] and paddle1.y > 0:
        paddle1.y -= PADDLE_SPEED
    if keys[pygame.K_s] and paddle1.y < HEIGHT - PADDLE_HEIGHT:
        paddle1.y += PADDLE_SPEED
    if keys[pygame.K_UP] and paddle2.y > 0:
        paddle2.y -= PADDLE_SPEED
    if keys[pygame.K_DOWN] and paddle2.y < HEIGHT - PADDLE_HEIGHT:
        paddle2.y += PADDLE_SPEED

Move the Ball

Inside the game loop, update the position of the ball:

    ## Move the ball
    ball.x += ball_speed_x
    ball.y += ball_speed_y

Handle Ball Collisions

Inside the game loop, handle collisions of the ball with the paddles and walls:

    ## Ball collision with paddles
    if ball.colliderect(paddle1) or ball.colliderect(paddle2):
        ball_speed_x *= -1

    ## Ball collision with walls
    if ball.y > HEIGHT - BALL_HEIGHT or ball.y < 0:
        ball_speed_y *= -1

Update Scores and Reset the Ball

Inside the game loop, update the scores and reset the ball when it goes beyond the paddle:

    ## Increase the score and reset the ball
    if ball.x < 0:
        score2 += 1
        ball.center = (WIDTH / 2, HEIGHT / 2)
        ball_speed_x *= random.choice((1, -1))
        ball_speed_y *= random.choice((1, -1))
    if ball.x > WIDTH:
        score1 += 1
        ball.center = (WIDTH / 2, HEIGHT / 2)
        ball_speed_x *= random.choice((1, -1))
        ball_speed_y *= random.choice((1, -1))

Handle Power-up Collisions and Movement

Inside the game loop, handle power-up collisions with the paddles and move the power-up:

    ## Power-up collision with paddles
    if powerup.colliderect(paddle1) or powerup.colliderect(paddle2):
        powerup_active = True
        powerup.x = WIDTH / 2 - POWERUP_WIDTH / 2
        powerup.y = HEIGHT / 2 - POWERUP_HEIGHT / 2

    ## Power-up movement
    if powerup_active:
        powerup.x += powerup_speed_x
        powerup.y += powerup_speed_y

        if powerup.x > WIDTH - POWERUP_WIDTH or powerup.x < 0:
            powerup_speed_x *= -1
        if powerup.y > HEIGHT - POWERUP_HEIGHT or powerup.y < 0:
            powerup_speed_y *= -1

Draw the Game Elements

Inside the game loop, draw the paddles, ball, power-up, and score on the game window:

    ## Draw the game elements
    screen.fill(BACKGROUND_COLOR)
    pygame.draw.rect(screen, PADDLE_COLOR, paddle1)
    pygame.draw.rect(screen, PADDLE_COLOR, paddle2)
    pygame.draw.ellipse(screen, BALL_COLOR, ball)
    pygame.draw.rect(screen, POWERUP_COLOR, powerup)

Draw the Score

Inside the game loop, draw the scores at the top center of the game window:

    ## Draw the score
    score_text = game_font.render(f"{score1} : {score2}", True, SCORE_COLOR)
    screen.blit(score_text, (WIDTH / 2 - score_text.get_width() / 2, 10))

Update the Display

Inside the game loop, update the display to show the changes:

    ## Update the display
    pygame.display.flip()

Set the FPS

Inside the game loop, set the frame rate to control the speed of the game:

    ## Set the FPS
    clock.tick(FPS)

Quit the Game

After the game loop, add the following line to quit Pygame when the game is finished:

## Quit the game
pygame.quit()

Switch to Desktop and run the project using the following command:

python pong_game.py

Now, you can play the Pong game using the arrow keys and the W and S keys on your keyboard.

Alt text

Summary

Congratulations! You have completed the step-by-step project on creating a Pong game using Python and Pygame. You have learned how to set up the game window, define the properties of the paddles and ball, handle game events, move the paddles and ball, handle collisions, and draw the game elements. Experiment with different modifications to add your own enhancements to the game and have fun playing it!

Other Python Tutorials you may like