(Underdepths) Inital Plan

This commit is contained in:
AlexKucera committed 2026-08-12 14:44:19 +02:00
1 parent 08c239dfe8
commit dce898841d
3 files changed
+564

No files matched your search

+156
View File
@@ -0,0 +1,156 @@
# AGENTS.md — Underdepths Roguelike
## Project
Building "Underdepths," a turn-based roguelike dungeon crawler in Python.
Read `plan.md` for the complete game design document. It is the source of truth
for all gameplay mechanics, data, and acceptance criteria.
## Tech Stack
- Python 3.11+
- pygame-ce (rendering + input only)
- Standard library for everything else (json, random, math, dataclasses, heapq, array)
- No other third-party packages unless absolutely necessary
## Conventions
- Use `@dataclass(slots=True)` for all game entities and state objects.
- Type hints on every function signature.
- Constants live in `data/constants.py`. No magic numbers scattered in logic.
- Functions are small and named clearly. No comments explaining *what*, only *why*.
- Error handling at boundaries: file I/O (save/load), user input. Game logic
should never raise on valid game states.
- The message log is the primary feedback mechanism. Every combat event,
item pickup, level-up, and status change must log a human-readable message.
## Architecture Rules
- `GameSession` (in `engine/game_state.py`) is the single source of truth for
all mutable state. It is what gets serialized for save/load.
- Systems are pure functions that take state and return new state or mutate
in place. No hidden global state.
- Rendering reads from `GameSession`; it never mutates game state.
- Input handling translates key presses into intent (move, pickup, use item),
which the game loop applies to state.
## Orchestration
This project uses a **self-driving build pipeline**. Your first action is to
write `orchestrate.sh` — a bash script that drives the entire build using
`pi -p` (non-interactive mode) as the build primitive. Then you execute it.
### How it works
```
orchestrate.sh
├── reads .build_state to find last completed phase
├── for each remaining phase:
│ ├── dispatches build work via `pi -p "<phase prompt>"`
│ ├── runs the phase gate (python tests/smoke.py --phase N)
│ ├── if gate fails: feeds error output back via `pi -p "<fix prompt>"`
│ ├── Ralph loop: retries up to MAX_RETRIES until gate passes
│ └── on pass: advances .build_state
├── after all phases: goal check — verifies ALL acceptance criteria
│ ├── if any fail: dispatches targeted fix via `pi -p`
│ └── loops until all pass or MAX_RETRIES exhausted
└── prints build summary
```
### State machine
`.build_state` is a single integer: the index of the last completed phase.
This makes the pipeline **resumable** — if it crashes, re-running
`orchestrate.sh` picks up where it left off. Delete `.build_state` to start
over.
### Phase definitions
Each phase has: a name, a build directive (what to tell `pi -p`), and a
gate command (what to run to verify). The script defines them inline.
**Phase 0 — Orchestration setup:**
Write `orchestrate.sh`, `tests/smoke.py` (stub with phase functions), and
`.build_state`. This phase is you — you write it directly, not via `pi -p`.
**Phase 1 — Foundation:**
- Build: `data/constants.py`, `entities/entity.py`, `engine/map_gen.py`,
`entities/player.py`, `entities/enemy.py`, minimal `main.py` game loop.
- Gate: generate 5 maps, assert each has ≥3 rooms, all rooms reachable via
flood fill, no room overlaps. Print ASCII render to confirm.
**Phase 2 — Core Systems (parallelizable):**
FOV, A*, and combat are independent. Dispatch them as separate `pi -p`
calls that can run concurrently:
- `engine/fov.py` — recursive shadowcasting, sight radius 8
- `engine/pathfinding.py` — A* with Manhattan heuristic
- `engine/combat.py` — hit chance, damage reduction, crits
- `ai/behaviors.py` — depends on pathfinding + FOV, build after those land
- Gate: FOV (walled-in player sees only self), A* (path exists between any two
floor tiles), combat (1000 simulated attacks, damage in expected range), AI
(enemy chases player through a test corridor)
**Phase 3 — Content Layer:**
- Items, inventory, equipment, potions, scrolls
- XP, leveling, progression
- All 7 enemy types with behaviors
- Boss arena on floor 9
- Gate: spawn each enemy type, verify stats. Equip item, verify stat changes.
Kill enemy, verify XP + level-up at threshold.
**Phase 4 — Polish & Persist:**
- Save/load JSON, menu system, death/victory screens, UI panels
- Gate: save → load → assert state equality. All menu states reachable.
### Goal backstop
After Phase 4, the script does NOT declare success. It runs a final goal check:
`pi -p` with a prompt that reads every acceptance criterion in `plan.md`,
runs `python main.py` headless for a smoke playthrough, and reports which
checkboxes pass/fail. Any failure gets dispatched as a fix task. The loop
repeats until ALL criteria pass. This is the backstop that prevents early
stopping — the pipeline cannot exit successfully while any criterion is unmet.
### Retry semantics
Gates that fail feed the actual error output (stdout + stderr) back into the
next `pi -p` call, not just "try again." The agent sees what broke and
fixes specifically that. Max 3 retries per phase before the pipeline halts
with a diagnostic.
## Build Order
Follow the phase definitions in the Orchestration section above. Build
incrementally. Run `python tests/smoke.py --phase N` after each phase. Do not
proceed if it fails. Fix the failure, then continue.
## Definition of Done
ALL acceptance criteria in `plan.md` → Acceptance Criteria section must pass.
The game must be playable start to finish via `python main.py`. It must not
crash. It must have win and lose states. It must save and load.
When you believe you are done:
1. Run `python tests/smoke.py` — must pass.
2. Run `python main.py` and play through: move, fight, pick up items, descend
stairs, save, quit, relaunch, continue. Verify it works.
3. Check every acceptance criterion checkbox in `plan.md`.
4. If anything fails, fix it. Do not stop until all pass.
## What Kills Entries
- **Crashes during play.** Every code path must be safe. Test edge cases:
empty inventory, no item at feet, attacking with full HP enemy, descending
stairs on the last floor.
- **Systems that don't actually work.** If A* is there but enemies walk into
walls, the judge sees that. Each system must be genuinely functional.
- **Stopping early.** The prompt must produce a complete game. If you finish
a phase and the acceptance criteria aren't all met, keep building.
## Anti-Patterns to Avoid
- Don't add networking, audio, or graphical assets (sprites/tiles).
- Don't build a character creation screen or class system.
- Don't add crafting or shops.
- Don't write more files than needed — merge where natural.
- Don't stub functions. Every function must have a real implementation.
+357
View File
@@ -0,0 +1,357 @@
# 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 and input (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, glyph, color, 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, colors, key bindings
render/
renderer.py # Draw map, entities, UI panels
camera.py # Viewport offset (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
```python
@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, starts on floor 0
- "Continue" — only if save.json exists
- "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
| Key | Action |
|-----|--------|
| Arrows / hjkl | Move / melee attack (walk into enemy) |
| `g` | Pick up item at feet |
| `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) |
| `>` | Descend stairs (must be standing on stairs) |
| `S` | Save and quit |
| `?` | Help overlay (show all keys) |
| `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
- **Tile size:** 16×16 pixels (use `pygame.draw.rect` with distinct colors per tile/entity type).
- **Viewport:** camera follows player, centered. Show ~50×30 tiles.
- **Colors:**
- Wall: dark gray `(60, 60, 70)`, visible; `(30, 30, 35)`, explored-not-visible.
- Floor: `(40, 35, 30)`, visible; `(20, 18, 15)`, explored-not-visible.
- Player: white `(255, 255, 255)` — draw as a filled circle or `@`-shaped glyph.
- Enemies: type-coded colors (Rat: brown, Goblin: green, Skeleton: white-gray, Orc: dark red, Wraith: translucent purple, Slime: bright green, Dragon: bright red).
- Items: yellow (weapons), blue (armor), red (potions), cyan (scrolls).
- Stairs: bright yellow `>`.
- **UI Panels:**
- Top bar: Floor N/10, HP bar (red/green), Level, XP bar.
- Right panel: message log (last 8 messages).
- Bottom: current equipment (weapon, armor).
- **Messages** scroll, newest at bottom. Color-coded: combat (white), damage taken (red), level up (green), items (yellow).
## 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
### 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.
### 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 audio/music (nice but not judged; add only if time permits and it's zero-risk)
- No procedural item generation (fixed catalog is enough)
- No character creation/class selection (one class: adventurer)
- No crafting system
- No NPC dialogue or shops
+51
View File
@@ -0,0 +1,51 @@
# PROMPT — The One Message
> Paste this as the first and only message in a fresh Pi session
> running in a directory containing `plan.md` and `AGENTS.md`.
---
Read `AGENTS.md` for build conventions and orchestration architecture.
Read `plan.md` for the complete game design document.
Both are in the current directory. They are your specification — follow them exactly.
You are building **Underdepths**, a turn-based roguelike in Python with pygame-ce.
## How to work
1. **Read both files completely before writing any code.**
2. **Your first action is to build a self-driving pipeline.** Write
`orchestrate.sh` — a bash script that drives the entire game build using
`pi -p` as the primitive. The pipeline:
- Tracks progress via `.build_state` (resumable across crashes)
- Dispatches each build phase to `pi -p` with a targeted prompt
- Runs verification gates after each phase (`python tests/smoke.py --phase N`)
- Feeds gate failures back into `pi -p` with the actual error output (Ralph loop)
- Parallelizes independent systems (FOV, A*, combat) as concurrent `pi -p` calls
- Goal backstop after all phases: verifies EVERY acceptance criterion in
`plan.md`, dispatches fixes for any that fail, loops until all pass
3. **Then execute the pipeline.** Run `./orchestrate.sh`. Let it drive the build
through all four phases to completion.
4. **Do not stop until every acceptance criterion in `plan.md` is met.** The
goal backstop is your guarantee — if any system is incomplete or broken, the
pipeline dispatches a fix and retries.
5. **Write real implementations.** No stubs, no TODO comments left behind. Every
function must work.
## Completion criteria
You are done when ALL of these are true:
- `python main.py` launches a playable game with a menu.
- All 7 enemy types exist with their specified AI behaviors and stats.
- A* pathfinding, recursive shadowcasting FOV, BSP dungeon generation, combat
with hit/damage/crit mechanics, XP/leveling, items/inventory/equipment, and
save/load all work.
- The game has a win state (kill the dragon on floor 10) and a lose state
(player death → game over, save deleted).
- `python tests/smoke.py` passes.
- You can play: move, explore, fight, loot, descend stairs, level up, save,
quit, relaunch, and continue — all without crashes.
Do not stop early. Do not ask for clarification. The specification is complete.
Build the game.