Pong

Two paddles, one ball. Beat the computer to seven points; where the ball hits your paddle decides its angle.

Beginner2 min readUpdated
Pong screenshot: blue player paddle, yellow computer paddle, white ball and a 4 to 3 score
Screenshot captured from the Python source below running in pygame-ce.
Difficulty
Beginner
Source size
177 lines, 1 file
Requires
Python 3.10+, pygame-ce or pygame
Assets
None (drawn in code)

Controls

  • Up Down W S Move your paddle
  • Space Serve or start a new match
On this page

What you'll learn#

  • Vector-based ball movement with pygame.Vector2
  • Rebound angles that depend on where the ball hits
  • A simple computer opponent with a speed limit
  • Scoring, serving and match state

Run it on your computer#

  1. Install Python 3.10 or newer and Pygame: python -m pip install pygame-ce (or pygame). See the installation guides.
  2. Download pong.py into any folder.
  3. Open a terminal in that folder and run python pong.py.

No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.

How it works#

Rebound angles#

When the ball touches a paddle, the game measures how far from the paddle's centre it hit, from -1 at the top edge to +1 at the bottom, and converts that into an angle of up to 55 degrees. Hitting near the edge sends the ball off steeply, which gives the player control. The speed increases by 6% per hit, capped at 760 pixels per second.

Avoiding double hits#

The ball's velocity is checked before bouncing (b.vel.x * side < 0), and the ball is moved just outside the paddle after the bounce. Without these two lines a ball can get stuck inside a paddle and bounce back and forth every frame.

A fair computer player#

The computer paddle moves towards the ball only while it approaches, and otherwise drifts back to the middle. Its speed limit (cpu_speed) is lower than the fastest ball, so it can be beaten with angled shots.

Complete source code#

"""Pong - a Pygame.net game project.

Classic paddle tennis against a computer opponent. First to 7 points wins.
Where the ball meets your paddle decides its rebound angle.

Run it:   pip install pygame-ce     (or: pip install pygame)
          python pong.py
Controls: Up/Down or W/S to move, Space to serve or restart.
License:  MIT - https://pygame.net/licenses/
"""
import asyncio
import math
import random

import pygame

WIDTH, HEIGHT = 640, 480
FPS = 60
PADDLE_W, PADDLE_H = 12, 80
BALL = 12
WIN_SCORE = 7

BG = (16, 26, 48)
LINE = (44, 62, 100)
WHITE = (230, 236, 247)
YELLOW = (244, 197, 49)
BLUE = (91, 147, 230)


class Paddle:
    def __init__(self, x, color):
        self.rect = pygame.Rect(0, 0, PADDLE_W, PADDLE_H)
        self.rect.center = (x, HEIGHT // 2)
        self.color = color
        self.y = float(self.rect.y)

    def move(self, dy):
        self.y = max(0, min(HEIGHT - PADDLE_H, self.y + dy))
        self.rect.y = round(self.y)


class Ball:
    def __init__(self):
        self.rect = pygame.Rect(0, 0, BALL, BALL)
        self.reset(direction=1)

    def reset(self, direction):
        self.pos = pygame.Vector2(WIDTH / 2, HEIGHT / 2)
        self.vel = pygame.Vector2(0, 0)
        self.direction = direction
        self.rect.center = (round(self.pos.x), round(self.pos.y))

    def serve(self, rng):
        angle = rng.uniform(-0.6, 0.6)
        speed = 320
        self.vel = pygame.Vector2(math.cos(angle) * speed * self.direction, math.sin(angle) * speed)

    @property
    def moving(self):
        return self.vel.length_squared() > 0


class Game:
    def __init__(self, seed=None):
        self.rng = random.Random(seed)
        self.font = pygame.font.Font(None, 72)
        self.small = pygame.font.Font(None, 28)
        self.player = Paddle(30, BLUE)
        self.cpu = Paddle(WIDTH - 30, YELLOW)
        self.ball = Ball()
        self.scores = [0, 0]
        self.winner = None
        self.cpu_speed = 260

    def handle_event(self, event):
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            if self.winner is not None:
                self.__init__()
            elif not self.ball.moving:
                self.ball.serve(self.rng)
        elif event.type == pygame.MOUSEBUTTONDOWN and not self.ball.moving and self.winner is None:
            self.ball.serve(self.rng)

    def update(self, dt, keys=None):
        if keys is None:
            keys = pygame.key.get_pressed()
        speed = 360 * dt
        if keys[pygame.K_UP] or keys[pygame.K_w]:
            self.player.move(-speed)
        if keys[pygame.K_DOWN] or keys[pygame.K_s]:
            self.player.move(speed)

        # Computer: follows the ball with a speed limit and a small dead zone.
        target = self.ball.pos.y if self.ball.vel.x > 0 else HEIGHT / 2
        diff = target - self.cpu.rect.centery
        if abs(diff) > 10:
            self.cpu.move(max(-self.cpu_speed * dt, min(self.cpu_speed * dt, diff)))

        if not self.ball.moving or self.winner is not None:
            return
        b = self.ball
        b.pos += b.vel * dt
        b.rect.center = (round(b.pos.x), round(b.pos.y))

        if b.rect.top <= 0 and b.vel.y < 0 or b.rect.bottom >= HEIGHT and b.vel.y > 0:
            b.vel.y *= -1

        for paddle, side in ((self.player, 1), (self.cpu, -1)):
            if b.rect.colliderect(paddle.rect) and b.vel.x * side < 0:
                # -1 at the top edge, +1 at the bottom edge of the paddle
                offset = (b.rect.centery - paddle.rect.centery) / (PADDLE_H / 2)
                offset = max(-1.0, min(1.0, offset))
                speed = min(b.vel.length() * 1.06, 760)
                angle = offset * math.radians(55)
                b.vel = pygame.Vector2(math.cos(angle) * speed * side, math.sin(angle) * speed)
                if side == 1:
                    b.rect.left = paddle.rect.right
                else:
                    b.rect.right = paddle.rect.left
                b.pos.x = b.rect.centerx

        if b.rect.right < 0:
            self.point(1)
        elif b.rect.left > WIDTH:
            self.point(0)

    def point(self, who):
        self.scores[who] += 1
        if self.scores[who] >= WIN_SCORE:
            self.winner = who
        self.ball.reset(direction=-1 if who == 0 else 1)

    def draw(self, surface):
        surface.fill(BG)
        for y in range(0, HEIGHT, 24):
            pygame.draw.rect(surface, LINE, (WIDTH // 2 - 2, y + 4, 4, 14))
        left = self.font.render(str(self.scores[0]), True, BLUE)
        right = self.font.render(str(self.scores[1]), True, YELLOW)
        surface.blit(left, left.get_rect(midtop=(WIDTH // 2 - 60, 18)))
        surface.blit(right, right.get_rect(midtop=(WIDTH // 2 + 60, 18)))
        pygame.draw.rect(surface, self.player.color, self.player.rect, border_radius=4)
        pygame.draw.rect(surface, self.cpu.color, self.cpu.rect, border_radius=4)
        pygame.draw.rect(surface, WHITE, self.ball.rect, border_radius=3)
        if self.winner is not None:
            msg = "You win!" if self.winner == 0 else "Computer wins"
            t = self.font.render(msg, True, WHITE)
            surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 10)))
            h = self.small.render("Press Space for a new match", True, WHITE)
            surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 40)))
        elif not self.ball.moving:
            h = self.small.render("Press Space to serve", True, WHITE)
            surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT - 40)))


async def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Pong - Pygame.net")
    clock = pygame.time.Clock()
    game = Game()
    running = True
    while running:
        dt = min(clock.tick(FPS) / 1000, 0.05)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            else:
                game.handle_event(event)
        game.update(dt)
        game.draw(screen)
        pygame.display.flip()
        await asyncio.sleep(0)
    pygame.quit()


if __name__ == "__main__":
    asyncio.run(main())

The code is released under the MIT license: use it, change it and build on it. See licenses.

Ideas to extend it#

  1. Add a two-player mode where the right paddle uses the arrow keys.
  2. Make the computer's speed increase as the score gets closer.
  3. Add sound effects for paddle hits and points (sound and music).
  4. Add spin: moving the paddle while hitting curves the ball.
  5. Let the player choose the winning score from a menu.
↑ ↓ to moveEnter to openEsc to close