Breakout

Clear the wall of coloured bricks with a bouncing ball. Top rows are worth more, and each level is faster.

Intermediate2 min readUpdated
Breakout screenshot: rows of coloured bricks with gaps, a ball and a paddle
Screenshot captured from the Python source below running in pygame-ce.
Difficulty
Intermediate
Source size
183 lines, 1 file
Requires
Python 3.10+, pygame-ce or pygame
Assets
None (drawn in code)

Controls

  • Left Right A D or mouse Move the paddle
  • Space or click Launch the ball, next level, restart
On this page

What you'll learn#

  • Building a grid of objects with nested loops
  • Detecting which side of a brick was hit by moving one axis at a time
  • Using collidelist to find the brick that was hit
  • Lives, levels and a ready 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 breakout.py into any folder.
  3. Open a terminal in that folder and run python breakout.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#

Which side was hit?#

A ball that hits the side of a brick should reverse horizontally; one that hits the top or bottom should reverse vertically. The game moves the ball along x first and checks bricks, then along y and checks again. Whichever axis caused the overlap is the one to reverse. This is the same axis-separation idea used for walls in the collision detection tutorial.

Finding the brick quickly#

self.ball.collidelist(...) returns the index of the first brick the ball overlaps, or -1. Popping that index removes the brick and gives its row, which decides the points.

Controlling the angle#

Like Pong, the paddle maps the hit position to an angle, here up to 60 degrees either side of straight up. The ball's speed is preserved, so only its direction changes.

Complete source code#

breakout.pyDownloadRun online
"""Breakout - a Pygame.net game project.

Clear the wall of bricks with a bouncing ball. Top rows are worth more.
Each cleared wall starts a faster level; you have three lives.

Run it:   pip install pygame-ce     (or: pip install pygame)
          python breakout.py
Controls: Left/Right or A/D (or the mouse) to move, Space to launch or restart.
License:  MIT - https://pygame.net/licenses/
"""
import asyncio
import math

import pygame

WIDTH, HEIGHT = 640, 480
FPS = 60
COLS, ROWS = 10, 6
BRICK_W, BRICK_H, GAP = 58, 20, 4
TOP = 70

BG = (16, 26, 48)
WHITE = (230, 236, 247)
PADDLE = (157, 194, 255)
ROW_COLORS = [(232, 93, 82), (240, 140, 64), (244, 197, 49), (110, 200, 120), (91, 147, 230), (150, 120, 230)]


class Game:
    def __init__(self):
        self.font = pygame.font.Font(None, 30)
        self.big = pygame.font.Font(None, 64)
        self.score = 0
        self.lives = 3
        self.level = 1
        self.state = "ready"   # ready, playing, won_level, over
        self.paddle = pygame.Rect(0, 0, 90, 12)
        self.paddle.midbottom = (WIDTH // 2, HEIGHT - 24)
        self.paddle_x = float(self.paddle.x)
        self.build_wall()
        self.reset_ball()

    def build_wall(self):
        left = (WIDTH - (COLS * BRICK_W + (COLS - 1) * GAP)) // 2
        self.bricks = []
        for r in range(ROWS):
            for c in range(COLS):
                rect = pygame.Rect(left + c * (BRICK_W + GAP), TOP + r * (BRICK_H + GAP), BRICK_W, BRICK_H)
                self.bricks.append((rect, r))

    def reset_ball(self):
        self.ball = pygame.Rect(0, 0, 10, 10)
        self.ball_pos = pygame.Vector2(self.paddle.centerx, self.paddle.top - 8)
        self.ball_vel = pygame.Vector2(0, 0)
        self.sync_ball()

    def sync_ball(self):
        self.ball.center = (round(self.ball_pos.x), round(self.ball_pos.y))

    def launch(self):
        speed = 300 + 30 * (self.level - 1)
        self.ball_vel = pygame.Vector2(speed * 0.45, -speed * 0.89)
        self.state = "playing"

    def handle_event(self, event):
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE or event.type == pygame.MOUSEBUTTONDOWN:
            if self.state == "ready":
                self.launch()
            elif self.state == "won_level":
                self.level += 1
                self.build_wall()
                self.reset_ball()
                self.state = "ready"
            elif self.state == "over":
                self.__init__()
        elif event.type == pygame.MOUSEMOTION:
            self.paddle_x = event.pos[0] - self.paddle.width / 2

    def move_paddle(self, dt, keys):
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.paddle_x -= 460 * dt
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.paddle_x += 460 * dt
        self.paddle_x = max(0, min(WIDTH - self.paddle.width, self.paddle_x))
        self.paddle.x = round(self.paddle_x)

    def update(self, dt, keys=None):
        if keys is None:
            keys = pygame.key.get_pressed()
        self.move_paddle(dt, keys)
        if self.state == "ready":
            self.ball_pos.update(self.paddle.centerx, self.paddle.top - 8)
            self.sync_ball()
            return
        if self.state != "playing":
            return

        # Move one axis at a time so we know which side of a brick was hit.
        self.ball_pos.x += self.ball_vel.x * dt
        self.sync_ball()
        if self.ball.left <= 0 or self.ball.right >= WIDTH:
            self.ball_vel.x *= -1
            self.ball_pos.x = max(5, min(WIDTH - 5, self.ball_pos.x))
        hit = self.hit_brick()
        if hit:
            self.ball_vel.x *= -1
            self.ball_pos.x += self.ball_vel.x * dt

        self.ball_pos.y += self.ball_vel.y * dt
        self.sync_ball()
        if self.ball.top <= 0:
            self.ball_vel.y = abs(self.ball_vel.y)
        hit = self.hit_brick()
        if hit:
            self.ball_vel.y *= -1
            self.ball_pos.y += self.ball_vel.y * dt

        if self.ball.colliderect(self.paddle) and self.ball_vel.y > 0:
            offset = (self.ball.centerx - self.paddle.centerx) / (self.paddle.width / 2)
            offset = max(-1.0, min(1.0, offset))
            speed = self.ball_vel.length()
            angle = math.radians(-90 + offset * 60)
            self.ball_vel = pygame.Vector2(math.cos(angle) * speed, math.sin(angle) * speed)
            self.ball_pos.y = self.paddle.top - 6

        if self.ball.top > HEIGHT:
            self.lives -= 1
            if self.lives <= 0:
                self.state = "over"
            else:
                self.state = "ready"
                self.reset_ball()
        self.sync_ball()

    def hit_brick(self):
        index = self.ball.collidelist([b[0] for b in self.bricks])
        if index == -1:
            return False
        _, row = self.bricks.pop(index)
        self.score += (ROWS - row) * 10
        if not self.bricks:
            self.state = "won_level"
            self.ball_vel.update(0, 0)
        return True

    def draw(self, surface):
        surface.fill(BG)
        for rect, row in self.bricks:
            pygame.draw.rect(surface, ROW_COLORS[row], rect, border_radius=3)
            pygame.draw.line(surface, (255, 255, 255), rect.topleft, (rect.right - 1, rect.top), 1)
        pygame.draw.rect(surface, PADDLE, self.paddle, border_radius=6)
        pygame.draw.circle(surface, WHITE, self.ball.center, 5)
        surface.blit(self.font.render(f"Score {self.score}", True, WHITE), (16, 18))
        lv = self.font.render(f"Level {self.level}   Lives {self.lives}", True, WHITE)
        surface.blit(lv, (WIDTH - lv.get_width() - 16, 18))
        msg = {"ready": "Press Space to launch", "won_level": "Wall cleared! Space for next level", "over": "Game over - Space to restart"}.get(self.state)
        if msg:
            t = self.font.render(msg, True, (244, 197, 49))
            surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 60)))


async def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Breakout - Pygame.net")
    clock = pygame.time.Clock()
    game = Game()
    running = True
    while running:
        dt = min(clock.tick(FPS) / 1000, 0.03)
        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 bricks that take two hits and change colour when damaged.
  2. Drop a power-up from some bricks that widens the paddle for ten seconds.
  3. Design levels as text grids, like the platformer does.
  4. Add a particle burst when a brick breaks.
  5. Show a lives indicator with small paddle icons.
↑ ↓ to moveEnter to openEsc to close