From 8259ca8ddfa620013e9fead8bf0b01d3986e7f35 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 12 Aug 2026 15:59:16 +0200 Subject: [PATCH] (Underdepths) Prepare for Pass 2 --- underdepths/.build_logs/goal-audit-1.log | 12 - underdepths/.build_logs/goal-gate.log | 55 -- underdepths/.build_logs/phase-1-build.log | 15 - underdepths/.build_logs/phase-1-gate.log | 51 -- underdepths/.build_logs/phase-2-ai-1.log | 13 - underdepths/.build_logs/phase-2-combat-1.log | 9 - underdepths/.build_logs/phase-2-fov-1.log | 10 - underdepths/.build_logs/phase-2-gate.log | 1 - underdepths/.build_logs/phase-2-path-1.log | 13 - underdepths/.build_logs/phase-3-build.log | 20 - underdepths/.build_logs/phase-3-gate.log | 1 - underdepths/.build_logs/phase-4-build.log | 6 - underdepths/.build_logs/phase-4-gate.log | 2 - underdepths/.build_state | 1 - underdepths/AGENTS.md | 21 +- underdepths/ai/behaviors.py | 286 ------- underdepths/data/constants.py | 141 ---- underdepths/data/enemies.py | 72 -- underdepths/data/items.py | 106 --- underdepths/engine/combat.py | 95 --- underdepths/engine/fov.py | 103 --- underdepths/engine/game_state.py | 274 ------- underdepths/engine/map_gen.py | 284 ------- underdepths/engine/pathfinding.py | 72 -- underdepths/engine/serializers.py | 187 ----- underdepths/entities/enemy.py | 22 - underdepths/entities/entity.py | 16 - underdepths/entities/item.py | 18 - underdepths/entities/player.py | 56 -- underdepths/main.py | 686 ---------------- underdepths/orchestrate.sh | 108 --- underdepths/plan.md | 39 +- underdepths/prompt.md | 16 +- underdepths/tests/smoke.py | 819 ------------------- 34 files changed, 61 insertions(+), 3569 deletions(-) delete mode 100644 underdepths/.build_logs/goal-audit-1.log delete mode 100644 underdepths/.build_logs/goal-gate.log delete mode 100644 underdepths/.build_logs/phase-1-build.log delete mode 100644 underdepths/.build_logs/phase-1-gate.log delete mode 100644 underdepths/.build_logs/phase-2-ai-1.log delete mode 100644 underdepths/.build_logs/phase-2-combat-1.log delete mode 100644 underdepths/.build_logs/phase-2-fov-1.log delete mode 100644 underdepths/.build_logs/phase-2-gate.log delete mode 100644 underdepths/.build_logs/phase-2-path-1.log delete mode 100644 underdepths/.build_logs/phase-3-build.log delete mode 100644 underdepths/.build_logs/phase-3-gate.log delete mode 100644 underdepths/.build_logs/phase-4-build.log delete mode 100644 underdepths/.build_logs/phase-4-gate.log delete mode 100644 underdepths/.build_state delete mode 100644 underdepths/ai/behaviors.py delete mode 100644 underdepths/data/constants.py delete mode 100644 underdepths/data/enemies.py delete mode 100644 underdepths/data/items.py delete mode 100644 underdepths/engine/combat.py delete mode 100644 underdepths/engine/fov.py delete mode 100644 underdepths/engine/game_state.py delete mode 100644 underdepths/engine/map_gen.py delete mode 100644 underdepths/engine/pathfinding.py delete mode 100644 underdepths/engine/serializers.py delete mode 100644 underdepths/entities/enemy.py delete mode 100644 underdepths/entities/entity.py delete mode 100644 underdepths/entities/item.py delete mode 100644 underdepths/entities/player.py delete mode 100644 underdepths/main.py delete mode 100755 underdepths/orchestrate.sh delete mode 100644 underdepths/tests/smoke.py diff --git a/underdepths/.build_logs/goal-audit-1.log b/underdepths/.build_logs/goal-audit-1.log deleted file mode 100644 index e44b53a..0000000 --- a/underdepths/.build_logs/goal-audit-1.log +++ /dev/null @@ -1,12 +0,0 @@ -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Extension error (): Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message. -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Implemented and verified all acceptance criteria. - -- Fixed slime splitting onto player tiles. -- Randomized boss-arena placement. -- Fixed full-inventory scrolling and combat message colors. -- Added honest deterministic headless coverage: movement, combat, pickup/use/equip, stairs, save/relaunch/load, death, victory, AI, FOV, procedural variation, 18,000 rendered turns. -- `SDL_VIDEODRIVER=dummy python tests/smoke.py` — phases 1–4 PASS. -- `compileall`, launch smoke, and `git diff --check` pass. diff --git a/underdepths/.build_logs/goal-gate.log b/underdepths/.build_logs/goal-gate.log deleted file mode 100644 index 5a719cf..0000000 --- a/underdepths/.build_logs/goal-gate.log +++ /dev/null @@ -1,55 +0,0 @@ -pygame-ce 2.5.8 (SDL 2.32.10, Python 3.13.13) -################################################################################ -################################################################################ -#######################################.......############################....## -#######################################.......################.......#####....## -#######################################...@...................................## -#######################################.......################.......#####....## -#######################################.......################.......########### -##########################################.###################.......########### -##########################################.###################.......########### -##########################################.###################.......########### -##########################################.###################.......########### -##########################################.######################.############## -######........############################.######################.############## -######........############################.######################.############## -######.....................................######################.############## -######........##############........#############################.############## -######........##############........#############################.############## -##########.#################........#############################.############## -##########.#################........#############################.############## -##########.#################........#############################.############## -##########.#################........#############################.############## -##########.#################........#############################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.######################....######.############## -##########.#####################.######################....######.############## -##########.#####################...........................######.############## -##########.#####################.######################....######.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########...........###########.################################.############## -##########...........###########.################################.############## -##########...........###########.################################.############## -###########..........###########.################################.############## -################################.################################.############## -################################.#......########################..........###### -################################.#......########################..........###### -################################.#......########################..........###### -################################........########################.....>....###### -##################################......########################..........###### -##################################......########################..........###### -##################################......######################################## -################################################################################ -################################################################################ -phase 1: PASS -phase 2: PASS -phase 3: PASS -phase 4: PASS diff --git a/underdepths/.build_logs/phase-1-build.log b/underdepths/.build_logs/phase-1-build.log deleted file mode 100644 index 3aa3ae0..0000000 --- a/underdepths/.build_logs/phase-1-build.log +++ /dev/null @@ -1,15 +0,0 @@ -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Implemented Phase 1 foundation: - -- BSP dungeon generation, entities, player/enemy models, `GameSession` -- Minimal playable pygame movement/rendering -- Phase 1 smoke gate with 5 maps, overlap and flood-fill checks, ASCII output -- Installed `pygame-ce` - -Verified: -- `python tests/smoke.py --phase 1` — **PASS** -- Headless pygame render — **PASS** -- 100-map generation stress check — **PASS** - -Later phases remain untouched. diff --git a/underdepths/.build_logs/phase-1-gate.log b/underdepths/.build_logs/phase-1-gate.log deleted file mode 100644 index dea26f0..0000000 --- a/underdepths/.build_logs/phase-1-gate.log +++ /dev/null @@ -1,51 +0,0 @@ -################################################################################ -################################################################################ -#######################################.......############################....## -#######################################.......################.......#####....## -#######################################...@...................................## -#######################################.......################.......#####....## -#######################################.......################.......########### -##########################################.###################.......########### -##########################################.###################.......########### -##########################################.###################.......########### -##########################################.###################.......########### -##########################################.######################.############## -######........############################.######################.############## -######........############################.######################.############## -######.....................................######################.############## -######........##############........#############################.############## -######........##############........#############################.############## -##########.#################........#############################.############## -##########.#################........#############################.############## -##########.#################........#############################.############## -##########.#################........#############################.############## -##########.#################........#############################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.######################....######.############## -##########.#####################.######################....######.############## -##########.#####################...........................######.############## -##########.#####################.######################....######.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########.#####################.################################.############## -##########...........###########.################################.############## -##########...........###########.################################.############## -##########...........###########.################################.############## -###########..........###########.################################.############## -################################.################################.############## -################################.#......########################..........###### -################################.#......########################..........###### -################################.#......########################..........###### -################################........########################.....>....###### -##################################......########################..........###### -##################################......########################..........###### -##################################......######################################## -################################################################################ -################################################################################ -phase 1: PASS diff --git a/underdepths/.build_logs/phase-2-ai-1.log b/underdepths/.build_logs/phase-2-ai-1.log deleted file mode 100644 index 07d6148..0000000 --- a/underdepths/.build_logs/phase-2-ai-1.log +++ /dev/null @@ -1,13 +0,0 @@ -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Implemented: - -- `ai/behaviors.py`: wander, chase/last-known, flee, ranged/kiting, phase, split; ordered enemy turns. -- Integrated AI/combat into `engine/game_state.py`, `engine/combat.py`, `main.py`. -- Added AI state/constants. -- Replaced Phase 2 smoke stub with real FOV, A*, 1000-attack combat, corridor chase gates. - -Verified: -- `python tests/smoke.py --phase 2` → **PASS** -- Phase 1 regression → **PASS** -- Compile and `git diff --check` → **PASS** diff --git a/underdepths/.build_logs/phase-2-combat-1.log b/underdepths/.build_logs/phase-2-combat-1.log deleted file mode 100644 index 8f4ac6f..0000000 --- a/underdepths/.build_logs/phase-2-combat-1.log +++ /dev/null @@ -1,9 +0,0 @@ -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Implemented: - -- `engine/combat.py`: hit clamp, armor, weapon bonus, crits, enemy/player death, XP, readable logs. -- `data/constants.py`: combat tuning constants and dead state. -- Verified compilation, 1,000 simulated attacks, death/XP/logging, and Phase 1 smoke gate. - -Skipped `tests/smoke.py`: concurrent Phase 2 edits unsafe; follow-up owns integration. diff --git a/underdepths/.build_logs/phase-2-fov-1.log b/underdepths/.build_logs/phase-2-fov-1.log deleted file mode 100644 index a32751a..0000000 --- a/underdepths/.build_logs/phase-2-fov-1.log +++ /dev/null @@ -1,10 +0,0 @@ -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -[LCM] Failed to initialize: database is locked -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Implemented: - -- `engine/fov.py`: recursive shadowcasting, 8 octants, visibility reset, explored persistence, wall occlusion. -- `data/constants.py`: `FOV_RADIUS = 8`. -- Left `tests/smoke.py` untouched due concurrent edits. - -Verified compilation, open-map radius coverage, wall blocking, explored persistence, 100 generated maps, and Phase 1 smoke gate. diff --git a/underdepths/.build_logs/phase-2-gate.log b/underdepths/.build_logs/phase-2-gate.log deleted file mode 100644 index fa607f4..0000000 --- a/underdepths/.build_logs/phase-2-gate.log +++ /dev/null @@ -1 +0,0 @@ -phase 2: PASS diff --git a/underdepths/.build_logs/phase-2-path-1.log b/underdepths/.build_logs/phase-2-path-1.log deleted file mode 100644 index 31897f4..0000000 --- a/underdepths/.build_logs/phase-2-path-1.log +++ /dev/null @@ -1,13 +0,0 @@ -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -[LCM] Failed to initialize: database is locked -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Implemented `engine/pathfinding.py`: - -- Grid A* with Manhattan heuristic -- Cardinal movement -- Wall/out-of-bounds rejection -- Occupied-tile avoidance -- Empty path when unreachable -- Full type hints - -Assertions and compile check pass. Left `tests/smoke.py` untouched due concurrent edits. diff --git a/underdepths/.build_logs/phase-3-build.log b/underdepths/.build_logs/phase-3-build.log deleted file mode 100644 index d76275a..0000000 --- a/underdepths/.build_logs/phase-3-build.log +++ /dev/null @@ -1,20 +0,0 @@ -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Python mapper failed: Error: Command failed: python3 /Users/alex/.pi/agent/npm/node_modules/pi-hashline-readmap/scripts/python_outline.py /Users/alex/Projects/scripting/agentic-labs-challenge/underdepths/ai/behaviors.py - -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Implemented Phase 3 Content Layer. - -- Complete item/enemy catalogs, inventory, equipment, consumables, scrolls -- Full XP progression and thresholds -- Depth-gated spawning, slime splitting, dragon breath -- Floor-9 boss arena with two healing potions -- Gameplay controls/rendering/log display wired -- Deterministic RNG stored in `GameSession` -- Comprehensive Phase 3 smoke assertions - -Verification: -- `python tests/smoke.py --phase 3` — **PASS** -- Phase 2 regression gate — **PASS** -- Headless rendering/input check — **PASS** diff --git a/underdepths/.build_logs/phase-3-gate.log b/underdepths/.build_logs/phase-3-gate.log deleted file mode 100644 index 1fc1caa..0000000 --- a/underdepths/.build_logs/phase-3-gate.log +++ /dev/null @@ -1 +0,0 @@ -phase 3: PASS diff --git a/underdepths/.build_logs/phase-4-build.log b/underdepths/.build_logs/phase-4-build.log deleted file mode 100644 index 9cd8246..0000000 --- a/underdepths/.build_logs/phase-4-build.log +++ /dev/null @@ -1,6 +0,0 @@ -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty' -Implemented Phase 4 in `main.py`, `engine/serializers.py`, `data/constants.py`, `engine/game_state.py`, and `tests/smoke.py`. - -- `python tests/smoke.py --phase 4` ✅ -- Full smoke suite + compile checks ✅ diff --git a/underdepths/.build_logs/phase-4-gate.log b/underdepths/.build_logs/phase-4-gate.log deleted file mode 100644 index 01d862e..0000000 --- a/underdepths/.build_logs/phase-4-gate.log +++ /dev/null @@ -1,2 +0,0 @@ -pygame-ce 2.5.8 (SDL 2.32.10, Python 3.13.13) -phase 4: PASS diff --git a/underdepths/.build_state b/underdepths/.build_state deleted file mode 100644 index b8626c4..0000000 --- a/underdepths/.build_state +++ /dev/null @@ -1 +0,0 @@ -4 diff --git a/underdepths/AGENTS.md b/underdepths/AGENTS.md index be7ee0e..cce9998 100644 --- a/underdepths/AGENTS.md +++ b/underdepths/AGENTS.md @@ -98,9 +98,10 @@ calls that can run concurrently: - Gate: spawn each enemy type, verify stats. Equip item, verify stat changes. Kill enemy, verify XP + level-up at threshold. -**Phase 4 — Polish & Persist:** +**Phase 4 — Polish, Audio & Persist:** - Save/load JSON, menu system, death/victory screens, UI panels -- Gate: save → load → assert state equality. All menu states reachable. +- A visible How to Play screen, contextual pickup/stairs prompts, and simple generated sound effects with graceful silent fallback +- Gate: save → load → assert state equality; all menu states reachable; simulated `g` pickup and `>` descent work; audio-disabled mode does not crash. ### Goal backstop @@ -128,12 +129,15 @@ proceed if it fails. Fix the failure, then continue. 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. +crash. It must have win and lose states. It must save and load. Controls must +be explained in-game, with contextual prompts for item pickup and stairs. 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. +2. Run `python main.py` and play through: read How to Play, move, fight, stand + on an item and press `g`, stand on stairs and press `>` (`Shift+.`), save, + quit, relaunch, and continue. Confirm sound effects play when audio exists + and the game still works when audio initialization fails. 3. Check every acceptance criterion checkbox in `plan.md`. 4. If anything fails, fix it. Do not stop until all pass. @@ -142,6 +146,9 @@ When you believe you are done: - **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. +- **Hidden or broken controls.** The game must visibly explain controls. While the + player stands on an item show `Press G to pick up`; while on stairs show + `Press > (Shift+.) to descend`. Automated tests must exercise both actions. - **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 @@ -149,7 +156,9 @@ When you believe you are done: ## Anti-Patterns to Avoid -- Don't add networking, audio, or graphical assets (sprites/tiles). +- Don't add networking or graphical assets (sprites/tiles). +- Don't add music, external audio files, or a complex audio engine. Generate a + few short tones with pygame and continue silently if no audio device exists. - 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. diff --git a/underdepths/ai/behaviors.py b/underdepths/ai/behaviors.py deleted file mode 100644 index 0ec5c8c..0000000 --- a/underdepths/ai/behaviors.py +++ /dev/null @@ -1,286 +0,0 @@ -from __future__ import annotations - -import random -from dataclasses import replace - -from data.constants import ( - AI_FLEE_HP_RATIO, - AI_RANGED_ATTACK_DISTANCE, - AI_RANGED_DISTANCE_PENALTY, - AI_RANGED_KITE_DISTANCE, - AI_WAIT_CHANCE, - CARDINAL_DIRECTIONS, - DRAGON_BREATH_DAMAGE, - DRAGON_BREATH_INTERVAL, - GAME_STATE_DEAD, - GAME_STATE_PLAYING, - HIT_MIN_CHANCE, -) -from engine.combat import attack, calculate_hit_chance -from engine.fov import compute_fov -from engine.game_state import GameSession -from engine.pathfinding import find_path, manhattan_distance -from entities.enemy import Enemy - - -def take_enemy_turns(session: GameSession, rng: random.Random | None = None) -> None: - compute_fov(session.current_map, session.player.x, session.player.y) - roller = rng or session.roller() - for entity in list(session.current_map.entities): - if session.state != GAME_STATE_PLAYING: - break - if isinstance(entity, Enemy) and entity.hp > 0: - take_enemy_turn(session, entity, roller) - if rng is None: - session.save_roller(roller) - - -def take_enemy_turn( - session: GameSession, - enemy: Enemy, - rng: random.Random | None = None, -) -> None: - if enemy.speed > 1 and session.turn % enemy.speed: - return - - roller = rng or session.roller() - if enemy.behavior == "wander": - _wander(session, enemy, roller) - elif enemy.behavior == "flee": - if enemy.hp < enemy.max_hp * AI_FLEE_HP_RATIO: - _step_away(session, enemy, roller) - else: - _chase(session, enemy, roller) - elif enemy.behavior == "ranged": - _ranged(session, enemy, roller) - elif enemy.behavior == "phase": - _phase(session, enemy, roller) - elif enemy.behavior == "dragon": - _dragon(session, enemy, roller) - else: - _chase(session, enemy, roller) - - -def spawn_split_copies(session: GameSession, enemy: Enemy) -> list[Enemy]: - if enemy.behavior != "split" or enemy.has_split: - return [] - - occupied = _occupied(session, enemy) - positions = [ - position - for position in (enemy.position, *_adjacent(enemy.position)) - if session.current_map.is_floor(*position) - and position != session.player.position - and position not in occupied - ][:2] - hp = max(1, enemy.max_hp // 2) - power = max(1, enemy.power // 2) - copies = [ - replace( - enemy, - x=x, - y=y, - name=f"Small {enemy.name.removeprefix('Green ')}", - hp=hp, - max_hp=hp, - power=power, - behavior="chase", - xp_reward=max(1, enemy.xp_reward // 2), - last_known_position=None, - has_split=True, - ) - for x, y in positions - ] - session.current_map.entities.extend(copies) - if copies: - session.add_message(f"The {enemy.name} splits into {len(copies)} smaller slimes!") - return copies - - -def _chase(session: GameSession, enemy: Enemy, roller: random.Random) -> None: - player = session.player - visible = _player_visible(session, enemy) - if visible: - enemy.last_known_position = player.position - elif enemy.last_known_position is None: - _wander(session, enemy, roller) - return - - if manhattan_distance(enemy.position, player.position) == 1: - if visible: - attack(session, enemy, player, rng=roller) - return - - target = enemy.last_known_position - if target is None: - return - if enemy.position == target: - enemy.last_known_position = None - _wander(session, enemy, roller) - return - - path = find_path(session.current_map, enemy.position, target, _occupied(session, enemy)) - if path: - _move_to(session, enemy, path[0]) - else: - _wander(session, enemy, roller) - - -def _wander(session: GameSession, enemy: Enemy, roller: random.Random) -> None: - if roller.random() < AI_WAIT_CHANCE: - return - directions = list(CARDINAL_DIRECTIONS) - roller.shuffle(directions) - for dx, dy in directions: - if _move_to(session, enemy, (enemy.x + dx, enemy.y + dy)): - return - - -def _step_away(session: GameSession, enemy: Enemy, roller: random.Random) -> None: - occupied = _occupied(session, enemy) - choices = [ - position - for position in _adjacent(enemy.position) - if session.current_map.is_floor(*position) and position not in occupied - ] - if not choices: - return - farthest = max(manhattan_distance(position, session.player.position) for position in choices) - _move_to( - session, - enemy, - roller.choice( - [position for position in choices if manhattan_distance(position, session.player.position) == farthest] - ), - ) - - -def _ranged(session: GameSession, enemy: Enemy, roller: random.Random) -> None: - if not _player_visible(session, enemy): - _wander(session, enemy, roller) - return - - enemy.last_known_position = session.player.position - distance = manhattan_distance(enemy.position, session.player.position) - if distance <= AI_RANGED_KITE_DISTANCE: - _step_away(session, enemy, roller) - elif distance > AI_RANGED_ATTACK_DISTANCE: - _fire_projectile(session, enemy, distance, roller) - - -def _fire_projectile( - session: GameSession, - enemy: Enemy, - distance: int, - roller: random.Random, -) -> None: - chance = max( - HIT_MIN_CHANCE, - calculate_hit_chance(enemy, session.player) - - (distance - AI_RANGED_ATTACK_DISTANCE) * AI_RANGED_DISTANCE_PENALTY, - ) - if roller.random() >= chance: - session.add_message(f"{enemy.name} fires at you and misses") - return - - damage = enemy.ranged_power or enemy.power - session.player.hp -= damage - session.add_message(f"{enemy.name} shoots you for {damage} damage!") - if session.player.hp <= 0: - session.state = GAME_STATE_DEAD - session.add_message("You died!") - - -def _phase(session: GameSession, enemy: Enemy, roller: random.Random) -> None: - player = session.player - if player.invisibility_turns > 0: - return - if manhattan_distance(enemy.position, player.position) == 1: - attack(session, enemy, player, rng=roller) - return - - occupied = _occupied(session, enemy) - choices = [ - position - for position in _adjacent(enemy.position) - if session.current_map.in_bounds(*position) and position not in occupied - ] - if choices: - nearest = min(manhattan_distance(position, player.position) for position in choices) - enemy.x, enemy.y = roller.choice( - [position for position in choices if manhattan_distance(position, player.position) == nearest] - ) - - -def _dragon(session: GameSession, enemy: Enemy, roller: random.Random) -> None: - if ( - session.turn > 0 - and session.turn % DRAGON_BREATH_INTERVAL == 0 - and _player_visible(session, enemy) - ): - dragon_breath(session, enemy) - return - _chase(session, enemy, roller) - - -def dragon_breath(session: GameSession, enemy: Enemy) -> list[tuple[int, int]]: - line = _line_between(enemy.position, session.player.position) - session.add_message(f"The {enemy.name} breathes fire in a searing line!") - if session.player.position in line: - session.player.hp -= DRAGON_BREATH_DAMAGE - session.add_message(f"Dragon fire burns you for {DRAGON_BREATH_DAMAGE} damage!") - if session.player.hp <= 0: - session.state = GAME_STATE_DEAD - session.add_message("You died!") - return line - - -def _line_between(start: tuple[int, int], end: tuple[int, int]) -> list[tuple[int, int]]: - x, y = start - target_x, target_y = end - dx = abs(target_x - x) - dy = -abs(target_y - y) - step_x = 1 if x < target_x else -1 - step_y = 1 if y < target_y else -1 - error = dx + dy - line: list[tuple[int, int]] = [] - while (x, y) != end: - twice_error = 2 * error - if twice_error >= dy: - error += dy - x += step_x - if twice_error <= dx: - error += dx - y += step_y - line.append((x, y)) - return line - - -def _player_visible(session: GameSession, enemy: Enemy) -> bool: - if session.player.invisibility_turns > 0: - return False - return bool(session.current_map.visible[session.current_map.index(enemy.x, enemy.y)]) - - -def _move_to(session: GameSession, enemy: Enemy, target: tuple[int, int]) -> bool: - if ( - target == session.player.position - or not session.current_map.is_floor(*target) - or target in _occupied(session, enemy) - ): - return False - enemy.x, enemy.y = target - return True - - -def _occupied(session: GameSession, moving_enemy: Enemy) -> set[tuple[int, int]]: - return { - entity.position - for entity in session.current_map.entities - if isinstance(entity, Enemy) and entity is not moving_enemy and entity.hp > 0 - } - - -def _adjacent(position: tuple[int, int]) -> list[tuple[int, int]]: - x, y = position - return [(x + dx, y + dy) for dx, dy in CARDINAL_DIRECTIONS] diff --git a/underdepths/data/constants.py b/underdepths/data/constants.py deleted file mode 100644 index cae4f16..0000000 --- a/underdepths/data/constants.py +++ /dev/null @@ -1,141 +0,0 @@ -from __future__ import annotations - -MAP_WIDTH = 80 -MAP_HEIGHT = 50 -FLOOR_COUNT = 10 - -TILE_WALL = 0 -TILE_FLOOR = 1 -FOV_RADIUS = 8 - -BSP_MIN_SPLITS = 5 -BSP_MAX_SPLITS = 8 -ROOM_MIN_WIDTH = 4 -ROOM_MAX_WIDTH = 10 -ROOM_MIN_HEIGHT = 4 -ROOM_MAX_HEIGHT = 8 -ROOM_MARGIN = 1 - -TILE_SIZE = 16 -VIEWPORT_WIDTH = 50 -VIEWPORT_HEIGHT = 30 -FPS = 60 - -WALL_COLOR = (60, 60, 70) -FLOOR_COLOR = (40, 35, 30) -PLAYER_COLOR = (255, 255, 255) -STAIRS_COLOR = (255, 220, 40) -BACKGROUND_COLOR = (0, 0, 0) -PLAYER_GLYPH = "@" -STAIRS_GLYPH = ">" - -PLAYER_MAX_HP = 50 -PLAYER_POWER = 4 -PLAYER_ARMOR = 0 -PLAYER_ACCURACY = 5 -PLAYER_EVASION = 2 -PLAYER_CRIT_CHANCE = 0.10 -PLAYER_SPEED = 1 - -INVENTORY_CAPACITY = 26 -HEALING_AMOUNT = 30 -STRENGTH_BONUS = 5 -STRENGTH_DURATION = 20 -INVISIBILITY_DURATION = 15 -FIREBALL_DAMAGE = 20 -FIREBALL_RADIUS = 3 - -LEVEL_THRESHOLDS = (30, 70, 140, 250, 400, 600, 850, 1150, 1500) -LEVEL_HP_GAINS = (10, 10, 10, 10, 15, 15, 15, 15, 20) -LEVEL_POWER_GAINS = (1, 1, 1, 1, 2, 2, 2, 2, 3) - -ENEMY_ACCURACY = 3 -ENEMY_EVASION = 0 -ENEMY_CRIT_CHANCE = 0.05 -DRAGON_BREATH_DAMAGE = 15 -DRAGON_BREATH_INTERVAL = 3 - -FLOOR_SPAWN_COUNTS = ( - (3, 4, 2, 3), - (3, 4, 2, 3), - (4, 6, 2, 3), - (4, 6, 2, 3), - (5, 7, 3, 4), - (5, 7, 3, 4), - (6, 8, 3, 4), - (6, 8, 3, 4), - (7, 9, 4, 5), -) -BOSS_FLOOR = 9 -BOSS_ARENA_WIDTH = 20 -BOSS_ARENA_HEIGHT = 15 -BOSS_HEALING_POTIONS = 2 - -HIT_BASE_CHANCE = 0.7 -HIT_ACCURACY_SCALE = 0.05 -HIT_MIN_CHANCE = 0.1 -HIT_MAX_CHANCE = 0.95 -CRITICAL_DAMAGE_MULTIPLIER = 2 - -CARDINAL_DIRECTIONS = ((0, -1), (-1, 0), (1, 0), (0, 1)) -AI_WAIT_CHANCE = 0.5 -AI_FLEE_HP_RATIO = 0.30 -AI_RANGED_KITE_DISTANCE = 2 -AI_RANGED_ATTACK_DISTANCE = 3 -AI_RANGED_DISTANCE_PENALTY = 0.05 - -MESSAGE_LOG_LIMIT = 50 -GAME_STATE_PLAYING = "playing" -GAME_STATE_DEAD = "dead" -GAME_TITLE = "Underdepths" -GAME_STATE_VICTORY = "victory" - -SAVE_FILENAME = "save.json" -GAME_STATE_MENU = "menu" -GAME_STATE_SAVED = "saved" - -TOP_PANEL_HEIGHT = 48 -RIGHT_PANEL_WIDTH = 320 -BOTTOM_PANEL_HEIGHT = 56 -WINDOW_WIDTH = VIEWPORT_WIDTH * TILE_SIZE + RIGHT_PANEL_WIDTH -WINDOW_HEIGHT = TOP_PANEL_HEIGHT + VIEWPORT_HEIGHT * TILE_SIZE + BOTTOM_PANEL_HEIGHT - -EXPLORED_WALL_COLOR = (30, 30, 35) -EXPLORED_FLOOR_COLOR = (20, 18, 15) -UI_BACKGROUND_COLOR = (12, 12, 16) -UI_PANEL_COLOR = (24, 24, 30) -UI_BORDER_COLOR = (75, 75, 90) -UI_TEXT_COLOR = (225, 225, 230) -UI_MUTED_COLOR = (145, 145, 155) -UI_HEALTH_COLOR = (55, 190, 75) -UI_HEALTH_MISSING_COLOR = (110, 35, 35) -UI_XP_COLOR = (70, 125, 220) -UI_ITEM_COLOR = (235, 205, 70) -UI_DAMAGE_COLOR = (235, 75, 65) -UI_LEVEL_COLOR = (80, 220, 110) -UI_OVERLAY_COLOR = (16, 16, 22) -UI_PADDING = 12 -UI_LINE_HEIGHT = 22 -UI_BAR_HEIGHT = 16 -UI_SMALL_FONT_SIZE = 18 -UI_FONT_SIZE = 22 -UI_TITLE_FONT_SIZE = 40 -OVERLAY_WIDTH = 600 -OVERLAY_HEIGHT = 400 -ENTITY_INSET = 2 -ITEM_INSET = 4 -MESSAGE_WRAP_WIDTH = 34 - -HELP_LINES = ( - "Arrows / hjkl Move or melee attack", - "g Pick up item at feet", - "i Open inventory", - "e View/equip equipment", - "q Quaff a potion", - "r Read a scroll", - "> Descend stairs", - "S Save and quit", - "? Show this help", - "Esc Close or cancel", - "Arrows/letters Select; Enter confirms", -) \ No newline at end of file diff --git a/underdepths/data/enemies.py b/underdepths/data/enemies.py deleted file mode 100644 index 812f853..0000000 --- a/underdepths/data/enemies.py +++ /dev/null @@ -1,72 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from collections.abc import Mapping -from types import MappingProxyType - -from data.constants import ENEMY_ACCURACY, ENEMY_CRIT_CHANCE, ENEMY_EVASION -from entities.enemy import Enemy - - -@dataclass(frozen=True, slots=True) -class EnemyDefinition: - name: str - floors: tuple[int, int] - hp: int - power: int - armor: int - speed: int - behavior: str - xp: int - glyph: str - color: tuple[int, int, int] - ranged_power: int = 0 - - -ENEMY_CATALOG: Mapping[str, EnemyDefinition] = MappingProxyType({ - "Rat": EnemyDefinition("Rat", (0, 3), 8, 3, 0, 1, "wander", 5, "r", (140, 100, 60)), - "Goblin": EnemyDefinition("Goblin", (0, 5), 15, 5, 1, 1, "chase", 12, "g", (40, 180, 60)), - "Skeleton Archer": EnemyDefinition( - "Skeleton Archer", (2, 7), 12, 4, 1, 1, "ranged", 15, "s", (210, 210, 200), ranged_power=6 - ), - "Orc Warrior": EnemyDefinition( - "Orc Warrior", (3, 8), 30, 8, 3, 1, "flee", 25, "o", (150, 45, 35) - ), - "Wraith": EnemyDefinition("Wraith", (5, 8), 20, 10, 0, 2, "phase", 30, "w", (150, 80, 190)), - "Green Slime": EnemyDefinition( - "Green Slime", (4, 8), 18, 5, 1, 1, "split", 18, "S", (70, 230, 70) - ), - "Ancient Dragon": EnemyDefinition( - "Ancient Dragon", (9, 9), 120, 15, 8, 1, "dragon", 200, "D", (240, 40, 30) - ), -}) - - -def create_enemy(name: str, x: int, y: int) -> Enemy: - definition = ENEMY_CATALOG[name] - return Enemy( - x=x, - y=y, - glyph=definition.glyph, - color=definition.color, - name=definition.name, - hp=definition.hp, - max_hp=definition.hp, - power=definition.power, - armor=definition.armor, - accuracy=ENEMY_ACCURACY, - evasion=ENEMY_EVASION, - crit_chance=ENEMY_CRIT_CHANCE, - speed=definition.speed, - behavior=definition.behavior, - xp_reward=definition.xp, - ranged_power=definition.ranged_power, - ) - - -def enemy_names_for_floor(floor_index: int) -> tuple[str, ...]: - return tuple( - name - for name, enemy in ENEMY_CATALOG.items() - if name != "Ancient Dragon" and enemy.floors[0] <= floor_index <= enemy.floors[1] - ) diff --git a/underdepths/data/items.py b/underdepths/data/items.py deleted file mode 100644 index a977cca..0000000 --- a/underdepths/data/items.py +++ /dev/null @@ -1,106 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from collections.abc import Mapping -from types import MappingProxyType - -from data.constants import ( - FIREBALL_DAMAGE, - FIREBALL_RADIUS, - HEALING_AMOUNT, - INVISIBILITY_DURATION, - STRENGTH_BONUS, - STRENGTH_DURATION, -) -from entities.item import Item - - -@dataclass(frozen=True, slots=True) -class ItemDefinition: - name: str - category: str - glyph: str - color: tuple[int, int, int] - min_floor: int = 0 - power_bonus: int = 0 - armor_bonus: int = 0 - crit_bonus: float = 0.0 - evasion_bonus: float = 0.0 - effect: str = "" - amount: int = 0 - duration: int = 0 - radius: int = 0 - - -ITEM_CATALOG: Mapping[str, ItemDefinition] = MappingProxyType({ - "Rusty Dagger": ItemDefinition("Rusty Dagger", "weapon", "/", (230, 210, 80), power_bonus=2), - "Short Sword": ItemDefinition("Short Sword", "weapon", "/", (230, 210, 80), min_floor=2, power_bonus=4), - "Battle Axe": ItemDefinition("Battle Axe", "weapon", "/", (230, 210, 80), min_floor=4, power_bonus=7), - "War Hammer": ItemDefinition( - "War Hammer", "weapon", "/", (230, 210, 80), min_floor=7, power_bonus=10, crit_bonus=-0.05 - ), - "Leather Armor": ItemDefinition("Leather Armor", "armor", "[", (70, 130, 230), armor_bonus=2), - "Chain Mail": ItemDefinition("Chain Mail", "armor", "[", (70, 130, 230), min_floor=3, armor_bonus=4), - "Plate Armor": ItemDefinition( - "Plate Armor", "armor", "[", (70, 130, 230), min_floor=6, armor_bonus=7, evasion_bonus=-2.0 - ), - "Healing Potion": ItemDefinition( - "Healing Potion", "potion", "!", (220, 50, 50), effect="healing", amount=HEALING_AMOUNT - ), - "Strength Potion": ItemDefinition( - "Strength Potion", - "potion", - "!", - (220, 50, 50), - effect="strength", - amount=STRENGTH_BONUS, - duration=STRENGTH_DURATION, - ), - "Invisibility Potion": ItemDefinition( - "Invisibility Potion", - "potion", - "!", - (220, 50, 50), - effect="invisibility", - duration=INVISIBILITY_DURATION, - ), - "Scroll of Fireball": ItemDefinition( - "Scroll of Fireball", - "scroll", - "?", - (50, 220, 220), - effect="fireball", - amount=FIREBALL_DAMAGE, - radius=FIREBALL_RADIUS, - ), - "Scroll of Teleport": ItemDefinition( - "Scroll of Teleport", "scroll", "?", (50, 220, 220), effect="teleport" - ), - "Scroll of Mapping": ItemDefinition( - "Scroll of Mapping", "scroll", "?", (50, 220, 220), effect="mapping" - ), -}) - - -def create_item(name: str, x: int = 0, y: int = 0) -> Item: - definition = ITEM_CATALOG[name] - return Item( - x=x, - y=y, - glyph=definition.glyph, - color=definition.color, - name=definition.name, - category=definition.category, - power_bonus=definition.power_bonus, - armor_bonus=definition.armor_bonus, - crit_bonus=definition.crit_bonus, - evasion_bonus=definition.evasion_bonus, - effect=definition.effect, - amount=definition.amount, - duration=definition.duration, - radius=definition.radius, - ) - - -def item_names_for_floor(floor_index: int) -> tuple[str, ...]: - return tuple(name for name, item in ITEM_CATALOG.items() if item.min_floor <= floor_index) diff --git a/underdepths/engine/combat.py b/underdepths/engine/combat.py deleted file mode 100644 index 5172e63..0000000 --- a/underdepths/engine/combat.py +++ /dev/null @@ -1,95 +0,0 @@ -from __future__ import annotations - -import random - -from data.constants import ( - CRITICAL_DAMAGE_MULTIPLIER, - GAME_STATE_DEAD, - GAME_STATE_VICTORY, - HIT_ACCURACY_SCALE, - HIT_BASE_CHANCE, - HIT_MAX_CHANCE, - HIT_MIN_CHANCE, -) -from engine.game_state import GameSession, award_xp -from entities.enemy import Enemy -from entities.player import Player - -Combatant = Player | Enemy - - -def calculate_hit_chance(attacker: Combatant, defender: Combatant) -> float: - chance = HIT_BASE_CHANCE + (attacker.accuracy - defender.evasion) * HIT_ACCURACY_SCALE - return min(HIT_MAX_CHANCE, max(HIT_MIN_CHANCE, chance)) - - -def calculate_damage( - attacker: Combatant, - defender: Combatant, - weapon_bonus: int = 0, - critical: bool = False, -) -> int: - reduced = max(0, attacker.power + weapon_bonus - defender.armor) - return reduced * (CRITICAL_DAMAGE_MULTIPLIER if critical else 1) - - -def attack( - session: GameSession, - attacker: Combatant, - defender: Combatant, - weapon_bonus: int = 0, - rng: random.Random | None = None, -) -> int: - roller = rng or session.roller() - if roller.random() >= calculate_hit_chance(attacker, defender): - if rng is None: - session.save_roller(roller) - session.add_message(f"{_subject(attacker)} {_verb(attacker, 'miss')} {_object(defender)}") - return 0 - - critical = roller.random() < attacker.crit_chance - if rng is None: - session.save_roller(roller) - damage = calculate_damage(attacker, defender, weapon_bonus, critical) - defender.hp -= damage - prefix = "Critical hit! " if critical else "" - session.add_message( - f"{prefix}{_subject(attacker)} {_verb(attacker, 'hit')} {_object(defender)} " - f"for {damage} damage!" - ) - if defender.hp <= 0: - handle_death(session, defender) - return damage - - -def handle_death(session: GameSession, defender: Combatant) -> None: - if isinstance(defender, Player): - session.state = GAME_STATE_DEAD - session.add_message("You died!") - return - - if defender in session.current_map.entities: - session.current_map.entities.remove(defender) - session.add_message(f"You defeated the {defender.name}! (+{defender.xp_reward} XP)") - award_xp(session, defender.xp_reward) - if defender.behavior == "split": - from ai.behaviors import spawn_split_copies - - spawn_split_copies(session, defender) - if defender.name == "Ancient Dragon": - session.state = GAME_STATE_VICTORY - session.add_message("You slew the Ancient Dragon! You conquered Underdepths.") - - -def _subject(combatant: Combatant) -> str: - return "You" if isinstance(combatant, Player) else combatant.name - - -def _object(combatant: Combatant) -> str: - return "you" if isinstance(combatant, Player) else f"the {combatant.name}" - - -def _verb(combatant: Combatant, verb: str) -> str: - if isinstance(combatant, Player): - return verb - return "misses" if verb == "miss" else f"{verb}s" diff --git a/underdepths/engine/fov.py b/underdepths/engine/fov.py deleted file mode 100644 index a0b03a6..0000000 --- a/underdepths/engine/fov.py +++ /dev/null @@ -1,103 +0,0 @@ -from __future__ import annotations - -from data.constants import FOV_RADIUS, TILE_FLOOR -from engine.map_gen import GameMap - -_OCTANTS: tuple[tuple[int, int, int, int], ...] = ( - (1, 0, 0, 1), - (0, 1, 1, 0), - (0, -1, 1, 0), - (-1, 0, 0, 1), - (-1, 0, 0, -1), - (0, -1, -1, 0), - (0, 1, -1, 0), - (1, 0, 0, -1), -) - - -def compute_fov( - game_map: GameMap, - origin_x: int, - origin_y: int, - radius: int = FOV_RADIUS, -) -> None: - for index in range(len(game_map.visible)): - game_map.visible[index] = 0 - if not game_map.in_bounds(origin_x, origin_y): - return - - _mark_visible(game_map, origin_x, origin_y) - for xx, xy, yx, yy in _OCTANTS: - _cast_light(game_map, origin_x, origin_y, 1, 1.0, 0.0, radius, xx, xy, yx, yy) - - for index, visible in enumerate(game_map.visible): - if visible: - game_map.explored[index] = 1 - - -def _cast_light( - game_map: GameMap, - origin_x: int, - origin_y: int, - row: int, - start_slope: float, - end_slope: float, - radius: int, - xx: int, - xy: int, - yx: int, - yy: int, -) -> None: - if start_slope < end_slope: - return - - radius_squared = radius * radius - next_start_slope = start_slope - for distance in range(row, radius + 1): - blocked = False - delta_y = -distance - for delta_x in range(-distance, 1): - map_x = origin_x + delta_x * xx + delta_y * xy - map_y = origin_y + delta_x * yx + delta_y * yy - left_slope = (delta_x - 0.5) / (delta_y + 0.5) - right_slope = (delta_x + 0.5) / (delta_y - 0.5) - - if start_slope < right_slope: - continue - if end_slope > left_slope: - break - - in_bounds = game_map.in_bounds(map_x, map_y) - opaque = not in_bounds or game_map.tiles[game_map.index(map_x, map_y)] != TILE_FLOOR - if in_bounds and delta_x * delta_x + delta_y * delta_y <= radius_squared: - _mark_visible(game_map, map_x, map_y) - - if blocked: - if opaque: - next_start_slope = right_slope - continue - blocked = False - start_slope = next_start_slope - elif opaque and distance < radius: - blocked = True - _cast_light( - game_map, - origin_x, - origin_y, - distance + 1, - start_slope, - left_slope, - radius, - xx, - xy, - yx, - yy, - ) - next_start_slope = right_slope - - if blocked: - break - - -def _mark_visible(game_map: GameMap, x: int, y: int) -> None: - game_map.visible[game_map.index(x, y)] = 1 diff --git a/underdepths/engine/game_state.py b/underdepths/engine/game_state.py deleted file mode 100644 index 980d06d..0000000 --- a/underdepths/engine/game_state.py +++ /dev/null @@ -1,274 +0,0 @@ -from __future__ import annotations - -import random -from ast import literal_eval -from dataclasses import dataclass - -from data.constants import ( - FLOOR_COUNT, - GAME_STATE_PLAYING, - INVENTORY_CAPACITY, - LEVEL_HP_GAINS, - LEVEL_POWER_GAINS, - LEVEL_THRESHOLDS, - MESSAGE_LOG_LIMIT, - STRENGTH_BONUS, -) -from engine.fov import compute_fov -from engine.map_gen import GameMap, generate_dungeon -from entities.enemy import Enemy -from entities.item import Item -from entities.player import Player, create_player - - -@dataclass(slots=True) -class GameSession: - player: Player - dungeon: list[GameMap] - current_floor: int - log: list[str] - turn: int - state: str - rng_state: str - - @property - def current_map(self) -> GameMap: - return self.dungeon[self.current_floor] - - def add_message(self, message: str) -> None: - self.log.append(message) - del self.log[:-MESSAGE_LOG_LIMIT] - - def roller(self) -> random.Random: - roller = random.Random() - roller.setstate(_decode_rng_state(self.rng_state)) - return roller - - def save_roller(self, roller: random.Random) -> None: - self.rng_state = _encode_rng_state(roller.getstate()) - - -def _encode_rng_state(state: object) -> str: - return repr(state) - - -def _decode_rng_state(encoded: str) -> tuple[object, ...]: - return literal_eval(encoded) - -def new_game(seed: int | None = None) -> GameSession: - rng = random.Random(seed) - dungeon = [generate_dungeon(floor_index, rng) for floor_index in range(FLOOR_COUNT)] - spawn_x, spawn_y = dungeon[0].spawn - session = GameSession( - player=create_player(spawn_x, spawn_y), - dungeon=dungeon, - current_floor=0, - log=["You enter the Underdepths."], - turn=0, - state=GAME_STATE_PLAYING, - rng_state=_encode_rng_state(rng.getstate()), - ) - compute_fov(session.current_map, spawn_x, spawn_y) - return session - - -def pickup_item(session: GameSession) -> bool: - item = next( - ( - entity - for entity in session.current_map.entities - if isinstance(entity, Item) and entity.position == session.player.position - ), - None, - ) - if item is None: - session.add_message("There is nothing here to pick up.") - return False - if len(session.player.inventory) >= INVENTORY_CAPACITY: - session.add_message("Your inventory is full.") - return False - session.current_map.entities.remove(item) - session.player.inventory.append(item) - session.add_message(f"You pick up the {item.name}.") - return True - - -def equip_item(session: GameSession, item: Item) -> bool: - player = session.player - if item not in player.inventory or item.category not in {"weapon", "armor"}: - session.add_message(f"You cannot equip the {item.name}.") - return False - slot = "weapon" if item.category == "weapon" else "armor_item" - current = getattr(player, slot) - player.inventory.remove(item) - if current is not None: - _apply_equipment(player, current, -1) - player.inventory.append(current) - setattr(player, slot, item) - _apply_equipment(player, item, 1) - session.add_message(f"You equip the {item.name}.") - return True - - -def use_item( - session: GameSession, - item: Item, - target: tuple[int, int] | None = None, - rng: random.Random | None = None, -) -> bool: - if item not in session.player.inventory or item.category not in {"potion", "scroll"}: - session.add_message(f"You cannot use the {item.name}.") - return False - if item.effect == "fireball" and target is None: - session.add_message("Choose a target for the fireball.") - return False - - roller = rng or session.roller() - used = _apply_item_effect(session, item, target, roller) - if used: - session.player.inventory.remove(item) - if rng is None: - session.save_roller(roller) - return used - - -def award_xp(session: GameSession, amount: int) -> int: - player = session.player - player.xp += amount - levels_gained = 0 - while player.level <= len(LEVEL_THRESHOLDS) and player.xp >= LEVEL_THRESHOLDS[player.level - 1]: - index = player.level - 1 - hp_gain = LEVEL_HP_GAINS[index] - power_gain = LEVEL_POWER_GAINS[index] - player.level += 1 - player.max_hp += hp_gain - player.power += power_gain - player.hp = player.max_hp - levels_gained += 1 - session.add_message( - f"You reach level {player.level}! (HP +{hp_gain}, Power +{power_gain})" - ) - return levels_gained - - -def tick_player_effects(session: GameSession) -> None: - player = session.player - if player.strength_turns > 0: - player.strength_turns -= 1 - if player.strength_turns == 0: - player.power -= STRENGTH_BONUS - session.add_message("Your supernatural strength fades.") - if player.invisibility_turns > 0: - player.invisibility_turns -= 1 - if player.invisibility_turns == 0: - session.add_message("You become visible again.") - - -def descend_floor(session: GameSession) -> bool: - if session.current_map.stairs_down is None or session.player.position != session.current_map.stairs_down: - session.add_message("There are no stairs here.") - return False - if session.current_floor + 1 >= len(session.dungeon): - session.add_message("There is nowhere deeper to descend.") - return False - session.current_floor += 1 - session.player.x, session.player.y = session.current_map.spawn - session.add_message(f"You descend to floor {session.current_floor + 1}.") - return True - - -def _apply_equipment(player: Player, item: Item, direction: int) -> None: - player.power += item.power_bonus * direction - player.armor += item.armor_bonus * direction - player.crit_chance += item.crit_bonus * direction - player.evasion += item.evasion_bonus * direction - - -def _apply_item_effect( - session: GameSession, - item: Item, - target: tuple[int, int] | None, - roller: random.Random, -) -> bool: - player = session.player - if item.effect == "healing": - healed = min(item.amount, player.max_hp - player.hp) - player.hp += healed - session.add_message(f"You drink the {item.name} and recover {healed} HP.") - elif item.effect == "strength": - if player.strength_turns == 0: - player.power += item.amount - player.strength_turns = item.duration - session.add_message(f"Power surges through you for {item.duration} turns.") - elif item.effect == "invisibility": - player.invisibility_turns = item.duration - session.add_message(f"You vanish from sight for {item.duration} turns.") - elif item.effect == "fireball" and target is not None: - _cast_fireball(session, target, item.amount, item.radius) - elif item.effect == "teleport": - occupied = { - entity.position - for entity in session.current_map.entities - if isinstance(entity, Enemy) and entity.hp > 0 - } - choices = [ - (x, y) - for y in range(session.current_map.height) - for x in range(session.current_map.width) - if session.current_map.is_floor(x, y) and (x, y) not in occupied - and (x, y) != player.position - ] - if not choices: - session.add_message("The teleport spell fizzles.") - return False - player.x, player.y = roller.choice(choices) - session.add_message("Space twists and you teleport across the floor.") - elif item.effect == "mapping": - for index in range(len(session.current_map.explored)): - session.current_map.explored[index] = 1 - session.add_message("The scroll reveals the entire floor.") - else: - return False - return True - - -def _cast_fireball( - session: GameSession, target: tuple[int, int], damage: int, radius: int -) -> None: - from engine.combat import handle_death - - session.add_message(f"A fireball explodes at {target}!") - for entity in list(session.current_map.entities): - if not isinstance(entity, Enemy) or entity.hp <= 0: - continue - dx = entity.x - target[0] - dy = entity.y - target[1] - if dx * dx + dy * dy > radius * radius: - continue - entity.hp -= damage - session.add_message(f"The {entity.name} takes {damage} fire damage!") - if entity.hp <= 0: - handle_death(session, entity) - - -def move_player(session: GameSession, dx: int, dy: int) -> bool: - target = session.player.x + dx, session.player.y + dy - enemy = next( - ( - entity - for entity in session.current_map.entities - if isinstance(entity, Enemy) and entity.position == target and entity.hp > 0 - ), - None, - ) - if enemy is not None: - from engine.combat import attack - - attack(session, session.player, enemy) - elif session.current_map.is_floor(*target): - session.player.x, session.player.y = target - else: - return False - tick_player_effects(session) - session.turn += 1 - return True diff --git a/underdepths/engine/map_gen.py b/underdepths/engine/map_gen.py deleted file mode 100644 index f62e71b..0000000 --- a/underdepths/engine/map_gen.py +++ /dev/null @@ -1,284 +0,0 @@ -from __future__ import annotations - -import random -from array import array -from dataclasses import dataclass - -from data.constants import ( - BSP_MAX_SPLITS, - BSP_MIN_SPLITS, - BOSS_ARENA_HEIGHT, - BOSS_ARENA_WIDTH, - BOSS_FLOOR, - FLOOR_SPAWN_COUNTS, - MAP_HEIGHT, - MAP_WIDTH, - ROOM_MARGIN, - ROOM_MAX_HEIGHT, - ROOM_MAX_WIDTH, - ROOM_MIN_HEIGHT, - ROOM_MIN_WIDTH, - TILE_FLOOR, - TILE_WALL, -) -from entities.entity import Entity - - -@dataclass(frozen=True, slots=True) -class Rect: - x: int - y: int - width: int - height: int - - @property - def right(self) -> int: - return self.x + self.width - - @property - def bottom(self) -> int: - return self.y + self.height - - @property - def center(self) -> tuple[int, int]: - return self.x + self.width // 2, self.y + self.height // 2 - - def intersects(self, other: Rect) -> bool: - return not ( - self.right <= other.x - or other.right <= self.x - or self.bottom <= other.y - or other.bottom <= self.y - ) - - -@dataclass(slots=True) -class GameMap: - width: int - height: int - tiles: array[int] - rooms: list[Rect] - explored: array[int] - visible: array[int] - entities: list[Entity] - stairs_down: tuple[int, int] | None - spawn: tuple[int, int] - floor_index: int - - def index(self, x: int, y: int) -> int: - return y * self.width + x - - def in_bounds(self, x: int, y: int) -> bool: - return 0 <= x < self.width and 0 <= y < self.height - - def is_floor(self, x: int, y: int) -> bool: - return self.in_bounds(x, y) and self.tiles[self.index(x, y)] == TILE_FLOOR - - def ascii(self) -> str: - rows: list[str] = [] - for y in range(self.height): - row: list[str] = [] - for x in range(self.width): - position = (x, y) - if position == self.spawn: - row.append("@") - elif position == self.stairs_down: - row.append(">") - else: - row.append("." if self.is_floor(x, y) else "#") - rows.append("".join(row)) - return "\n".join(rows) - - -@dataclass(slots=True) -class _Node: - region: Rect - depth: int - left: _Node | None = None - right: _Node | None = None - room: Rect | None = None - - @property - def is_leaf(self) -> bool: - return self.left is None - - -_MIN_REGION_WIDTH = ROOM_MIN_WIDTH + ROOM_MARGIN * 2 -_MIN_REGION_HEIGHT = ROOM_MIN_HEIGHT + ROOM_MARGIN * 2 - - -def _split(node: _Node, rng: random.Random) -> bool: - can_split_vertical = node.region.width >= _MIN_REGION_WIDTH * 2 - can_split_horizontal = node.region.height >= _MIN_REGION_HEIGHT * 2 - if not can_split_vertical and not can_split_horizontal: - return False - - split_vertical = node.depth % 2 == 0 - if split_vertical and not can_split_vertical: - split_vertical = False - elif not split_vertical and not can_split_horizontal: - split_vertical = True - - region = node.region - if split_vertical: - offset = rng.randint(_MIN_REGION_WIDTH, region.width - _MIN_REGION_WIDTH) - first = Rect(region.x, region.y, offset, region.height) - second = Rect(region.x + offset, region.y, region.width - offset, region.height) - else: - offset = rng.randint(_MIN_REGION_HEIGHT, region.height - _MIN_REGION_HEIGHT) - first = Rect(region.x, region.y, region.width, offset) - second = Rect(region.x, region.y + offset, region.width, region.height - offset) - - node.left = _Node(first, node.depth + 1) - node.right = _Node(second, node.depth + 1) - return True - - -def _carve_tile(game_map: GameMap, x: int, y: int) -> None: - game_map.tiles[game_map.index(x, y)] = TILE_FLOOR - - -def _carve_room(game_map: GameMap, room: Rect) -> None: - for y in range(room.y, room.bottom): - for x in range(room.x, room.right): - _carve_tile(game_map, x, y) - - -def _carve_corridor( - game_map: GameMap, - start: tuple[int, int], - end: tuple[int, int], - rng: random.Random, -) -> None: - x1, y1 = start - x2, y2 = end - corner = (x2, y1) if rng.random() < 0.5 else (x1, y2) - for x in range(min(x1, corner[0]), max(x1, corner[0]) + 1): - _carve_tile(game_map, x, y1) - for y in range(min(y1, corner[1]), max(y1, corner[1]) + 1): - _carve_tile(game_map, corner[0], y) - for x in range(min(corner[0], x2), max(corner[0], x2) + 1): - _carve_tile(game_map, x, y2) - for y in range(min(corner[1], y2), max(corner[1], y2) + 1): - _carve_tile(game_map, x2, y) - - -def _carve_tree(game_map: GameMap, node: _Node, rng: random.Random) -> tuple[int, int]: - if node.is_leaf: - region = node.region - room_width = rng.randint(ROOM_MIN_WIDTH, min(ROOM_MAX_WIDTH, region.width - ROOM_MARGIN * 2)) - room_height = rng.randint(ROOM_MIN_HEIGHT, min(ROOM_MAX_HEIGHT, region.height - ROOM_MARGIN * 2)) - room = Rect( - rng.randint(region.x + ROOM_MARGIN, region.right - room_width - ROOM_MARGIN), - rng.randint(region.y + ROOM_MARGIN, region.bottom - room_height - ROOM_MARGIN), - room_width, - room_height, - ) - node.room = room - game_map.rooms.append(room) - _carve_room(game_map, room) - return room.center - - if node.left is None or node.right is None: - raise RuntimeError("invalid BSP tree") - left_center = _carve_tree(game_map, node.left, rng) - right_center = _carve_tree(game_map, node.right, rng) - _carve_corridor(game_map, left_center, right_center, rng) - return left_center - - -def generate_dungeon(floor_index: int = 0, rng: random.Random | None = None) -> GameMap: - rng = rng or random.Random() - if floor_index == BOSS_FLOOR: - return _generate_boss_arena(rng) - - root = _Node(Rect(1, 1, MAP_WIDTH - 2, MAP_HEIGHT - 2), 0) - leaves = [root] - for _ in range(rng.randint(BSP_MIN_SPLITS, BSP_MAX_SPLITS)): - candidates = [leaf for leaf in leaves if _split_possible(leaf)] - if not candidates: - break - leaf = max(candidates, key=lambda candidate: candidate.region.width * candidate.region.height) - leaves.remove(leaf) - if _split(leaf, rng): - if leaf.left is None or leaf.right is None: - raise RuntimeError("BSP split did not create children") - leaves.extend((leaf.left, leaf.right)) - - game_map = _empty_map(floor_index) - _carve_tree(game_map, root, rng) - game_map.spawn = game_map.rooms[0].center - game_map.stairs_down = max( - (room.center for room in game_map.rooms), - key=lambda center: abs(center[0] - game_map.spawn[0]) + abs(center[1] - game_map.spawn[1]), - ) - _spawn_content(game_map, rng) - return game_map - - -def _empty_map(floor_index: int) -> GameMap: - size = MAP_WIDTH * MAP_HEIGHT - return GameMap( - width=MAP_WIDTH, - height=MAP_HEIGHT, - tiles=array("B", [TILE_WALL]) * size, - rooms=[], - explored=array("B", [0]) * size, - visible=array("B", [0]) * size, - entities=[], - stairs_down=None, - spawn=(0, 0), - floor_index=floor_index, - ) - - -def _generate_boss_arena(rng: random.Random) -> GameMap: - from data.enemies import create_enemy - from data.items import create_item - - game_map = _empty_map(BOSS_FLOOR) - arena = Rect( - rng.randint(1, MAP_WIDTH - BOSS_ARENA_WIDTH - 1), - rng.randint(1, MAP_HEIGHT - BOSS_ARENA_HEIGHT - 1), - BOSS_ARENA_WIDTH, - BOSS_ARENA_HEIGHT, - ) - game_map.rooms.append(arena) - _carve_room(game_map, arena) - entrance_x = arena.x + 1 - entrance_y = arena.y + arena.height // 2 - game_map.spawn = (entrance_x, entrance_y) - game_map.entities.append(create_enemy("Ancient Dragon", arena.right - 2, entrance_y)) - potion_positions = ((entrance_x + 1, entrance_y - 1), (entrance_x + 1, entrance_y + 1)) - game_map.entities.extend(create_item("Healing Potion", x, y) for x, y in potion_positions) - return game_map - - -def _spawn_content(game_map: GameMap, rng: random.Random) -> None: - from data.enemies import create_enemy, enemy_names_for_floor - from data.items import create_item, item_names_for_floor - - minimum_enemies, maximum_enemies, minimum_items, maximum_items = FLOOR_SPAWN_COUNTS[game_map.floor_index] - enemy_count = rng.randint(minimum_enemies, maximum_enemies) - item_count = rng.randint(minimum_items, maximum_items) - blocked = {game_map.spawn, game_map.stairs_down} - positions = [ - (x, y) - for y in range(game_map.height) - for x in range(game_map.width) - if game_map.is_floor(x, y) and (x, y) not in blocked - ] - rng.shuffle(positions) - enemy_names = enemy_names_for_floor(game_map.floor_index) - item_names = item_names_for_floor(game_map.floor_index) - for position in positions[:enemy_count]: - game_map.entities.append(create_enemy(rng.choice(enemy_names), *position)) - for position in positions[enemy_count : enemy_count + item_count]: - game_map.entities.append(create_item(rng.choice(item_names), *position)) - - -def _split_possible(node: _Node) -> bool: - return ( - node.region.width >= _MIN_REGION_WIDTH * 2 - or node.region.height >= _MIN_REGION_HEIGHT * 2 - ) diff --git a/underdepths/engine/pathfinding.py b/underdepths/engine/pathfinding.py deleted file mode 100644 index fe13caa..0000000 --- a/underdepths/engine/pathfinding.py +++ /dev/null @@ -1,72 +0,0 @@ -from __future__ import annotations - -import heapq -from collections.abc import Iterable, Iterator - -from engine.map_gen import GameMap - -Position = tuple[int, int] - - -def manhattan_distance(start: Position, goal: Position) -> int: - return abs(start[0] - goal[0]) + abs(start[1] - goal[1]) - - -def _neighbors(position: Position) -> Iterator[Position]: - x, y = position - yield x, y - 1 - yield x - 1, y - yield x + 1, y - yield x, y + 1 - - -def _reconstruct_path( - came_from: dict[Position, Position], start: Position, goal: Position -) -> list[Position]: - path: list[Position] = [] - current = goal - while current != start: - path.append(current) - current = came_from[current] - path.reverse() - return path - - -def find_path( - game_map: GameMap, - start: Position, - goal: Position, - occupied: Iterable[Position] = (), -) -> list[Position]: - """Return cardinal steps after start through goal, or an empty list if unreachable.""" - if start == goal or not game_map.is_floor(*start) or not game_map.is_floor(*goal): - return [] - - blocked = set(occupied) - blocked.discard(start) - frontier: list[tuple[int, int, Position]] = [ - (manhattan_distance(start, goal), 0, start) - ] - came_from: dict[Position, Position] = {} - costs = {start: 0} - - while frontier: - _, cost, current = heapq.heappop(frontier) - if cost != costs.get(current): - continue - if current == goal: - return _reconstruct_path(came_from, start, goal) - - for neighbor in _neighbors(current): - if neighbor in blocked or not game_map.is_floor(*neighbor): - continue - new_cost = cost + 1 - known_cost = costs.get(neighbor) - if known_cost is not None and new_cost >= known_cost: - continue - costs[neighbor] = new_cost - came_from[neighbor] = current - priority = new_cost + manhattan_distance(neighbor, goal) - heapq.heappush(frontier, (priority, new_cost, neighbor)) - - return [] diff --git a/underdepths/engine/serializers.py b/underdepths/engine/serializers.py deleted file mode 100644 index 3d9446f..0000000 --- a/underdepths/engine/serializers.py +++ /dev/null @@ -1,187 +0,0 @@ -from __future__ import annotations - -import json -from array import array -from dataclasses import fields -from pathlib import Path -from typing import Any, Mapping - -from data.constants import FLOOR_COUNT, SAVE_FILENAME -from engine.fov import compute_fov -from engine.game_state import GameSession -from engine.map_gen import GameMap, Rect -from entities.enemy import Enemy -from entities.item import Item -from entities.player import Player - -SAVE_VERSION = 1 -DEFAULT_SAVE_PATH = Path(__file__).resolve().parents[1] / SAVE_FILENAME - - -def _field_data(value: object) -> dict[str, Any]: - return {field.name: getattr(value, field.name) for field in fields(value)} - - -def _item_to_dict(item: Item) -> dict[str, Any]: - return _field_data(item) - - -def _item_from_dict(data: Mapping[str, Any]) -> Item: - values = dict(data) - values["color"] = tuple(values["color"]) - return Item(**values) - - -def _enemy_to_dict(enemy: Enemy) -> dict[str, Any]: - return _field_data(enemy) - - -def _enemy_from_dict(data: Mapping[str, Any]) -> Enemy: - values = dict(data) - values["color"] = tuple(values["color"]) - if values.get("last_known_position") is not None: - values["last_known_position"] = tuple(values["last_known_position"]) - return Enemy(**values) - - -def _player_to_dict(player: Player) -> dict[str, Any]: - data = _field_data(player) - data["inventory"] = [_item_to_dict(item) for item in player.inventory] - data["weapon"] = _item_to_dict(player.weapon) if player.weapon else None - data["armor_item"] = _item_to_dict(player.armor_item) if player.armor_item else None - return data - - -def _player_from_dict(data: Mapping[str, Any]) -> Player: - values = dict(data) - values["color"] = tuple(values["color"]) - values["inventory"] = [_item_from_dict(item) for item in values["inventory"]] - values["weapon"] = _item_from_dict(values["weapon"]) if values.get("weapon") else None - values["armor_item"] = ( - _item_from_dict(values["armor_item"]) if values.get("armor_item") else None - ) - return Player(**values) - - -def _map_to_dict(game_map: GameMap) -> dict[str, Any]: - entities = [] - for entity in game_map.entities: - if isinstance(entity, Enemy): - entities.append({"type": "enemy", "data": _enemy_to_dict(entity)}) - elif isinstance(entity, Item): - entities.append({"type": "item", "data": _item_to_dict(entity)}) - else: - raise TypeError(f"unsupported entity type: {type(entity).__name__}") - return { - "width": game_map.width, - "height": game_map.height, - "tiles": list(game_map.tiles), - "rooms": [_field_data(room) for room in game_map.rooms], - "explored": list(game_map.explored), - "entities": entities, - "stairs_down": game_map.stairs_down, - "spawn": game_map.spawn, - "floor_index": game_map.floor_index, - } - - -def _map_from_dict(data: Mapping[str, Any]) -> GameMap: - entities = [] - for entry in data["entities"]: - kind = entry["type"] - if kind == "enemy": - entities.append(_enemy_from_dict(entry["data"])) - elif kind == "item": - entities.append(_item_from_dict(entry["data"])) - else: - raise ValueError(f"unknown entity type: {kind!r}") - width = int(data["width"]) - height = int(data["height"]) - tiles = array("B", data["tiles"]) - explored = array("B", data["explored"]) - if len(tiles) != width * height or len(explored) != width * height: - raise ValueError("save contains an invalid map grid") - stairs = data.get("stairs_down") - return GameMap( - width=width, - height=height, - tiles=tiles, - rooms=[Rect(**room) for room in data["rooms"]], - explored=explored, - visible=array("B", [0]) * (width * height), - entities=entities, - stairs_down=tuple(stairs) if stairs is not None else None, - spawn=tuple(data["spawn"]), - floor_index=int(data["floor_index"]), - ) - - -def session_to_dict(session: GameSession) -> dict[str, Any]: - return { - "version": SAVE_VERSION, - "player": _player_to_dict(session.player), - "dungeon": [_map_to_dict(game_map) for game_map in session.dungeon], - "current_floor": session.current_floor, - "log": list(session.log), - "turn": session.turn, - "state": session.state, - "rng_state": session.rng_state, - } - - -def session_from_dict(data: Mapping[str, Any]) -> GameSession: - try: - if data.get("version") != SAVE_VERSION: - raise ValueError("unsupported save version") - dungeon = [_map_from_dict(game_map) for game_map in data["dungeon"]] - current_floor = int(data["current_floor"]) - if len(dungeon) != FLOOR_COUNT or not 0 <= current_floor < len(dungeon): - raise ValueError("save must contain all ten floors and a valid current floor") - session = GameSession( - player=_player_from_dict(data["player"]), - dungeon=dungeon, - current_floor=current_floor, - log=[str(message) for message in data["log"]], - turn=int(data["turn"]), - state=str(data["state"]), - rng_state=str(data["rng_state"]), - ) - except (KeyError, TypeError, OverflowError) as error: - raise ValueError("save file is malformed") from error - compute_fov(session.current_map, session.player.x, session.player.y) - return session - - -def save_game(session: GameSession, path: str | Path = DEFAULT_SAVE_PATH) -> Path: - destination = Path(path) - destination.parent.mkdir(parents=True, exist_ok=True) - temporary = destination.with_suffix(destination.suffix + ".tmp") - try: - temporary.write_text( - json.dumps(session_to_dict(session), separators=(",", ":")), - encoding="utf-8", - ) - temporary.replace(destination) - except OSError: - temporary.unlink(missing_ok=True) - raise - return destination - - -def load_game(path: str | Path = DEFAULT_SAVE_PATH) -> GameSession: - source = Path(path) - try: - data = json.loads(source.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as error: - raise ValueError(f"could not load save: {error}") from error - if not isinstance(data, dict): - raise ValueError("save root must be an object") - return session_from_dict(data) - - -def delete_save(path: str | Path = DEFAULT_SAVE_PATH) -> None: - Path(path).unlink(missing_ok=True) - - -def save_exists(path: str | Path = DEFAULT_SAVE_PATH) -> bool: - return Path(path).is_file() diff --git a/underdepths/entities/enemy.py b/underdepths/entities/enemy.py deleted file mode 100644 index 3429407..0000000 --- a/underdepths/entities/enemy.py +++ /dev/null @@ -1,22 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass - -from entities.entity import Entity - - -@dataclass(slots=True) -class Enemy(Entity): - hp: int - max_hp: int - power: int - armor: int - accuracy: int - evasion: int - crit_chance: float - speed: int - behavior: str - xp_reward: int - last_known_position: tuple[int, int] | None = None - ranged_power: int = 0 - has_split: bool = False diff --git a/underdepths/entities/entity.py b/underdepths/entities/entity.py deleted file mode 100644 index c400a01..0000000 --- a/underdepths/entities/entity.py +++ /dev/null @@ -1,16 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass - - -@dataclass(slots=True) -class Entity: - x: int - y: int - glyph: str - color: tuple[int, int, int] - name: str - - @property - def position(self) -> tuple[int, int]: - return self.x, self.y diff --git a/underdepths/entities/item.py b/underdepths/entities/item.py deleted file mode 100644 index a4336f9..0000000 --- a/underdepths/entities/item.py +++ /dev/null @@ -1,18 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass - -from entities.entity import Entity - - -@dataclass(slots=True) -class Item(Entity): - category: str - power_bonus: int = 0 - armor_bonus: int = 0 - crit_bonus: float = 0.0 - evasion_bonus: float = 0.0 - effect: str = "" - amount: int = 0 - duration: int = 0 - radius: int = 0 diff --git a/underdepths/entities/player.py b/underdepths/entities/player.py deleted file mode 100644 index 8c1dba4..0000000 --- a/underdepths/entities/player.py +++ /dev/null @@ -1,56 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass, field - -from data.constants import ( - PLAYER_ACCURACY, - PLAYER_ARMOR, - PLAYER_COLOR, - PLAYER_CRIT_CHANCE, - PLAYER_EVASION, - PLAYER_GLYPH, - PLAYER_MAX_HP, - PLAYER_POWER, - PLAYER_SPEED, -) -from entities.entity import Entity -from entities.item import Item - - -@dataclass(slots=True) -class Player(Entity): - hp: int - max_hp: int - power: int - armor: int - accuracy: int - evasion: int - crit_chance: float - speed: int - level: int - xp: int - inventory: list[Item] = field(default_factory=list) - weapon: Item | None = None - armor_item: Item | None = None - strength_turns: int = 0 - invisibility_turns: int = 0 - - -def create_player(x: int, y: int) -> Player: - return Player( - x=x, - y=y, - glyph=PLAYER_GLYPH, - color=PLAYER_COLOR, - name="You", - hp=PLAYER_MAX_HP, - max_hp=PLAYER_MAX_HP, - power=PLAYER_POWER, - armor=PLAYER_ARMOR, - accuracy=PLAYER_ACCURACY, - evasion=PLAYER_EVASION, - crit_chance=PLAYER_CRIT_CHANCE, - speed=PLAYER_SPEED, - level=1, - xp=0, - ) diff --git a/underdepths/main.py b/underdepths/main.py deleted file mode 100644 index 446c64f..0000000 --- a/underdepths/main.py +++ /dev/null @@ -1,686 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from pathlib import Path -from textwrap import wrap - -import pygame - -from ai.behaviors import take_enemy_turns -from data.constants import ( - BACKGROUND_COLOR, - BOTTOM_PANEL_HEIGHT, - ENTITY_INSET, - EXPLORED_FLOOR_COLOR, - EXPLORED_WALL_COLOR, - FLOOR_COLOR, - FPS, - GAME_STATE_DEAD, - GAME_STATE_PLAYING, - GAME_STATE_VICTORY, - GAME_TITLE, - HELP_LINES, - ITEM_INSET, - LEVEL_THRESHOLDS, - MESSAGE_WRAP_WIDTH, - OVERLAY_HEIGHT, - OVERLAY_WIDTH, - PLAYER_COLOR, - RIGHT_PANEL_WIDTH, - STAIRS_COLOR, - TILE_SIZE, - TOP_PANEL_HEIGHT, - UI_BACKGROUND_COLOR, - UI_BAR_HEIGHT, - UI_BORDER_COLOR, - UI_DAMAGE_COLOR, - UI_FONT_SIZE, - UI_HEALTH_COLOR, - UI_HEALTH_MISSING_COLOR, - UI_ITEM_COLOR, - UI_LEVEL_COLOR, - UI_LINE_HEIGHT, - UI_MUTED_COLOR, - UI_OVERLAY_COLOR, - UI_PADDING, - UI_PANEL_COLOR, - UI_SMALL_FONT_SIZE, - UI_TEXT_COLOR, - UI_TITLE_FONT_SIZE, - UI_XP_COLOR, - VIEWPORT_HEIGHT, - VIEWPORT_WIDTH, - WALL_COLOR, - WINDOW_HEIGHT, - WINDOW_WIDTH, -) -from engine.fov import compute_fov -from engine.game_state import ( - GameSession, - descend_floor, - equip_item, - move_player, - new_game, - pickup_item, - tick_player_effects, - use_item, -) -from engine.serializers import ( - DEFAULT_SAVE_PATH, - delete_save, - load_game, - save_exists, - save_game, -) -from entities.item import Item - -MENU_NEW_GAME = "New Game" -MENU_CONTINUE = "Continue" -MENU_QUIT = "Quit" -MODE_GAME = "game" -MODE_INVENTORY = "inventory" -MODE_EQUIPMENT = "equipment" -MODE_POTION = "potion" -MODE_SCROLL = "scroll" -MODE_HELP = "help" -MODE_TARGET = "target" -ACTION_NONE = "none" -ACTION_TURN = "turn" -ACTION_SAVED = "saved" - -_MOVE_KEYS: dict[int, tuple[int, int]] = { - pygame.K_UP: (0, -1), - pygame.K_k: (0, -1), - pygame.K_DOWN: (0, 1), - pygame.K_j: (0, 1), - pygame.K_LEFT: (-1, 0), - pygame.K_h: (-1, 0), - pygame.K_RIGHT: (1, 0), - pygame.K_l: (1, 0), -} - - -@dataclass(slots=True) -class UIState: - mode: str = MODE_GAME - selected: int = 0 - target: tuple[int, int] | None = None - pending_item: Item | None = None - - -@dataclass(frozen=True, slots=True) -class Fonts: - small: pygame.font.Font - normal: pygame.font.Font - title: pygame.font.Font - - -def create_fonts() -> Fonts: - return Fonts( - small=pygame.font.Font(None, UI_SMALL_FONT_SIZE), - normal=pygame.font.Font(None, UI_FONT_SIZE), - title=pygame.font.Font(None, UI_TITLE_FONT_SIZE), - ) - - -def menu_options(save_path: str | Path = DEFAULT_SAVE_PATH) -> tuple[str, ...]: - if save_exists(save_path): - return MENU_NEW_GAME, MENU_CONTINUE, MENU_QUIT - return MENU_NEW_GAME, MENU_QUIT - - -def handle_menu_key( - key: int, selected: int, options: tuple[str, ...] -) -> tuple[int, str | None]: - if not options: - return 0, None - if key in {pygame.K_UP, pygame.K_k}: - return (selected - 1) % len(options), None - if key in {pygame.K_DOWN, pygame.K_j}: - return (selected + 1) % len(options), None - if key in {pygame.K_RETURN, pygame.K_KP_ENTER}: - return selected % len(options), options[selected % len(options)] - direct = { - pygame.K_n: MENU_NEW_GAME, - pygame.K_c: MENU_CONTINUE, - pygame.K_q: MENU_QUIT, - pygame.K_ESCAPE: MENU_QUIT, - }.get(key) - return selected % len(options), direct if direct in options else None - - -def activate_menu_option( - option: str, save_path: str | Path = DEFAULT_SAVE_PATH -) -> GameSession | None: - if option == MENU_QUIT: - return None - session = new_game() if option == MENU_NEW_GAME else load_game(save_path) - if session.state != GAME_STATE_PLAYING: - delete_save(save_path) - raise ValueError("the saved run has already ended") - compute_fov(session.current_map, session.player.x, session.player.y) - return session - - -def enforce_permadeath( - session: GameSession, save_path: str | Path = DEFAULT_SAVE_PATH -) -> bool: - if session.state not in {GAME_STATE_DEAD, GAME_STATE_VICTORY}: - return False - delete_save(save_path) - return True - - -def _finish_turn(session: GameSession) -> None: - tick_player_effects(session) - session.turn += 1 - take_enemy_turns(session) - compute_fov(session.current_map, session.player.x, session.player.y) - - -def _open_mode(ui: UIState, mode: str) -> None: - ui.mode = mode - ui.selected = 0 - ui.target = None - ui.pending_item = None - - -def selectable_items(session: GameSession, mode: str) -> list[Item]: - if mode == MODE_EQUIPMENT: - return [item for item in session.player.inventory if item.category in {"weapon", "armor"}] - if mode == MODE_POTION: - return [item for item in session.player.inventory if item.category == "potion"] - if mode == MODE_SCROLL: - return [item for item in session.player.inventory if item.category == "scroll"] - return list(session.player.inventory) - - -def _confirm_item(session: GameSession, ui: UIState, item: Item) -> str: - if item.category in {"weapon", "armor"}: - if equip_item(session, item): - _open_mode(ui, MODE_GAME) - _finish_turn(session) - return ACTION_TURN - return ACTION_NONE - if item.effect == "fireball": - ui.mode = MODE_TARGET - ui.target = session.player.position - ui.pending_item = item - return ACTION_NONE - if use_item(session, item): - _open_mode(ui, MODE_GAME) - _finish_turn(session) - return ACTION_TURN - return ACTION_NONE - - -def _handle_target_key(session: GameSession, key: int, ui: UIState) -> str: - if key == pygame.K_ESCAPE: - _open_mode(ui, MODE_SCROLL) - return ACTION_NONE - if key in _MOVE_KEYS and ui.target is not None: - dx, dy = _MOVE_KEYS[key] - x = min(max(0, ui.target[0] + dx), session.current_map.width - 1) - y = min(max(0, ui.target[1] + dy), session.current_map.height - 1) - ui.target = x, y - return ACTION_NONE - if key not in {pygame.K_RETURN, pygame.K_KP_ENTER}: - return ACTION_NONE - if ui.pending_item is None or ui.target is None: - _open_mode(ui, MODE_GAME) - return ACTION_NONE - if not session.current_map.visible[session.current_map.index(*ui.target)]: - session.add_message("You cannot target a place you cannot see.") - return ACTION_NONE - if use_item(session, ui.pending_item, ui.target): - _open_mode(ui, MODE_GAME) - _finish_turn(session) - return ACTION_TURN - return ACTION_NONE - - -def _handle_overlay_key(session: GameSession, key: int, ui: UIState) -> str: - if ui.mode == MODE_TARGET: - return _handle_target_key(session, key, ui) - if key == pygame.K_ESCAPE: - _open_mode(ui, MODE_GAME) - return ACTION_NONE - if ui.mode == MODE_HELP: - if key in {pygame.K_SLASH, getattr(pygame, "K_QUESTION", ord("?"))}: - _open_mode(ui, MODE_GAME) - return ACTION_NONE - - items = selectable_items(session, ui.mode) - if not items: - return ACTION_NONE - if key in {pygame.K_UP, pygame.K_k}: - ui.selected = (ui.selected - 1) % len(items) - return ACTION_NONE - if key in {pygame.K_DOWN, pygame.K_j}: - ui.selected = (ui.selected + 1) % len(items) - return ACTION_NONE - if pygame.K_a <= key <= pygame.K_z: - index = key - pygame.K_a - if index < len(items): - ui.selected = index - return _confirm_item(session, ui, items[index]) - return ACTION_NONE - if key in {pygame.K_RETURN, pygame.K_KP_ENTER}: - ui.selected %= len(items) - return _confirm_item(session, ui, items[ui.selected]) - return ACTION_NONE - - -def handle_key( - session: GameSession, - key: int, - ui: UIState | None = None, - save_path: str | Path = DEFAULT_SAVE_PATH, - mods: int = 0, -) -> str: - ui = ui or UIState() - if ui.mode != MODE_GAME: - return _handle_overlay_key(session, key, ui) - if key == pygame.K_ESCAPE: - return ACTION_NONE - if key == pygame.K_i: - _open_mode(ui, MODE_INVENTORY) - return ACTION_NONE - if key == pygame.K_e: - _open_mode(ui, MODE_EQUIPMENT) - return ACTION_NONE - if key == pygame.K_q: - _open_mode(ui, MODE_POTION) - return ACTION_NONE - if key == pygame.K_r: - _open_mode(ui, MODE_SCROLL) - return ACTION_NONE - if key in {pygame.K_SLASH, getattr(pygame, "K_QUESTION", ord("?"))} and ( - key != pygame.K_SLASH or mods & pygame.KMOD_SHIFT - ): - _open_mode(ui, MODE_HELP) - return ACTION_NONE - if key == pygame.K_s: - try: - save_game(session, save_path) - except OSError as error: - session.add_message(f"Could not save: {error}") - return ACTION_NONE - return ACTION_SAVED - if key in _MOVE_KEYS: - if not move_player(session, *_MOVE_KEYS[key]): - return ACTION_NONE - take_enemy_turns(session) - compute_fov(session.current_map, session.player.x, session.player.y) - return ACTION_TURN - if key == pygame.K_g: - if not pickup_item(session): - return ACTION_NONE - _finish_turn(session) - return ACTION_TURN - if key in {pygame.K_PERIOD, getattr(pygame, "K_GREATER", ord(">"))} and ( - key != pygame.K_PERIOD or mods & pygame.KMOD_SHIFT - ): - if not descend_floor(session): - return ACTION_NONE - _finish_turn(session) - return ACTION_TURN - return ACTION_NONE - - -def camera_origin(session: GameSession) -> tuple[int, int]: - game_map = session.current_map - x = min(max(0, session.player.x - VIEWPORT_WIDTH // 2), game_map.width - VIEWPORT_WIDTH) - y = min(max(0, session.player.y - VIEWPORT_HEIGHT // 2), game_map.height - VIEWPORT_HEIGHT) - return x, y - - -def _draw_bar( - screen: pygame.Surface, - rect: pygame.Rect, - ratio: float, - fill_color: tuple[int, int, int], - empty_color: tuple[int, int, int], -) -> None: - pygame.draw.rect(screen, empty_color, rect) - filled = rect.copy() - filled.width = round(rect.width * min(1.0, max(0.0, ratio))) - pygame.draw.rect(screen, fill_color, filled) - pygame.draw.rect(screen, UI_BORDER_COLOR, rect, 1) - - -def _draw_world(screen: pygame.Surface, session: GameSession, fonts: Fonts) -> None: - game_map = session.current_map - camera_x, camera_y = camera_origin(session) - for screen_y in range(VIEWPORT_HEIGHT): - map_y = camera_y + screen_y - for screen_x in range(VIEWPORT_WIDTH): - map_x = camera_x + screen_x - index = game_map.index(map_x, map_y) - if not game_map.explored[index]: - color = BACKGROUND_COLOR - elif game_map.visible[index]: - color = FLOOR_COLOR if game_map.is_floor(map_x, map_y) else WALL_COLOR - else: - color = EXPLORED_FLOOR_COLOR if game_map.is_floor(map_x, map_y) else EXPLORED_WALL_COLOR - pygame.draw.rect( - screen, - color, - ( - screen_x * TILE_SIZE, - TOP_PANEL_HEIGHT + screen_y * TILE_SIZE, - TILE_SIZE, - TILE_SIZE, - ), - ) - - if game_map.stairs_down is not None: - stairs_x, stairs_y = game_map.stairs_down - stairs_index = game_map.index(stairs_x, stairs_y) - if game_map.explored[stairs_index]: - color = STAIRS_COLOR if game_map.visible[stairs_index] else UI_MUTED_COLOR - glyph = fonts.small.render(">", True, color) - screen.blit( - glyph, - ( - (stairs_x - camera_x) * TILE_SIZE, - TOP_PANEL_HEIGHT + (stairs_y - camera_y) * TILE_SIZE, - ), - ) - - for entity in game_map.entities: - if not game_map.visible[game_map.index(entity.x, entity.y)]: - continue - screen_x = entity.x - camera_x - screen_y = entity.y - camera_y - if not 0 <= screen_x < VIEWPORT_WIDTH or not 0 <= screen_y < VIEWPORT_HEIGHT: - continue - inset = ITEM_INSET if isinstance(entity, Item) else ENTITY_INSET - pygame.draw.rect( - screen, - entity.color, - ( - screen_x * TILE_SIZE + inset, - TOP_PANEL_HEIGHT + screen_y * TILE_SIZE + inset, - TILE_SIZE - inset * 2, - TILE_SIZE - inset * 2, - ), - ) - - player_x = (session.player.x - camera_x) * TILE_SIZE + TILE_SIZE // 2 - player_y = TOP_PANEL_HEIGHT + (session.player.y - camera_y) * TILE_SIZE + TILE_SIZE // 2 - pygame.draw.circle(screen, PLAYER_COLOR, (player_x, player_y), TILE_SIZE // 2) - - -def _message_color(message: str) -> tuple[int, int, int]: - lowered = message.lower() - if "reach level" in lowered: - return UI_LEVEL_COLOR - if any(word in lowered for word in ("pick up", "equip", "potion", "scroll")): - return UI_ITEM_COLOR - if any(phrase in lowered for phrase in ("hits you", "shoots you", "burns you", "you died")): - return UI_DAMAGE_COLOR - return UI_TEXT_COLOR - - -def _draw_panels(screen: pygame.Surface, session: GameSession, fonts: Fonts) -> None: - map_width = VIEWPORT_WIDTH * TILE_SIZE - map_height = VIEWPORT_HEIGHT * TILE_SIZE - pygame.draw.rect(screen, UI_PANEL_COLOR, (0, 0, map_width, TOP_PANEL_HEIGHT)) - pygame.draw.rect( - screen, - UI_PANEL_COLOR, - (map_width, 0, RIGHT_PANEL_WIDTH, WINDOW_HEIGHT), - ) - pygame.draw.rect( - screen, - UI_PANEL_COLOR, - (0, TOP_PANEL_HEIGHT + map_height, map_width, BOTTOM_PANEL_HEIGHT), - ) - pygame.draw.line(screen, UI_BORDER_COLOR, (map_width, 0), (map_width, WINDOW_HEIGHT)) - - floor_text = fonts.normal.render( - f"Floor {session.current_floor + 1}/10", True, UI_TEXT_COLOR - ) - screen.blit(floor_text, (UI_PADDING, UI_PADDING)) - - hp_x = floor_text.get_width() + UI_PADDING * 2 - hp_width = map_width // 3 - hp_rect = pygame.Rect(hp_x, UI_PADDING, hp_width, UI_BAR_HEIGHT) - _draw_bar( - screen, - hp_rect, - session.player.hp / max(1, session.player.max_hp), - UI_HEALTH_COLOR, - UI_HEALTH_MISSING_COLOR, - ) - hp_text = fonts.small.render( - f"HP {max(0, session.player.hp)}/{session.player.max_hp}", True, UI_TEXT_COLOR - ) - screen.blit(hp_text, (hp_x + UI_PADDING // 2, UI_PADDING)) - - level_text = fonts.normal.render(f"Level {session.player.level}", True, UI_TEXT_COLOR) - level_x = hp_rect.right + UI_PADDING - screen.blit(level_text, (level_x, UI_PADDING)) - previous_xp = LEVEL_THRESHOLDS[session.player.level - 2] if session.player.level > 1 else 0 - next_xp = ( - LEVEL_THRESHOLDS[session.player.level - 1] - if session.player.level <= len(LEVEL_THRESHOLDS) - else session.player.xp - ) - xp_ratio = 1.0 if next_xp == previous_xp else (session.player.xp - previous_xp) / (next_xp - previous_xp) - xp_rect = pygame.Rect(level_x + level_text.get_width() + UI_PADDING, UI_PADDING, map_width - level_x - level_text.get_width() - UI_PADDING * 2, UI_BAR_HEIGHT) - _draw_bar(screen, xp_rect, xp_ratio, UI_XP_COLOR, UI_BACKGROUND_COLOR) - - log_title = fonts.normal.render("Messages", True, UI_TEXT_COLOR) - screen.blit(log_title, (map_width + UI_PADDING, UI_PADDING)) - lines: list[tuple[str, tuple[int, int, int]]] = [] - for message in session.log[-8:]: - color = _message_color(message) - lines.extend((line, color) for line in wrap(message, MESSAGE_WRAP_WIDTH) or [message]) - lines = lines[-8:] - log_bottom = TOP_PANEL_HEIGHT + map_height - UI_PADDING - for offset, (line, color) in enumerate(reversed(lines), start=1): - text = fonts.small.render(line, True, color) - screen.blit(text, (map_width + UI_PADDING, log_bottom - offset * UI_LINE_HEIGHT)) - - weapon = session.player.weapon.name if session.player.weapon else "None" - armor = session.player.armor_item.name if session.player.armor_item else "None" - equipment = fonts.normal.render( - f"Weapon: {weapon} Armor: {armor}", True, UI_TEXT_COLOR - ) - screen.blit(equipment, (UI_PADDING, TOP_PANEL_HEIGHT + map_height + UI_PADDING)) - - -def _overlay_title(mode: str) -> str: - return { - MODE_INVENTORY: "Inventory", - MODE_EQUIPMENT: "Equipment", - MODE_POTION: "Quaff a Potion", - MODE_SCROLL: "Read a Scroll", - MODE_HELP: "Help", - MODE_TARGET: "Target Fireball", - }.get(mode, "") - - -def _draw_overlay( - screen: pygame.Surface, session: GameSession, ui: UIState, fonts: Fonts -) -> None: - if ui.mode == MODE_GAME: - return - left = (WINDOW_WIDTH - OVERLAY_WIDTH) // 2 - top = (WINDOW_HEIGHT - OVERLAY_HEIGHT) // 2 - rect = pygame.Rect(left, top, OVERLAY_WIDTH, OVERLAY_HEIGHT) - pygame.draw.rect(screen, UI_OVERLAY_COLOR, rect) - pygame.draw.rect(screen, UI_BORDER_COLOR, rect, 2) - title = fonts.title.render(_overlay_title(ui.mode), True, UI_TEXT_COLOR) - screen.blit(title, (left + UI_PADDING, top + UI_PADDING)) - y = top + title.get_height() + UI_PADDING * 2 - - if ui.mode == MODE_HELP: - for line in HELP_LINES: - screen.blit(fonts.normal.render(line, True, UI_TEXT_COLOR), (left + UI_PADDING, y)) - y += UI_LINE_HEIGHT - return - if ui.mode == MODE_TARGET: - line = "Arrows/hjkl move target; Enter casts; Esc cancels" - screen.blit(fonts.normal.render(line, True, UI_TEXT_COLOR), (left + UI_PADDING, y)) - if ui.target is not None: - target = fonts.normal.render(f"Target: {ui.target}", True, UI_ITEM_COLOR) - screen.blit(target, (left + UI_PADDING, y + UI_LINE_HEIGHT * 2)) - camera_x, camera_y = camera_origin(session) - x = (ui.target[0] - camera_x) * TILE_SIZE - target_y = TOP_PANEL_HEIGHT + (ui.target[1] - camera_y) * TILE_SIZE - pygame.draw.rect(screen, UI_ITEM_COLOR, (x, target_y, TILE_SIZE, TILE_SIZE), 2) - return - - if ui.mode == MODE_EQUIPMENT: - weapon = session.player.weapon.name if session.player.weapon else "None" - armor = session.player.armor_item.name if session.player.armor_item else "None" - for line in (f"Weapon: {weapon}", f"Armor: {armor}"): - screen.blit(fonts.normal.render(line, True, UI_MUTED_COLOR), (left + UI_PADDING, y)) - y += UI_LINE_HEIGHT - y += UI_PADDING - - items = selectable_items(session, ui.mode) - if not items: - empty = fonts.normal.render("No matching items. Esc closes.", True, UI_MUTED_COLOR) - screen.blit(empty, (left + UI_PADDING, y)) - return - ui.selected %= len(items) - rows = max(1, (top + OVERLAY_HEIGHT - UI_PADDING - y) // UI_LINE_HEIGHT) - start = min(max(0, ui.selected - rows + 1), max(0, len(items) - rows)) - for index in range(start, min(len(items), start + rows)): - item = items[index] - prefix = chr(ord("a") + index) - color = UI_ITEM_COLOR if index == ui.selected else UI_TEXT_COLOR - marker = ">" if index == ui.selected else " " - text = fonts.normal.render(f"{marker} {prefix}) {item.name}", True, color) - screen.blit(text, (left + UI_PADDING, y)) - y += UI_LINE_HEIGHT - - -def render( - screen: pygame.Surface, - session: GameSession, - ui: UIState | None = None, - fonts: Fonts | None = None, -) -> None: - fonts = fonts or create_fonts() - ui = ui or UIState() - screen.fill(UI_BACKGROUND_COLOR) - _draw_world(screen, session, fonts) - _draw_panels(screen, session, fonts) - _draw_overlay(screen, session, ui, fonts) - - -def render_menu( - screen: pygame.Surface, - selected: int, - save_path: str | Path = DEFAULT_SAVE_PATH, - message: str = "", - fonts: Fonts | None = None, -) -> None: - fonts = fonts or create_fonts() - screen.fill(UI_BACKGROUND_COLOR) - title = fonts.title.render(GAME_TITLE, True, UI_TEXT_COLOR) - screen.blit(title, ((WINDOW_WIDTH - title.get_width()) // 2, WINDOW_HEIGHT // 4)) - options = menu_options(save_path) - for index, option in enumerate(options): - color = UI_ITEM_COLOR if index == selected % len(options) else UI_TEXT_COLOR - text = fonts.normal.render(option, True, color) - screen.blit( - text, - ( - (WINDOW_WIDTH - text.get_width()) // 2, - WINDOW_HEIGHT // 2 + index * UI_LINE_HEIGHT * 2, - ), - ) - if message: - text = fonts.small.render(message, True, UI_DAMAGE_COLOR) - screen.blit(text, ((WINDOW_WIDTH - text.get_width()) // 2, WINDOW_HEIGHT - UI_PADDING * 3)) - - -def render_end_screen( - screen: pygame.Surface, session: GameSession, fonts: Fonts | None = None -) -> None: - fonts = fonts or create_fonts() - screen.fill(UI_BACKGROUND_COLOR) - if session.state == GAME_STATE_DEAD: - title_text = "You died" - detail = f"You died on floor {session.current_floor + 1}. You reached level {session.player.level}." - color = UI_DAMAGE_COLOR - else: - title_text = "Victory" - detail = "You slew the Ancient Dragon! You conquered Underdepths." - color = UI_LEVEL_COLOR - title = fonts.title.render(title_text, True, color) - message = fonts.normal.render(detail, True, UI_TEXT_COLOR) - prompt = fonts.small.render("Press any key to return to the menu.", True, UI_MUTED_COLOR) - center_y = WINDOW_HEIGHT // 2 - screen.blit(title, ((WINDOW_WIDTH - title.get_width()) // 2, center_y - UI_LINE_HEIGHT * 3)) - screen.blit(message, ((WINDOW_WIDTH - message.get_width()) // 2, center_y)) - screen.blit(prompt, ((WINDOW_WIDTH - prompt.get_width()) // 2, center_y + UI_LINE_HEIGHT * 2)) - - -def main(max_frames: int | None = None) -> None: - pygame.init() - screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) - pygame.display.set_caption(GAME_TITLE) - fonts = create_fonts() - clock = pygame.time.Clock() - session: GameSession | None = None - ui = UIState() - menu_selected = 0 - menu_message = "" - running = True - frames = 0 - while running and (max_frames is None or frames < max_frames): - for event in pygame.event.get(): - if event.type == pygame.QUIT: - running = False - continue - if event.type != pygame.KEYDOWN: - continue - if session is None: - options = menu_options() - menu_selected, option = handle_menu_key(event.key, menu_selected, options) - if option == MENU_QUIT: - running = False - elif option is not None: - try: - session = activate_menu_option(option) - ui = UIState() - menu_message = "" - except ValueError as error: - menu_message = str(error) - continue - if session.state in {GAME_STATE_DEAD, GAME_STATE_VICTORY}: - enforce_permadeath(session) - session = None - menu_selected = 0 - continue - result = handle_key(session, event.key, ui, mods=event.mod) - enforce_permadeath(session) - if result == ACTION_SAVED: - session = None - ui = UIState() - menu_selected = 0 - - if session is None: - options = menu_options() - menu_selected %= len(options) - render_menu(screen, menu_selected, message=menu_message, fonts=fonts) - elif session.state in {GAME_STATE_DEAD, GAME_STATE_VICTORY}: - enforce_permadeath(session) - render_end_screen(screen, session, fonts) - else: - render(screen, session, ui, fonts) - pygame.display.flip() - clock.tick(FPS) - frames += 1 - pygame.quit() - - -if __name__ == "__main__": - main() diff --git a/underdepths/orchestrate.sh b/underdepths/orchestrate.sh deleted file mode 100755 index 6b88ad8..0000000 --- a/underdepths/orchestrate.sh +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env bash -set -uo pipefail - -MAX_RETRIES="${MAX_RETRIES:-3}" -PYTHON="${PYTHON:-python}" -STATE_FILE=.build_state -LOG_DIR=.build_logs -mkdir -p "$LOG_DIR" -[[ -f "$STATE_FILE" ]] || printf '0\n' > "$STATE_FILE" - -phase_name() { - case "$1" in - 1) printf 'Foundation' ;; - 2) printf 'Core Systems' ;; - 3) printf 'Content Layer' ;; - 4) printf 'Polish & Persist' ;; - esac -} - -phase_prompt() { - case "$1" in - 1) cat <<'PROMPT' -Read AGENTS.md and plan.md completely. Implement Phase 1 Foundation only: data/constants.py, entities/entity.py, entities/player.py, entities/enemy.py, engine/game_state.py, BSP engine/map_gen.py, and a minimal playable pygame main.py. Use dataclass(slots=True), full type hints, no stubs. Implement tests/smoke.py phase 1 gate: generate 5 maps; require >=3 non-overlapping rooms; flood-fill every floor tile from spawn; print one ASCII map. Run python tests/smoke.py --phase 1 and fix it before returning. Do not implement later phases. -PROMPT - ;; - 3) cat <<'PROMPT' -Read AGENTS.md and plan.md completely. Implement Phase 3 Content Layer against the existing phases: the complete fixed item catalog, 26-slot inventory, equipment, all potions and scrolls, XP and every level threshold, all six regular enemy types and Ancient Dragon with exact stats/behaviors, slime splitting, dragon breath, depth-gated spawning, and the floor-9 boss arena with two healing potions. Keep GameSession the only mutable-state root and log every event. Replace the phase 3 smoke gate with real assertions for every enemy's stats, equipment stat changes, item effects, XP/level-up, splitting, and boss arena. Run python tests/smoke.py --phase 3 and fix failures. No stubs or TODOs. -PROMPT - ;; - 4) cat <<'PROMPT' -Read AGENTS.md and plan.md completely. Implement Phase 4 Polish & Persist: exact JSON save/load of GameSession and all 10 floors including timers, menu/New Game/conditional Continue/Quit, save-and-quit, permadeath save deletion, death/victory screens, camera, colored pygame tile rendering, FOV/exploration, all UI panels, inventory/equipment/item selection, help, and every documented control. Preserve headless testability. Replace phase 4 smoke gate with real save/load equality and state/menu reachability assertions. Run python tests/smoke.py --phase 4 and fix failures. No stubs or TODOs. -PROMPT - ;; - esac -} - -run_pi() { - local label="$1" prompt="$2" log - log="$LOG_DIR/$label.log" - printf '\n==> %s\n' "$label" - pi -p "$prompt" 2>&1 | tee "$log" - return "${PIPESTATUS[0]}" -} - -run_gate() { - local phase="$1" log - log="$LOG_DIR/phase-${phase}-gate.log" - "$PYTHON" tests/smoke.py --phase "$phase" 2>&1 | tee "$log" - return "${PIPESTATUS[0]}" -} - -fix_phase() { - local phase="$1" attempt="$2" output - output="$(<"$LOG_DIR/phase-${phase}-gate.log")" - run_pi "phase-${phase}-fix-${attempt}" "Read AGENTS.md and plan.md. Phase ${phase} ($(phase_name "$phase")) failed its gate. Fix the implementation or strengthen/correct the gate without deleting valid assertions. Run the gate before returning. Actual stdout/stderr:\n\n${output}" -} - -build_phase_2() { - local attempt="$1" pids=() rc=0 - local common='Read AGENTS.md and plan.md completely. Implement only the named Phase 2 subsystem against existing code, with full type hints and no stubs. Do not edit unrelated subsystem files. Add focused assertions to tests/smoke.py only if safe under concurrent edits; otherwise leave gate integration to the follow-up.' - run_pi "phase-2-fov-${attempt}" "$common Implement engine/fov.py recursive shadowcasting in 8 octants, radius 8, updating visible and explored." & pids+=("$!") - run_pi "phase-2-path-${attempt}" "$common Implement engine/pathfinding.py A* with Manhattan heuristic and occupied-tile avoidance." & pids+=("$!") - run_pi "phase-2-combat-${attempt}" "$common Implement engine/combat.py exact hit clamp, armor reduction, critical hits, death/XP, and human-readable logging." & pids+=("$!") - for pid in "${pids[@]}"; do wait "$pid" || rc=1; done - (( rc == 0 )) || return 1 - run_pi "phase-2-ai-${attempt}" 'Read AGENTS.md and plan.md completely. FOV, A*, and combat now exist. Implement ai/behaviors.py with every Phase 2 behavior integration required by the design, then implement a real tests/smoke.py phase 2 gate covering walled-in FOV, A* between floor tiles, 1000 combat attacks with bounded outcomes, and an enemy chasing through a corridor. Run python tests/smoke.py --phase 2 and fix it. No stubs or TODOs.' -} - -last="$(tr -dc '0-4' < "$STATE_FILE")" -last="${last:-0}" -for phase in 1 2 3 4; do - (( phase <= last )) && continue - printf '\n######## Phase %s: %s ########\n' "$phase" "$(phase_name "$phase")" - passed=0 - for ((attempt=1; attempt<=MAX_RETRIES; attempt++)); do - if (( phase == 2 )); then - if (( attempt == 1 )); then build_phase_2 "$attempt" || true; else fix_phase "$phase" "$attempt" || true; fi - elif (( attempt == 1 )); then - run_pi "phase-${phase}-build" "$(phase_prompt "$phase")" || true - else - fix_phase "$phase" "$attempt" || true - fi - if run_gate "$phase"; then passed=1; break; fi - done - if (( passed == 0 )); then - printf 'Phase %s failed after %s attempts. See %s.\n' "$phase" "$MAX_RETRIES" "$LOG_DIR" >&2 - exit 1 - fi - printf '%s\n' "$phase" > "$STATE_FILE" -done - -printf '\n######## Goal backstop ########\n' -goal_passed=0 -for ((attempt=1; attempt<=MAX_RETRIES; attempt++)); do - run_pi "goal-audit-${attempt}" 'Read AGENTS.md and plan.md completely. Audit every checkbox in plan.md Acceptance Criteria against the real game. Run the full smoke suite and a deterministic SDL_VIDEODRIVER=dummy headless playthrough that exercises movement, combat, pickup/use/equip, stairs, save/load, death, and victory. Fix every failure you find; do not merely report it. Keep tests honest. Return only after all criteria are implemented and python tests/smoke.py passes.' || true - if "$PYTHON" tests/smoke.py 2>&1 | tee "$LOG_DIR/goal-gate.log"; then - goal_passed=1 - break - fi - gate_output="$(<"$LOG_DIR/goal-gate.log")" - run_pi "goal-fix-${attempt}" "The final acceptance gate failed. Read AGENTS.md and plan.md, fix every actual cause, and rerun the full suite. Actual stdout/stderr:\n\n${gate_output}" || true -done - -if (( goal_passed == 0 )); then - printf 'Final acceptance gate failed after %s attempts. See %s.\n' "$MAX_RETRIES" "$LOG_DIR" >&2 - exit 1 -fi -printf '\nUnderdepths build complete: all phase and final gates pass.\n' diff --git a/underdepths/plan.md b/underdepths/plan.md index 93a3432..7dd0720 100644 --- a/underdepths/plan.md +++ b/underdepths/plan.md @@ -5,7 +5,7 @@ A turn-based roguelike dungeon crawler. Descend through 10 procedurally generate ## Tech Stack - **Python 3.11+** -- **pygame-ce** for rendering and input (colored tile grid, not ASCII) +- **pygame-ce** for rendering, input, and simple generated sound effects (colored tile grid, not ASCII) - **No other dependencies.** Everything else is stdlib. ## Architecture @@ -258,8 +258,9 @@ menu → playing → dead (game over screen, delete save) ``` **Main menu:** -- "New Game" — generates fresh dungeon, starts on floor 0 +- "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. @@ -267,17 +268,26 @@ menu → playing → dead (game over screen, delete save) ## 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 `>` (`Shift+.`) 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 item at feet | +| `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) | -| `>` | Descend stairs (must be standing on stairs) | +| `>` (`Shift+.`) | Descend only while standing on the yellow stairs tile | | `S` | Save and quit | -| `?` | Help overlay (show all keys) | +| `?` | Open How to Play | +| `m` | Mute/unmute sound effects | | `Esc` | Close menus / cancel | ## Enemy Roster @@ -308,9 +318,19 @@ menu → playing → dead (game over screen, delete save) - **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). + - Bottom: current equipment and sound state. + - Context prompt: on an item show `Press G to pick up `; on stairs show `Press > (Shift+.) 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: @@ -323,6 +343,9 @@ The game is DONE when ALL of these are true: - [ ] 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 `>` 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. @@ -333,6 +356,8 @@ The game is DONE when ALL of these are true: - [ ] **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 `>`, 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 @@ -350,7 +375,7 @@ The game is DONE when ALL of these are true: ## 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 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 diff --git a/underdepths/prompt.md b/underdepths/prompt.md index f3909ee..96c34ba 100644 --- a/underdepths/prompt.md +++ b/underdepths/prompt.md @@ -31,6 +31,13 @@ You are building **Underdepths**, a turn-based roguelike in Python with pygame-c pipeline dispatches a fix and retries. 5. **Write real implementations.** No stubs, no TODO comments left behind. Every function must work. +6. **Make controls discoverable and verify them.** Provide How to Play from the + main menu and before every New Game. Show `Press G to pick up` while standing + on an item and `Press > (Shift+.) to descend` while standing on stairs. The + smoke suite must simulate both actions; rendering instructions alone is not enough. +7. **Add simple resilient audio.** Generate short sound effects in memory with + pygame/stdlib only, add an `m` mute toggle, and fall back silently when no + audio device is available. Do not add asset files or music. ## Completion criteria @@ -41,11 +48,16 @@ You are done when ALL of these are true: - A* pathfinding, recursive shadowcasting FOV, BSP dungeon generation, combat with hit/damage/crit mechanics, XP/leveling, items/inventory/equipment, and save/load all work. +- How to Play clearly explains every control. Context prompts make pickup (`g`) + and descent (`>` / `Shift+.`) discoverable, and input tests prove both work. +- Simple generated sound effects cover core events, mute works, and unavailable + audio never prevents launch or play. - 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. +- You can play: move, explore, fight, stand on loot and press `g`, stand on + stairs and press `>` (`Shift+.`), 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. diff --git a/underdepths/tests/smoke.py b/underdepths/tests/smoke.py deleted file mode 100644 index 5895298..0000000 --- a/underdepths/tests/smoke.py +++ /dev/null @@ -1,819 +0,0 @@ -from __future__ import annotations - -import argparse -from array import array -import random -import os -import tempfile -os.environ.setdefault("SDL_VIDEODRIVER", "dummy") - -import pygame -import sys -from collections import deque -from collections.abc import Callable -from itertools import combinations -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) - -import main as game_main - -from ai.behaviors import dragon_breath, take_enemy_turns -from data.constants import ( - BOSS_ARENA_HEIGHT, - BOSS_ARENA_WIDTH, - DRAGON_BREATH_DAMAGE, - FLOOR_SPAWN_COUNTS, - GAME_STATE_DEAD, - GAME_STATE_PLAYING, - GAME_STATE_VICTORY, - INVENTORY_CAPACITY, - LEVEL_HP_GAINS, - LEVEL_POWER_GAINS, - LEVEL_THRESHOLDS, - TILE_FLOOR, - FPS, - TILE_WALL, - WINDOW_HEIGHT, - WINDOW_WIDTH, -) -from data.enemies import ENEMY_CATALOG, create_enemy -from data.items import ITEM_CATALOG, create_item -from engine.combat import attack, calculate_damage, handle_death -from engine.fov import compute_fov -from engine.game_state import ( - GameSession, - award_xp, - equip_item, - pickup_item, - tick_player_effects, - use_item, - new_game, -) -from engine.map_gen import GameMap, generate_dungeon -from engine.serializers import load_game, save_game, session_to_dict -from engine.pathfinding import find_path, manhattan_distance -from entities.enemy import Enemy -from entities.item import Item -from entities.player import create_player - - -def _test_map( - width: int, - height: int, - floors: set[tuple[int, int]], - spawn: tuple[int, int], -) -> GameMap: - size = width * height - tiles = array("B", [TILE_WALL]) * size - for x, y in floors: - tiles[y * width + x] = TILE_FLOOR - return GameMap( - width=width, - height=height, - tiles=tiles, - rooms=[], - explored=array("B", [0]) * size, - visible=array("B", [0]) * size, - entities=[], - stairs_down=spawn, - spawn=spawn, - floor_index=0, - ) - - -def _enemy(x: int, y: int, behavior: str = "chase") -> Enemy: - return Enemy( - x=x, - y=y, - glyph="g", - color=(0, 180, 0), - name="Goblin", - hp=100, - max_hp=100, - power=5, - armor=1, - accuracy=5, - evasion=1, - crit_chance=0.1, - speed=1, - behavior=behavior, - xp_reward=12, - ) - - -def _session(game_map: GameMap, player_position: tuple[int, int]) -> GameSession: - return GameSession( - player=create_player(*player_position), - dungeon=[game_map], - current_floor=0, - log=[], - turn=0, - state=GAME_STATE_PLAYING, - rng_state=repr(random.Random(0).getstate()), - ) - - -def _reachable_floor(game_map: GameMap) -> set[tuple[int, int]]: - visited = {game_map.spawn} - pending = deque([game_map.spawn]) - while pending: - x, y = pending.popleft() - for dx, dy in ((0, -1), (0, 1), (-1, 0), (1, 0)): - neighbor = x + dx, y + dy - if neighbor not in visited and game_map.is_floor(*neighbor): - visited.add(neighbor) - pending.append(neighbor) - return visited - - -def phase_1() -> None: - maps = [generate_dungeon(index, random.Random(index)) for index in range(5)] - for game_map in maps: - assert len(game_map.rooms) >= 3, "map has fewer than three rooms" - assert all( - not first.intersects(second) - for first, second in combinations(game_map.rooms, 2) - ), "rooms overlap" - floor_tiles = { - (x, y) - for y in range(game_map.height) - for x in range(game_map.width) - if game_map.tiles[game_map.index(x, y)] == TILE_FLOOR - } - assert _reachable_floor(game_map) == floor_tiles, "not every floor tile is reachable" - print(maps[0].ascii()) - - first_run = new_game(seed=1001) - second_run = new_game(seed=2002) - assert len(first_run.dungeon) == len(second_run.dungeon) == 10 - assert all(game_map.floor_index == index for index, game_map in enumerate(first_run.dungeon)) - assert all( - first_run.dungeon[index].tiles != second_run.dungeon[index].tiles - for index in range(9) - ), "ordinary floors were not procedurally varied between runs" - - -def phase_2() -> None: - walled_map = _test_map(7, 7, {(3, 3)}, (3, 3)) - compute_fov(walled_map, 3, 3) - visible_floors = { - (x, y) - for y in range(walled_map.height) - for x in range(walled_map.width) - if walled_map.is_floor(x, y) and walled_map.visible[walled_map.index(x, y)] - } - assert visible_floors == {(3, 3)}, "FOV sees floor beyond enclosing walls" - assert walled_map.explored[walled_map.index(3, 3)], "visible origin was not explored" - - sight_line = _test_map(21, 3, {(x, 1) for x in range(1, 20)}, (1, 1)) - compute_fov(sight_line, 1, 1) - old_origin = sight_line.index(1, 1) - compute_fov(sight_line, 19, 1) - assert not sight_line.visible[old_origin] and sight_line.explored[old_origin], ( - "previously seen tiles were not remembered outside current FOV" - ) - - occlusion_map = _test_map(13, 3, {(x, 1) for x in range(1, 12)}, (1, 1)) - occlusion_map.tiles[occlusion_map.index(5, 1)] = TILE_WALL - compute_fov(occlusion_map, 1, 1) - assert occlusion_map.visible[occlusion_map.index(5, 1)], "blocking wall was not visible" - assert not occlusion_map.visible[occlusion_map.index(6, 1)], "FOV saw through a wall" - radius_map = _test_map(13, 3, {(x, 1) for x in range(1, 12)}, (1, 1)) - compute_fov(radius_map, 1, 1) - assert radius_map.visible[radius_map.index(9, 1)], "FOV radius did not reach eight tiles" - assert not radius_map.visible[radius_map.index(10, 1)], "FOV exceeded radius eight" - - path_map = generate_dungeon(0, random.Random(20)) - for goal in _reachable_floor(path_map) - {path_map.spawn}: - path = find_path(path_map, path_map.spawn, goal) - assert path and path[-1] == goal, f"A* failed to reach floor tile {goal}" - assert all( - manhattan_distance(first, second) == 1 - for first, second in zip((path_map.spawn, *path), path) - ), "A* returned non-cardinal steps" - - combat_map = _test_map(5, 5, {(x, y) for y in range(5) for x in range(5)}, (1, 1)) - combat_session = _session(combat_map, (1, 1)) - defender = _enemy(2, 1) - combat_map.entities.append(defender) - normal_damage = calculate_damage(combat_session.player, defender) - roller = random.Random(7) - outcomes: set[int] = set() - for _ in range(1000): - defender.hp = defender.max_hp - outcomes.add(attack(combat_session, combat_session.player, defender, rng=roller)) - assert outcomes == {0, normal_damage, normal_damage * 2}, f"unexpected combat outcomes: {outcomes}" - assert defender.hp >= defender.max_hp - normal_damage * 2, "combat exceeded bounded damage" - - corridor = {(x, 2) for x in range(1, 8)} - ai_map = _test_map(9, 5, corridor, (1, 2)) - ai_session = _session(ai_map, (1, 2)) - chaser = _enemy(7, 2) - ai_map.entities.append(chaser) - positions: list[tuple[int, int]] = [] - for _ in range(5): - ai_session.turn += 1 - take_enemy_turns(ai_session, random.Random(ai_session.turn)) - positions.append(chaser.position) - assert positions == [(6, 2), (5, 2), (4, 2), (3, 2), (2, 2)], f"enemy did not chase through corridor: {positions}" - - ranged_map = _test_map(9, 5, {(x, y) for y in range(1, 4) for x in range(1, 8)}, (1, 2)) - ranged_session = _session(ranged_map, (1, 2)) - archer = create_enemy("Skeleton Archer", 6, 2) - ranged_map.entities.append(archer) - take_enemy_turns(ranged_session, random.Random(1)) - assert ranged_session.player.hp == ranged_session.player.max_hp - archer.ranged_power, ( - "ranged enemy did not fire from distance" - ) - archer.x, archer.y = 2, 2 - previous_distance = manhattan_distance(archer.position, ranged_session.player.position) - take_enemy_turns(ranged_session, random.Random(2)) - assert manhattan_distance(archer.position, ranged_session.player.position) > previous_distance, ( - "ranged enemy did not kite at close range" - ) - - phase_map = _test_map(7, 5, {(1, 2), (5, 2)}, (1, 2)) - phase_session = _session(phase_map, (1, 2)) - wraith = create_enemy("Wraith", 5, 2) - phase_map.entities.append(wraith) - phase_session.turn = 2 - take_enemy_turns(phase_session, random.Random(3)) - assert wraith.position == (4, 2) and not phase_map.is_floor(*wraith.position), ( - "wraith did not phase through a wall" - ) - - flee_map = _test_map(7, 5, {(x, y) for y in range(1, 4) for x in range(1, 6)}, (1, 2)) - flee_session = _session(flee_map, (1, 2)) - orc = create_enemy("Orc Warrior", 3, 2) - orc.hp = 1 - flee_map.entities.append(orc) - previous_distance = manhattan_distance(orc.position, flee_session.player.position) - take_enemy_turns(flee_session, random.Random(4)) - assert manhattan_distance(orc.position, flee_session.player.position) > previous_distance, ( - "low-health orc did not flee" - ) - - detour_floors = {(x, y) for y in (1, 3) for x in range(1, 8)} | {(1, 2), (7, 2)} - detour_map = _test_map(9, 5, detour_floors, (1, 1)) - detour_session = _session(detour_map, detour_map.spawn) - first = _enemy(7, 1) - blocker = _enemy(6, 1) - detour_map.entities.extend((first, blocker)) - first.last_known_position = detour_session.player.position - take_enemy_turns(detour_session, random.Random(5)) - assert first.position == (7, 2), "A* did not route around another enemy" - - known_map = _test_map(11, 3, {(x, 1) for x in range(1, 10)}, (1, 1)) - known_session = _session(known_map, known_map.spawn) - pursuer = _enemy(9, 1) - pursuer.last_known_position = (1, 1) - known_map.entities.append(pursuer) - take_enemy_turns(known_session, random.Random(6)) - assert pursuer.position == (8, 1), "enemy did not pursue the player's last known position" - - -def phase_3() -> None: - expected_enemies = { - "Rat": ((0, 3), 8, 3, 0, 1, "wander", 5, 0), - "Goblin": ((0, 5), 15, 5, 1, 1, "chase", 12, 0), - "Skeleton Archer": ((2, 7), 12, 4, 1, 1, "ranged", 15, 6), - "Orc Warrior": ((3, 8), 30, 8, 3, 1, "flee", 25, 0), - "Wraith": ((5, 8), 20, 10, 0, 2, "phase", 30, 0), - "Green Slime": ((4, 8), 18, 5, 1, 1, "split", 18, 0), - "Ancient Dragon": ((9, 9), 120, 15, 8, 1, "dragon", 200, 0), - } - assert set(ENEMY_CATALOG) == set(expected_enemies) - for name, expected in expected_enemies.items(): - definition = ENEMY_CATALOG[name] - actual = ( - definition.floors, - definition.hp, - definition.power, - definition.armor, - definition.speed, - definition.behavior, - definition.xp, - definition.ranged_power, - ) - assert actual == expected, f"incorrect {name} definition: {actual}" - enemy = create_enemy(name, 1, 1) - assert (enemy.hp, enemy.max_hp, enemy.power, enemy.armor) == ( - definition.hp, - definition.hp, - definition.power, - definition.armor, - ) - assert (enemy.speed, enemy.behavior, enemy.xp_reward, enemy.ranged_power) == ( - definition.speed, - definition.behavior, - definition.xp, - definition.ranged_power, - ) - - expected_items = { - "Rusty Dagger": ("weapon", 0, 2, 0, 0.0, 0.0, "", 0, 0, 0), - "Short Sword": ("weapon", 2, 4, 0, 0.0, 0.0, "", 0, 0, 0), - "Battle Axe": ("weapon", 4, 7, 0, 0.0, 0.0, "", 0, 0, 0), - "War Hammer": ("weapon", 7, 10, 0, -0.05, 0.0, "", 0, 0, 0), - "Leather Armor": ("armor", 0, 0, 2, 0.0, 0.0, "", 0, 0, 0), - "Chain Mail": ("armor", 3, 0, 4, 0.0, 0.0, "", 0, 0, 0), - "Plate Armor": ("armor", 6, 0, 7, 0.0, -2.0, "", 0, 0, 0), - "Healing Potion": ("potion", 0, 0, 0, 0.0, 0.0, "healing", 30, 0, 0), - "Strength Potion": ("potion", 0, 0, 0, 0.0, 0.0, "strength", 5, 20, 0), - "Invisibility Potion": ( - "potion", - 0, - 0, - 0, - 0.0, - 0.0, - "invisibility", - 0, - 15, - 0, - ), - "Scroll of Fireball": ("scroll", 0, 0, 0, 0.0, 0.0, "fireball", 20, 0, 3), - "Scroll of Teleport": ("scroll", 0, 0, 0, 0.0, 0.0, "teleport", 0, 0, 0), - "Scroll of Mapping": ("scroll", 0, 0, 0, 0.0, 0.0, "mapping", 0, 0, 0), - } - assert set(ITEM_CATALOG) == set(expected_items) - for name, expected in expected_items.items(): - item = ITEM_CATALOG[name] - actual = ( - item.category, - item.min_floor, - item.power_bonus, - item.armor_bonus, - item.crit_bonus, - item.evasion_bonus, - item.effect, - item.amount, - item.duration, - item.radius, - ) - assert actual == expected, f"incorrect {name} definition: {actual}" - - for floor_index, counts in enumerate(FLOOR_SPAWN_COUNTS): - game_map = generate_dungeon(floor_index, random.Random(100 + floor_index)) - enemies = [entity for entity in game_map.entities if isinstance(entity, Enemy)] - items = [entity for entity in game_map.entities if isinstance(entity, Item)] - assert counts[0] <= len(enemies) <= counts[1] - assert counts[2] <= len(items) <= counts[3] - assert all( - ENEMY_CATALOG[enemy.name].floors[0] - <= floor_index - <= ENEMY_CATALOG[enemy.name].floors[1] - for enemy in enemies - ), f"floor {floor_index} spawned a depth-gated enemy" - assert all(ITEM_CATALOG[item.name].min_floor <= floor_index for item in items) - - open_map = _test_map(9, 9, {(x, y) for y in range(9) for x in range(9)}, (1, 1)) - item_session = _session(open_map, (1, 1)) - item_session.player.inventory.extend( - create_item("Healing Potion") for _ in range(INVENTORY_CAPACITY) - ) - ground_item = create_item("Rusty Dagger", 1, 1) - open_map.entities.append(ground_item) - assert not pickup_item(item_session), "inventory accepted a 27th item" - item_session.player.inventory.pop() - assert pickup_item(item_session) and len(item_session.player.inventory) == INVENTORY_CAPACITY - item_session.player.inventory.clear() - - dagger = create_item("Rusty Dagger") - hammer = create_item("War Hammer") - plate = create_item("Plate Armor") - item_session.player.inventory.extend((dagger, hammer, plate)) - assert equip_item(item_session, dagger) - assert item_session.player.power == 6 - assert equip_item(item_session, hammer) - assert item_session.player.power == 14 and item_session.player.weapon is hammer - assert dagger in item_session.player.inventory - assert abs(item_session.player.crit_chance - 0.05) < 1e-9 - assert equip_item(item_session, plate) - assert item_session.player.armor == 7 and item_session.player.armor_item is plate - assert abs(item_session.player.evasion) < 1e-9 - - healing = create_item("Healing Potion") - item_session.player.inventory.append(healing) - item_session.player.hp = 10 - assert use_item(item_session, healing) and item_session.player.hp == 40 - strength = create_item("Strength Potion") - item_session.player.inventory.append(strength) - assert use_item(item_session, strength) - assert item_session.player.power == 19 and item_session.player.strength_turns == 20 - for _ in range(20): - tick_player_effects(item_session) - assert item_session.player.power == 14 and item_session.player.strength_turns == 0 - invisibility = create_item("Invisibility Potion") - item_session.player.inventory.append(invisibility) - assert use_item(item_session, invisibility) - assert item_session.player.invisibility_turns == 15 - for _ in range(15): - tick_player_effects(item_session) - assert item_session.player.invisibility_turns == 0 - - mapping = create_item("Scroll of Mapping") - item_session.player.inventory.append(mapping) - assert use_item(item_session, mapping) - assert all(item_session.current_map.explored), "mapping did not reveal every tile" - old_position = item_session.player.position - teleport = create_item("Scroll of Teleport") - item_session.player.inventory.append(teleport) - assert use_item(item_session, teleport, rng=random.Random(4)) - assert item_session.player.position != old_position - assert item_session.current_map.is_floor(*item_session.player.position) - - near_enemy = create_enemy("Orc Warrior", 4, 4) - far_enemy = create_enemy("Rat", 8, 8) - open_map.entities.extend((near_enemy, far_enemy)) - fireball = create_item("Scroll of Fireball") - item_session.player.inventory.append(fireball) - assert use_item(item_session, fireball, target=(4, 4)) - assert near_enemy.hp == 10 and far_enemy.hp == 8 - - progression_map = _test_map(3, 3, {(x, y) for y in range(3) for x in range(3)}, (1, 1)) - progression_session = _session(progression_map, (1, 1)) - rat = create_enemy("Rat", 2, 1) - progression_map.entities.append(rat) - progression_session.player.xp = 25 - progression_session.player.hp = 1 - handle_death(progression_session, rat) - assert progression_session.player.level == 2 - assert progression_session.player.xp == 30 - assert progression_session.player.hp == progression_session.player.max_hp == 60 - assert progression_session.player.power == 5 - assert any("defeated the Rat" in message for message in progression_session.log) - assert any("reach level 2" in message for message in progression_session.log) - - expected_hp = progression_session.player.max_hp - expected_power = progression_session.player.power - previous_threshold = LEVEL_THRESHOLDS[0] - for level_index, threshold in enumerate(LEVEL_THRESHOLDS[1:], start=1): - progression_session.player.hp = 1 - assert award_xp(progression_session, threshold - previous_threshold) == 1 - expected_hp += LEVEL_HP_GAINS[level_index] - expected_power += LEVEL_POWER_GAINS[level_index] - assert progression_session.player.level == level_index + 2 - assert progression_session.player.hp == expected_hp - assert progression_session.player.max_hp == expected_hp - assert progression_session.player.power == expected_power - previous_threshold = threshold - - split_map = _test_map(5, 5, {(x, y) for y in range(5) for x in range(5)}, (1, 1)) - split_session = _session(split_map, (1, 1)) - slime = create_enemy("Green Slime", 2, 2) - split_map.entities.append(slime) - handle_death(split_session, slime) - small_slimes = [entity for entity in split_map.entities if isinstance(entity, Enemy)] - assert len(small_slimes) == 2 - assert all( - slime.name == "Small Slime" - and slime.hp == slime.max_hp == 9 - and slime.power == 2 - and slime.has_split - and slime.behavior == "chase" - for slime in small_slimes - ) - - narrow_map = _test_map(5, 3, {(1, 1), (2, 1), (3, 1)}, (1, 1)) - narrow_session = _session(narrow_map, narrow_map.spawn) - adjacent_slime = create_enemy("Green Slime", 2, 1) - narrow_map.entities.append(adjacent_slime) - handle_death(narrow_session, adjacent_slime) - split_positions = { - entity.position for entity in narrow_map.entities if isinstance(entity, Enemy) - } - assert split_positions == {(2, 1), (3, 1)}, "slime split stacked a copy on the player" - - breath_map = _test_map(7, 5, {(x, y) for y in range(5) for x in range(7)}, (1, 2)) - breath_session = _session(breath_map, (1, 2)) - dragon = create_enemy("Ancient Dragon", 4, 2) - breath_map.entities.append(dragon) - breath_session.turn = 3 - take_enemy_turns(breath_session, random.Random(1)) - assert breath_session.player.hp == breath_session.player.max_hp - DRAGON_BREATH_DAMAGE - assert dragon.position == (4, 2), "dragon moved on its breath turn" - line = dragon_breath(breath_session, dragon) - assert line[-1] == breath_session.player.position - - boss_map = generate_dungeon(9, random.Random(9)) - assert len(boss_map.rooms) == 1 - assert (boss_map.rooms[0].width, boss_map.rooms[0].height) == ( - BOSS_ARENA_WIDTH, - BOSS_ARENA_HEIGHT, - ) - boss_enemies = [entity for entity in boss_map.entities if isinstance(entity, Enemy)] - boss_items = [entity for entity in boss_map.entities if isinstance(entity, Item)] - assert len(boss_enemies) == 1 and boss_enemies[0].name == "Ancient Dragon" - assert len(boss_items) == 2 and all(item.name == "Healing Potion" for item in boss_items) - assert boss_map.stairs_down is None - alternate_boss_map = generate_dungeon(9, random.Random(10)) - assert boss_map.rooms[0] != alternate_boss_map.rooms[0], ( - "boss arena placement was not procedurally varied" - ) - boss_session = _session(boss_map, boss_map.spawn) - handle_death(boss_session, boss_enemies[0]) - assert boss_session.state == GAME_STATE_VICTORY - assert any("conquered Underdepths" in message for message in boss_session.log) - - -def _acceptance_playthrough(save_path: Path) -> None: - arena = _test_map( - 8, - 5, - {(x, y) for y in range(1, 4) for x in range(1, 7)}, - (1, 2), - ) - arena.stairs_down = (6, 2) - session = new_game(seed=808) - session.dungeon[0] = arena - session.player = create_player(*arena.spawn) - session.rng_state = repr(random.Random(1).getstate()) - ui = game_main.UIState() - - dagger = create_item("Rusty Dagger", *session.player.position) - arena.entities.append(dagger) - assert game_main.handle_key(session, pygame.K_g, ui, save_path) == game_main.ACTION_TURN - assert dagger in session.player.inventory - assert game_main.handle_key(session, pygame.K_e, ui, save_path) == game_main.ACTION_NONE - assert game_main.handle_key(session, pygame.K_RETURN, ui, save_path) == game_main.ACTION_TURN - assert session.player.weapon is dagger and session.player.power == 6 - - assert game_main.handle_key(session, pygame.K_RIGHT, ui, save_path) == game_main.ACTION_TURN - assert session.player.position == (2, 2) - - potion = create_item("Healing Potion", *session.player.position) - arena.entities.append(potion) - assert game_main.handle_key(session, pygame.K_g, ui, save_path) == game_main.ACTION_TURN - session.player.hp = 20 - assert game_main.handle_key(session, pygame.K_q, ui, save_path) == game_main.ACTION_NONE - assert game_main.handle_key(session, pygame.K_RETURN, ui, save_path) == game_main.ACTION_TURN - assert session.player.hp == 50 and potion not in session.player.inventory - - rat = create_enemy("Rat", 3, 2) - rat.hp = 1 - arena.entities.append(rat) - session.rng_state = repr(random.Random(1).getstate()) - assert game_main.handle_key(session, pygame.K_RIGHT, ui, save_path) == game_main.ACTION_TURN - assert rat not in arena.entities and any("defeated the Rat" in message for message in session.log) - - for _ in range(4): - assert game_main.handle_key(session, pygame.K_RIGHT, ui, save_path) == game_main.ACTION_TURN - assert session.player.position == arena.stairs_down - assert game_main.handle_key( - session, - pygame.K_PERIOD, - ui, - save_path, - pygame.KMOD_SHIFT, - ) == game_main.ACTION_TURN - assert session.current_floor == 1 and session.player.position == session.current_map.spawn - - expected = session_to_dict(session) - - assert game_main.handle_key(session, pygame.K_s, ui, save_path) == game_main.ACTION_SAVED - assert save_path.is_file() - del session - menu_options = game_main.menu_options(save_path) - _, option = game_main.handle_menu_key(pygame.K_c, 0, menu_options) - assert option == game_main.MENU_CONTINUE - relaunched = game_main.activate_menu_option(option, save_path) - assert relaunched is not None and session_to_dict(relaunched) == expected - - death_map = _test_map(5, 5, {(x, y) for y in range(1, 4) for x in range(1, 4)}, (1, 2)) - death = _session(death_map, death_map.spawn) - death.player.hp = 1 - death.rng_state = repr(random.Random(1).getstate()) - death_map.entities.extend( - ( - create_item("Healing Potion", *death.player.position), - create_enemy("Goblin", 2, 2), - ) - ) - assert game_main.handle_key(death, pygame.K_g, game_main.UIState(), save_path) == game_main.ACTION_TURN - assert death.state == GAME_STATE_DEAD - assert game_main.enforce_permadeath(death, save_path) and not save_path.exists() - - victory_map = _test_map(5, 5, {(x, y) for y in range(1, 4) for x in range(1, 4)}, (1, 2)) - victory = _session(victory_map, victory_map.spawn) - victory.player.power = 20 - victory.rng_state = repr(random.Random(1).getstate()) - dragon = create_enemy("Ancient Dragon", 2, 2) - dragon.hp = 1 - victory_map.entities.append(dragon) - assert game_main.handle_key(victory, pygame.K_RIGHT, game_main.UIState(), save_path) == game_main.ACTION_TURN - assert victory.state == GAME_STATE_VICTORY - save_game(victory, save_path) - assert game_main.enforce_permadeath(victory, save_path) and not save_path.exists() - - stable = new_game(seed=810) - stable.current_map.entities.clear() - stable.player.x, stable.player.y = stable.current_map.rooms[0].center - stable_ui = game_main.UIState() - stable_keys = [ - key - for key, (dx, dy) in game_main._MOVE_KEYS.items() - if stable.current_map.is_floor(stable.player.x + dx, stable.player.y + dy) - ] - assert stable_keys - stable_key = stable_keys[0] - reverse_key = { - pygame.K_UP: pygame.K_DOWN, - pygame.K_k: pygame.K_j, - pygame.K_DOWN: pygame.K_UP, - pygame.K_j: pygame.K_k, - pygame.K_LEFT: pygame.K_RIGHT, - pygame.K_h: pygame.K_l, - pygame.K_RIGHT: pygame.K_LEFT, - pygame.K_l: pygame.K_h, - }[stable_key] - pygame.init() - stable_surface = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT)) - for turn in range(FPS * 60 * 5): - key = stable_key if turn % 2 == 0 else reverse_key - assert game_main.handle_key(stable, key, stable_ui, save_path) == game_main.ACTION_TURN - pygame.event.pump() - game_main.render(stable_surface, stable, stable_ui) - assert stable.turn == FPS * 60 * 5 and stable.state == GAME_STATE_PLAYING - pygame.quit() - - - pygame.init() - surface = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT)) - full_inventory = new_game(seed=809) - full_inventory.player.inventory = [create_item("Healing Potion") for _ in range(INVENTORY_CAPACITY)] - inventory_ui = game_main.UIState(mode=game_main.MODE_INVENTORY, selected=INVENTORY_CAPACITY - 1) - game_main.render(surface, full_inventory, inventory_ui) - pygame.quit() - - -def phase_4() -> None: - with tempfile.TemporaryDirectory() as directory: - save_path = Path(directory) / "save.json" - assert game_main.menu_options(save_path) == ( - game_main.MENU_NEW_GAME, - game_main.MENU_QUIT, - ) - - session = new_game(seed=404) - assert len(session.dungeon) == 10 - session.current_floor = 6 - session.player.x, session.player.y = session.current_map.spawn - session.player.hp = 37 - session.player.xp = 222 - session.player.strength_turns = 11 - session.player.invisibility_turns = 7 - session.turn = 91 - session.log.extend(("A saved message.", "Another saved message.")) - dagger = create_item("Rusty Dagger") - session.player.inventory.extend( - (dagger, create_item("Healing Potion"), create_item("Scroll of Mapping")) - ) - assert equip_item(session, dagger) - for index, game_map in enumerate(session.dungeon): - game_map.explored[game_map.index(*game_map.spawn)] = 1 - if game_map.entities and isinstance(game_map.entities[0], Enemy): - game_map.entities[0].last_known_position = game_map.spawn - game_map.entities[0].has_split = index % 2 == 0 - compute_fov(session.current_map, session.player.x, session.player.y) - expected = session_to_dict(session) - - save_game(session, save_path) - assert save_path.is_file() - assert '"visible"' not in save_path.read_text(encoding="utf-8") - loaded = load_game(save_path) - assert session_to_dict(loaded) == expected, "save/load did not restore exact serializable state" - assert len(loaded.dungeon) == 10 - assert loaded.player.strength_turns == 11 - assert loaded.player.invisibility_turns == 7 - assert any(loaded.current_map.visible), "load did not recompute current FOV" - assert all(not any(game_map.visible) for index, game_map in enumerate(loaded.dungeon) if index != loaded.current_floor) - - assert game_main.menu_options(save_path) == ( - game_main.MENU_NEW_GAME, - game_main.MENU_CONTINUE, - game_main.MENU_QUIT, - ) - options = game_main.menu_options(save_path) - assert game_main.handle_menu_key(pygame.K_n, 0, options)[1] == game_main.MENU_NEW_GAME - assert game_main.handle_menu_key(pygame.K_c, 0, options)[1] == game_main.MENU_CONTINUE - assert game_main.handle_menu_key(pygame.K_q, 0, options)[1] == game_main.MENU_QUIT - selected, action = game_main.handle_menu_key(pygame.K_DOWN, 0, options) - assert selected == 1 and action is None - assert game_main.activate_menu_option(game_main.MENU_QUIT, save_path) is None - continued = game_main.activate_menu_option(game_main.MENU_CONTINUE, save_path) - assert continued is not None and session_to_dict(continued) == expected - fresh = game_main.activate_menu_option(game_main.MENU_NEW_GAME, save_path) - assert fresh is not None and fresh.current_floor == 0 and fresh.turn == 0 - - controls = new_game(seed=405) - ui = game_main.UIState() - for key, mode in ( - (pygame.K_i, game_main.MODE_INVENTORY), - (pygame.K_e, game_main.MODE_EQUIPMENT), - (pygame.K_q, game_main.MODE_POTION), - (pygame.K_r, game_main.MODE_SCROLL), - ): - assert game_main.handle_key(controls, key, ui, save_path) == game_main.ACTION_NONE - assert ui.mode == mode - game_main.handle_key(controls, pygame.K_ESCAPE, ui, save_path) - assert ui.mode == game_main.MODE_GAME - game_main.handle_key( - controls, - getattr(pygame, "K_QUESTION", ord("?")), - ui, - save_path, - pygame.KMOD_SHIFT, - ) - assert ui.mode == game_main.MODE_HELP - game_main.handle_key(controls, pygame.K_ESCAPE, ui, save_path) - assert ui.mode == game_main.MODE_GAME - - equip = create_item("Rusty Dagger") - controls.player.inventory.append(equip) - game_main.handle_key(controls, pygame.K_e, ui, save_path) - assert game_main.handle_key(controls, pygame.K_RETURN, ui, save_path) == game_main.ACTION_TURN - assert controls.player.weapon is equip and ui.mode == game_main.MODE_GAME - - potion = create_item("Healing Potion") - controls.player.inventory.append(potion) - controls.player.hp = 1 - game_main.handle_key(controls, pygame.K_q, ui, save_path) - assert game_main.handle_key(controls, pygame.K_a, ui, save_path) == game_main.ACTION_TURN - assert controls.player.hp == 31 and potion not in controls.player.inventory - - mapping = create_item("Scroll of Mapping") - controls.player.inventory.append(mapping) - game_main.handle_key(controls, pygame.K_r, ui, save_path) - assert game_main.handle_key(controls, pygame.K_RETURN, ui, save_path) == game_main.ACTION_TURN - assert all(controls.current_map.explored) - - fireball = create_item("Scroll of Fireball") - controls.player.inventory.append(fireball) - game_main.handle_key(controls, pygame.K_r, ui, save_path) - assert game_main.handle_key(controls, pygame.K_RETURN, ui, save_path) == game_main.ACTION_NONE - assert ui.mode == game_main.MODE_TARGET - game_main.handle_key(controls, pygame.K_ESCAPE, ui, save_path) - assert ui.mode == game_main.MODE_SCROLL - game_main.handle_key(controls, pygame.K_ESCAPE, ui, save_path) - - ground_item = create_item("Healing Potion", *controls.player.position) - controls.current_map.entities.append(ground_item) - assert game_main.handle_key(controls, pygame.K_g, ui, save_path) == game_main.ACTION_TURN - assert ground_item in controls.player.inventory - - controls.player.x, controls.player.y = controls.current_map.stairs_down or controls.player.position - previous_floor = controls.current_floor - assert game_main.handle_key( - controls, pygame.K_PERIOD, ui, save_path, pygame.KMOD_SHIFT - ) == game_main.ACTION_TURN - assert controls.current_floor == previous_floor + 1 - - assert game_main.handle_key(controls, pygame.K_s, ui, save_path) == game_main.ACTION_SAVED - assert save_path.is_file() - controls.state = GAME_STATE_DEAD - assert game_main.enforce_permadeath(controls, save_path) - assert not save_path.exists() - controls.state = GAME_STATE_VICTORY - save_game(controls, save_path) - assert game_main.enforce_permadeath(controls, save_path) - assert not save_path.exists() - - pygame.init() - surface = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT)) - controls.state = GAME_STATE_PLAYING - compute_fov(controls.current_map, controls.player.x, controls.player.y) - game_main.render(surface, controls, game_main.UIState()) - game_main.render_menu(surface, 0, save_path) - controls.state = GAME_STATE_DEAD - game_main.render_end_screen(surface, controls) - controls.state = GAME_STATE_VICTORY - game_main.render_end_screen(surface, controls) - pygame.quit() - - game_main.main(max_frames=1) - with tempfile.TemporaryDirectory() as directory: - _acceptance_playthrough(Path(directory) / "acceptance-save.json") - - -PHASES: dict[int, Callable[[], None]] = { - 1: phase_1, - 2: phase_2, - 3: phase_3, - 4: phase_4, -} - - -def main() -> None: - parser = argparse.ArgumentParser() - parser.add_argument("--phase", type=int, choices=PHASES) - args = parser.parse_args() - selected = [args.phase] if args.phase else list(PHASES) - for number in selected: - PHASES[number]() - print(f"phase {number}: PASS") - - -if __name__ == "__main__": - main()