Build your first game

Put windows, input, movement and collisions together into a complete game. You will build Star Catcher, where you move a basket to catch falling stars.

Beginner3 min readUpdated
On this page

What you'll learn

  • How to plan a small game before coding
  • Organising a game into settings, objects, setup and a main loop
  • Spawning objects over time and removing them safely
  • Score, lives, difficulty and a restart screen

Prerequisites: The game loop, keyboard input and collision detection (the rect section is enough).

Star Catcher: a blue basket at the bottom, yellow stars falling, score and lives at the top
The finished Star Catcher game

Plan the game#

Write down the rules before writing code. For Star Catcher:

  • The player moves a basket left and right along the bottom.
  • Stars fall from random positions at the top.
  • Catching a star scores a point. Missing one costs a life. Three misses and the game is over.
  • Stars fall faster and appear more often as the score grows.
  • Space restarts after a game over.

Each rule maps to a few lines of code. When a game feels too big to start, the plan is too vague: break it down further.

Step 1: Settings#

Collect numbers you may want to tweak at the top of the file. Changing PLAYER_SPEED later is easier than hunting through the code.

catch_game.py (settings)
"""Star Catcher: the complete game from the "Build your first game" tutorial."""
import random

import pygame

# --- Settings ---------------------------------------------------------------
WIDTH, HEIGHT = 640, 480
FPS = 60
PLAYER_SPEED = 400        # pixels per second
START_LIVES = 3

BG = (20, 26, 46)
WHITE = (230, 236, 247)
YELLOW = (244, 197, 49)
BLUE = (91, 147, 230)
RED = (232, 93, 82)

Step 2: The game objects#

Each kind of object gets a class with update and draw methods. Positions are stored as floats (self.x, self.y) for smooth movement, and copied into the Rect used for drawing and collisions.

catch_game.py (game objects)
# --- Game objects ------------------------------------------------------------
class Basket:
    def __init__(self):
        self.rect = pygame.Rect(0, 0, 90, 20)
        self.rect.midbottom = (WIDTH // 2, HEIGHT - 20)
        self.x = float(self.rect.x)

    def update(self, dt, keys):
        direction = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a])
        self.x += direction * PLAYER_SPEED * dt
        self.x = max(0, min(WIDTH - self.rect.width, self.x))
        self.rect.x = round(self.x)

    def draw(self, surface):
        pygame.draw.rect(surface, BLUE, self.rect, border_radius=6)


class Star:
    def __init__(self, speed):
        self.rect = pygame.Rect(random.randint(10, WIDTH - 30), -20, 20, 20)
        self.y = float(self.rect.y)
        self.speed = speed

    def update(self, dt):
        self.y += self.speed * dt
        self.rect.y = round(self.y)

    def draw(self, surface):
        pygame.draw.circle(surface, YELLOW, self.rect.center, 10)

The basket reads the keyboard state each frame, so holding a key moves it smoothly. max(0, min(...)) keeps it inside the window.

Step 3: Setup and game state#

new_game() returns a dictionary holding everything that changes during a game. Restarting is then just game = new_game(), with no risk of forgetting to reset a variable.

catch_game.py (setup)
# --- Setup -------------------------------------------------------------------
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Star Catcher")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
big_font = pygame.font.Font(None, 72)


def new_game():
    return {"basket": Basket(), "stars": [], "score": 0, "lives": START_LIVES,
            "spawn_timer": 0.0, "over": False}


game = new_game()

Step 4: The main loop#

catch_game.py (main loop)
# --- Main loop ---------------------------------------------------------------
running = True
while running:
    dt = clock.tick(FPS) / 1000

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and game["over"]:
            game = new_game()

    if not game["over"]:
        keys = pygame.key.get_pressed()
        game["basket"].update(dt, keys)

        # Spawn stars faster as the score goes up.
        game["spawn_timer"] -= dt
        if game["spawn_timer"] <= 0:
            speed = 180 + game["score"] * 6
            game["stars"].append(Star(speed))
            game["spawn_timer"] = max(0.35, 1.0 - game["score"] * 0.02)

        for star in game["stars"][:]:          # iterate over a copy so we can remove
            star.update(dt)
            if star.rect.colliderect(game["basket"].rect):
                game["stars"].remove(star)
                game["score"] += 1
            elif star.rect.top > HEIGHT:
                game["stars"].remove(star)
                game["lives"] -= 1
                if game["lives"] <= 0:
                    game["over"] = True

    # Draw
    screen.fill(BG)
    for star in game["stars"]:
        star.draw(screen)
    game["basket"].draw(screen)
    screen.blit(font.render(f"Score: {game['score']}", True, WHITE), (16, 12))
    lives_text = font.render(f"Lives: {game['lives']}", True, RED)
    screen.blit(lives_text, (WIDTH - lives_text.get_width() - 16, 12))
    if game["over"]:
        text = big_font.render("Game over", True, YELLOW)
        screen.blit(text, text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 20)))
        hint = font.render("Press Space to play again", True, WHITE)
        screen.blit(hint, hint.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 30)))
    pygame.display.flip()

pygame.quit()

Points worth studying:

  • Spawning with a timer. spawn_timer counts down by dt. When it reaches zero a star appears and the timer resets to a delay that shrinks with the score, never below 0.35 seconds.
  • Difficulty. Each star's speed is 180 + score × 6, so the game ramps up smoothly.
  • Removing while looping. for star in game["stars"][:] loops over a copy, so removing stars from the real list doesn't skip any.
  • Game over freezes updates but keeps drawing, so the final screen stays visible under the message.

The complete program#

catch_game.pyDownload
"""Star Catcher: the complete game from the "Build your first game" tutorial."""
import random

import pygame

# --- Settings ---------------------------------------------------------------
WIDTH, HEIGHT = 640, 480
FPS = 60
PLAYER_SPEED = 400        # pixels per second
START_LIVES = 3

BG = (20, 26, 46)
WHITE = (230, 236, 247)
YELLOW = (244, 197, 49)
BLUE = (91, 147, 230)
RED = (232, 93, 82)


# --- Game objects ------------------------------------------------------------
class Basket:
    def __init__(self):
        self.rect = pygame.Rect(0, 0, 90, 20)
        self.rect.midbottom = (WIDTH // 2, HEIGHT - 20)
        self.x = float(self.rect.x)

    def update(self, dt, keys):
        direction = (keys[pygame.K_RIGHT] or keys[pygame.K_d]) - (keys[pygame.K_LEFT] or keys[pygame.K_a])
        self.x += direction * PLAYER_SPEED * dt
        self.x = max(0, min(WIDTH - self.rect.width, self.x))
        self.rect.x = round(self.x)

    def draw(self, surface):
        pygame.draw.rect(surface, BLUE, self.rect, border_radius=6)


class Star:
    def __init__(self, speed):
        self.rect = pygame.Rect(random.randint(10, WIDTH - 30), -20, 20, 20)
        self.y = float(self.rect.y)
        self.speed = speed

    def update(self, dt):
        self.y += self.speed * dt
        self.rect.y = round(self.y)

    def draw(self, surface):
        pygame.draw.circle(surface, YELLOW, self.rect.center, 10)


# --- Setup -------------------------------------------------------------------
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Star Catcher")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
big_font = pygame.font.Font(None, 72)


def new_game():
    return {"basket": Basket(), "stars": [], "score": 0, "lives": START_LIVES,
            "spawn_timer": 0.0, "over": False}


game = new_game()

# --- Main loop ---------------------------------------------------------------
running = True
while running:
    dt = clock.tick(FPS) / 1000

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and game["over"]:
            game = new_game()

    if not game["over"]:
        keys = pygame.key.get_pressed()
        game["basket"].update(dt, keys)

        # Spawn stars faster as the score goes up.
        game["spawn_timer"] -= dt
        if game["spawn_timer"] <= 0:
            speed = 180 + game["score"] * 6
            game["stars"].append(Star(speed))
            game["spawn_timer"] = max(0.35, 1.0 - game["score"] * 0.02)

        for star in game["stars"][:]:          # iterate over a copy so we can remove
            star.update(dt)
            if star.rect.colliderect(game["basket"].rect):
                game["stars"].remove(star)
                game["score"] += 1
            elif star.rect.top > HEIGHT:
                game["stars"].remove(star)
                game["lives"] -= 1
                if game["lives"] <= 0:
                    game["over"] = True

    # Draw
    screen.fill(BG)
    for star in game["stars"]:
        star.draw(screen)
    game["basket"].draw(screen)
    screen.blit(font.render(f"Score: {game['score']}", True, WHITE), (16, 12))
    lives_text = font.render(f"Lives: {game['lives']}", True, RED)
    screen.blit(lives_text, (WIDTH - lives_text.get_width() - 16, 12))
    if game["over"]:
        text = big_font.render("Game over", True, YELLOW)
        screen.blit(text, text.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 20)))
        hint = font.render("Press Space to play again", True, WHITE)
        screen.blit(hint, hint.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 30)))
    pygame.display.flip()

pygame.quit()

Run it with python catch_game.py. Use the arrow keys or A and D to move.

Common mistakes#

  • Stars falling at different speeds on different computers: multiply movement by dt, as here.
  • Game over triggers several times: guard updates with if not game["over"].
  • Everything restarts except one variable: keep all per-game values in one place (the new_game() dictionary or a class).

Make it yours#

  1. Add a bad object (a red bomb) that ends the game when caught.
  2. Give the basket a speed boost while holding Shift.
  3. Add sounds for catching and missing, following sound and music.
  4. Add a title screen and a saved high score using menus and the score system.
  5. Replace the circles with images from the pixel art editor.

When you're ready for a bigger project, read through the Snake and Breakout source code. They use the same structure with a few more ideas.

↑ ↓ to moveEnter to openEsc to close