> Source URL: /unit-3/resources/pygame-setup.guide
# Pygame Setup Guide

Pygame lets you build games and visual simulations with Python. You get a window, the ability to draw shapes and images, handle keyboard and mouse input, and play sounds. If you have ever wanted to make a game, this is a great way to start.

No game development experience is needed. Pygame handles the graphics and input — you write the logic that makes your game work.

## Quick Setup

If you have not used `uv` before, review the [Packages and uv](../../resources/packages.guide.md) guide first.

Open your terminal, navigate to your project folder, and run:

```bash
uv init
uv add pygame-ce
```

We use `pygame-ce` (Community Edition) instead of the original `pygame` package. It is actively maintained, faster, and fully compatible. You still import it as `pygame` in your code.

Create a file called `game.py`:

```python
import pygame

pygame.init()

screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill("black")

    pygame.draw.circle(screen, "blue", (400, 300), 40)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
```

Run it:

```bash
uv run python game.py
```

You should see a window with a blue circle on a black background. Close the window or press `Ctrl+C` in your terminal to quit.

## How Pygame Works

Every Pygame program follows the same pattern: the **game loop**. This loop runs many times per second (typically 60 times) and does three things each frame:

1. **Handle events** — check for keyboard presses, mouse clicks, and the window close button
2. **Update state** — move objects, check collisions, update scores
3. **Draw everything** — clear the screen, draw all objects in their new positions, then flip the display

```python
while running:
    # 1. Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 2. Update state
    x += speed

    # 3. Draw
    screen.fill("black")
    pygame.draw.rect(screen, "red", (x, y, 50, 50))
    pygame.display.flip()
    clock.tick(60)
```

The `clock.tick(60)` call limits the loop to 60 frames per second so your game runs at a consistent speed.

## Handling Input

Pygame gives you two ways to read keyboard input:

**Event-based** — fires once when a key is pressed or released. Good for menus, jumping, shooting.

```python
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            player_jump()
```

**State-based** — checks if a key is currently held down. Good for movement.

```python
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    player_x -= 5
if keys[pygame.K_RIGHT]:
    player_x += 5
```

## Recommended Project Structure

```
my-project/
├── game.py             # Main file (game loop, rendering)
├── logic.py            # Your business logic (game rules, scoring, physics)
├── assets/             # Images, sounds, fonts
│   ├── player.png
│   └── ...
├── data/               # Level data, high scores, config
├── pyproject.toml      # Dependencies (created by uv)
└── README.md
```

Put your game loop and drawing code in `game.py`. Put your game rules, collision detection, scoring, and any algorithms in `logic.py`. This separation matters — the logic in `logic.py` is the code you should understand deeply and be ready to explain.

## Project Ideas

Here are some ideas that are realistic for a 3-week timeline. Start with the simplest version that is playable, then add features.

**Snake** — The classic. Control a snake that grows when it eats food. Game over when you hit the walls or yourself. *MVP: a moving snake that eats one food item at a time, grows longer, and ends when it hits a wall.*

**Pong** — Two paddles, one ball. Can be single-player (vs. a simple AI) or two-player (shared keyboard). *MVP: one paddle controlled by the player, one that follows the ball, a bouncing ball, and a score counter.*

**Top-Down Maze Runner** — Navigate a character through a maze. Generate the maze from a grid or load it from a file. *MVP: a player that moves through a hardcoded maze, with walls that block movement, and a goal to reach.*

**Particle Simulation** — Simulate particles that move, bounce, attract, or repel each other. Great if you are interested in physics or generative art. *MVP: particles that spawn, move with velocity, and bounce off the edges of the window.*

**Simple Platformer** — A character that can run and jump across platforms. *MVP: a player with gravity, a few static platforms, and left/right/jump controls.*

## Tutorials and Resources

- [Pygame Getting Started](https://www.pygame.org/wiki/GettingStarted) — official wiki page covering installation, verification, and first steps
- [Pygame Documentation](https://www.pygame.org/docs/) — full API reference with a quick-start code example
- [Real Python: Pygame — A Primer](https://realpython.com/pygame-a-primer/) — comprehensive beginner tutorial covering the game loop, sprites, input, and collision
- [Real Python: Build an Asteroids Game](https://realpython.com/asteroids-game-python/) — step-by-step project building a full game with classes, sprites, and sound
- [Pygame Tutorials Index](https://www.pygame.org/wiki/tutorials) — community-curated list of tutorials from beginner to intermediate

## Agent Prompts

Use these prompts with your coding agent (Cursor, Claude Code, etc.) to get started. Copy and paste them, then modify to fit your project.

**Plan your game:**

```text
Read my project.spec.md. I want to build a [type of game] using Pygame. Help me think through what objects I need (player, enemies, items, etc.), what the game loop should do each frame, and what the simplest playable version looks like. Ask me questions to help narrow down the scope.
```

**Scaffold your project:**

```text
Read my project.spec.md and set up my Pygame project. Create game.py with the basic game loop, a window, and a placeholder player object I can move with arrow keys. Create logic.py with a simple function for the game rules. Explain how the game loop works so I understand the structure.
```

**Add a game mechanic:**

```text
Look at my game.py. I want to add [describe the mechanic — collision detection, scoring, enemies, etc.]. Show me how to implement it and put the core logic in logic.py. Explain how it works step by step so I can modify it later.
```

**Debug a visual issue:**

```text
My game is running but [describe the problem — the player is not showing up, things are flickering, movement is too fast, etc.]. Look at my game.py and help me figure out what is wrong. Explain what is happening in the game loop that causes this and how to fix it.
```


---

## Backlinks

The following sources link to this document:

- [Pygame Setup Guide](/unit-3/projects/final-project-checkpoint-1.project.llm.md)
- [Pygame Setup Guide](/unit-3/project-paths/edison-w/edison-w-2026-04-18.guide.llm.md)
- [Pygame Setup Guide](/unit-3/project-paths/edison-w/edison-w-2026-04-14.guide.llm.md)
- [Pygame Setup Guide](/unit-3/project-paths/yeoram-k/yeoram-k-2026-04-14.guide.llm.md)
