Breakout

Bounce the ball with the paddle, smash the coloured bricks (top rows score more) and do not let the ball drop. Teaches how a sprite finds a character on the screen, a grid of bricks, points and lives.

Open in Tokbit Level: Expert. Free in the browser, nothing to install, no account needed.

Run the example in Tokbit and step through it: before each step say what will happen and check it in the Variables panel. Then change it your way.

Flowchart

Flowchart of the Breakout example

Python program

The same program as Python code. In Tokbit you see it when you switch from Diagram to Python above the flowchart.

"""The classic Breakout: bounce the ball with the paddle and knock down the brick wall. Teaches sprite-character collision, a grid of bricks, points and lives."""
# Tokbit screen functions, not in plain Python:
from tokbit import (
    cls, at, color, background, border, char_at, key, sleep, beep, note,
    sprite_at, sprite_color, sprite_hide, sprite_shape, BLACK, WHITE, RED,
    CYAN, GREEN, YELLOW, ORANGE, LIGHT_RED, DARK_GREY, LIGHT_GREEN, LIGHT_GREY,
)

def build_wall():
    """A wall of 5 rows of 10 bricks; a brick is 4 characters, each row has its colour."""
    colors: list[int] = [RED, ORANGE, YELLOW, GREEN, CYAN]
    for r in range(5):
        color(colors[r])
        for c in range(10):
            at(c * 4, r + 3)
            print("[##]", end="")

def show_status(score: int, lives: int):
    """Score and lives at the top."""
    color(WHITE)
    at(0, 0)
    print("Score: " + str(score) + "   Lives: " + str(lives) + "  ", end="")

def move_paddle(x: int, k: str) -> int:
    """The paddle moves 16 points with the arrows and stays on the screen (it is 32 points wide)."""
    if k == "left":
        return max(0, x - 16)
    if k == "right":
        return min(288, x + 16)
    return x

def bounce(ball: int, paddle: int, speed: int) -> int:
    """The bounce off the paddle depends on where the ball hits, as in Tennis: left edge to the left, right edge to the right, middle straight up."""
    d: int = ball + 2 - paddle
    if d < 11:
        return -speed
    if d > 21:
        return speed
    return 0

def hit_brick(ball: list[int]) -> int:
    """Hitting a brick: erases it (with a flash), bounces the ball and returns points (top row 5, bottom 1), otherwise 0."""
    col: int = (ball[0] + 2) // 8
    row: int = (ball[1] + 2) // 8
    if row < 3 or row > 7 or col < 0 or col > 39:
        return 0
    # Sprite × character collision: what is on the screen where the ball is.
    if char_at(col, row) == " ":
        return 0
    start: int = col // 4 * 4
    color(WHITE)
    at(start, row)
    print("****", end="")
    # The pitch depends on the row; the tone also lets the brick flash.
    beep(900 - row * 100, 30)
    at(start, row)
    print("    ", end="")
    ball[3] = -ball[3]
    return 8 - row

def lose_ball():
    """Losing a life: the paddle flashes and the tone falls."""
    # The paddle flashes red and the tone falls.
    for i in range(6):
        if i % 2 == 0:
            sprite_color(1, RED)
            sprite_color(2, RED)
        else:
            sprite_color(1, LIGHT_GREY)
            sprite_color(2, LIGHT_GREY)
        beep(200 - i * 20, 60)
    sprite_color(1, LIGHT_GREY)
    sprite_color(2, LIGHT_GREY)

def game_over(win: bool, score: int):
    """The end: a win with a fanfare, or a loss."""
    for n in range(3):
        sprite_hide(n)
    if win:
        color(LIGHT_GREEN)
        at(10, 12)
        print("THE WALL IS DOWN!", end="")
        notes: list[str] = ["C4", "E4", "G4", "C5", "G4", "C5"]
        for i in range(len(notes)):
            note(notes[i], 120)
    else:
        color(LIGHT_RED)
        at(14, 12)
        print("GAME OVER", end="")
        beep(110, 400)
    color(WHITE)
    at(12, 14)
    print("Score: " + str(score), end="")

background(BLACK)
border(DARK_GREY)
cls()
# The ball: a small round shape in the corner of the grid.
ball_shape: list[str] = [".##.............", "####............", "####............", ".##.............", "................", "................", "................", "................", "................", "................", "................", "................", "................", "................", "................", "................"]
# The paddle from two sprites side by side (32 points).
paddle_l: list[str] = ["................", "................", "................", "................", "................", "................", "................", "................", "................", "................", "................", "................", "..##############", ".###############", ".###############", "..##############"]
paddle_r: list[str] = ["................", "................", "................", "................", "................", "................", "................", "................", "................", "................", "................", "................", "##############..", "###############.", "###############.", "##############.."]
sprite_shape(0, ball_shape)
sprite_color(0, WHITE)
sprite_shape(1, paddle_l)
sprite_shape(2, paddle_r)
sprite_color(1, LIGHT_GREY)
sprite_color(2, LIGHT_GREY)
build_wall()
# The ball: x, y, horizontal and vertical step.
ball: list[int] = [150, 150, 2, -2]
paddle: int = 144
speed: int = 2
score: int = 0
lives: int = 3
bricks: int = 50
show_status(score, lives)
# The game loop: paddle, ball movement, bounces off walls, bricks and the paddle, losing a life, while there are lives and bricks.
while lives > 0 and bricks > 0:
    paddle = move_paddle(paddle, key())
    ball[0] = ball[0] + ball[2]
    ball[1] = ball[1] + ball[3]
    if ball[0] < 0 or ball[0] > 316:
        ball[2] = -ball[2]
        ball[0] = max(0, min(316, ball[0]))
    if ball[1] < 8:
        ball[3] = speed
        ball[1] = 8
    points: int = hit_brick(ball)
    if points > 0:
        score = score + points
        bricks = bricks - 1
        # Every 10 bricks the ball speeds up, up to 4 points per frame.
        if bricks % 10 == 0 and speed < 4:
            speed = speed + 1
        show_status(score, lives)
    sprite_at(1, paddle, 176)
    sprite_at(2, paddle + 16, 176)
    sprite_at(0, ball[0], ball[1])
    # Bouncing off the paddle: the ball is falling and crossed the paddle's top edge (y 188) above it in this frame. Also catches a fast ball that would otherwise jump over the paddle.
    if ball[3] > 0 and ball[1] + 4 >= 188 and ball[1] + 4 - ball[3] <= 192 and paddle - 3 <= ball[0] <= paddle + 31:
        ball[1] = 184
        ball[3] = -speed
        ball[2] = bounce(ball[0], paddle, speed)
        if ball[2] == 0:
            ball[2] = 1
        beep(440, 20)
    if ball[1] > 196:
        lives = lives - 1
        lose_ball()
        show_status(score, lives)
        ball = [paddle + 14, 150, 2, -speed]
    sleep(20)
game_over(bricks == 0, score)

All examples