383 lines
18 KiB
Markdown
383 lines
18 KiB
Markdown
# 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, 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, 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
|
||
|
||
- **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 and sound state.
|
||
- Context prompt: on an item show `Press G to pick up <name>`; on stairs show `Press F to descend`.
|
||
- **Messages** scroll, newest at bottom. Color-coded: combat (white), damage taken (red), level up (green), items (yellow).
|
||
|
||
## 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
|
||
|
||
### 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.
|
||
|
||
### 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
|