Python and Pygame: Building a Pong Game Exercise

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up Pygame
  4. Creating the Game Window
  5. Drawing the Paddles and Ball
  6. Moving the Paddles
  7. Moving the Ball
  8. Collisions and Scoring
  9. Finishing Touches
  10. Summary

Introduction

In this tutorial, we will build a simplified version of the classic Pong game using Python and the Pygame library. Pong is a two-player sports game where each player controls a paddle by moving it vertically across the screen. The goal is to hit the ball with the paddle and prevent it from entering the player’s side of the screen. By the end of this tutorial, you will have a functional Pong game that you can play and modify.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming and some familiarity with object-oriented programming concepts. It would be helpful to have Pygame installed on your system. If you haven’t installed Pygame yet, you can do so by running the following command in your terminal: pip install pygame

Setting Up Pygame

Before we dive into the code, let’s set up the Pygame library in our project. Create a new Python file called pong.py and import the pygame module: python import pygame Next, we need to initialize Pygame and set up the game window. Add the following code to your pong.py file: ```python pygame.init()

WIDTH = 800
HEIGHT = 400

win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong Game")
``` In this code, we initialize Pygame with `pygame.init()` and define the width and height of our game window. We create a Pygame display surface called `win` with the desired width and height, and set the window caption to "Pong Game".

Creating the Game Window

Now that we have set up the game window, we can start building the game itself. Let’s begin by creating a game loop that will handle user input, update the game state, and render the graphics.

Inside the while loop, add the following code: ```python BLACK = (0, 0, 0)

def redraw_window():
    win.fill(BLACK)
    pygame.display.update()

run = True
while run:
    redraw_window()

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

pygame.quit()
``` Here, we define a constant `BLACK` that represents the RGB color for the background. We also create a helper function `redraw_window()` that fills the screen with the background color and updates the Pygame display.

Inside the game loop, we call redraw_window() to refresh the screen and handle the QUIT event to exit the game when the window is closed.

Drawing the Paddles and Ball

Now that we have our game window set up, let’s draw the paddles and the ball on the screen.

First, we need to define some constants related to the paddles and the ball. Add the following code before the game loop: ```python PADDLE_WIDTH = 10 PADDLE_HEIGHT = 60 PADDLE_SPEED = 5 BALL_RADIUS = 8 BALL_SPEED_X = 3 BALL_SPEED_Y = 3

WHITE = (255, 255, 255)
``` These constants represent the dimensions and movement speeds of the paddles and the ball, as well as the RGB color for the paddles.

Next, we will create two paddle objects using Pygame’s Rect class. Add the following code inside the game loop, after the redraw_window() function call: python paddle1 = pygame.Rect(50, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT) paddle2 = pygame.Rect(WIDTH - 50 - PADDLE_WIDTH, HEIGHT // 2 - PADDLE_HEIGHT // 2, PADDLE_WIDTH, PADDLE_HEIGHT) Here, we create two rectangles using the pygame.Rect() constructor. The first paddle is positioned on the left side of the screen, and the second paddle is positioned on the right side.

Finally, let’s draw the paddles and the ball on the screen. Add the following code inside the redraw_window() function, before pygame.display.update(): python pygame.draw.rect(win, WHITE, paddle1) pygame.draw.rect(win, WHITE, paddle2) pygame.draw.circle(win, WHITE, (WIDTH // 2, HEIGHT // 2), BALL_RADIUS) In this code, we use pygame.draw.rect() to draw the paddles and pygame.draw.circle() to draw the ball. We pass the window surface, the color, and the shape parameters to these functions.

Moving the Paddles

Now that we have the paddles and the ball on the screen, let’s make the paddles move based on user input.

Inside the game loop, after the event handling code, add the following code: ```python 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
``` Here, we use the `pygame.key.get_pressed()` function to get a list of all pressed keys. We check if the "W" key is pressed (`pygame.K_w`), and if so, we move the first paddle up by `PADDLE_SPEED` pixels. Likewise, we check if the "S" key is pressed (`pygame.K_s`), and if so, we move the first paddle down. We do the same for the second paddle using the "UP" and "DOWN" arrow keys.

Moving the Ball

Now that the paddles can move, let’s make the ball move across the screen and bounce off the paddles and the walls.

Inside the game loop, after the paddle movement code, add the following code: ```python ball = pygame.Rect(WIDTH // 2 - BALL_RADIUS, HEIGHT // 2 - BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2)

ball.x += BALL_SPEED_X
ball.y += BALL_SPEED_Y

if ball.left <= 0 or ball.right >= WIDTH:
    BALL_SPEED_X *= -1
if ball.top <= 0 or ball.bottom >= HEIGHT:
    BALL_SPEED_Y *= -1

if paddle1.colliderect(ball) or paddle2.colliderect(ball):
    BALL_SPEED_X *= -1
``` Here, we create a rectangle representing the ball's position and size. We update the ball's position by adding `BALL_SPEED_X` and `BALL_SPEED_Y` to its X and Y coordinates, respectively.

We check if the ball reaches the left or right edge of the screen, and if so, we reverse its X direction by multiplying BALL_SPEED_X by -1. Similarly, we check if the ball reaches the top or bottom edge of the screen, and if so, we reverse its Y direction by multiplying BALL_SPEED_Y by -1.

Finally, we check if the ball collides with either paddle using the colliderect() method. If a collision occurs, we reverse the ball’s X direction to simulate bouncing off the paddles.

Collisions and Scoring

To complete our Pong game, we need to implement collision detection with the walls, add score tracking, and display the current score on the screen.

First, let’s define two variables to keep track of the players’ scores. Add the following code before the game loop: python score1 = 0 score2 = 0 Next, inside the game loop, after the ball movement code, add the following code: python if ball.left <= 0: score2 += 1 ball.x, ball.y = WIDTH // 2 - BALL_RADIUS, HEIGHT // 2 - BALL_RADIUS elif ball.right >= WIDTH: score1 += 1 ball.x, ball.y = WIDTH // 2 - BALL_RADIUS, HEIGHT // 2 - BALL_RADIUS In this code, we check if the ball reaches the left or right edge of the screen. If it reaches the left edge, player 2 scores a point, and we reset the ball’s position to the center. If it reaches the right edge, player 1 scores a point, and we do the same.

Next, let’s display the score on the screen. Add the following code inside the redraw_window() function, before pygame.display.update(): python font = pygame.font.Font(None, 36) text1 = font.render(str(score1), 1, WHITE) text2 = font.render(str(score2), 1, WHITE) win.blit(text1, (WIDTH // 4, 10)) win.blit(text2, (3 * WIDTH // 4, 10)) Here, we create a pygame.font.Font object with a font size of 36. We then render the score as text using font.render(), passing the score value converted to a string, an antialiasing parameter, and the desired color. Finally, we use win.blit() to draw the score text on the screen.

Finishing Touches

To make the game more enjoyable, we can add some additional features, such as a background image, sound effects, different ball speeds, and game over logic.

To add a background image, make sure you have an image file in the same directory as your Python script, and add the following code before the game loop: python background = pygame.image.load("background.jpg") Inside the redraw_window() function, replace win.fill(BLACK) with: python win.blit(background, (0, 0)) To add sound effects, you can download sound files in a compatible format and use Pygame’s sound functions to play them at appropriate times.

To implement different ball speeds, you can introduce variables for BALL_SPEED_X and BALL_SPEED_Y, and modify them based on certain events or game conditions.

Finally, to add game over logic, you can set a maximum score limit and check if either player reaches it. When the game is over, you can display a message on the screen and provide an option to restart the game.

Feel free to experiment and enhance the game according to your creativity and preferences!

Summary

In this tutorial, we learned how to build a simple Pong game using Python and the Pygame library. We covered the basics of setting up Pygame, creating the game window, drawing the paddles and the ball, and handling user input to move the paddles. We also implemented the movement and collision detection for the ball, added scoring functionality, and displayed the current scores on the screen. Finally, we discussed some additional features that can be implemented to enhance the game.

With this knowledge, you can further explore Pygame and create your own games or modify existing ones. Have fun coding and let your imagination run wild!