Files
agentic-labs-challenge/underdepths/plan.md
T

22 KiB
Raw Blame History

Underdepths — Game Design Document

A turn-based roguelike dungeon crawler. Descend through 10 procedurally generated floors, fight monsters with distinct AI behaviors, collect items, level up, and slay the boss on the final floor. Permadeath with save/quit/reload.

Tech Stack

  • Python 3.11+
  • pygame-ce for rendering, input, and simple generated sound effects (colored tile grid, not ASCII)
  • No other dependencies. Everything else is stdlib.

Architecture

main.py              # entry point, game loop, state machine
engine/
  game_state.py      # GameSession: holds all mutable state, save/load
  map_gen.py         # BSP dungeon generation
  fov.py             # Recursive shadowcasting
  pathfinding.py     # A* on the dungeon grid
  combat.py          # Damage calculation, hit resolution
  serializers.py     # JSON save/load
entities/
  entity.py          # Base Entity: position, sprite key, name
  player.py          # Player: stats, inventory, leveling
  enemy.py           # Enemy: AI behavior type, stats
  item.py            # Item: type, effect, equipment data
ai/
  behaviors.py       # AI dispatch: wander, chase, flee, ranged, split
data/
  enemies.py         # Enemy roster (stats per type)
  items.py           # Item catalog
  constants.py       # Tuning constants, palettes, key bindings
  sprites.py         # Pixel-art patterns: 2D palette-key grids per entity/tile/item
render/
  renderer.py        # Compose map, entities, UI panels (pure read of state)
  sprites.py         # Rasterize pixel-art grids to cached Surfaces
  effects.py         # Lighting/vignette, particles, screen-shake, HP bars
  camera.py          # Viewport offset (smooth easing follow player)

This is a guideline, not a cage. Merge files if it's simpler. The only hard rule: GameSession is the single source of truth for all mutable state, and it's what gets serialized.

Core Data Model

@dataclass
class GameSession:
    player: Player
    dungeon: list[GameMap]       # all 10 floors, generated up front
    current_floor: int
    log: list[str]               # message log (last 50)
    turn: int
    state: str                   # "playing", "dead", "victory", "menu"

@dataclass
class GameMap:
    width: int                   # 80
    height: int                  # 50
    tiles: np.ndarray            # 0=wall, 1=floor (use array.array if numpy not available)
    rooms: list[Rect]            # rooms placed by BSP
    explored: np.ndarray         # bool grid — tiles player has seen
    visible: np.ndarray          # bool grid — tiles player sees this turn
    entities: list[Entity]       # enemies + items on this floor
    stairs_down: tuple[int, int] # position of stairs (except floor 9)
    floor_index: int

Systems

1. Procedural Dungeon Generation (map_gen.py)

Algorithm: BSP Tree

  1. Start with the full map as all walls.
  2. Recursively split the map into two regions (alternate horizontal/vertical), 5–8 splits total.
  3. For each leaf region, carve a room (fill a random sub-rectangle as floor, shrink 1-2 tiles from region edges).
  4. Connect sibling regions with L-shaped corridors.
  5. Place stairs down in the last room generated (rooms farthest from spawn).
  6. Spawn enemies and items per floor (see distribution below).

Room size: 4×4 to 10×8 tiles. Map size: 80×50 tiles. 1-tile wall border.

Per-floor spawning (scaled by depth):

Floor Enemies Items
0–1 3–4 2–3
2–3 4–6 2–3
4–5 5–7 3–4
6–7 6–8 3–4
8 7–9 4–5
9 0 (boss arena) 2 (healing potions)

Enemies on each floor are drawn from the roster, gated by depth (see Enemy Roster). Items are drawn from the item catalog.

Generate all 10 floors at game start. This makes save/load simpler (serialize all floors).

2. Field of View (fov.py)

Algorithm: Recursive Shadowcasting (8 octants).

Write this from scratch — do not use a library. The algorithm:

  1. Start from the player's position.
  2. For each of 8 octants, cast shadows recursively.
  3. A tile is visible if there's an unblocked line from the player.
  4. Walls block sight (but are themselves visible if adjacent to a visible floor tile).
  5. Sight radius: 8 tiles.

Mark visible tiles on the visible grid each turn. After computing, merge visible into explored (once explored, always remembered — rendered darker).

3. A* Pathfinding (pathfinding.py)

Grid-based A with Manhattan heuristic.*

Write from scratch. Used by enemies to path toward the player when chasing.

  • Walkable: floor tiles that are not occupied by another entity.
  • Obstacles: walls, closed doors, other enemies (treat as impassable so enemies don't stack).
  • Heuristic: Manhattan distance.
  • Recompute path each turn the enemy is actively chasing (positions change).
  • Fallback: if no path found (fully blocked), enemy wanders or waits.

4. Combat (combat.py)

Turn-based. Player moves/attacks into an enemy → melee attack. Enemy adjacent to player → melee attack.

Hit resolution:

hit_chance = clamp(0.7 + (attacker.accuracy - defender.evasion) * 0.05, 0.1, 0.95)
if random() < hit_chance: hit
else: miss (log "X misses Y")

Damage calculation:

base = attacker.power + weapon_bonus
reduced = max(0, base - defender.armor)
is_crit = random() < attacker.crit_chance
damage = reduced * (2 if is_crit else 1)
defender.hp -= damage

Log all combat events: "You hit the Goblin for 8 damage!", "Goblin misses you", "Critical hit! You hit the Orc for 24 damage!", "You defeated the Goblin! (+15 XP)".

Death: HP ≤ 0. Enemy death → remove from map, award XP. Player death → state = "dead", game over.

5. Enemy AI (ai/behaviors.py)

Each enemy has a behavior type. Each turn (after player acts), all enemies act in order.

Behaviors:

Type Trigger Action
wander Always Move 1 tile in a random walkable direction, or wait (50/50). Never seeks player.
chase Player visible A* path toward player. Adjacent → melee attack.
chase Player not visible Move toward player's last known position. If reached and still no sight → wander.
flee HP < 30% max Move away from player (maximize distance). Otherwise behaves as chase.
ranged Player visible, distance > 3 Fire projectile (arrow/bolt). Damage = fixed ranged power, hit_chance with distance penalty.
ranged Player visible, distance ≤ 2 Step away from player (kiting).
ranged Player not visible Wander.
phase Always Move toward player ignoring walls (can pass through walls), but slower (acts every 2 turns). Adjacent → melee.
split HP ≤ threshold On death, spawn 2 smaller copies of self (half HP, half power). Only splits once (spawned copies don't split).

Last known position: Each enemy with chase/ranged behavior tracks the last tile where it saw the player. Updated whenever the player is in FOV.

6. Items & Inventory (entities/item.py)

Inventory: 26-slot (arbitrary large). Player picks up items by walking over them and pressing g.

Item types:

Category Effect
Weapon Equips to weapon slot. Adds power bonus.
Armor Equips to armor slot. Adds armor (damage reduction).
Potion (healing) Restores 30 HP. Consumed on use.
Potion (strength) +5 power for 20 turns. Consumed on use.
Potion (invisibility) Enemies can't see you for 15 turns. Consumed on use.
Scroll (fireball) Deals 20 damage to all enemies within 3 tiles of target position.
Scroll (teleport) Teleports player to a random walkable tile on the current floor.
Scroll (mapping) Reveals entire current floor (all tiles set to explored).

Equipment: One weapon slot, one armor slot. Equipping replaces the current item (old one goes to inventory).

Item catalog (base game):

Item Type Stats
Rusty Dagger Weapon power +2
Short Sword Weapon power +4
Battle Axe Weapon power +7
War Hammer Weapon power +10, crit_chance -5%
Leather Armor Armor armor 2
Chain Mail Armor armor 4
Plate Armor Armor armor 7, evasion -10%
Healing Potion Potion heal 30
Strength Potion Potion +5 power / 20 turns
Invisibility Potion Potion invisible / 15 turns
Scroll of Fireball Scroll 20 dmg AoE radius 3
Scroll of Teleport Scroll random relocate
Scroll of Mapping Scroll reveal floor

Item distribution by depth: better weapons/armor appear deeper. Potions and scrolls are uniform across depth.

7. Progression (entities/player.py)

XP and Leveling:

Level XP Required (cumulative) HP Gain Power Gain
1→2 30 +10 +1
2→3 70 +10 +1
3→4 140 +10 +1
4→5 250 +10 +1
5→6 400 +15 +2
6→7 600 +15 +2
7→8 850 +15 +2
8→9 1150 +15 +2
9→10 1500 +20 +3

Level-up fully heals the player. Log: "You reach level N! (HP +X, Power +Y)".

Base player stats:

hp: 50, max_hp: 50
power: 4
armor: 0
accuracy: 5 (flat bonus to hit_chance)
evasion: 2 (flat penalty to enemy hit_chance)
crit_chance: 0.10
speed: 1 (acts every turn)

8. Save/Load (engine/serializers.py)

JSON serialization.

On S key: serialize GameSession to save.json in the game directory. Quit the game.

On startup: if save.json exists, offer "Continue" in the menu. Load restores exact state — player stats, inventory, current floor, explored tiles, entity positions, turn counter.

Serialize:

  • Player: all stats, level, XP, inventory, equipped items, position
  • Dungeon: all 10 floors (tiles, explored, entities, stairs position)
  • current_floor, turn, log

Do NOT serialize: visible grid (recomputed on load via FOV), temporary effect timers? Actually DO serialize timers (strength potion, invisibility) with remaining turns.

Permadeath rule: On death, delete save.json. Cannot continue after death.

9. Game Flow & States

State machine:

menu → playing → dead (game over screen, delete save)
               → victory (win screen, delete save)
               → saved (quit to menu, save persists)

Main menu:

  • "New Game" — generates fresh dungeon, then shows How to Play before the first turn
  • "Continue" — only if save.json exists
  • "How to Play" — always available; explains every key and the pickup/descent steps
  • "Quit"

Death screen: "You died on floor N. You reached level M." Press any key → menu. Victory screen: "You slew the Ancient Dragon! You conquered Underdepths." Press any key → menu.

Controls

The controls must be explained inside the game, not only in this document. Show a How to Play screen from the main menu and before the first turn of every New Game. The ? key reopens it during play. Keep the explanation plain:

  1. Move onto an item's tile, then press g to pick it up.
  2. Move onto the yellow > stairs tile, then press f to descend.
  3. Walking into an enemy attacks it. Item menus show their own selection keys.
Key Action
Arrows / hjkl Move / melee attack (walk into enemy)
g Pick up the item under the player
i Open inventory
e Open equipment (view equipped, equip from inventory)
q Quaff a potion (select from inventory)
r Read a scroll (select from inventory)
f Descend — only while standing on the yellow stairs tile (a plain letter so it works in every keyboard locale)
S Save and quit
? Open How to Play
m Mute/unmute sound effects
Esc Close menus / cancel

Enemy Roster

Enemy Floors HP Power Armor Speed Behavior XP Notes
Rat 0–3 8 3 0 1 wander 5 Weak, ignores player
Goblin 0–5 15 5 1 1 chase 12 A* pathfinds to player
Skeleton Archer 2–7 12 4 (ranged: 6) 1 1 ranged 15 Kites, shoots from distance
Orc Warrior 3–8 30 8 3 1 flee 25 Tanky, flees when low
Wraith 5–8 20 10 0 2 (slow) phase 30 Moves through walls, acts every 2 turns
Green Slime 4–8 18 5 1 1 split 18 Splits into 2 Small Slimes (HP 9) on death. Small slimes don't split.
Ancient Dragon (boss) 9 120 15 8 1 chase + special 200 Every 3rd turn: breath weapon — 15 damage to all tiles in a line toward player. Floor 9 only.

Floor 9 (boss arena): Single large room (20×15). Dragon starts on the far side. Two healing potions placed near entrance. No other enemies. Stairs appear (or victory triggers) only after dragon is dead.

Rendering

The look is procedural pixel-art: every entity, tile, and UI icon is a hand-authored pixel pattern drawn with pygame.draw.rect — never a flat colored square, never an external image file. Aim for a clean, detailed retro-roguelike feel.

Pixel-art sprites

  • Define each sprite in data/sprites.py as a 2D grid of single-character palette keys (e.g. "." transparent, "K" outline, "W"/"s"/"h" shades), roughly 12×12 to 16×16 cells. render/sprites.py rasterizes a grid to a pygame.Surface once (keyed by name + frame) and caches it; the renderer blits the cached surface scaled to TILE.
  • Every entity gets a DISTINCT, recognizable sprite — not a recolor of a blob:
    • Player (adventurer): hooded figure; the equipped weapon (dagger/sword/ axe/hammer) and armor visibly change the sprite. 4-directional facing when moving.
    • Rat: small body, pink tail, round ears, whiskers.
    • Goblin: green humanoid, pointed ears, crude weapon, loincloth.
    • Skeleton Archer: white-gray bones, drawn bow, quiver, glowing eye sockets.
    • Orc Warrior: hulking dark-red brute, heavy plate, tusks, big blade.
    • Wraith: translucent purple wisps, tattered cloak, no legs, glowing eyes.
    • Green Slime: glossy blob with highlight, two googly eyes, a drip.
    • Ancient Dragon: large multi-hue red boss — horns, spread wings, scales, fangs.
    • Items: pixel-art icons (weapon, armor, potion flask, scroll) with the category accent (yellow / blue / red / cyan) as the dominant hue.
    • Stairs: a pixel-art descending staircase / > arrow, glowing yellow.
  • Animate: 2–3 idle frames cycled by turn/time (gentle breathe/bob via a sine offset); attack = a short lunge; taking damage = a white hit-flash; death = a poof. Small Slimes use a smaller, cuter variant of the slime sprite.

Tiles & lighting

  • Walls: pixel-art stone/brick with a lighter top edge and darker bottom for depth (beveled), plus seeded per-tile variation so walls aren't uniform.
  • Floor: subtle dithering / specular flecks and slight per-tile shade variation.
  • Lighting: radial torch-light centered on the player out to SIGHT_RADIUS (brightness falloff); tiles outside FOV are unlit (black); explored-not-visible tiles are remembered but tinted dark blue-gray and dimmer. Soft screen vignette. Walls occlude light (derived from the FOV grid).
  • Shadows: a soft ellipse shadow under each entity and feature.

Juice (procedural effects in render/effects.py)

  • Particle bursts: hit sparks, critical-hit star burst, blood/slime/ash poof on death, level-up stars, pickup sparkle, stairs shimmer. Pool and cap the counts.
  • Screen-shake on player damage and big hits (decaying offset).
  • Smooth camera that eases toward the player.
  • Floating combat text is welcome (e.g. -8, MISS!, CRIT!).

UI (polished)

  • Bordered panels (1-px pixel frame, subtle inner bevel).
  • Top bar: Floor N/10, HP bar (heart icon + green/red fill), Level, XP bar.
  • Right panel: last 8 log messages, color-coded (combat white, damage red, level-up green, items yellow).
  • Bottom bar: equipment slots drawn as pixel-art icons, active effect timers, and a sound on/off icon.
  • Context prompt line: on an item show Press G to pick up <name>; on stairs Press F to descend — styled as part of the UI, not console text.
  • Use pygame.font.SysFont (no font asset files).

Colors & viewport

  • Base palette in data/constants.py (PALETTE / COLORS): walls dark gray (60,60,70) visible / (30,30,35) explored; floor (40,35,30) / (20,18,15). Keep the type accent colors (rat brown, goblin green, skeleton white-gray, orc dark red, wraith purple, slime green, dragon red; items yellow/blue/red/cyan; stairs yellow) as the dominant hue of each sprite's palette.
  • Viewport: camera follows the player; show ~48×28 tiles at TILE pixels (TILE ≥ 16; 20 recommended for a comfortable pixel-art canvas).
  • Messages scroll, newest at bottom, color-coded.

Audio

Use pygame.mixer only. Generate a few short tones in memory with stdlib array; do not require audio asset files. Play distinct quiet effects for player hit/miss, damage taken, pickup/use, stairs, level-up, death, and victory. Initialize audio at the application boundary. If mixer initialization or sound creation fails, disable audio and keep the game fully playable. m toggles mute. Audio is feedback only and must never alter game state or block input.

Acceptance Criteria

The game is DONE when ALL of these are true:

Floor (must-haves)

  • Game launches without errors via python main.py
  • Runs for at least 5 minutes of continuous play without crashing
  • Has a main menu with New Game / Continue / Quit
  • Has a WIN state (kill the dragon on floor 10)
  • Has a LOSE state (player HP reaches 0, game over screen)
  • More than one floor — 10 floors, each procedurally generated
  • More than one enemy type — 6 regular + 1 boss
  • How to Play is available from the menu and shown before a New Game
  • Standing on an item/stairs shows the exact key needed; g pickup and f descent work
  • Simple sound effects play when audio is available; missing audio devices fall back silently
  • Entities, tiles, and items are drawn as distinct procedural pixel-art sprites (not flat colored squares); no external image files are loaded

Systems Depth (judging criteria)

  • A pathfinding* — enemies pathfind around walls toward the player (chase and flee behaviors). Visible when a goblin navigates a corridor to reach you.
  • FOV — recursive shadowcasting. Player can only see tiles within line of sight. Explored tiles remembered but darker. Walls block vision.
  • Procedural generation — BSP dungeon generation. Each floor is different every playthrough.
  • Enemy AI — at least 4 distinct behaviors visible: wander (rat), chase (goblin/orc), ranged/kiting (skeleton archer), phase-through-walls (wraith). Ideally also split (slime) and boss breath weapon.
  • Combat — melee and ranged, hit chance, damage reduction from armor, critical hits. Messages logged.
  • Progression — XP from kills, level up with stat increases, fully heal on level up.
  • Items & inventory — pick up, equip weapons/armor, quaff potions, read scrolls. At least 4 distinct item effects.
  • Save/load — press S to save and quit. Relaunch → Continue → exact state restored.
  • Control usability — an automated input smoke test places an item under the player, presses g, and verifies inventory; then places the player on stairs, presses f, and verifies the floor changes.
  • Audio safety — generated effects need no asset files, mute works, and forced mixer-init failure does not crash.

Visual Polish (judging criteria)

  • Procedural pixel-art — every entity, tile, and item is a hand-coded multi-color pixel pattern; the 7 enemies + player + items + stairs are each visually distinct and recognizable (not recolors of one shape)
  • Lighting — radial torch-light around the player, explored tiles remembered but dimmed, walls occlude light, screen vignette
  • Depth & shadow — beveled/textured walls, per-tile floor variation, soft shadows under entities
  • Juice — particle effects on hits/crits/deaths/pickups/level-ups/stairs, screen-shake on damage, easing camera, idle animation on entities
  • Polished UI — bordered panels, HP/XP bars with icons, color-coded log, equipment shown as icons, styled context prompts; clean and readable

Video Requirements (what must be visible in one continuous take)

  • Core loop played: move, explore, fight, loot, descend
  • Two systems interacting: e.g., enemy A* pathfinding through a generated dungeon while FOV limits what you see
  • A failure/death: player dies, game over screen appears
  • Save, quit, relaunch, continue from save

Tuning Notes

  • If the game is too hard: increase potion drop rate, reduce enemy HP, increase player base HP.
  • If too easy: add more enemies per floor, increase enemy power scaling.
  • The first 2 floors should be forgiving (rats and a few goblins). Difficulty ramps from floor 3+.
  • Leave a constants.py with all tunable values in one place so balancing is trivial.

What NOT to Build

  • No networking/multiplayer (not required, adds fragility)
  • No music, external audio assets, positional audio, or audio settings beyond mute; short generated effects are enough
  • No procedural item generation (fixed catalog is enough)
  • No character creation/class selection (one class: adventurer)
  • No crafting system
  • No NPC dialogue or shops
  • No external image / sprite-sheet / font / data asset files — all visuals are procedural pixel-art drawn from in-code palettes with pygame.draw only