(Underdepths) Prepare for Pass 7

This commit is contained in:
AlexKucera committed 2026-08-15 19:39:24 +02:00
1 parent 03dbe778aa
commit e0ea5bb034
30 files changed
+183 -5713

No files matched your search

-1
View File
@@ -1 +0,0 @@
4
-5
View File
@@ -1,5 +0,0 @@
.build_logs/
.orchestrate.lock/
__pycache__/
*.py[cod]
save.json
+51 -22
View File
@@ -81,9 +81,12 @@ Write `orchestrate.sh`, `tests/smoke.py` (stub with phase functions), and
**Phase 1 — Foundation:**
- Build: `data/constants.py`, `entities/entity.py`, `engine/map_gen.py`,
`entities/player.py`, `entities/enemy.py`, minimal `main.py` game loop.
- Gate: generate 5 maps, assert each has ≥3 rooms, all rooms reachable via
flood fill, no room overlaps, and (floors 0–8) `stairs_down` is a floor tile
reachable from the spawn room. Print ASCII render to confirm.
- Gate: generate at least 5 maps, assert each has 8–12 BSP rooms, all rooms reachable
via flood fill, no room overlaps, and every stored corridor path has
`len(path) - 1 <= MAX_CORRIDOR_LENGTH == 14`. Verify every path tile is floor,
every endpoint touches a recorded room or junction, and the generator carved no
unrecorded corridors. On floors 0–8, `stairs_down` must be a floor tile reachable
from the spawn room. Print an ASCII render and the measured longest section.
**Phase 2 — Core Systems (parallelizable):**
FOV, A*, and combat are independent. Dispatch them as separate `pi -p`
@@ -97,19 +100,28 @@ calls that can run concurrently:
(enemy chases player through a test corridor)
**Phase 3 — Content Layer:**
- Items, inventory, equipment, potions, scrolls
- Items, inventory, weapon/armor/boots equipment, potions, scrolls
- Guaranteed Shoes of Hermes on display floor 2 and Hunter's Bow on display floor 3
- Bow ranged attack and the Shoes' held-running capability flag
- XP, leveling, progression
- All 7 enemy types with behaviors
- All 7 enemy types with behaviors; regular-floor initial density is exactly
`4 + 2 * floor_index` (4, 6, 8, …, 20)
- Boss arena on floor 9
- Gate: spawn each enemy type, verify stats. Equip item, verify stat changes.
Kill enemy, verify XP + level-up at threshold.
- Gate: spawn each enemy type and verify stats; verify exact strictly increasing
density on floors 0–8 and the guaranteed reachable Shoes/Bow placements. Equip
every slot and verify stat/capability changes. Through the normal Bow action,
place a nearer chasing target and a farther fleeing target and verify the fleeing
target is selected; place a target behind a wall and verify it cannot be hit;
verify a valid shot spends a turn and can damage/kill with correct logs. Kill an
enemy and verify XP + level-up at threshold.
**Phase 4 — Polish, Visuals, Audio & Persist:**
- Save/load JSON, menu system, death/victory screens, UI panels
- A visible How to Play screen, contextual pickup/stairs prompts, and simple generated sound effects with graceful silent fallback
- Procedural pixel-art sprites / effects / lighting / UI per plan.md Rendering (`data/sprites.py`, `render/sprites.py`, `render/effects.py`)
- Poll held direction keys only while Shoes of Hermes are equipped: one immediate step, 180 ms initial delay, 75 ms repeat, one complete turn per repeated step, immediate stop on release/block/menu/floor/state change/death/victory
- Procedural pixel-art sprites / effects / lighting / UI per plan.md Rendering, including distinct Bow and winged Shoes (`data/sprites.py`, `render/sprites.py`, `render/effects.py`)
- This phase is large — split it into sequential sub-dispatches (e.g. 4a persistence+audio, 4b actions+render+sprites+main) that run BEFORE the single phase gate, if one dispatch cannot finish within the TTL
- Gate: save → load → assert state equality; all menu states reachable; simulated `g` pickup and `f` descent work; audio-disabled mode does not crash; **stairs are visibly rendered** (the renderer blits a distinct stairs sprite on `stairs_down` — assert this, since invisible stairs make the game unwinnable).
- Gate: save → load → assert state equality including weapon/armor/boots; all menu states reachable; simulated `g` pickup and `f` descent work. Drive the real movement input clock: without Shoes, holding moves once; with Shoes, assert no repeat at 179 ms, one at 180 ms, then one per 75 ms, and no further movement after release, block, menu, floor change, death, or victory. Through real `b` input, assert the Bow prefers a fleeing target over a nearer chaser, cannot shoot through a wall, spends a turn, and can kill. Audio-disabled mode does not crash; **stairs are visibly rendered** with a distinct stairs sprite on `stairs_down`.
### Goal backstop
@@ -129,9 +141,12 @@ with a diagnostic.
### Operational hardening (learned the hard way)
- Wrap EVERY `pi -p` dispatch in `timeout --kill-after=30 <ttl>`. The pi (node)
process ignores SIGTERM, so plain `timeout <ttl>` lets a stuck dispatch linger
past its deadline and stall the whole loop. `--kill-after` escalates to SIGKILL.
- Bound EVERY `pi -p` dispatch with a hard TTL and SIGKILL escalation. Use GNU
`timeout --kill-after=30` when available, or Homebrew's `gtimeout` on macOS.
Detect the executable at startup. If neither exists, implement the same behavior
with Python stdlib `subprocess.Popen(start_new_session=True)`, `wait(timeout=...)`,
and `os.killpg(..., signal.SIGKILL)`; never run an unbounded dispatch. The pi
(node) process ignores SIGTERM, so plain timeout handling can stall the pipeline.
- Never run two `orchestrate.sh` instances in the same directory at once:
concurrent `pi -p` agents editing the same files corrupt them. The pipeline is
resumable via `.build_state` — just re-run a single instance.
@@ -151,29 +166,43 @@ 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. Controls must
be explained in-game, with contextual prompts for item pickup and stairs.
It must look polished: distinct procedural pixel-art sprites, FOV lighting, particle juice, and a clean bordered UI — not flat colored squares.
crash. It must have win and lose states. It must save and load. Corridors must
stay within the 14-step section limit, monster density must rise every regular
floor, Shoes of Hermes must provide deliberate hold-to-run, and the Bow must let
the player shoot visible fleeing enemies. Controls must be explained in-game,
with contextual prompts for item pickup and stairs. It must look polished:
distinct procedural pixel-art sprites, FOV lighting, particle juice, and a clean
bordered UI — not flat colored squares.
When you believe you are done:
1. Run `python tests/smoke.py` — must pass.
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 `f`, 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.
on an item and press `g`, equip Shoes of Hermes and hold/release a direction,
equip the Hunter's Bow and shoot a fleeing enemy with `b`, stand on stairs and
press `f`, save, quit, relaunch, and continue. Confirm sound effects play when
audio exists and the game still works when audio initialization fails.
3. Generate multiple maps and inspect the longest corridor plus regular-floor
enemy counts.
4. Check every acceptance criterion checkbox in `plan.md`.
5. If anything fails, fix it. Do not stop until all pass.
## What Kills Entries
- **Crashes during play.** Every code path must be safe. Test edge cases:
empty inventory, no item at feet, attacking with full HP enemy, descending
stairs on the last floor.
empty inventory, no item at feet, attacking a full-HP enemy, and attempting
descent on floor 9 where `stairs_down` is `None` (it must safely do nothing).
- **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 F 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.
- **Long, empty traversal.** Every generated corridor section must be at most 14
steps, and initial monster counts on floors 0–8 must be exactly 4 through 20 in
increments of 2. Tests must measure both rather than trusting constants.
- **Fake mobility or ranged items.** Shoes of Hermes must poll held keys and apply
complete turns until release; OS key repeat is not the feature. The guaranteed
Hunter's Bow must fire with `b`, respect visibility/range/walls, spend a turn,
and be able to damage and kill a fleeing enemy.
- **Unwinnable floors.** Every floor 0–8 MUST have stairs on a floor tile
reachable from spawn AND visibly rendered (the `>` staircase) so the player
can find it and press `f` to descend. Floor 9 is won by slaying a dragon the
-325
View File
@@ -1,325 +0,0 @@
from __future__ import annotations
import math
import random
from data.constants import (
BOSS_BREATH_DAMAGE,
BOSS_BREATH_INTERVAL,
FLEE_HP_FRACTION,
KITE_MAX_DISTANCE,
RANGED_HIT_PENALTY_PER_TILE,
RANGED_MIN_DISTANCE,
SIGHT_RADIUS,
SPLIT_COPIES,
SPLIT_STAT_DIVISOR,
TILE_WALL,
WANDER_WAIT_CHANCE,
)
from engine.combat import attack, log_message
from engine.map_gen import GameMap
from engine.pathfinding import astar, random_step
from entities.enemy import Enemy
from entities.player import Player
Position = tuple[int, int]
_STEPS: tuple[tuple[int, int], ...] = ((0, -1), (0, 1), (-1, 0), (1, 0))
def _distance(a: Position, b: Position) -> float:
return math.hypot(a[0] - b[0], a[1] - b[1])
def _is_adjacent(enemy: Enemy, player: Player) -> bool:
return abs(enemy.x - player.x) + abs(enemy.y - player.y) == 1
def _line_of_sight(game_map: GameMap, start: Position, end: Position) -> bool:
"""Bresenham ray; walls on intermediate tiles block sight."""
x, y = start
x1, y1 = end
dx = abs(x1 - x)
dy = -abs(y1 - y)
sx = 1 if x < x1 else -1
sy = 1 if y < y1 else -1
err = dx + dy
while (x, y) != (x1, y1):
e2 = 2 * err
if e2 >= dy:
err += dy
x += sx
if e2 <= dx:
err += dx
y += sy
if (x, y) == (x1, y1):
return True
if game_map.tile_at(x, y) == TILE_WALL:
return False
return True
def sees_player(enemy: Enemy, player: Player, game_map: GameMap) -> bool:
if player.is_invisible:
return False
return _distance(enemy.position, player.position) <= SIGHT_RADIUS and _line_of_sight(
game_map, enemy.position, player.position
)
def _blocked_positions(game_map: GameMap, enemy: Enemy, player: Player) -> set[Position]:
blocked = {player.position}
blocked.update(
entity.position
for entity in game_map.entities
if entity is not enemy and entity.blocks_movement
)
return blocked
def _walkable_options(
enemy: Enemy, game_map: GameMap, blocked: set[Position]
) -> list[Position]:
return [
(enemy.x + dx, enemy.y + dy)
for dx, dy in _STEPS
if game_map.is_walkable(enemy.x + dx, enemy.y + dy)
and (enemy.x + dx, enemy.y + dy) not in blocked
]
def _act_wander(
enemy: Enemy, game_map: GameMap, blocked: set[Position], rng: random.Random
) -> None:
if rng.random() < WANDER_WAIT_CHANCE:
return
options = _walkable_options(enemy, game_map, blocked)
if options:
enemy.x, enemy.y = rng.choice(options)
def _move_toward(
enemy: Enemy,
target: Position,
game_map: GameMap,
blocked: set[Position],
rng: random.Random,
) -> None:
path = astar(game_map, enemy.position, target, blocked)
if path:
enemy.x, enemy.y = path[0]
return
fallback = random_step(game_map, enemy.position)
if fallback is not None and fallback not in blocked:
enemy.x, enemy.y = fallback
def _move_away(
enemy: Enemy,
player: Player,
game_map: GameMap,
blocked: set[Position],
rng: random.Random,
) -> None:
options = _walkable_options(enemy, game_map, blocked)
if options:
enemy.x, enemy.y = max(
options,
key=lambda pos: (_distance(pos, player.position), rng.random()),
)
def _pursue_last_known(
enemy: Enemy,
game_map: GameMap,
blocked: set[Position],
rng: random.Random,
) -> None:
if enemy.last_known_position is None:
_act_wander(enemy, game_map, blocked, rng)
return
if enemy.position == enemy.last_known_position:
enemy.last_known_position = None
_act_wander(enemy, game_map, blocked, rng)
return
_move_toward(enemy, enemy.last_known_position, game_map, blocked, rng)
def _act_chase(
enemy: Enemy,
player: Player,
game_map: GameMap,
log: list[str],
rng: random.Random,
) -> None:
if _is_adjacent(enemy, player):
attack(enemy, player, log, rng=rng)
return
blocked = _blocked_positions(game_map, enemy, player)
if sees_player(enemy, player, game_map):
enemy.last_known_position = player.position
_move_toward(enemy, player.position, game_map, blocked, rng)
else:
_pursue_last_known(enemy, game_map, blocked, rng)
def _act_flee(
enemy: Enemy,
player: Player,
game_map: GameMap,
log: list[str],
rng: random.Random,
) -> None:
if enemy.hp < enemy.max_hp * FLEE_HP_FRACTION:
_move_away(enemy, player, game_map, _blocked_positions(game_map, enemy, player), rng)
return
_act_chase(enemy, player, game_map, log, rng)
def _act_ranged(
enemy: Enemy,
player: Player,
game_map: GameMap,
log: list[str],
rng: random.Random,
) -> None:
dist = _distance(enemy.position, player.position)
blocked = _blocked_positions(game_map, enemy, player)
if sees_player(enemy, player, game_map):
enemy.last_known_position = player.position
if dist <= KITE_MAX_DISTANCE:
_move_away(enemy, player, game_map, blocked, rng)
elif dist > RANGED_MIN_DISTANCE:
power = enemy.ranged_power or enemy.power
attack(
enemy,
player,
log,
rng=rng,
power_override=power,
hit_modifier=-RANGED_HIT_PENALTY_PER_TILE * dist,
)
else:
_move_toward(enemy, player.position, game_map, blocked, rng)
else:
_pursue_last_known(enemy, game_map, blocked, rng)
def _act_phase(
enemy: Enemy,
player: Player,
game_map: GameMap,
log: list[str],
rng: random.Random,
) -> None:
if _is_adjacent(enemy, player):
attack(enemy, player, log, rng=rng)
return
blocked = _blocked_positions(game_map, enemy, player)
dx, dy = player.x - enemy.x, player.y - enemy.y
sx = (dx > 0) - (dx < 0)
sy = (dy > 0) - (dy < 0)
x_first = abs(dx) >= abs(dy)
candidates = (
(enemy.x + (sx if x_first else 0), enemy.y + (sy if not x_first else 0)),
(enemy.x + (0 if x_first else sx), enemy.y + (sy if x_first else 0)),
)
for step in candidates:
if step != enemy.position and game_map.in_bounds(*step) and step not in blocked:
enemy.x, enemy.y = step
return
def dragon_breath(dragon: Enemy, player: Player, game_map: GameMap, log: list[str]) -> None:
"""Breath weapon: flat damage to everything on the Bresenham line toward
the player. Stops at walls; the player takes BOSS_BREATH_DAMAGE if caught."""
log_message(log, "The Ancient Dragon breathes a torrent of flame!")
x, y = dragon.position
px, py = player.position
dx = abs(px - x)
dy = -abs(py - y)
sx = 1 if x < px else -1
sy = 1 if y < py else -1
err = dx + dy
while (x, y) != (px, py):
e2 = 2 * err
if e2 >= dy:
err += dy
x += sx
if e2 <= dx:
err += dx
y += sy
if (x, y) == (px, py):
break
if game_map.tile_at(x, y) == TILE_WALL:
return
player.hp -= BOSS_BREATH_DAMAGE
log_message(log, f"You are caught in the flames and take {BOSS_BREATH_DAMAGE} damage!")
def take_turn(
enemy: Enemy,
player: Player,
game_map: GameMap,
turn: int,
log: list[str],
rng: random.Random | None = None,
) -> None:
"""Dispatch one enemy turn. Pure with respect to globals: everything it
reads or mutates is passed in (enemy, map, log, turn)."""
rng = rng or random
if enemy.speed > 1 and turn % enemy.speed != 0:
return
if enemy.behavior == "chase":
_act_chase(enemy, player, game_map, log, rng)
elif enemy.behavior == "flee":
_act_flee(enemy, player, game_map, log, rng)
elif enemy.behavior == "ranged":
_act_ranged(enemy, player, game_map, log, rng)
elif enemy.behavior == "phase":
_act_phase(enemy, player, game_map, log, rng)
elif enemy.behavior == "split":
_act_chase(enemy, player, game_map, log, rng)
elif enemy.behavior == "boss":
if (
turn % BOSS_BREATH_INTERVAL == 0
and sees_player(enemy, player, game_map)
and not _is_adjacent(enemy, player)
):
dragon_breath(enemy, player, game_map, log)
else:
_act_chase(enemy, player, game_map, log, rng)
else:
_act_wander(enemy, game_map, _blocked_positions(game_map, enemy, player), rng)
def split_on_death(enemy: Enemy) -> list[Enemy]:
"""Split death hook: two half-stat copies, spawned adjacent to the corpse.
Copies cannot split again. Returns [] when no splits remain."""
if enemy.splits_remaining <= 0:
return []
half_hp = max(1, enemy.max_hp // SPLIT_STAT_DIVISOR)
half_power = max(1, enemy.power // SPLIT_STAT_DIVISOR)
copies = [
Enemy(
x=enemy.x + dx,
y=enemy.y,
key=enemy.key,
name=f"Small {enemy.name}",
sprite_key=enemy.sprite_key,
hp=half_hp,
max_hp=half_hp,
power=half_power,
armor=enemy.armor,
accuracy=enemy.accuracy,
evasion=enemy.evasion,
crit_chance=enemy.crit_chance,
speed=enemy.speed,
behavior=enemy.behavior,
xp_reward=max(1, enemy.xp_reward // SPLIT_STAT_DIVISOR),
splits_remaining=enemy.splits_remaining - 1,
)
for dx in (-1, 1)
]
return copies[:SPLIT_COPIES]
-104
View File
@@ -1,104 +0,0 @@
from __future__ import annotations
from typing import Final
MAP_WIDTH: Final = 80
MAP_HEIGHT: Final = 50
TILE_SIZE: Final = 20
TILE_WALL: Final = 0
TILE_FLOOR: Final = 1
MAP_BORDER: Final = 1
ROOM_MIN_WIDTH: Final = 4
ROOM_MAX_WIDTH: Final = 10
ROOM_MIN_HEIGHT: Final = 4
ROOM_MAX_HEIGHT: Final = 8
ROOM_MARGIN: Final = 1
BSP_MIN_SPLITS: Final = 5
BSP_MAX_SPLITS: Final = 8
FINAL_FLOOR: Final = 9
SIGHT_RADIUS: Final = 8
FPS: Final = 60
GAME_TITLE: Final = "Underdepths"
SAVE_FILENAME: Final = "save.json"
# -- rendering layout (48x28-tile viewport at TILE_SIZE px) -------------------
VIEW_TILES_W: Final = 48
VIEW_TILES_H: Final = 28
TOP_BAR_H: Final = 36
BOTTOM_BAR_H: Final = 64
LOG_PANEL_W: Final = 300
SCREEN_W: Final = VIEW_TILES_W * TILE_SIZE + LOG_PANEL_W
SCREEN_H: Final = TOP_BAR_H + VIEW_TILES_H * TILE_SIZE + BOTTOM_BAR_H
LIGHT_STEPS: Final = 12
PARTICLE_CAP: Final = 320
MAX_LOG_SHOWN: Final = 8
IDLE_FRAMES: Final = 3
IDLE_FRAME_MS: Final = 260
PLAYER_MAX_HP: Final = 50
PLAYER_POWER: Final = 4
PLAYER_ARMOR: Final = 0
PLAYER_ACCURACY: Final = 5
PLAYER_EVASION: Final = 2
PLAYER_CRIT_CHANCE: Final = 0.10
PLAYER_SPEED: Final = 1
HIT_BASE_CHANCE: Final = 0.7
HIT_CHANCE_SCALE: Final = 0.05
HIT_CHANCE_MIN: Final = 0.1
HIT_CHANCE_MAX: Final = 0.95
CRIT_MULTIPLIER: Final = 2
LOG_MAX_MESSAGES: Final = 50
WANDER_WAIT_CHANCE: Final = 0.5
FLEE_HP_FRACTION: Final = 0.3
RANGED_MIN_DISTANCE: Final = 3.0
KITE_MAX_DISTANCE: Final = 2.0
RANGED_HIT_PENALTY_PER_TILE: Final = 0.03
SPLIT_COPIES: Final = 2
SPLIT_STAT_DIVISOR: Final = 2
STRENGTH_BONUS: Final = 5
STRENGTH_TURNS: Final = 20
INVISIBILITY_TURNS: Final = 15
HEAL_AMOUNT: Final = 30
FIREBALL_DAMAGE: Final = 20
FIREBALL_RADIUS: Final = 3.0
BOSS_BREATH_INTERVAL: Final = 3
BOSS_BREATH_DAMAGE: Final = 15
BOSS_ARENA_WIDTH: Final = 20
BOSS_ARENA_HEIGHT: Final = 15
# (enemy_lo, enemy_hi), (item_lo, item_hi) per depth band
SPAWN_TABLE: Final[dict[tuple[int, int], tuple[tuple[int, int], tuple[int, int]]]] = {
(0, 1): ((3, 4), (2, 3)),
(2, 3): ((4, 6), (2, 3)),
(4, 5): ((5, 7), (3, 4)),
(6, 7): ((6, 8), (3, 4)),
(8, 8): ((7, 9), (4, 5)),
}
# floors where a weapon able to beat armor 8 is guaranteed on the map
GUARANTEED_HEAVY_WEAPONS: Final[dict[int, tuple[str, ...]]] = {
4: ("battle_axe",),
7: ("war_hammer", "battle_axe"),
}
# level -> (cumulative xp required, hp gain, power gain) on reaching that level
LEVEL_TABLE: Final[dict[int, tuple[int, int, int]]] = {
2: (30, 10, 1),
3: (70, 10, 1),
4: (140, 10, 1),
5: (250, 10, 1),
6: (400, 15, 2),
7: (600, 15, 2),
8: (850, 15, 2),
9: (1150, 15, 2),
10: (1500, 20, 3),
}
Color = tuple[int, int, int]
COLORS: Final[dict[str, Color]] = {
"background": (8, 8, 12),
"wall": (60, 60, 70),
"floor": (40, 35, 30),
"player": (90, 170, 230),
"stairs": (245, 210, 70),
}
-141
View File
@@ -1,141 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Final
from entities.enemy import Enemy
@dataclass(frozen=True, slots=True)
class EnemyDef:
key: str
name: str
hp: int
power: int
armor: int
speed: int
behavior: str
xp: int
accuracy: int
evasion: int
ranged_power: int = 0
min_floor: int = 0
max_floor: int = 8
sprite_key: str = ""
ENEMY_ROSTER: Final[dict[str, EnemyDef]] = {
d.key: d
for d in (
EnemyDef("rat", "Rat", 8, 3, 0, 1, "wander", 5, 1, 0, min_floor=0, max_floor=3, sprite_key="rat"),
EnemyDef(
"goblin", "Goblin", 15, 5, 1, 1, "chase", 12, 2, 1, min_floor=0, max_floor=5, sprite_key="goblin"
),
EnemyDef(
"skeleton_archer",
"Skeleton Archer",
12,
4,
1,
1,
"ranged",
15,
3,
1,
ranged_power=6,
min_floor=2,
max_floor=7,
sprite_key="skeleton_archer",
),
EnemyDef(
"orc_warrior",
"Orc Warrior",
30,
8,
3,
1,
"flee",
25,
3,
0,
min_floor=3,
max_floor=8,
sprite_key="orc_warrior",
),
EnemyDef(
"wraith",
"Wraith",
20,
10,
0,
2,
"phase",
30,
4,
2,
min_floor=5,
max_floor=8,
sprite_key="wraith",
),
EnemyDef(
"green_slime",
"Green Slime",
18,
5,
1,
1,
"split",
18,
2,
0,
min_floor=4,
max_floor=8,
sprite_key="green_slime",
),
EnemyDef(
"ancient_dragon",
"Ancient Dragon",
120,
15,
8,
1,
"boss",
200,
6,
0,
min_floor=9,
max_floor=9,
sprite_key="ancient_dragon",
),
)
}
def make_enemy(key: str, x: int = 0, y: int = 0) -> Enemy:
d = ENEMY_ROSTER[key]
return Enemy(
x=x,
y=y,
key=key,
name=d.name,
sprite_key=d.sprite_key or "enemy",
hp=d.hp,
max_hp=d.hp,
power=d.power,
armor=d.armor,
accuracy=d.accuracy,
evasion=d.evasion,
speed=d.speed,
behavior=d.behavior,
ranged_power=d.ranged_power,
xp_reward=d.xp,
splits_remaining=1 if d.behavior == "split" else 0,
)
def enemies_for_floor(floor_index: int) -> list[str]:
return [
key
for key, d in ENEMY_ROSTER.items()
if d.min_floor <= floor_index <= d.max_floor and d.behavior != "boss"
]
-75
View File
@@ -1,75 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Final
@dataclass(frozen=True, slots=True)
class ItemDef:
key: str
name: str
category: str # "weapon" | "armor" | "potion" | "scroll"
power: int = 0
armor: int = 0
crit_modifier: float = 0.0
evasion_modifier: int = 0 # flat points; 2 points == 10% hit chance
effect: str = "" # heal | strength | invisibility | fireball | teleport | mapping
min_floor: int = 0
max_floor: int = 9
sprite_key: str = ""
ITEM_CATALOG: Final[dict[str, ItemDef]] = {
d.key: d
for d in (
ItemDef("rusty_dagger", "Rusty Dagger", "weapon", power=2, sprite_key="item_weapon"),
ItemDef("short_sword", "Short Sword", "weapon", power=4, min_floor=1, sprite_key="item_weapon"),
ItemDef("battle_axe", "Battle Axe", "weapon", power=7, min_floor=4, sprite_key="item_weapon"),
ItemDef(
"war_hammer",
"War Hammer",
"weapon",
power=10,
crit_modifier=-0.05,
min_floor=6,
sprite_key="item_weapon",
),
ItemDef("leather_armor", "Leather Armor", "armor", armor=2, sprite_key="item_armor"),
ItemDef("chain_mail", "Chain Mail", "armor", armor=4, min_floor=2, sprite_key="item_armor"),
ItemDef(
"plate_armor",
"Plate Armor",
"armor",
armor=7,
evasion_modifier=-2,
min_floor=5,
sprite_key="item_armor",
),
ItemDef("healing_potion", "Healing Potion", "potion", effect="heal", sprite_key="item_potion"),
ItemDef(
"strength_potion", "Strength Potion", "potion", effect="strength", sprite_key="item_potion"
),
ItemDef(
"invisibility_potion",
"Invisibility Potion",
"potion",
effect="invisibility",
sprite_key="item_potion",
),
ItemDef(
"scroll_fireball",
"Scroll of Fireball",
"scroll",
effect="fireball",
sprite_key="item_scroll",
),
ItemDef(
"scroll_teleport", "Scroll of Teleport", "scroll", effect="teleport", sprite_key="item_scroll"
),
ItemDef("scroll_mapping", "Scroll of Mapping", "scroll", effect="mapping", sprite_key="item_scroll"),
)
}
def items_for_floor(floor_index: int) -> list[ItemDef]:
return [d for d in ITEM_CATALOG.values() if d.min_floor <= floor_index <= d.max_floor]
-643
View File
@@ -1,643 +0,0 @@
"""Hand-authored pixel-art grids: 2D palette-key patterns per entity/tile/item.
'.' is transparent. Every other char maps to an RGB tuple in PALETTES.
Rows must be uniform width (asserted by the self-check below).
"""
from __future__ import annotations
# -- player -------------------------------------------------------------------
# Hooded adventurer, three facings ("side" faces right; left = mirrored blit).
PLAYER_DOWN: list[str] = [
"............",
"....KKKK....",
"...KHHHHK...",
"..KHHHHHHK..",
"..KHhhhhHK..",
"..KHFFFFHK..",
"..KHFKFKHK..",
"...KFFFFK...",
"..KTTTTTTK..",
".KTKtTTtKTK.",
"...KTTTTK...",
"...KBKKBK...",
]
PLAYER_UP: list[str] = [
"............",
"....KKKK....",
"...KHHHHK...",
"..KHHHHHHK..",
"..KHHHHHHK..",
"..KHhhhhHK..",
"..KHHHHHHK..",
"...KHHHHK...",
"..KTTTTTTK..",
".KTKTTTTKTK.",
"...KTTTTK...",
"...KBKKBK...",
]
PLAYER_SIDE: list[str] = [
"............",
"....KKKK....",
"...KHHHHK...",
"..KHHHHHK...",
"..KHHhhhK...",
"..KHHFFFK...",
"..KHHFKFK...",
"...KFFFK....",
"..KTTTTTK...",
"..KtTTTTKK..",
"...KTTTTK...",
"...KBKKBK...",
]
# Weapon overlays merge onto the base grid (non-'.' chars replace).
_OVERLAY_DAGGER: list[str] = [
"............",
"............",
"............",
"..........K.",
".........KwK",
".........KwK",
".........KwK",
"........KBK.",
"........KBK.",
"............",
"............",
"............",
]
_OVERLAY_SWORD: list[str] = [
"..........K.",
".........KwK",
".........KwK",
".........KwK",
".........KwK",
".........KwK",
"........KGwK",
"........KBK.",
"........KBK.",
"............",
"............",
"............",
]
_OVERLAY_AXE: list[str] = [
"............",
".......KMMK.",
"......KMMMK.",
"......KMMMK.",
".......KMK..",
".......KBK..",
".......KBK..",
".......KBK..",
".......KBK..",
"............",
"............",
"............",
]
_OVERLAY_HAMMER: list[str] = [
"............",
"......KMMMK.",
"......KMMMK.",
"......KMMMK.",
"......KMMMK.",
".......KBK..",
".......KBK..",
".......KBK..",
".......KBK..",
"............",
"............",
"............",
]
WEAPON_OVERLAYS: dict[str, list[str]] = {
"rusty_dagger": _OVERLAY_DAGGER,
"short_sword": _OVERLAY_SWORD,
"battle_axe": _OVERLAY_AXE,
"war_hammer": _OVERLAY_HAMMER,
}
# Tunic palette overrides per armor key: T main / t shade.
ARMOR_TUNICS: dict[str, dict[str, tuple[int, int, int]]] = {
"leather_armor": {"T": (130, 90, 50), "t": (95, 64, 34)},
"chain_mail": {"T": (150, 155, 165), "t": (105, 110, 120)},
"plate_armor": {"T": (205, 210, 220), "t": (150, 155, 168)},
}
# -- enemies ------------------------------------------------------------------
RAT: list[str] = [
"............",
".......KPK..",
"..KK...KPzK.",
".KzzK.KBBK..",
"..KzBBBBBBK.",
"..KBBBBBBEK.",
"PPKBPPbBBKWW",
"...KBBBK....",
"..KbK.KbK...",
"...W....W...",
"............",
"............",
]
GOBLIN: list[str] = [
"............",
"...K....K...",
"..KGK..KGK..",
"..KGGKKGGK..",
"..KGEGGEGK..",
"..KGGGGGGK..",
"...KGttGK...",
"..KgGGGGgK..",
".KGKLLLLKGK.",
".KGKLLLLKGWK",
"..KGLLLGK.WK",
"..KGK..KGK..",
]
SKELETON_ARCHER: list[str] = [
"............",
"....KWWK....",
"...KWWWWK.QQ",
"...KEWWEK.QQ",
"...KWWWWK...",
"....KwWw..QQ",
"...KWWWWK..B",
"..KwKWWKwK.B",
"..KwKWWKwKSB",
"...KWWWWK.SB",
"...KwKKwK..B",
"...KK..KK...",
]
ORC_WARRIOR: list[str] = [
"..........M.",
"...KKKK...M.",
"..KRRRRK..MK",
"..KERREK..MK",
"..KRRRRK.MmK",
"...KTTTK.MmK",
".KKRRRRKKMmK",
"KRRRRRRRKMmK",
"KRRrRRrRRMmK",
"KRRRRRRRRMK.",
".KRRK.KRRK..",
".KrrK.KrrK..",
]
WRAITH: list[str] = [
"............",
"....KPPK....",
"...KPPPPK...",
"..KPpPPpPK..",
"..KPEPPEPK..",
"..KPPPPPPK..",
"..KpPPPPpK..",
"..KpPPPPpK..",
"...KpPPpK...",
"..KpKpKpKK..",
"...pK.pK.p..",
"....p...p...",
]
GREEN_SLIME: list[str] = [
"..........D.",
"....KKKK..D.",
"..KKGLLKKKD.",
".KGGLLLLGGK.",
".KGLWWLWWGK.",
".KGLEWLEWGK.",
".KGGGGGGGGK.",
".KgGGGGGGgK.",
"..KgGGGGgK..",
"...KKKKKK...",
"............",
"............",
]
# 20x20 multi-hue boss: horns, spread wings, scales, fangs, orange belly.
ANCIENT_DRAGON: list[str] = [
"......YY....YY......",
".....KYK....KYK.....",
"....KYYK...KYYK.KK..",
"....KYK...KDDDKKDDK.",
"...KRRRK..KDDDDDDDK.",
"..KRRRRRK.KDDDDDDDK.",
"..KRERRRK..KDDDDDK..",
"..KRRRRRK...KKKKK...",
".KRWRRRRRK..KrrrK...",
"KRRWRRRRRKKrrrrrrK..",
"KRRRRRRRRRrrrrrrrK..",
"KRRQRRRRRRrrrrrrrK..",
".KRQQQRRRRRrrrrrKK..",
".KRQQQQRRRRrrrrrrKYK",
".KRQQQQRRRRrrrrrKKYK",
"..KRQQQRRRRKrrrK.KK.",
"..KRRKKRRRKKrrK.....",
"..KYKY...KYKY.......",
"...KK.....KK........",
"....................",
]
# -- items --------------------------------------------------------------------
WEAPON_DAGGER: list[str] = [
"............",
"........KK..",
".......KwK..",
"......KwK...",
".KK..KwK....",
".KGwKwK.....",
"..KBBK......",
"..KBBK......",
"...KGK......",
"............",
"............",
"............",
]
WEAPON_SWORD: list[str] = [
".........KK.",
"........KwK.",
".......KwK..",
"......KwK...",
".....KwK....",
".KK.KwK.....",
".KGwKwK.....",
"..KBBK......",
"..KBBK......",
"...KGK......",
"............",
"............",
]
WEAPON_AXE: list[str] = [
"............",
"...KKK......",
"..KwwwK.....",
".KwwwwwK....",
".KwwwwwK.KK.",
"..KwwwK.KBBK",
"...KK..KBBK.",
".......KBBK.",
"........KBBK",
".........KK.",
"............",
"............",
]
WEAPON_HAMMER: list[str] = [
"............",
"...KKKK.....",
"..KwwwwK....",
"..KwwwwK.KK.",
"..KwwwwK.KBK",
"...KKKK..KBK",
".........KBK",
".........KBK",
".........KBK",
".........KK.",
"............",
"............",
]
ARMOR_CHEST: list[str] = [
"............",
"..KK....KK..",
".KAAK..KAAK.",
".KAAAKKAAAK.",
".KAAAAAAAAK.",
".KAAAAAAAAK.",
".KAAyAAyAAK.",
".KAAAAAAAAK.",
"..KAAAAAAK..",
"...KKKKKK...",
"............",
"............",
]
POTION_FLASK: list[str] = [
"....KKK.....",
"....KBK.....",
"....KBK.....",
"...KHHHK....",
"..KWHHHHK...",
"..KWHHHHK...",
".KWWLLLWWK..",
".KWLLLLLWK..",
".KLLLLLLLK..",
"..KLLLLLK...",
"...KKKKK....",
"............",
]
SCROLL: list[str] = [
"............",
"..KKKKKKKK..",
".KRRPPPPRRK.",
".KPPPPPPPPK.",
".KPPCCCPPPK.",
".KPPCCCCPPK.",
".KPPCCCPPPK.",
".KPPPPPPPPK.",
".KRpPPPPpRK.",
"..KKKKKKKK..",
"............",
"............",
]
STAIRS: list[str] = [
"............",
"...OO....O..",
"..O.KKKKK.O.",
".O.KYYYYYYK.",
"..KKyyyyyK..",
".KYYYYYyK...",
".KyyyyyK....",
"KYYYYYyK....",
"KyyyyK......",
"KKKKK.......",
"....O....O..",
"............",
]
# -- tiles (10x10, blitted at 2 px per cell) -----------------------------------
WALL_VARIANTS: list[list[str]] = [
[
"EEEEEEEEEE",
"BBBBBbBBBB",
"BBBBBbBBBB",
"bbbbbbbbbb",
"BBbBBBBBBB",
"BBbBBBBBBB",
"bbbbbbbbbb",
"BBBBBBBbBB",
"BBBBBBBbBB",
"DDDDDDDDDD",
],
[
"EEEEEEEEEE",
"BBbBBBBBBB",
"BBbBBBBBBB",
"bbbbbbbbbb",
"BBBBBBBbBB",
"BBBBBBBbBB",
"bbbbbbbbbb",
"BBBBbBBBBc",
"BBBBbBBBBc",
"DDDDDDDDDD",
],
[
"EEEEEEEEEE",
"BBBcBBBBBB",
"BBBcBBBBBB",
"bbbbbbbbbb",
"BBBBBBbBBB",
"BBBBBBbBBB",
"bbbbbbbbbb",
"BBbBBBBBBB",
"BBbBBBBBBc",
"DDDDDDDDDD",
],
]
FLOOR_VARIANTS: list[list[str]] = [
[
"FFFFFFFFFF",
"FFFfFFFFFF",
"FFFFFFFdFF",
"FdFFFFFFFF",
"FFFFFFFFfF",
"FFFdFFFFFF",
"FFFFFFFfFF",
"FFfFFFFFFF",
"FFFFFFFdFF",
"FFFFFFFFFF",
],
[
"FFFFFFFFFF",
"FFFFFFFfFF",
"FFdFFFFFFF",
"FFFFFFFFFd",
"FFFfFFFFFF",
"FFFFFFFdFF",
"FFFFFFFFfF",
"FdFFFFFFFF",
"FFFfFFFFFF",
"FFFFFFFFFF",
],
[
"FFFFFFFdFF",
"FFFFFFFFFF",
"FFfFFFFFFd",
"FFFFFFFdFF",
"FFFFFFFFFF",
"FdFFFFFfFF",
"FFFFFFdFFF",
"FFfFFFFFFF",
"FFFFFFFfFF",
"FFFFdFFFFF",
],
]
# sprite key -> grid (aliases share grids)
GRIDS: dict[str, list[str]] = {
"rat": RAT,
"goblin": GOBLIN,
"skeleton_archer": SKELETON_ARCHER,
"orc_warrior": ORC_WARRIOR,
"wraith": WRAITH,
"green_slime": GREEN_SLIME,
"small_green_slime": GREEN_SLIME,
"ancient_dragon": ANCIENT_DRAGON,
"weapon_dagger": WEAPON_DAGGER,
"weapon_sword": WEAPON_SWORD,
"weapon_axe": WEAPON_AXE,
"weapon_hammer": WEAPON_HAMMER,
"armor_leather": ARMOR_CHEST,
"armor_chain": ARMOR_CHEST,
"armor_plate": ARMOR_CHEST,
"potion_heal": POTION_FLASK,
"potion_strength": POTION_FLASK,
"potion_invis": POTION_FLASK,
"scroll": SCROLL,
"stairs": STAIRS,
}
_BASE_PALETTE: dict[str, tuple[int, int, int]] = {
"K": (18, 14, 16),
"W": (238, 238, 232),
"w": (180, 185, 195),
"B": (60, 60, 70),
"b": (42, 42, 50),
"D": (30, 30, 35),
"E": (88, 88, 100),
"c": (48, 48, 56),
"F": (40, 35, 30),
"f": (52, 46, 40),
"d": (30, 26, 22),
}
PALETTES: dict[str, dict[str, tuple[int, int, int]]] = {
"rat": {
**_BASE_PALETTE,
"B": (135, 95, 60),
"b": (100, 68, 40),
"P": (235, 160, 170),
"z": (210, 130, 145),
"E": (20, 15, 10),
},
"goblin": {
**_BASE_PALETTE,
"G": (95, 150, 65),
"g": (62, 105, 42),
"E": (230, 60, 50),
"L": (120, 80, 45),
"W": (150, 105, 60),
"t": (240, 235, 220),
},
"skeleton_archer": {
**_BASE_PALETTE,
"W": (225, 225, 215),
"w": (165, 165, 155),
"E": (120, 240, 255),
"B": (150, 110, 60),
"S": (230, 230, 230),
"Q": (100, 70, 130),
},
"orc_warrior": {
**_BASE_PALETTE,
"R": (150, 50, 42),
"r": (105, 32, 28),
"E": (255, 200, 60),
"T": (240, 238, 225),
"M": (160, 165, 175),
"m": (110, 115, 125),
},
"wraith": {
**_BASE_PALETTE,
"P": (125, 80, 190),
"p": (75, 45, 125),
"E": (255, 130, 240),
},
"green_slime": {
**_BASE_PALETTE,
"G": (95, 195, 85),
"g": (55, 135, 55),
"L": (190, 245, 170),
"W": (245, 245, 245),
"E": (25, 20, 15),
"D": (95, 195, 85),
},
"small_green_slime": {
**_BASE_PALETTE,
"G": (120, 210, 105),
"g": (70, 150, 65),
"L": (200, 250, 180),
"W": (245, 245, 245),
"E": (25, 20, 15),
"D": (120, 210, 105),
},
"ancient_dragon": {
**_BASE_PALETTE,
"R": (200, 55, 45),
"r": (160, 40, 34),
"Q": (235, 120, 60),
"Y": (235, 215, 120),
"E": (255, 230, 90),
"W": (245, 240, 230),
"D": (120, 25, 22),
},
"weapon_dagger": {**_BASE_PALETTE, "w": (170, 160, 140), "G": (150, 120, 60), "B": (110, 78, 45)},
"weapon_sword": {**_BASE_PALETTE, "w": (200, 205, 215), "G": (220, 180, 90), "B": (110, 78, 45)},
"weapon_axe": {**_BASE_PALETTE, "w": (185, 190, 200), "B": (110, 78, 45)},
"weapon_hammer": {**_BASE_PALETTE, "w": (175, 178, 188), "B": (110, 78, 45)},
"armor_leather": {**_BASE_PALETTE, "A": (130, 90, 50), "y": (95, 64, 34)},
"armor_chain": {**_BASE_PALETTE, "A": (150, 155, 165), "y": (105, 110, 120)},
"armor_plate": {**_BASE_PALETTE, "A": (205, 210, 220), "y": (150, 155, 168)},
"potion_heal": {**_BASE_PALETTE, "L": (210, 60, 60), "H": (150, 40, 40), "B": (140, 100, 60)},
"potion_strength": {**_BASE_PALETTE, "L": (240, 140, 50), "H": (180, 95, 35), "B": (140, 100, 60)},
"potion_invis": {**_BASE_PALETTE, "L": (170, 200, 235), "H": (120, 145, 180), "B": (140, 100, 60)},
"scroll": {**_BASE_PALETTE, "P": (225, 205, 150), "p": (190, 165, 110), "C": (90, 230, 230), "R": (150, 120, 80)},
"stairs": {
**_BASE_PALETTE,
"Y": (245, 210, 70),
"y": (200, 160, 40),
"O": (255, 245, 170),
},
}
# player palette (before armor tunic overrides)
PALETTES["player"] = {
**_BASE_PALETTE,
"H": (52, 86, 150),
"h": (34, 58, 105),
"F": (230, 190, 150),
"T": (110, 118, 140),
"t": (80, 86, 105),
"B": (70, 45, 25),
"w": (200, 205, 215),
"G": (200, 170, 90),
"M": (160, 165, 175),
}
# sprite key -> scale factor relative to TILE_SIZE (dragon spans 1.5 tiles)
SCALE_FACTORS: dict[str, float] = {
"ancient_dragon": 1.5,
"small_green_slime": 0.75,
}
PLAYER_FACINGS = ("down", "up", "side")
def player_grid(weapon_key: str, armor_key: str, facing: str) -> list[str]:
base = {"down": PLAYER_DOWN, "up": PLAYER_UP, "side": PLAYER_SIDE}[facing]
overlay = WEAPON_OVERLAYS.get(weapon_key)
if overlay is None:
return base
return [
"".join(overlay_char if overlay_char != "." else base_char
for base_char, overlay_char in zip(row_base, row_overlay))
for row_base, row_overlay in zip(base, overlay)
]
def player_palette(armor_key: str) -> dict[str, tuple[int, int, int]]:
palette = dict(PALETTES["player"])
palette.update(ARMOR_TUNICS.get(armor_key, {}))
return palette
def validate() -> None:
names = [name for name, value in globals().items()
if isinstance(value, list) and value and isinstance(value[0], str)
and name.isupper()]
grids = {name: value for name, value in globals().items() if name in names}
for name, grid in grids.items():
width = len(grid[0])
assert width > 0, name
for i, row in enumerate(grid):
assert len(row) == width, f"{name} row {i} ragged: {len(row)} != {width}"
for facing in PLAYER_FACINGS:
grid = player_grid("war_hammer", "plate_armor", facing)
assert len(grid) == len(PLAYER_DOWN) and len(grid[0]) == len(PLAYER_DOWN[0]), facing
for key in GRIDS:
assert key in PALETTES, f"palette missing for {key}"
assert len(ANCIENT_DRAGON) == 20 and len(ANCIENT_DRAGON[0]) == 20, "dragon must be 20x20"
for variant in WALL_VARIANTS + FLOOR_VARIANTS:
assert len(variant) == 10 and len(variant[0]) == 10
if __name__ == "__main__":
validate()
for name, grid in sorted(GRIDS.items()):
print(f"== {name} ==")
print("\n".join(grid))
print("sprites self-check: PASS")
-103
View File
@@ -1,103 +0,0 @@
from __future__ import annotations
import math
from array import array
import pygame
SAMPLE_RATE: int = 22050
MASTER_VOLUME: float = 0.25
# name -> list of (freq_start, freq_end, milliseconds)
_TONES: dict[str, list[tuple[float, float, int]]] = {
"hit": [(240, 180, 70)],
"crit": [(330, 200, 60), (500, 380, 80)],
"miss": [(120, 90, 60)],
"hurt": [(200, 90, 160)],
"pickup": [(420, 640, 90)],
"use": [(520, 520, 60), (700, 700, 70)],
"stairs": [(400, 380, 90), (320, 300, 90), (250, 230, 110)],
"level_up": [(330, 330, 80), (440, 440, 80), (550, 550, 120)],
"death": [(160, 55, 500)],
"victory": [(392, 392, 120), (494, 494, 120), (587, 587, 120), (784, 784, 260)],
"menu": [(500, 500, 40)],
}
def generate_tone(
freq_start: float, freq_end: float, milliseconds: int, volume: float = MASTER_VOLUME
) -> array:
"""Linear frequency sweep as signed 16-bit mono samples."""
count = max(1, SAMPLE_RATE * milliseconds // 1000)
samples = array("h", bytes(2 * count))
phase = 0.0
for i in range(count):
t = i / count
freq = freq_start + (freq_end - freq_start) * t
phase += 2.0 * math.pi * freq / SAMPLE_RATE
envelope = 1.0 - t * 0.5 # gentle decay so blips never click hard
samples[i] = int(32000 * volume * envelope * math.sin(phase))
return samples
class SoundEffects:
"""In-memory generated effects. Any mixer failure degrades to silence."""
def __init__(self) -> None:
self.enabled = False
self.muted = False
self._sounds: dict[str, pygame.mixer.Sound] = {}
try:
pygame.mixer.init(frequency=SAMPLE_RATE, size=-16, channels=1)
for name, notes in _TONES.items():
samples = array("h")
for freq_start, freq_end, ms in notes:
samples.extend(generate_tone(freq_start, freq_end, ms))
self._sounds[name] = pygame.mixer.Sound(buffer=samples.tobytes())
self.enabled = True
except Exception: # ponytail: mixer/mem format quirks vary by platform; silence is always safe
self.enabled = False
def play(self, name: str) -> None:
if not self.enabled or self.muted:
return
sound = self._sounds.get(name)
if sound is not None:
try:
sound.play()
except pygame.error:
pass
def toggle_mute(self) -> bool:
self.muted = not self.muted
return self.muted
if __name__ == "__main__":
import os
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
pygame.init()
effects = SoundEffects()
assert effects.enabled, "dummy audio driver should initialize the mixer"
for name in _TONES:
effects.play(name)
effects.toggle_mute()
assert effects.muted
effects.play("hit") # must be silent, not crash
# Forced mixer failure degrades to a fully-disabled, playable game.
class _Broken:
@staticmethod
def init(**kwargs):
raise pygame.error("no audio device")
original = pygame.mixer.init
pygame.mixer.init = _Broken.init
try:
broken = SoundEffects()
finally:
pygame.mixer.init = original
assert not broken.enabled and not broken.play("hit")
pygame.quit()
print("audio self-check: PASS")
-136
View File
@@ -1,136 +0,0 @@
from __future__ import annotations
import random
from data.constants import (
CRIT_MULTIPLIER,
HIT_BASE_CHANCE,
HIT_CHANCE_MAX,
HIT_CHANCE_MIN,
HIT_CHANCE_SCALE,
LEVEL_TABLE,
LOG_MAX_MESSAGES,
)
from entities.enemy import Enemy
from entities.player import Player
Combatant = Player | Enemy
def combat_power(combatant: Combatant, weapon_bonus: int = 0) -> int:
if isinstance(combatant, Player):
return combatant.total_power + weapon_bonus
return combatant.power + weapon_bonus
def combat_armor(combatant: Combatant) -> int:
return combatant.total_armor if isinstance(combatant, Player) else combatant.armor
def combat_evasion(combatant: Combatant) -> int:
return combatant.total_evasion if isinstance(combatant, Player) else combatant.evasion
def combat_crit(combatant: Combatant) -> float:
return combatant.total_crit if isinstance(combatant, Player) else combatant.crit_chance
def log_message(log: list[str], message: str) -> None:
log.append(message)
del log[:-LOG_MAX_MESSAGES]
def new_log_messages(before: list[str] | tuple[str, ...], after: list[str]) -> list[str]:
"""Return appended entries even when the bounded log dropped old entries."""
for start in range(len(before) + 1):
overlap = before[start:]
if after[:len(overlap)] == list(overlap):
return after[len(overlap):]
return after
def hit_chance(attacker: Combatant, defender: Combatant) -> float:
chance = HIT_BASE_CHANCE + (attacker.accuracy - combat_evasion(defender)) * HIT_CHANCE_SCALE
return max(HIT_CHANCE_MIN, min(HIT_CHANCE_MAX, chance))
def roll_hit(attacker: Combatant, defender: Combatant, rng: random.Random) -> bool:
return rng.random() < hit_chance(attacker, defender)
def attack(
attacker: Combatant,
defender: Combatant,
log: list[str],
rng: random.Random | None = None,
weapon_bonus: int = 0,
power_override: int | None = None,
hit_modifier: float = 0.0,
) -> bool:
"""Resolve one melee/ranged attack. Returns True if the defender died."""
rng = rng or random
attacker_name = "You" if isinstance(attacker, Player) else attacker.name
defender_name = "you" if isinstance(defender, Player) else defender.name
chance = max(
HIT_CHANCE_MIN,
min(HIT_CHANCE_MAX, hit_chance(attacker, defender) + hit_modifier),
)
if rng.random() >= chance:
log_message(log, f"{attacker_name} miss{'es' if attacker_name != 'You' else ''} {defender_name}.")
return False
base = power_override if power_override is not None else combat_power(attacker, weapon_bonus)
reduced = max(0, base - combat_armor(defender))
is_crit = rng.random() < combat_crit(attacker)
damage = reduced * (CRIT_MULTIPLIER if is_crit else 1)
defender.hp -= damage
if is_crit:
log_message(log, f"Critical hit! {attacker_name} hit {defender_name} for {damage} damage!")
else:
log_message(log, f"{attacker_name} hit {defender_name} for {damage} damage!")
if defender.hp > 0:
return False
if isinstance(defender, Enemy):
if isinstance(attacker, Player):
log_message(log, f"You defeated the {defender.name}! (+{defender.xp_reward} XP)")
award_xp(attacker, defender.xp_reward, log)
else:
log_message(log, "You die...")
return True
def award_xp(player: Player, amount: int, log: list[str]) -> None:
player.xp += amount
while True:
next_level = player.level + 1
entry = LEVEL_TABLE.get(next_level)
if entry is None or player.xp < entry[0]:
break
_, hp_gain, power_gain = entry
player.level += 1
player.max_hp += hp_gain
player.hp = player.max_hp
player.power += power_gain
log_message(log, f"You reach level {player.level}! (HP +{hp_gain}, Power +{power_gain})")
if __name__ == "__main__":
log: list[str] = []
rng = random.Random(42)
player = Player(x=0, y=0)
goblin = Enemy(x=1, y=0, name="Goblin", hp=15, max_hp=15, power=5, armor=1,
accuracy=2, evasion=1, xp_reward=12)
assert hit_chance(player, goblin) == 0.7 + (5 - 1) * 0.05
assert hit_chance(goblin, player) == 0.7 + (2 - 2) * 0.05
while goblin.alive:
attack(player, goblin, log, rng=rng, weapon_bonus=4)
assert not goblin.alive and player.xp == 12
award_xp(player, 25, log)
assert player.level == 2 and player.hp == player.max_hp == 60
assert any("defeated the Goblin" in m for m in log)
assert any("reach level 2" in m for m in log)
print("combat self-check: PASS")
-375
View File
@@ -1,375 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
from engine.audio import SoundEffects
from engine.game_state import GameSession
from engine.combat import new_log_messages
from engine.serializers import delete_save, has_save, load_game, save_game
from entities.item import Item
MENU = "menu"
HOWTO = "howto"
PLAYING = "playing"
INVENTORY = "inventory"
EQUIPMENT = "equipment"
POTIONS = "potions"
SCROLLS = "scrolls"
DEAD = "dead"
VICTORY = "victory"
GAME_OVER_SCREENS = {DEAD, VICTORY}
_LETTERS = "abcdefghijklmnopqrstuvwxyz"
@dataclass(slots=True)
class GameFlow:
"""Turns key intents into game actions and owns menu/UI state."""
session: GameSession | None = None
screen: str = MENU
menu_index: int = 0
selection: int = 0
running: bool = True
audio: SoundEffects | None = None
# -- menu --------------------------------------------------------
@property
def menu_items(self) -> list[str]:
items = ["New Game"]
if has_save():
items.append("Continue")
items.extend(["How to Play", "Quit"])
return items
def _clamp_menu_index(self) -> None:
self.menu_index = max(0, min(self.menu_index, len(self.menu_items) - 1))
def new_game(self) -> None:
self.session = GameSession.new_game()
self.screen = HOWTO
def continue_game(self) -> bool:
if not has_save():
return False
try:
self.session = load_game()
except (OSError, ValueError, KeyError):
return False
if self.session.state in GAME_OVER_SCREENS:
self.session = None
return False
self.session.state = PLAYING
self.screen = PLAYING
return True
def _menu_confirm(self) -> None:
self._clamp_menu_index()
choice = self.menu_items[self.menu_index]
self._play("menu")
if choice == "New Game":
self.new_game()
elif choice == "Continue":
if not self.continue_game():
self.menu_index = 0
elif choice == "How to Play":
self.screen = HOWTO
elif choice == "Quit":
self.running = False
# -- key dispatch -------------------------------------------------
def handle_key(self, key: str) -> None:
if self.screen == MENU:
self._handle_menu_key(key)
elif self.screen in GAME_OVER_SCREENS:
self._return_to_menu()
elif self.screen == HOWTO:
self.screen = PLAYING if self.session is not None else MENU
elif self.screen == PLAYING:
self._handle_play_key(key)
else:
self._handle_list_key(key)
def _handle_menu_key(self, key: str) -> None:
if key == "up":
self.menu_index -= 1
self._clamp_menu_index()
elif key == "down":
self.menu_index += 1
self._clamp_menu_index()
elif key == "confirm":
self._menu_confirm()
elif key == "quit":
self.running = False
def _handle_play_key(self, key: str) -> None:
session = self.session
assert session is not None
moves = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}
if key in moves:
self._act(lambda: session.player_move_or_attack(*moves[key]))
elif key == "pickup":
self._act(session.pickup)
elif key == "descend":
self._act(session.descend)
elif key == "inventory":
self.selection = 0
self.screen = INVENTORY
elif key == "equipment":
self.selection = 0
self.screen = EQUIPMENT
elif key == "quaff":
self.selection = 0
self.screen = POTIONS
elif key == "read":
self.selection = 0
self.screen = SCROLLS
elif key == "save":
self._save_and_quit()
elif key == "help":
self.screen = HOWTO
elif key == "mute":
self._toggle_mute()
def _handle_list_key(self, key: str) -> None:
session = self.session
assert session is not None
if key == "cancel":
self.screen = PLAYING
return
items, action = self._list_target()
if key in ("up", "down"):
step = -1 if key == "up" else 1
self.selection = max(0, min(self.selection + step, max(0, len(items) - 1)))
return
if key == "confirm":
index = self.selection
elif key in _LETTERS:
index = _LETTERS.index(key)
else:
return
if not items or index >= len(items):
return
item = items[index]
if action == "equip" and item.category in ("weapon", "armor"):
self._act(lambda: session.equip(item))
if self.screen != PLAYING:
self.selection = min(self.selection, max(0, len(items) - 2))
elif action == "unequip" and item is not None:
self._unequip(item)
elif action == "quaff" and item.category == "potion":
self._act(lambda: session.quaff(item))
if self.screen != PLAYING and items:
self.selection = min(self.selection, len(items) - 1)
elif action == "read" and item.category == "scroll":
self._act(lambda: session.read_scroll(item))
if self.screen != PLAYING and not self._list_target()[0]:
self.screen = PLAYING
def _list_target(self) -> tuple[list[Item], str]:
"""(visible list, action) for the current list screen."""
session = self.session
assert session is not None
if self.screen == INVENTORY:
return list(session.player.inventory), "equip"
if self.screen == EQUIPMENT:
return [session.player.equipped_weapon, session.player.equipped_armor], "unequip"
if self.screen == POTIONS:
return [i for i in session.player.inventory if i.category == "potion"], "quaff"
if self.screen == SCROLLS:
return [i for i in session.player.inventory if i.category == "scroll"], "read"
return [], ""
def _unequip(self, item: Item) -> None:
session = self.session
assert session is not None
if session.player.equipped_weapon is item:
session.player.equipped_weapon = None
elif session.player.equipped_armor is item:
session.player.equipped_armor = None
else:
return
session.player.inventory.append(item)
self._log_sound(f"You remove the {item.name}.", "use")
def _save_and_quit(self) -> None:
session = self.session
assert session is not None
session.state = "saved"
try:
save_game(session)
except OSError:
session.state = PLAYING
self._log_sound("The save could not be written.", "miss")
return
self.session = None
self.screen = MENU
self._clamp_menu_index()
def _act(self, action) -> None:
"""Run one player action, then handle sounds and game-over."""
session = self.session
assert session is not None
log_before = tuple(session.log)
hp_before = session.player.hp
action()
self._sounds_for(new_log_messages(log_before, session.log), session.player.hp < hp_before)
self._check_game_over()
def _check_game_over(self) -> None:
session = self.session
assert session is not None
if session.state == "dead":
delete_save()
self.screen = DEAD
self._play("death")
elif session.state == "victory":
delete_save()
self.screen = VICTORY
self._play("victory")
def _return_to_menu(self) -> None:
self.session = None
self.screen = MENU
self._clamp_menu_index()
def context_prompt(self) -> str | None:
session = self.session
if session is None or session.state != PLAYING:
return None
items = session.items_at(session.player.x, session.player.y)
if items:
return f"Press G to pick up the {items[0].name}"
if session.current_map.stairs_down == session.player.position:
return "Press F to descend"
return None
# -- audio -------------------------------------------------------
def _play(self, name: str) -> None:
if self.audio is not None:
self.audio.play(name)
def _log_sound(self, message: str, sound: str) -> None:
session = self.session
if session is not None:
from engine.combat import log_message
log_message(session.log, message)
self._play(sound)
def _toggle_mute(self) -> None:
if self.audio is not None:
self.audio.toggle_mute()
def _sounds_for(self, messages: list[str], took_damage: bool) -> None:
for message in messages:
if "slew the Ancient Dragon" in message:
self._play("victory")
elif "You die" in message:
self._play("death")
elif "hit you" in message or "misses you" in message or "caught in the flames" in message:
self._play("hurt")
elif "reach level" in message:
self._play("level_up")
elif "You descend to floor" in message:
self._play("stairs")
elif "pick up" in message or "You equip" in message:
self._play("pickup")
elif "quaff" in message or "drink the" in message or "erupts" in message or "floods" in message or "blink" in message:
self._play("use")
elif "Critical hit! You hit" in message:
self._play("crit")
elif "You hit" in message:
self._play("hit")
elif "You miss" in message:
self._play("miss")
if took_damage:
self._play("hurt")
if __name__ == "__main__":
import tempfile
from pathlib import Path
import engine.serializers as serializers
from data.enemies import make_enemy
from data.items import ITEM_CATALOG
with tempfile.TemporaryDirectory() as tmp:
original_path = serializers.SAVE_PATH
serializers.SAVE_PATH = Path(tmp) / "save.json"
try:
flow = GameFlow()
assert flow.screen == MENU and flow.menu_items == ["New Game", "How to Play", "Quit"]
# New Game -> How to Play -> playing.
flow.handle_key("confirm")
assert flow.screen == HOWTO and flow.session is not None
flow.handle_key("space")
assert flow.screen == PLAYING
session = flow.session
# Contextual prompts: item pickup.
hero = session.player
axe = Item.from_def(ITEM_CATALOG["battle_axe"], hero.x, hero.y)
session.current_map.entities.append(axe)
assert flow.context_prompt() == "Press G to pick up the Battle Axe"
flow.handle_key("pickup")
assert axe in hero.inventory
assert flow.context_prompt() is None
# Inventory screen: letter selection equips.
flow.handle_key("inventory")
assert flow.screen == INVENTORY
flow.handle_key("a")
assert hero.equipped_weapon is axe and axe not in hero.inventory
# Equipment screen: unequip back to inventory.
flow.handle_key("equipment")
assert flow.screen == EQUIPMENT
flow.handle_key("a")
assert hero.equipped_weapon is None and axe in hero.inventory
flow.handle_key("cancel")
# Stairs descent with prompt.
hero.x, hero.y = session.current_map.stairs_down
assert flow.context_prompt() == "Press F to descend"
flow.handle_key("descend")
assert session.current_floor == 1
assert flow.context_prompt() is None
# Save and quit -> menu with Continue.
flow.handle_key("save")
assert flow.screen == MENU and flow.session is None
assert flow.menu_items == ["New Game", "Continue", "How to Play", "Quit"]
# Continue restores exact floor.
flow.menu_index = 1
flow.handle_key("confirm")
assert flow.screen == PLAYING and flow.session.current_floor == 1
# Permadeath: dying deletes the save.
session = flow.session
session.player.hp = 1
orc = make_enemy("orc_warrior", session.player.x, session.player.y + 1)
session.current_map.entities.append(orc)
while session.state == "playing":
session.player.hp = 1
session.player_move_or_attack(0, 0)
assert session.state == "dead"
flow._check_game_over()
assert flow.screen == DEAD and not serializers.has_save()
flow.handle_key("space")
assert flow.screen == MENU and "Continue" not in flow.menu_items
# Quit from menu stops the loop.
flow.menu_index = len(flow.menu_items) - 1
flow.handle_key("confirm")
assert not flow.running
finally:
serializers.SAVE_PATH = original_path
print("flow self-check: PASS")
-128
View File
@@ -1,128 +0,0 @@
from __future__ import annotations
from data.constants import SIGHT_RADIUS, TILE_WALL
from engine.map_gen import GameMap
# Row/column multipliers for the 8 shadowcasting octants (Bergström layout).
_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 _set_visible(game_map: GameMap, x: int, y: int) -> None:
game_map.visible[y][x] = 1
game_map.explored[y][x] = 1
def _is_blocked(game_map: GameMap, x: int, y: int) -> bool:
return game_map.tile_at(x, y) == TILE_WALL
def _cast_light(
game_map: GameMap,
cx: int,
cy: int,
row: int,
start: float,
end: float,
radius: int,
xx: int,
xy: int,
yx: int,
yy: int,
) -> None:
"""Scan one octant. Rows are dy; dx ascends from axis to diagonal, so
cell slopes rise through the call. The visible cone is [end, start];
each wall recurses for the light passing left of it, then narrows the
cone to the light passing right."""
if start <= end:
return
radius2 = radius * radius
for j in range(row, radius + 1):
if start <= end:
return
dx = 0
while dx <= j:
x, y = cx + dx * xx + j * xy, cy + dx * yx + j * yy
l_slope = (dx - 0.5) / (j + 0.5)
r_slope = (dx + 0.5) / (j - 0.5)
if r_slope <= end:
dx += 1
continue
if l_slope >= start:
break
if dx * dx + j * j <= radius2 and game_map.in_bounds(x, y):
_set_visible(game_map, x, y)
if _is_blocked(game_map, x, y):
if l_slope > end and j < radius:
_cast_light(
game_map,
cx,
cy,
j + 1,
l_slope,
end,
radius,
xx,
xy,
yx,
yy,
)
end = r_slope
if end >= start:
break
dx += 1
def compute_fov(game_map: GameMap, x: int, y: int, radius: int = SIGHT_RADIUS) -> None:
"""Recursive shadowcasting: fills visible, merges into explored."""
for row in game_map.visible:
for i in range(len(row)):
row[i] = 0
if game_map.in_bounds(x, y):
_set_visible(game_map, x, y)
for xx, xy, yx, yy in _OCTANTS:
_cast_light(game_map, x, y, 1, 1.0, 0.0, radius, xx, xy, yx, yy)
_reveal_wall_faces(game_map)
def _reveal_wall_faces(game_map: GameMap) -> None:
"""Walls adjacent to a visible floor tile are themselves visible."""
lit: list[tuple[int, int]] = []
for wy in range(game_map.height):
for wx in range(game_map.width):
if game_map.visible[wy][wx]:
continue
if game_map.tile_at(wx, wy) != TILE_WALL:
continue
for ax, ay in ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)):
fx, fy = wx + ax, wy + ay
if (
game_map.in_bounds(fx, fy)
and game_map.visible[fy][fx]
and game_map.tile_at(fx, fy) != TILE_WALL
):
lit.append((wx, wy))
break
for wx, wy in lit:
_set_visible(game_map, wx, wy)
def visible_tiles(game_map: GameMap) -> list[tuple[int, int]]:
return [
(x, y_coord)
for y_coord, row in enumerate(game_map.visible)
for x, cell in enumerate(row)
if cell
]
-262
View File
@@ -1,262 +0,0 @@
from __future__ import annotations
import random
from dataclasses import dataclass, field
from ai.behaviors import split_on_death, take_turn
from data.constants import (
FIREBALL_DAMAGE,
FIREBALL_RADIUS,
FINAL_FLOOR,
HEAL_AMOUNT,
INVISIBILITY_TURNS,
STRENGTH_BONUS,
STRENGTH_TURNS,
)
from data.items import ITEM_CATALOG
from engine.combat import attack, award_xp, log_message
from engine.fov import compute_fov
from engine.map_gen import GameMap, generate_map
from entities.enemy import Enemy
from entities.item import Item
from entities.player import Player
@dataclass(slots=True)
class GameSession:
"""Single source of truth for all mutable state."""
player: Player
dungeon: list[GameMap]
current_floor: int
log: list[str] = field(default_factory=list)
turn: int = 0
state: str = "playing"
rng: random.Random = field(default_factory=random.Random)
@classmethod
def new_game(cls, seed: int | None = None) -> GameSession:
rng = random.Random(seed)
dungeon = [generate_map(floor_index=floor, seed=rng.randrange(2**32)) for floor in range(FINAL_FLOOR + 1)]
first = dungeon[0]
session = cls(
player=Player(x=first.spawn[0], y=first.spawn[1]),
dungeon=dungeon,
current_floor=0,
rng=rng,
)
session.update_fov()
log_message(session.log, "You descend into the Underdepths. Good luck.")
return session
@property
def current_map(self) -> GameMap:
return self.dungeon[self.current_floor]
def update_fov(self) -> None:
compute_fov(self.current_map, self.player.x, self.player.y)
def entity_at(self, x: int, y: int) -> Enemy | None:
return next(
(
entity
for entity in self.current_map.entities
if isinstance(entity, Enemy) and entity.alive and entity.position == (x, y)
),
None,
)
def items_at(self, x: int, y: int) -> list[Item]:
return [
entity
for entity in self.current_map.entities
if isinstance(entity, Item) and entity.position == (x, y)
]
# -- player actions -------------------------------------------------
def player_move_or_attack(self, dx: int, dy: int) -> None:
if self.state != "playing":
return
target = self.player.x + dx, self.player.y + dy
enemy = self.entity_at(*target)
if enemy is not None:
died = attack(self.player, enemy, self.log, rng=self.rng)
if died:
self._on_enemy_death(enemy)
elif self.current_map.is_walkable(*target):
self.player.move(dx, dy)
self.end_turn()
def pickup(self) -> bool:
items = self.items_at(self.player.x, self.player.y)
if not items:
return False
item = items[0]
self.current_map.entities.remove(item)
item.x, item.y = 0, 0
self.player.inventory.append(item)
log_message(self.log, f"You pick up the {item.name}.")
return True
def equip(self, item: Item) -> bool:
if item not in self.player.inventory:
return False
if item.category == "weapon":
old = self.player.equipped_weapon
self.player.equipped_weapon = item
elif item.category == "armor":
old = self.player.equipped_armor
self.player.equipped_armor = item
else:
return False
self.player.inventory.remove(item)
item.x, item.y = 0, 0
if old is not None:
self.player.inventory.append(old)
log_message(self.log, f"You equip the {item.name}.")
return True
def quaff(self, item: Item) -> bool:
if item.category != "potion" or item not in self.player.inventory:
return False
player = self.player
if item.effect == "heal":
healed = player.heal(HEAL_AMOUNT)
log_message(self.log, f"You quaff the {item.name}. You recover {healed} HP.")
elif item.effect == "strength":
player.strength_turns = STRENGTH_TURNS
log_message(
self.log,
f"You quaff the {item.name}. Your power surges (+{STRENGTH_BONUS} for {STRENGTH_TURNS} turns).",
)
elif item.effect == "invisibility":
player.invisible_turns = INVISIBILITY_TURNS
log_message(
self.log,
f"You drink the {item.name} and fade from sight for {INVISIBILITY_TURNS} turns.",
)
else:
return False
player.inventory.remove(item)
self.end_turn()
return True
def read_scroll(self, item: Item) -> bool:
if item.category != "scroll" or item not in self.player.inventory:
return False
effect = item.effect
player = self.player
game_map = self.current_map
if effect == "fireball":
log_message(self.log, "The scroll erupts in a ball of flame!")
for entity in list(game_map.entities):
if not isinstance(entity, Enemy) or not entity.alive:
continue
dist = ((entity.x - player.x) ** 2 + (entity.y - player.y) ** 2) ** 0.5
if dist > FIREBALL_RADIUS:
continue
entity.hp -= FIREBALL_DAMAGE
log_message(self.log, f"The {entity.name} is scorched for {FIREBALL_DAMAGE} damage!")
if entity.hp <= 0:
log_message(
self.log, f"You defeated the {entity.name}! (+{entity.xp_reward} XP)"
)
award_xp(player, entity.xp_reward, self.log)
self._on_enemy_death(entity)
elif effect == "teleport":
options = [
(x, y)
for y in range(game_map.height)
for x in range(game_map.width)
if game_map.is_walkable(x, y)
and self.entity_at(x, y) is None
and (x, y) != player.position
]
if options:
player.x, player.y = self.rng.choice(options)
log_message(self.log, "The world twists — you blink to a distant place.")
elif effect == "mapping":
for row in game_map.explored:
for i in range(len(row)):
row[i] = 1
log_message(self.log, "Knowledge of the floor floods your mind.")
else:
return False
player.inventory.remove(item)
self.end_turn()
return True
def descend(self) -> bool:
if self.current_map.stairs_down != self.player.position:
return False
if self.current_floor >= FINAL_FLOOR:
return False
self.current_floor += 1
spawn = self.current_map.spawn
self.player.x, self.player.y = spawn
log_message(self.log, f"You descend to floor {self.current_floor + 1}.")
self.end_turn()
return True
# -- turn engine -----------------------------------------------------
def end_turn(self) -> None:
if self.state != "playing":
return
self.turn += 1
if self.player.strength_turns > 0:
self.player.strength_turns -= 1
if self.player.invisible_turns > 0:
self.player.invisible_turns -= 1
for enemy in [e for e in self.current_map.entities if isinstance(e, Enemy) and e.alive]:
take_turn(enemy, self.player, self.current_map, self.turn, self.log, rng=self.rng)
if self.player.hp <= 0:
self.state = "dead"
log_message(self.log, "You die...")
self.update_fov()
def _on_enemy_death(self, enemy: Enemy) -> None:
self.current_map.entities.remove(enemy)
copies = split_on_death(enemy)
candidates = [
copy.position for copy in copies
] + [
enemy.position,
(enemy.x, enemy.y - 1),
(enemy.x, enemy.y + 1),
(enemy.x - 1, enemy.y - 1),
(enemy.x + 1, enemy.y - 1),
(enemy.x - 1, enemy.y + 1),
(enemy.x + 1, enemy.y + 1),
]
free = [
position for position in dict.fromkeys(candidates)
if self.current_map.is_walkable(*position) and self.entity_at(*position) is None
]
for copy, position in zip(copies, free):
copy.x, copy.y = position
self.current_map.entities.append(copy)
if copies and free:
log_message(self.log, f"The {enemy.name} splits into {min(len(copies), len(free))}!")
if enemy.key == "ancient_dragon":
self.state = "victory"
log_message(self.log, "You slew the Ancient Dragon! You conquered Underdepths.")
def find_heavy_weapon(dungeon: list[GameMap]) -> Item | None:
"""First Battle Axe / War Hammer placed anywhere in the dungeon floors 0-8."""
for game_map in dungeon[:FINAL_FLOOR]:
for entity in game_map.entities:
if isinstance(entity, Item) and entity.key in ("battle_axe", "war_hammer"):
return entity
return None
if __name__ == "__main__":
session = GameSession.new_game(seed=1)
assert session.state == "playing"
assert len(session.dungeon) == 10
session.player_move_or_attack(0, 0) # bump into nothing: still a turn
assert session.turn == 1
print("game_state self-check: PASS")
-332
View File
@@ -1,332 +0,0 @@
from __future__ import annotations
from array import array
from dataclasses import dataclass
import random
from data.constants import (
BOSS_ARENA_HEIGHT,
BOSS_ARENA_WIDTH,
BSP_MAX_SPLITS,
BSP_MIN_SPLITS,
FINAL_FLOOR,
GUARANTEED_HEAVY_WEAPONS,
MAP_BORDER,
MAP_HEIGHT,
MAP_WIDTH,
ROOM_MARGIN,
ROOM_MAX_HEIGHT,
ROOM_MAX_WIDTH,
ROOM_MIN_HEIGHT,
ROOM_MIN_WIDTH,
SPAWN_TABLE,
TILE_FLOOR,
TILE_WALL,
)
from data.enemies import enemies_for_floor, make_enemy
from data.items import ITEM_CATALOG, items_for_floor
from entities.entity import Entity
from entities.item import Item
Grid = list[array]
@dataclass(frozen=True, slots=True)
class Rect:
x: int
y: int
width: int
height: int
@property
def x2(self) -> int:
return self.x + self.width
@property
def y2(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 overlaps(self, other: Rect) -> bool:
return not (
self.x2 <= other.x
or other.x2 <= self.x
or self.y2 <= other.y
or other.y2 <= self.y
)
@dataclass(slots=True)
class GameMap:
width: int
height: int
tiles: Grid
rooms: list[Rect]
explored: Grid
visible: Grid
entities: list[Entity]
stairs_down: tuple[int, int] | None
floor_index: int
spawn: tuple[int, int]
def in_bounds(self, x: int, y: int) -> bool:
return 0 <= x < self.width and 0 <= y < self.height
def tile_at(self, x: int, y: int) -> int:
return self.tiles[y][x] if self.in_bounds(x, y) else TILE_WALL
def is_walkable(self, x: int, y: int) -> bool:
return self.tile_at(x, y) == TILE_FLOOR
@dataclass(slots=True)
class _Node:
region: Rect
depth: int = 0
left: _Node | None = None
right: _Node | None = None
room: Rect | None = None
@property
def is_leaf(self) -> bool:
return self.left is None and self.right is None
_MIN_REGION_WIDTH = ROOM_MIN_WIDTH + ROOM_MARGIN * 2
_MIN_REGION_HEIGHT = ROOM_MIN_HEIGHT + ROOM_MARGIN * 2
def _new_grid(width: int, height: int, value: int) -> Grid:
return [array("b", [value]) * width for _ in range(height)]
def _can_split(node: _Node) -> bool:
return (
node.region.width >= _MIN_REGION_WIDTH * 2
or node.region.height >= _MIN_REGION_HEIGHT * 2
)
def _split(node: _Node, rng: random.Random) -> bool:
region = node.region
prefer_vertical = node.depth % 2 == 0
can_vertical = region.width >= _MIN_REGION_WIDTH * 2
can_horizontal = region.height >= _MIN_REGION_HEIGHT * 2
vertical = prefer_vertical if can_vertical and can_horizontal else can_vertical
if not can_vertical and not can_horizontal:
return False
if vertical:
split_x = rng.randint(
region.x + _MIN_REGION_WIDTH,
region.x2 - _MIN_REGION_WIDTH,
)
first = Rect(region.x, region.y, split_x - region.x, region.height)
second = Rect(split_x, region.y, region.x2 - split_x, region.height)
else:
split_y = rng.randint(
region.y + _MIN_REGION_HEIGHT,
region.y2 - _MIN_REGION_HEIGHT,
)
first = Rect(region.x, region.y, region.width, split_y - region.y)
second = Rect(region.x, split_y, region.width, region.y2 - split_y)
node.left = _Node(first, node.depth + 1)
node.right = _Node(second, node.depth + 1)
return True
def _leaves(node: _Node) -> list[_Node]:
if node.is_leaf:
return [node]
leaves: list[_Node] = []
if node.left is not None:
leaves.extend(_leaves(node.left))
if node.right is not None:
leaves.extend(_leaves(node.right))
return leaves
def _make_room(region: Rect, rng: random.Random) -> Rect:
width = rng.randint(ROOM_MIN_WIDTH, min(ROOM_MAX_WIDTH, region.width - 2))
height = rng.randint(ROOM_MIN_HEIGHT, min(ROOM_MAX_HEIGHT, region.height - 2))
x = rng.randint(region.x + ROOM_MARGIN, region.x2 - width - ROOM_MARGIN)
y = rng.randint(region.y + ROOM_MARGIN, region.y2 - height - ROOM_MARGIN)
return Rect(x, y, width, height)
def _carve_room(tiles: Grid, room: Rect) -> None:
for y in range(room.y, room.y2):
for x in range(room.x, room.x2):
tiles[y][x] = TILE_FLOOR
def _carve_line(
tiles: Grid,
start: tuple[int, int],
end: tuple[int, int],
) -> None:
x, y = start
end_x, end_y = end
step_x = 1 if end_x >= x else -1
step_y = 1 if end_y >= y else -1
for current_x in range(x, end_x + step_x, step_x):
tiles[y][current_x] = TILE_FLOOR
for current_y in range(y, end_y + step_y, step_y):
tiles[current_y][end_x] = TILE_FLOOR
def _connect_tree(node: _Node, tiles: Grid, rng: random.Random) -> tuple[int, int]:
if node.room is not None:
return node.room.center
if node.left is None or node.right is None:
raise RuntimeError("invalid BSP tree")
left_center = _connect_tree(node.left, tiles, rng)
right_center = _connect_tree(node.right, tiles, rng)
if rng.random() < 0.5:
_carve_line(tiles, left_center, right_center)
else:
_carve_line(tiles, right_center, left_center)
return left_center
def _spawn_bands(floor_index: int) -> tuple[tuple[int, int], tuple[int, int]]:
for band, counts in SPAWN_TABLE.items():
if band[0] <= floor_index <= band[1]:
return counts
raise ValueError(f"no spawn band for floor {floor_index}")
def _random_free_tile(
game_map: GameMap,
rng: random.Random,
occupied: set[tuple[int, int]],
avoid_rooms: list[Rect] | None = None,
) -> tuple[int, int] | None:
for _ in range(200):
room = rng.choice(game_map.rooms)
if avoid_rooms and any(room.overlaps(a) for a in avoid_rooms):
continue
pos = rng.randint(room.x, room.x2 - 1), rng.randint(room.y, room.y2 - 1)
if pos == game_map.stairs_down or pos == game_map.spawn or pos in occupied:
continue
if not game_map.is_walkable(*pos):
continue
return pos
return None
def _populate_floor(game_map: GameMap, rng: random.Random) -> None:
enemy_band, item_band = _spawn_bands(game_map.floor_index)
occupied = {game_map.spawn, game_map.stairs_down}
spawn_room = game_map.rooms[0]
eligible = enemies_for_floor(game_map.floor_index)
for _ in range(rng.randint(*enemy_band)):
pos = _random_free_tile(game_map, rng, occupied, avoid_rooms=[spawn_room])
if pos is None:
break
occupied.add(pos)
game_map.entities.append(make_enemy(rng.choice(eligible), *pos))
catalog = items_for_floor(game_map.floor_index)
guaranteed = GUARANTEED_HEAVY_WEAPONS.get(game_map.floor_index, ())
for index in range(rng.randint(*item_band)):
pos = _random_free_tile(game_map, rng, occupied)
if pos is None:
break
occupied.add(pos)
if index == 0 and guaranteed:
item_def = ITEM_CATALOG[rng.choice(guaranteed)]
else:
item_def = rng.choice(catalog)
game_map.entities.append(Item.from_def(item_def, *pos))
def _generate_arena(floor_index: int) -> GameMap:
"""Floor 9: one large room, the dragon opposite the entrance, two
healing potions by the door, no stairs."""
x = (MAP_WIDTH - BOSS_ARENA_WIDTH) // 2
y = (MAP_HEIGHT - BOSS_ARENA_HEIGHT) // 2
room = Rect(x, y, BOSS_ARENA_WIDTH, BOSS_ARENA_HEIGHT)
tiles = _new_grid(MAP_WIDTH, MAP_HEIGHT, TILE_WALL)
_carve_room(tiles, room)
spawn = room.x + 2, room.y + room.height // 2
dragon_x = room.x2 - 2
dragon_y = room.y + room.height // 2
potion_def = ITEM_CATALOG["healing_potion"]
game_map = GameMap(
width=MAP_WIDTH,
height=MAP_HEIGHT,
tiles=tiles,
rooms=[room],
explored=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
visible=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
entities=[
make_enemy("ancient_dragon", dragon_x, dragon_y),
Item.from_def(potion_def, spawn[0] + 1, spawn[1] - 1),
Item.from_def(potion_def, spawn[0] + 1, spawn[1] + 1),
],
stairs_down=None,
floor_index=floor_index,
spawn=spawn,
)
return game_map
def generate_map(floor_index: int = 0, seed: int | None = None) -> GameMap:
rng = random.Random(seed)
if floor_index == FINAL_FLOOR:
return _generate_arena(floor_index)
tiles = _new_grid(MAP_WIDTH, MAP_HEIGHT, TILE_WALL)
root = _Node(
Rect(
MAP_BORDER,
MAP_BORDER,
MAP_WIDTH - MAP_BORDER * 2,
MAP_HEIGHT - MAP_BORDER * 2,
)
)
for _ in range(rng.randint(BSP_MIN_SPLITS, BSP_MAX_SPLITS)):
candidates = [leaf for leaf in _leaves(root) if _can_split(leaf)]
if not candidates:
break
largest = max(
candidates,
key=lambda leaf: leaf.region.width * leaf.region.height,
)
_split(largest, rng)
leaves = _leaves(root)
rooms: list[Rect] = []
for leaf in leaves:
leaf.room = _make_room(leaf.region, rng)
rooms.append(leaf.room)
_carve_room(tiles, leaf.room)
_connect_tree(root, tiles, rng)
spawn = rooms[0].center
farthest_room = max(
rooms[1:],
key=lambda room: abs(room.center[0] - spawn[0])
+ abs(room.center[1] - spawn[1]),
)
stairs_down = None if floor_index == FINAL_FLOOR else farthest_room.center
game_map = GameMap(
width=MAP_WIDTH,
height=MAP_HEIGHT,
tiles=tiles,
rooms=rooms,
explored=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
visible=_new_grid(MAP_WIDTH, MAP_HEIGHT, 0),
entities=[],
stairs_down=stairs_down,
floor_index=floor_index,
spawn=spawn,
)
_populate_floor(game_map, rng)
return game_map
-113
View File
@@ -1,113 +0,0 @@
from __future__ import annotations
import heapq
import random
from engine.map_gen import GameMap
Position = tuple[int, int]
_NEIGHBOURS: tuple[Position, ...] = ((0, -1), (0, 1), (-1, 0), (1, 0))
def _heuristic(a: Position, b: Position) -> int:
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def _walkable(game_map: GameMap, pos: Position, blocked: set[Position]) -> bool:
return game_map.is_walkable(*pos) and pos not in blocked
def astar(
game_map: GameMap,
start: Position,
goal: Position,
blocked: set[Position] | None = None,
) -> list[Position]:
"""A* path from start to goal (exclusive of start, inclusive of goal).
blocked: tiles occupied by entities, treated as impassable. The goal is
always enterable so an enemy adjacent-to/standing-on an occupied target
still paths to it.
Returns [] when no path exists.
"""
blocked = blocked or set()
if not _walkable(game_map, start, blocked) and not game_map.is_walkable(*start):
return []
if not game_map.is_walkable(*goal):
return []
came_from: dict[Position, Position] = {}
g_score: dict[Position, int] = {start: 0}
open_heap: list[tuple[int, int, Position]] = [
(_heuristic(start, goal), 0, start)
]
closed: set[Position] = set()
while open_heap:
_, _, current = heapq.heappop(open_heap)
if current == goal:
path: list[Position] = [current]
while current in came_from:
current = came_from[current]
path.append(current)
path.reverse()
return path[1:]
if current in closed:
continue
closed.add(current)
for dx, dy in _NEIGHBOURS:
nxt: Position = (current[0] + dx, current[1] + dy)
if nxt in closed or not game_map.in_bounds(*nxt):
continue
enterable = (
nxt == goal or _walkable(game_map, nxt, blocked)
)
if not enterable:
continue
tentative = g_score[current] + 1
if tentative < g_score.get(nxt, _INF):
g_score[nxt] = tentative
came_from[nxt] = current
heapq.heappush(
open_heap,
(tentative + _heuristic(nxt, goal), tentative, nxt),
)
return []
_INF: int = 1 << 30
def random_step(game_map: GameMap, start: Position) -> Position | None:
"""No-path fallback: one random walkable adjacent tile, or None (wait)."""
options = [
(start[0] + dx, start[1] + dy)
for dx, dy in _NEIGHBOURS
if game_map.is_walkable(start[0] + dx, start[1] + dy)
]
return random.choice(options) if options else None
if __name__ == "__main__":
from data.constants import MAP_HEIGHT, MAP_WIDTH, TILE_FLOOR
from engine.map_gen import generate_map
game_map = generate_map(0, seed=42)
floors = [
(x, y)
for y in range(MAP_HEIGHT)
for x in range(MAP_WIDTH)
if game_map.tiles[y][x] == TILE_FLOOR
]
for _ in range(50):
a, b = random.sample(floors, 2)
path = astar(game_map, a, b)
assert path and path[-1] == b, (a, b)
assert game_map.is_walkable(*a)
assert all(
game_map.is_walkable(*p) for p in path
), "path crosses a wall"
assert isinstance(random_step(game_map, a), (tuple, type(None)))
print("pathfinding ok")
-193
View File
@@ -1,193 +0,0 @@
from __future__ import annotations
import json
import random
from array import array
from dataclasses import fields
from pathlib import Path
from data.constants import SAVE_FILENAME
from engine.map_gen import GameMap, Rect
from entities.enemy import Enemy
from entities.entity import Entity
from entities.item import Item
from entities.player import Player
from engine.game_state import GameSession
SAVE_PATH = Path(__file__).resolve().parents[1] / SAVE_FILENAME
_TUPLE_FIELDS = {"last_known_position", "stairs_down", "spawn", "position"}
_ITEM_FIELDS = {"inventory", "equipped_weapon", "equipped_armor"}
def _entity_to_dict(entity: Entity) -> dict:
result = {f.name: getattr(entity, f.name) for f in fields(entity)}
for name in _ITEM_FIELDS & result.keys():
value = result[name]
if isinstance(value, list):
result[name] = [_entity_to_dict(i) for i in value]
elif value is not None:
result[name] = _entity_to_dict(value)
return {"kind": type(entity).__name__, **result}
def _entity_from_dict(data: dict) -> Entity:
cls = {"Player": Player, "Enemy": Enemy, "Item": Item}[data["kind"]]
kwargs = {k: v for k, v in data.items() if k != "kind"}
for name in _TUPLE_FIELDS & kwargs.keys():
if kwargs[name] is not None:
kwargs[name] = tuple(kwargs[name])
for name in _ITEM_FIELDS & kwargs.keys():
value = kwargs[name]
if isinstance(value, list):
kwargs[name] = [_entity_from_dict(i) for i in value]
elif value is not None:
kwargs[name] = _entity_from_dict(value)
return cls(**kwargs)
def _floor_to_dict(game_map: GameMap) -> dict:
return {
"width": game_map.width,
"height": game_map.height,
"tiles": [list(row) for row in game_map.tiles],
"explored": [list(row) for row in game_map.explored],
"rooms": [[r.x, r.y, r.width, r.height] for r in game_map.rooms],
"entities": [_entity_to_dict(e) for e in game_map.entities],
"stairs_down": list(game_map.stairs_down) if game_map.stairs_down else None,
"floor_index": game_map.floor_index,
"spawn": list(game_map.spawn),
}
def _floor_from_dict(data: dict) -> GameMap:
return GameMap(
width=data["width"],
height=data["height"],
tiles=[array("b", row) for row in data["tiles"]],
explored=[array("b", row) for row in data["explored"]],
rooms=[Rect(x, y, w, h) for x, y, w, h in data["rooms"]],
entities=[_entity_from_dict(e) for e in data["entities"]],
visible=[array("b", [0]) * data["width"] for _ in range(data["height"])],
stairs_down=tuple(data["stairs_down"]) if data["stairs_down"] else None,
floor_index=data["floor_index"],
spawn=tuple(data["spawn"]),
)
def _rng_state_to_list(state: tuple) -> list:
version, key, gauss = state
return [version, list(key), gauss]
def _rng_state_from_list(data: list) -> tuple:
version, key, gauss = data
return (version, tuple(key), gauss)
def session_to_dict(session: GameSession) -> dict:
return {
"player": _entity_to_dict(session.player),
"dungeon": [_floor_to_dict(m) for m in session.dungeon],
"current_floor": session.current_floor,
"log": list(session.log),
"turn": session.turn,
"state": session.state,
"rng": _rng_state_to_list(session.rng.getstate()),
}
def session_from_dict(data: dict) -> GameSession:
session = GameSession(
player=_entity_from_dict(data["player"]),
dungeon=[_floor_from_dict(m) for m in data["dungeon"]],
current_floor=data["current_floor"],
log=list(data["log"]),
turn=data["turn"],
state=data["state"],
rng=random.Random(),
)
session.rng.setstate(_rng_state_from_list(data["rng"]))
session.update_fov()
return session
def save_game(session: GameSession, path: Path | None = None) -> None:
path = SAVE_PATH if path is None else path
path.write_text(json.dumps(session_to_dict(session)))
def load_game(path: Path | None = None) -> GameSession:
path = SAVE_PATH if path is None else path
return session_from_dict(json.loads(path.read_text()))
def has_save(path: Path | None = None) -> bool:
path = SAVE_PATH if path is None else path
return path.is_file()
def delete_save(path: Path | None = None) -> None:
path = SAVE_PATH if path is None else path
path.unlink(missing_ok=True)
def _assert_sessions_equal(a: GameSession, b: GameSession) -> None:
assert a.turn == b.turn and a.current_floor == b.current_floor and a.state == b.state
assert a.log == b.log
pa, pb = a.player, b.player
for f in fields(Player):
assert getattr(pa, f.name) == getattr(pb, f.name), f"player.{f.name}"
assert pa.equipped_weapon == pb.equipped_weapon and pa.equipped_armor == pb.equipped_armor
for fa, fb in zip(a.dungeon, b.dungeon):
assert fa.tiles == fb.tiles and fa.explored == fb.explored
assert fa.stairs_down == fb.stairs_down and fa.spawn == fb.spawn
for ea, eb in zip(fa.entities, fb.entities):
assert type(ea) is type(eb)
for f in fields(ea):
assert getattr(ea, f.name) == getattr(eb, f.name), f"{ea}.{f.name}"
if __name__ == "__main__":
import tempfile
from data.items import ITEM_CATALOG
from data.enemies import make_enemy
session = GameSession.new_game(seed=42)
session.player.hp = 33
session.player.xp = 27
axe = Item.from_def(ITEM_CATALOG["battle_axe"])
session.player.inventory.append(axe)
session.equip(axe)
session.player.strength_turns = 12
session.player.invisible_turns = 3
session.player_move_or_attack(1, 0)
session.current_map.entities.append(make_enemy("green_slime", 5, 5))
session.current_map.entities[0].last_known_position = (7, 9)
session.current_map.entities[0].hp -= 3
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "save.json"
save_game(session, path)
assert has_save(path)
loaded = load_game(path)
_assert_sessions_equal(session, loaded)
loaded.current_map.entities.remove(loaded.current_map.entities[-1])
delete_save(path)
assert not has_save(path)
delete_save(path) # idempotent
# RNG continuity: identical inputs after load produce identical outcomes.
with tempfile.TemporaryDirectory() as tmp:
a = GameSession.new_game(seed=7)
save_game(a, Path(tmp) / "s.json")
b = load_game(Path(tmp) / "s.json")
for _ in range(20):
a.player_move_or_attack(1, 0)
b.player_move_or_attack(1, 0)
assert a.player.hp == b.player.hp and a.player.position == b.player.position
assert a.turn == b.turn == 20
print("serializers self-check: PASS")
-29
View File
@@ -1,29 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
from entities.entity import Entity
@dataclass(slots=True)
class Enemy(Entity):
key: str = ""
name: str = "Enemy"
sprite_key: str = "enemy"
hp: int = 1
max_hp: int = 1
power: int = 1
armor: int = 0
accuracy: int = 0
evasion: int = 0
crit_chance: float = 0.0
speed: int = 1
behavior: str = "wander"
ranged_power: int = 0
splits_remaining: int = 0
xp_reward: int = 0
last_known_position: tuple[int, int] | None = None
@property
def alive(self) -> bool:
return self.hp > 0
-20
View File
@@ -1,20 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
@dataclass(slots=True)
class Entity:
x: int = 0
y: int = 0
name: str = "Entity"
sprite_key: str = "entity"
blocks_movement: bool = True
@property
def position(self) -> tuple[int, int]:
return self.x, self.y
def move(self, dx: int, dy: int) -> None:
self.x += dx
self.y += dy
-34
View File
@@ -1,34 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass
from data.items import ItemDef
from entities.entity import Entity
@dataclass(slots=True)
class Item(Entity):
key: str = "item"
category: str = "misc"
effect: str = ""
power: int = 0
armor: int = 0
crit_modifier: float = 0.0
evasion_modifier: int = 0
blocks_movement: bool = False
@classmethod
def from_def(cls, item_def: ItemDef, x: int = 0, y: int = 0) -> Item:
return cls(
x=x,
y=y,
key=item_def.key,
name=item_def.name,
sprite_key=item_def.sprite_key or "item",
category=item_def.category,
effect=item_def.effect,
power=item_def.power,
armor=item_def.armor,
crit_modifier=item_def.crit_modifier,
evasion_modifier=item_def.evasion_modifier,
)
-72
View File
@@ -1,72 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass, field
from data.constants import (
PLAYER_ACCURACY,
PLAYER_ARMOR,
PLAYER_CRIT_CHANCE,
PLAYER_EVASION,
PLAYER_MAX_HP,
PLAYER_POWER,
PLAYER_SPEED,
STRENGTH_BONUS,
)
from entities.entity import Entity
from entities.item import Item
@dataclass(slots=True)
class Player(Entity):
name: str = "Player"
sprite_key: str = "player"
hp: int = PLAYER_MAX_HP
max_hp: int = PLAYER_MAX_HP
power: int = PLAYER_POWER
armor: int = PLAYER_ARMOR
accuracy: int = PLAYER_ACCURACY
evasion: int = PLAYER_EVASION
crit_chance: float = PLAYER_CRIT_CHANCE
speed: int = PLAYER_SPEED
level: int = 1
xp: int = 0
inventory: list[Item] = field(default_factory=list)
equipped_weapon: Item | None = None
equipped_armor: Item | None = None
strength_turns: int = 0
invisible_turns: int = 0
@property
def total_power(self) -> int:
bonus = self.equipped_weapon.power if self.equipped_weapon else 0
if self.strength_turns > 0:
bonus += STRENGTH_BONUS
return self.power + bonus
@property
def total_armor(self) -> int:
return self.armor + (self.equipped_armor.armor if self.equipped_armor else 0)
@property
def total_evasion(self) -> int:
return self.evasion + (self.equipped_armor.evasion_modifier if self.equipped_armor else 0)
@property
def total_crit(self) -> float:
return max(
0.0,
self.crit_chance + (self.equipped_weapon.crit_modifier if self.equipped_weapon else 0.0),
)
@property
def is_invisible(self) -> bool:
return self.invisible_turns > 0
@property
def alive(self) -> bool:
return self.hp > 0
def heal(self, amount: int) -> int:
old_hp = self.hp
self.hp = min(self.max_hp, self.hp + max(0, amount))
return self.hp - old_hp
-74
View File
@@ -1,74 +0,0 @@
from __future__ import annotations
import os
import pygame
from data.constants import FPS, GAME_TITLE, SCREEN_H, SCREEN_W
from engine.audio import SoundEffects
from engine.flow import GameFlow
from render.renderer import Renderer
_KEY_INTENTS: dict[int, str] = {
pygame.K_UP: "up",
pygame.K_k: "up",
pygame.K_DOWN: "down",
pygame.K_j: "down",
pygame.K_LEFT: "left",
pygame.K_h: "left",
pygame.K_RIGHT: "right",
pygame.K_l: "right",
pygame.K_RETURN: "confirm",
pygame.K_KP_ENTER: "confirm",
pygame.K_ESCAPE: "cancel",
}
_CHAR_INTENTS: dict[str, str] = {
"g": "pickup",
"f": "descend",
"i": "inventory",
"e": "equipment",
"q": "quaff",
"r": "read",
"S": "save",
"?": "help",
"m": "mute",
}
def _intent_for(event: pygame.event.Event) -> str | None:
if event.key in _KEY_INTENTS:
return _KEY_INTENTS[event.key]
char = event.unicode
return _CHAR_INTENTS.get(char, char if char and char.isprintable() else None)
def main(max_frames: int | None = None) -> None:
pygame.init()
screen = pygame.display.set_mode((SCREEN_W, SCREEN_H))
pygame.display.set_caption(GAME_TITLE)
clock = pygame.time.Clock()
renderer = Renderer(screen)
flow = GameFlow(audio=SoundEffects())
frames = 0
if max_frames is None and os.environ.get("UNDERDEPTHS_MAX_FRAMES"):
max_frames = int(os.environ["UNDERDEPTHS_MAX_FRAMES"])
try:
while flow.running and (max_frames is None or frames < max_frames):
dt = clock.tick(FPS) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
flow.running = False
elif event.type == pygame.KEYDOWN:
intent = _intent_for(event)
if intent is not None:
flow.handle_key(intent)
renderer.draw(flow, dt)
frames += 1
finally:
pygame.quit()
if __name__ == "__main__":
main()
-114
View File
@@ -1,114 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
MAX_RETRIES=${MAX_RETRIES:-3}
DISPATCH_TTL=${DISPATCH_TTL:-50m}
ROOT=$(cd "$(dirname "$0")" && pwd)
STATE_FILE="$ROOT/.build_state"
LOCK_DIR="$ROOT/.orchestrate.lock"
LOG_DIR="$ROOT/.build_logs"
if ! mkdir "$LOCK_DIR" 2>/dev/null; then
echo "Another orchestrate.sh instance is running. Remove $LOCK_DIR only if it is stale." >&2
exit 1
fi
trap 'rm -rf "$LOCK_DIR"' EXIT INT TERM
mkdir -p "$LOG_DIR"
cd "$ROOT"
if command -v timeout >/dev/null 2>&1; then
TIMEOUT=timeout
elif command -v gtimeout >/dev/null 2>&1; then
TIMEOUT=gtimeout
else
echo "GNU timeout is required (brew install coreutils)." >&2
exit 1
fi
state=$(tr -dc '0-9' < "$STATE_FILE" 2>/dev/null || true)
state=${state:-0}
run_pi() {
local name=$1 prompt=$2 log="$LOG_DIR/$1.log"
echo "==> Dispatch: $name"
if ! "$TIMEOUT" --kill-after=30 "$DISPATCH_TTL" pi -p "$prompt" 2>&1 | tee "$log"; then
echo "Dispatch failed or timed out: $name (see $log)" >&2
return 1
fi
}
run_gate() {
local phase=$1 output
output=$(mktemp)
echo "==> Gate: phase $phase"
if PYGAME_HIDE_SUPPORT_PROMPT=1 SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy \
python tests/smoke.py --phase "$phase" >"$output" 2>&1; then
cat "$output"
rm -f "$output"
return 0
fi
cat "$output"
GATE_FAILURE=$(cat "$output")
rm -f "$output"
return 1
}
fix_until_green() {
local phase=$1 attempt=0
while ! run_gate "$phase"; do
attempt=$((attempt + 1))
if (( attempt > MAX_RETRIES )); then
echo "Phase $phase failed after $MAX_RETRIES retries." >&2
exit 1
fi
run_pi "phase-${phase}-fix-${attempt}" "Read AGENTS.md and plan.md completely. Phase $phase gate failed. Fix the implementation, not the test expectations, while preserving earlier phases. Run the gate before finishing. Actual failure:\n\n$GATE_FAILURE"
done
printf '%s\n' "$phase" > "$STATE_FILE"
state=$phase
}
if (( state < 1 )); then
run_pi phase-1 'Read AGENTS.md and plan.md completely. Implement Phase 1 Foundation exactly: constants, slotted typed entities, BSP dungeon generation, player/enemy models, and a minimal runnable pygame loop. Replace phase_1 in tests/smoke.py with substantive tests for 5 generated maps: >=3 non-overlapping rooms, connectivity by flood fill, and reachable floor-tile stairs on floors 0-8. Preserve later phase stubs. Run python tests/smoke.py --phase 1 before finishing. No TODOs or fake tests.'
fix_until_green 1
fi
if (( state < 2 )); then
echo "==> Phase 2 independent systems (parallel)"
run_pi phase-2-fov 'Read AGENTS.md and plan.md. Implement recursive shadowcasting FOV in engine/fov.py with radius 8, visible/explored updates, typing, and no stubs. Do not edit unrelated systems.' & p1=$!
run_pi phase-2-pathfinding 'Read AGENTS.md and plan.md. Implement A* pathfinding in engine/pathfinding.py using Manhattan distance, walls and occupied tiles as blockers, and a no-path fallback. Type every signature. Do not edit unrelated systems.' & p2=$!
run_pi phase-2-combat 'Read AGENTS.md and plan.md. Implement combat in engine/combat.py exactly per hit, armor, crit, damage, death, XP, and message-log rules. Type every signature. Do not edit unrelated systems.' & p3=$!
failed=0
wait "$p1" || failed=1
wait "$p2" || failed=1
wait "$p3" || failed=1
(( failed == 0 )) || { echo "A Phase 2 parallel dispatch failed." >&2; exit 1; }
run_pi phase-2-ai 'Read AGENTS.md and plan.md completely. FOV, pathfinding, and combat now exist. Implement all enemy AI dispatch behavior in ai/behaviors.py, including wander, chase/last-known, flee, ranged/kiting, phase cadence, split handling, and safe blocked-path fallback. Integrate without hidden state. Replace phase_2 in tests/smoke.py with substantive FOV, A*, 1000-attack combat-range, and corridor-chase AI tests. Preserve all earlier tests and later stubs. Run phases 1 and 2 before finishing.'
fix_until_green 2
fi
if (( state < 3 )); then
run_pi phase-3 'Read AGENTS.md and plan.md completely. Implement Phase 3 Content Layer: fixed item catalog, inventory/equipment and all potion/scroll effects; cumulative XP and leveling; exact roster/stats and all seven enemy types; depth-gated spawning; and the floor-9 boss arena with dragon breath, two healing potions, victory, and obtainable gear capable of damaging armor 8. Keep GameSession as sole mutable state and log every event. Replace phase_3 in tests/smoke.py with substantive roster, equip-stat, kill/XP/level-up, item-effect, boss-arena, and boss-winnability tests. Preserve prior tests. Run phases 1-3 before finishing. No stubs.'
fix_until_green 3
fi
if (( state < 4 )); then
run_pi phase-4a 'Read AGENTS.md and plan.md completely. Implement Phase 4a: GameSession integration, exact JSON save/load for all required state, permadeath save deletion, game actions/intents, menus/state transitions, generated in-memory pygame mixer sound effects, mute, and silent audio failure fallback. Add no assets. Preserve prior systems and tests. Do not attempt rendering yet. No stubs.'
run_pi phase-4b 'Read AGENTS.md and plan.md completely. Implement Phase 4b: all procedural multi-color pixel-art patterns and cached rasterization; pure renderer composition; distinct player/equipment, seven enemies, items, and visibly blitted glowing stairs; textured/beveled tiles, FOV torch lighting and explored dimming, shadows/vignette; capped particles, shake, easing camera, idle frames; polished bordered UI, bars/icons/log/context prompts; complete pygame main menu/game/death/victory/how-to-play/inventory/equipment/potion/scroll flow and every documented key. New Game must show How to Play. No flat-square entity art and no external assets. Integrate with existing state/actions.'
run_pi phase-4c-tests 'Read AGENTS.md and plan.md completely. Finish Phase 4 and replace phase_4 in tests/smoke.py with substantive tests for save/load equality, menu states, simulated g pickup and f descent, generated audio mute/failure safety, pure rendering, and proof the renderer blits a distinct stairs sprite. Extend the full suite with safe headless startup/playthrough checks and floor 0-8 stairs reachability. Preserve all prior tests; never weaken expectations. Fix implementation failures and run python tests/smoke.py --phase 4 before finishing.'
fix_until_green 4
fi
echo "==> Final acceptance backstop"
for attempt in $(seq 1 "$MAX_RETRIES"); do
if ! run_pi "goal-audit-$attempt" 'Read AGENTS.md and plan.md completely. Audit EVERY unchecked acceptance criterion in plan.md against the actual game. Run the complete smoke suite and a bounded headless main.py playthrough covering menu, How to Play, movement/combat, g pickup, f descent, save/quit/reload, audio-disabled mode, death, and victory. Inspect visuals structurally to ensure distinct multi-color procedural sprites, visible stairs, lighting, particles, camera/shake, and polished UI are genuinely wired into rendering. Fix every failure you find; do not merely report it, weaken tests, add stubs, or stop early. Ensure all 10 floors are winnable and the dragon is damageable. Finish only when python tests/smoke.py passes.'; then
echo "Goal-audit dispatch unavailable; running the local acceptance audit." >&2
fi
if run_gate 4 && python tests/audit_playthrough.py; then
echo "Underdepths build complete: all gates pass."
exit 0
fi
echo "Acceptance backstop attempt $attempt failed; retrying."
done
echo "Final acceptance backstop failed after $MAX_RETRIES attempts." >&2
exit 1
+83 -63
View File
@@ -54,14 +54,16 @@ class GameSession:
@dataclass
class GameMap:
width: int # 80
height: int # 50
width: int # 64
height: int # 40
tiles: np.ndarray # 0=wall, 1=floor (use array.array if numpy not available)
rooms: list[Rect] # rooms placed by BSP
junctions: list[Rect] # 3×3 connector breaks, distinct from BSP rooms
corridors: list[list[tuple[int, int]]] # ordered centerline paths, endpoints included
explored: np.ndarray # bool grid — tiles player has seen
visible: np.ndarray # bool grid — tiles player sees this turn
entities: list[Entity] # enemies + items on this floor
stairs_down: tuple[int, int] # position of stairs (except floor 9)
stairs_down: tuple[int, int] | None # None only on floor 9
floor_index: int
```
@@ -72,27 +74,34 @@ class GameMap:
**Algorithm: BSP Tree**
1. Start with the full map as all walls.
2. Recursively split the map into two regions (alternate horizontal/vertical), 5–8 splits total.
3. For each leaf region, carve a room (fill a random sub-rectangle as floor, shrink 1-2 tiles from region edges).
4. Connect sibling regions with L-shaped corridors.
2. Recursively split the map into 8–12 leaf regions, alternating horizontal and vertical cuts.
3. For each leaf region, carve a room (fill a random sub-rectangle as floor, shrink 1–2 tiles from region edges).
4. Connect sibling rooms from their nearest edge tiles. A corridor section is one ordered centerline path between room or junction boundaries, including an L-shaped corner. Store every section in `GameMap.corridors`, with both boundary endpoints included; its movement length is `len(path) - 1`. Every section MUST be at most `MAX_CORRIDOR_LENGTH = 14` movement steps. Insert a 3×3 junction recorded in `GameMap.junctions` when needed, or reject and regenerate the map; never ship a long featureless tunnel.
5. Place stairs down in the last room generated (rooms farthest from spawn). Stairs MUST land on a floor tile that is reachable from the player's spawn room through the carved corridors (verified by flood fill). Floors 0–8 always have stairs; floor 9 (boss arena) has NO descent — it is won by slaying the dragon.
6. Spawn enemies and items per floor (see distribution below).
**Room size:** 4×4 to 10×8 tiles.
**Map size:** 80×50 tiles. 1-tile wall border.
**Map size:** 64×40 tiles. 1-tile wall border.
**Corridor limit:** no uninterrupted room-to-room or room-to-junction section may exceed 14 steps. The phase gate generates multiple maps and checks each stored path has `len(path) - 1 <= 14`, every path tile is carved floor, and each endpoint touches a recorded room or junction. The generator must carve corridors only from these recorded paths.
**Per-floor spawning** (scaled by depth):
| Floor | Enemies | Items |
|-------|---------|-------|
| 0–1 | 3–4 | 2–3 |
| 2–3 | 4–6 | 2–3 |
| 4–5 | 5–7 | 3–4 |
| 6–7 | 6–8 | 3–4 |
| 8 | 7–9 | 4–5 |
| 9 | 0 (boss arena) | 2 (healing potions) |
| Internal floor (display) | Enemies placed initially | Items |
|--------------------------|----------------------------|-------|
| 0 (1/10) | 4 | 2–3 |
| 1 (2/10) | 6 | 3, including the guaranteed Shoes of Hermes |
| 2 (3/10) | 8 | 3–4, including a guaranteed Hunter's Bow |
| 3 (4/10) | 10 | 3–4 |
| 4 (5/10) | 12 | 3–4 |
| 5 (6/10) | 14 | 4–5 |
| 6 (7/10) | 16 | 4–5 |
| 7 (8/10) | 18 | 4–5 |
| 8 (9/10) | 20 | 5–6 |
| 9 (10/10) | 1 Ancient Dragon | 2 healing potions |
Enemies on each floor are drawn from the roster, gated by depth (see Enemy Roster). Items are drawn from the item catalog.
Regular-floor enemy density is deterministic and strictly increases by two per floor: `4 + 2 * floor_index`. Split-spawned Small Slimes do not count toward the initial target. Place enemies across separate reachable rooms so the ramp feels populated rather than clustered at the entrance.
Enemies on each floor are drawn from the roster, gated by depth (see Enemy Roster). Items are drawn from the item catalog. The guaranteed Shoes and Bow replace ordinary item rolls; they do not increase the table's item count.
Generate all 10 floors at game start. This makes save/load simpler (serialize all floors).
@@ -183,8 +192,9 @@ Each enemy has a `behavior` type. Each turn (after player acts), all enemies act
| Category | Effect |
|----------|--------|
| **Weapon** | Equips to weapon slot. Adds `power` bonus. |
| **Weapon** | Equips to weapon slot. Adds `power` bonus. A bow also enables the ranged fire action. |
| **Armor** | Equips to armor slot. Adds `armor` (damage reduction). |
| **Boots** | Equips to boots slot. Shoes of Hermes unlock held-direction running. |
| **Potion (healing)** | Restores 30 HP. Consumed on use. |
| **Potion (strength)** | +5 power for 20 turns. Consumed on use. |
| **Potion (invisibility)** | Enemies can't see you for 15 turns. Consumed on use. |
@@ -192,7 +202,11 @@ Each enemy has a `behavior` type. Each turn (after player acts), all enemies act
| **Scroll (teleport)** | Teleports player to a random walkable tile on the current floor. |
| **Scroll (mapping)** | Reveals entire current floor (all tiles set to explored). |
**Equipment:** One weapon slot, one armor slot. Equipping replaces the current item (old one goes to inventory).
**Equipment:** One weapon slot, one armor slot, and one boots slot. Equipping replaces the current item (old one goes to inventory).
**Shoes of Hermes:** Exactly one pair is guaranteed on display floor 2 (internal index 1), on a reachable floor tile outside the spawn tile. Once equipped, holding an arrow key or `h`/`j`/`k`/`l` repeatedly applies the same ordinary movement intent after a 180 ms initial delay and every 75 ms thereafter. Each repeated step is a complete turn: collision, melee, enemy actions, timers, FOV, and logs behave exactly like a tapped step. Release stops immediately. Running also stops when play leaves the `playing` state, a menu opens, the floor changes, or movement is blocked. Before the Shoes are equipped, one key press always means one step; operating-system key repeat must not provide accidental running. Poll held keys only during active play and keep the timing constants in `data/constants.py`.
**Bow:** A Hunter's Bow is guaranteed on display floor 3 (internal index 2) and may also appear in later weapon rolls. While it is equipped, `b` fires at the nearest visible enemy within range 8, preferring an enemy currently fleeing; walls block the shot. Firing spends one normal turn. Use the normal hit formula with a 3 percentage-point penalty per tile beyond the first, clamped to the standard 10–95% range, and the normal armor/critical-hit damage calculation. Arrows are unlimited; do not add ammunition management. Log no-target, miss, hit, critical hit, and kill outcomes. This gives the player a direct chance to finish enemies that move out of melee range.
**Item catalog (base game):**
@@ -200,6 +214,7 @@ Each enemy has a `behavior` type. Each turn (after player acts), all enemies act
|------|------|-------|
| Rusty Dagger | Weapon | power +2 |
| Short Sword | Weapon | power +4 |
| Hunter's Bow | Weapon | power +4, ranged fire range 8 |
| Battle Axe | Weapon | power +7 |
| War Hammer | Weapon | power +10, crit_chance -5% |
| Leather Armor | Armor | armor 2 |
@@ -211,8 +226,9 @@ Each enemy has a `behavior` type. Each turn (after player acts), all enemies act
| Scroll of Fireball | Scroll | 20 dmg AoE radius 3 |
| Scroll of Teleport | Scroll | random relocate |
| Scroll of Mapping | Scroll | reveal floor |
| Shoes of Hermes | Boots | enables held-direction running while equipped |
Item distribution by depth: better weapons/armor appear deeper. Potions and scrolls are uniform across depth.
Item distribution by depth: better weapons/armor appear deeper. Potions and scrolls are uniform across depth. Shoes of Hermes and the first Hunter's Bow use the guaranteed placements above.
### 7. Progression (entities/player.py)
@@ -253,7 +269,7 @@ On startup: if `save.json` exists, offer "Continue" in the menu. Load restores e
Serialize:
- Player: all stats, level, XP, inventory, equipped items, position
- Dungeon: all 10 floors (tiles, explored, entities, stairs position)
- Dungeon: all 10 floors (tiles, rooms, junctions, corridor paths, explored, entities, stairs position)
- current_floor, turn, log
Do NOT serialize: `visible` grid (recomputed on load via FOV), temporary effect timers? Actually DO serialize timers (strength potion, invisibility) with remaining turns.
@@ -286,17 +302,19 @@ New Game. The `?` key reopens it during play. Keep the explanation plain:
1. Move onto an item's tile, then press `g` to pick it up.
2. Move onto the yellow `>` stairs tile, then press `f` to descend.
3. Walking into an enemy attacks it. Item menus show their own selection keys.
3. Walking into an enemy attacks it. Equip Shoes of Hermes to hold a direction and run; every repeated step is still a full turn.
4. Equip the Hunter's Bow and press `b` to shoot the nearest visible enemy in range. Item menus show their own selection keys.
| Key | Action |
|-----|--------|
| Arrows / hjkl | Move / melee attack (walk into enemy) |
| Arrows / hjkl | Move / melee attack; hold to keep running only while Shoes of Hermes are equipped |
| `g` | Pick up the item under the player |
| `i` | Open inventory |
| `e` | Open equipment (view equipped, equip from inventory) |
| `q` | Quaff a potion (select from inventory) |
| `r` | Read a scroll (select from inventory) |
| `f` | Descend — only while standing on the yellow stairs tile (a plain letter so it works in every keyboard locale) |
| `b` | Fire an equipped bow at the nearest visible enemy in range, preferring a fleeing target |
| `S` | Save and quit |
| `?` | Open How to Play |
| `m` | Mute/unmute sound effects |
@@ -314,7 +332,7 @@ New Game. The `?` key reopens it during play. Keep the explanation plain:
| Green Slime | 4–8 | 18 | 5 | 1 | 1 | split | 18 | Splits into 2 Small Slimes (HP 9) on death. Small slimes don't split. |
| **Ancient Dragon** (boss) | 9 | 120 | 15 | 8 | 1 | chase + special | 200 | Every 3rd turn: breath weapon — 15 damage to all tiles in a line toward player. Floor 9 only. |
**Floor 9 (boss arena):** Single large room (20×15). Dragon starts on the far side. Two healing potions placed near entrance. No other enemies. Stairs appear (or victory triggers) only after dragon is dead.
**Floor 9 (boss arena):** Single large room (20×15). Dragon starts on the far side. Two healing potions are placed near the entrance. No other enemies and no stairs. Killing the dragon immediately sets the victory state.
## Rendering
@@ -331,8 +349,8 @@ feel.
the cached surface scaled to `TILE`.
- Every entity gets a DISTINCT, recognizable sprite — not a recolor of a blob:
- **Player (adventurer):** hooded figure; the equipped weapon (dagger/sword/
axe/hammer) and armor visibly change the sprite. 4-directional facing when
moving.
bow/axe/hammer), armor, and winged boots visibly change the sprite. 4-directional
facing when moving.
- **Rat:** small body, pink tail, round ears, whiskers.
- **Goblin:** green humanoid, pointed ears, crude weapon, loincloth.
- **Skeleton Archer:** white-gray bones, drawn bow, quiver, glowing eye sockets.
@@ -340,8 +358,7 @@ feel.
- **Wraith:** translucent purple wisps, tattered cloak, no legs, glowing eyes.
- **Green Slime:** glossy blob with highlight, two googly eyes, a drip.
- **Ancient Dragon:** large multi-hue red boss — horns, spread wings, scales, fangs.
- **Items:** pixel-art icons (weapon, armor, potion flask, scroll) with the
category accent (yellow / blue / red / cyan) as the dominant hue.
- **Items:** pixel-art icons (melee weapon, drawn bow, armor, winged Shoes of Hermes, potion flask, scroll) with a distinct category accent as the dominant hue.
- **Stairs:** a pixel-art descending staircase / `>` arrow, glowing yellow. The renderer MUST blit this sprite on every `stairs_down` tile so the descent is visually discoverable — invisible stairs make the game unwinnable and are a build failure.
- Animate: 2–3 idle frames cycled by turn/time (gentle breathe/bob via a sine
offset); attack = a short lunge; taking damage = a white hit-flash; death = a
@@ -369,8 +386,7 @@ feel.
- Top bar: Floor N/10, HP bar (heart icon + green/red fill), Level, XP bar.
- Right panel: last 8 log messages, color-coded (combat white, damage red,
level-up green, items yellow).
- Bottom bar: equipment slots drawn as pixel-art icons, active effect timers, and
a sound on/off icon.
- Bottom bar: weapon, armor, and boots slots drawn as pixel-art icons, active effect timers, and a sound on/off icon. When a bow is equipped, show `B: Fire`; when Shoes of Hermes are equipped, show a winged running indicator.
- Context prompt line: on an item show `Press G to pick up <name>`; on stairs
`Press F to descend` — styled as part of the UI, not console text.
- Use `pygame.font.SysFont` (no font asset files).
@@ -399,49 +415,53 @@ mute. Audio is feedback only and must never alter game state or block input.
The game is DONE when ALL of these are true:
### Floor (must-haves)
- [x] Game launches without errors via `python main.py`
- [x] Runs for at least 5 minutes of continuous play without crashing
- [x] Has a main menu with New Game / Continue / Quit
- [x] Has a WIN state (kill the dragon on floor 10)
- [x] Has a LOSE state (player HP reaches 0, game over screen)
- [x] More than one floor — 10 floors, each procedurally generated
- [x] More than one enemy type — 6 regular + 1 boss
- [x] How to Play is available from the menu and shown before a New Game
- [x] Standing on an item/stairs shows the exact key needed; `g` pickup and `f` descent work
- [x] Simple sound effects play when audio is available; missing audio devices fall back silently
- [x] Entities, tiles, and items are drawn as distinct procedural pixel-art sprites (not flat colored squares); no external image files are loaded
- [x] Every level is winnable: on floors 0–8 stairs exist, are reachable from spawn, and are VISIBLY RENDERED (the `>` staircase); floor 9 is won by slaying a dragon the player can actually damage with floor-9-appropriate gear
- [ ] Game launches without errors via `python main.py`
- [ ] Runs for at least 5 minutes of continuous play without crashing
- [ ] Has a main menu with New Game / Continue / Quit
- [ ] Has a WIN state (kill the dragon on floor 10)
- [ ] Has a LOSE state (player HP reaches 0, game over screen)
- [ ] More than one floor — 10 floors, each procedurally generated
- [ ] More than one enemy type — 6 regular + 1 boss
- [ ] How to Play is available from the menu and shown before a New Game
- [ ] Standing on an item/stairs shows the exact key needed; `g` pickup and `f` descent work
- [ ] Simple sound effects play when audio is available; missing audio devices fall back silently
- [ ] Entities, tiles, and items are drawn as distinct procedural pixel-art sprites (not flat colored squares); no external image files are loaded
- [ ] Every level is winnable: on floors 0–8 stairs exist, are reachable from spawn, and are VISIBLY RENDERED (the `>` staircase); floor 9 is won by slaying a dragon the player can actually damage with floor-9-appropriate gear
- [ ] Compact generation: no corridor section between room/junction boundaries exceeds 14 movement steps across repeated generated maps
- [ ] Monster density rises on every regular floor with initial counts 4, 6, 8, 10, 12, 14, 16, 18, and 20
- [ ] Shoes of Hermes are guaranteed on display floor 2; equipping them makes a held direction repeat complete turns at the specified 180 ms/75 ms cadence, and running stops on release, block, menu, floor change, death, or victory
- [ ] A Hunter's Bow is guaranteed on display floor 3; `b` prefers a visible fleeing target over a nearer non-fleeing target, cannot shoot through walls, spends a turn, and can kill at range
### Systems Depth (judging criteria)
- [x] **A* pathfinding** — enemies pathfind around walls toward the player (chase and flee behaviors). Visible when a goblin navigates a corridor to reach you.
- [x] **FOV** — recursive shadowcasting. Player can only see tiles within line of sight. Explored tiles remembered but darker. Walls block vision.
- [x] **Procedural generation** — BSP dungeon generation. Each floor is different every playthrough.
- [x] **Enemy AI** — at least 4 distinct behaviors visible: wander (rat), chase (goblin/orc), ranged/kiting (skeleton archer), phase-through-walls (wraith). Ideally also split (slime) and boss breath weapon.
- [x] **Combat** — melee and ranged, hit chance, damage reduction from armor, critical hits. Messages logged.
- [x] **Progression** — XP from kills, level up with stat increases, fully heal on level up.
- [x] **Items & inventory** — pick up, equip weapons/armor, quaff potions, read scrolls. At least 4 distinct item effects.
- [x] **Save/load** — press S to save and quit. Relaunch → Continue → exact state restored.
- [x] **Control usability** — an automated input smoke test places an item under the player, presses `g`, and verifies inventory; then places the player on stairs, presses `f`, and verifies the floor changes.
- [x] **Audio safety** — generated effects need no asset files, mute works, and forced mixer-init failure does not crash.
- [ ] **A* pathfinding** — enemies pathfind around walls toward the player (chase and flee behaviors). Visible when a goblin navigates a corridor to reach you.
- [ ] **FOV** — recursive shadowcasting. Player can only see tiles within line of sight. Explored tiles remembered but darker. Walls block vision.
- [ ] **Procedural generation** — compact BSP dungeon generation. Each floor is different every playthrough and every corridor section is at most 14 steps.
- [ ] **Enemy AI** — at least 4 distinct behaviors visible: wander (rat), chase (goblin/orc), ranged/kiting (skeleton archer), phase-through-walls (wraith). Ideally also split (slime) and boss breath weapon.
- [ ] **Combat** — melee and ranged, hit chance, damage reduction from armor, critical hits. Messages logged. The player's Hunter's Bow can kill a fleeing target.
- [ ] **Progression** — XP from kills, level up with stat increases, fully heal on level up.
- [ ] **Items & inventory** — pick up, equip weapons/armor/boots, quaff potions, read scrolls. Shoes of Hermes and Hunter's Bow work. At least 4 distinct item effects.
- [ ] **Save/load** — press S to save and quit. Relaunch → Continue → exact state restored, including equipped boots and bow.
- [ ] **Control usability** — an automated input smoke test places an item under the player, presses `g`, and verifies inventory; places the player on stairs, presses `f`, and verifies the floor changes; then drives the real movement input clock to verify one immediate step, no repeat before 180 ms, repeats every 75 ms only with equipped Shoes, and stops on release, block, menu, floor change, death, and victory.
- [ ] **Audio safety** — generated effects need no asset files, mute works, and forced mixer-init failure does not crash.
### Visual Polish (judging criteria)
- [x] **Procedural pixel-art** — every entity, tile, and item is a hand-coded multi-color pixel pattern; the 7 enemies + player + items + stairs are each visually distinct and recognizable (not recolors of one shape)
- [x] **Lighting** — radial torch-light around the player, explored tiles remembered but dimmed, walls occlude light, screen vignette
- [x] **Depth & shadow** — beveled/textured walls, per-tile floor variation, soft shadows under entities
- [x] **Juice** — particle effects on hits/crits/deaths/pickups/level-ups/stairs, screen-shake on damage, easing camera, idle animation on entities
- [x] **Polished UI** — bordered panels, HP/XP bars with icons, color-coded log, equipment shown as icons, styled context prompts; clean and readable
- [ ] **Procedural pixel-art** — every entity, tile, and item is a hand-coded multi-color pixel pattern; the 7 enemies, player equipment variants, Bow, winged Shoes, other items, and stairs are each visually distinct and recognizable (not recolors of one shape)
- [ ] **Lighting** — radial torch-light around the player, explored tiles remembered but dimmed, walls occlude light, screen vignette
- [ ] **Depth & shadow** — beveled/textured walls, per-tile floor variation, soft shadows under entities
- [ ] **Juice** — particle effects on hits/crits/deaths/pickups/level-ups/stairs, screen-shake on damage, easing camera, idle animation on entities
- [ ] **Polished UI** — bordered panels, HP/XP bars with icons, color-coded log, weapon/armor/boots shown as icons, styled context prompts; clean and readable
### Video Requirements (what must be visible in one continuous take)
- [x] Core loop played: move, explore, fight, loot, descend
- [x] Two systems interacting: e.g., enemy A* pathfinding through a generated dungeon while FOV limits what you see
- [x] A failure/death: player dies, game over screen appears
- [x] Save, quit, relaunch, continue from save
- [ ] Core loop played: move, explore, fight, loot, descend; demonstrate held running with Shoes of Hermes and a bow shot at a fleeing enemy
- [ ] Two systems interacting: e.g., enemy A* pathfinding through a generated dungeon while FOV limits what you see
- [ ] A failure/death: player dies, game over screen appears
- [ ] Save, quit, relaunch, continue from save
## Tuning Notes
- If the game is too hard: increase potion drop rate, reduce enemy HP, increase player base HP.
- If too easy: add more enemies per floor, increase enemy power scaling.
- The first 2 floors should be forgiving (rats and a few goblins). Difficulty ramps from floor 3+.
- If the game is too hard: increase potion drop rate, reduce enemy HP, increase player base HP; keep the required density counts intact.
- If too easy: increase enemy power scaling; keep the required strictly increasing density counts intact.
- The first 2 floors should be forgiving through roster and stats, not emptiness. Difficulty ramps from floor 3+ while density still rises on every floor.
- Leave a `constants.py` with all tunable values in one place so balancing is trivial.
## What NOT to Build
+49 -20
View File
@@ -26,8 +26,10 @@ You are building **Underdepths**, a turn-based roguelike in Python with pygame-c
`plan.md`, dispatches fixes for any that fail, loops until all pass
- Uses the DEFAULT model only — never passes `--model` or `--provider` to `pi -p`
(the whole build runs on whatever is configured as the default model)
- Wraps each dispatch in `timeout --kill-after=30`, and splits any phase too
large for one dispatch (e.g. phase 4) into sequential sub-builds before its gate
- Gives every dispatch a hard TTL with SIGKILL escalation: use GNU `timeout`,
Homebrew `gtimeout`, or an equivalent Python stdlib process-group watchdog
- Splits any phase too large for one dispatch (e.g. phase 4) into sequential
sub-builds before its gate
3. **Then execute the pipeline.** Run `./orchestrate.sh`. Let it drive the build
through all four phases to completion.
4. **Do not stop until every acceptance criterion in `plan.md` is met.** The
@@ -37,18 +39,31 @@ You are building **Underdepths**, a turn-based roguelike in Python with pygame-c
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 F 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
on an item and `Press F to descend` while standing on stairs. The smoke suite
must simulate both actions; rendering instructions alone is not enough.
7. **Build compact, populated floors.** Store each corridor as its ordered
centerline path between recorded room/junction boundaries. Keep `len(path) - 1`
at 14 movement steps or fewer; gates must also prove each path tile is floor and
no corridor was carved outside the recorded paths. Spawn exactly 4, 6, 8, 10,
12, 14, 16, 18, and 20 regular enemies on display floors 1–9.
8. **Add the two traversal/combat items exactly as specified.** Guarantee Shoes of
Hermes on display floor 2 and a Hunter's Bow on display floor 3. The Shoes must
use held-key polling, not OS key repeat: without them a press moves once; with
them equipped, holding repeats complete turns after 180 ms and every 75 ms until
release, block, menu, floor change, death, or victory. `b` fires an equipped Bow
at a visible in-range enemy, prefers a fleeing target even over a nearer chaser,
cannot shoot through walls, and consumes a turn. Test both mechanics through the
real input and action paths.
9. **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.
8. **Make it look polished.** Draw every entity, tile, and item as procedural
10. **Make it look polished.** Draw every entity, tile, and item as procedural
pixel-art — hand-coded multi-color pixel patterns rendered with `pygame.draw`,
no external image files. The 7 enemies, player, items, and stairs must each be
visually distinct and recognizable (not recolors). Add radial torch-light,
explored-tile dimming, beveled walls, drop shadows, particle bursts on
combat/death/pickups, screen-shake on damage, and a bordered UI with HP/XP
bars and icons. Plain colored squares are unacceptable.
no external image files. The 7 enemies, player, Bow, winged Shoes, other items,
and stairs must each be visually distinct and recognizable (not recolors). Add
radial torch-light, explored-tile dimming, beveled walls, drop shadows, particle
bursts on combat/death/pickups, screen-shake on damage, and a bordered UI with
HP/XP bars and weapon/armor/boots icons. Plain colored squares are unacceptable.
## Completion criteria
@@ -56,21 +71,35 @@ You are done when ALL of these are true:
- `python main.py` launches a playable game with a menu.
- All 7 enemy types exist with their specified AI behaviors and stats.
- A* pathfinding, recursive shadowcasting FOV, BSP dungeon generation, combat
with hit/damage/crit mechanics, XP/leveling, items/inventory/equipment, and
save/load all work.
- A* pathfinding, recursive shadowcasting FOV, compact BSP dungeon generation,
combat with hit/damage/crit mechanics, XP/leveling, items/inventory/equipment,
and save/load all work.
- Repeated map generation proves each recorded corridor has `len(path) - 1 <= 14`,
all its tiles are floor, its endpoints touch recorded rooms/junctions, and no
unrecorded corridor floor was carved.
- Initial enemy counts on regular floors are exactly 4, 6, 8, 10, 12, 14, 16,
18, and 20.
- Shoes of Hermes are reachable on display floor 2. Before equipping them, a held
direction moves once; after equipping, the real input clock gives no repeat before
180 ms, repeats every 75 ms, and stops on release, block, menu, floor change,
death, or victory.
- The Hunter's Bow is reachable on display floor 3. Through real `b` input it prefers
a fleeing target over a nearer chaser, cannot shoot through walls, spends a turn,
and can damage and kill at range.
- How to Play clearly explains every control. Context prompts make pickup (`g`)
and descent (`f`) discoverable, and input tests prove both work.
and descent (`f`) discoverable, and input tests prove pickup, descent, held
running, release-to-stop, and Bow fire work.
- Simple generated sound effects cover core events, mute works, and unavailable
audio never prevents launch or play.
- The game looks polished: distinct procedural pixel-art sprites, FOV-based
lighting, particle/juice effects, and a clean bordered UI — not flat squares.
- The game looks polished: distinct procedural pixel-art sprites including Bow
and winged Shoes, FOV-based lighting, particle/juice effects, and a clean
bordered UI — not flat squares.
- 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, stand on loot and press `g`, stand on
stairs and press `f`, level up, save, quit, relaunch, and continue
— all without crashes.
- You can play: move, explore, fight, loot, equip Shoes and hold to run, equip a
Bow and shoot a fleeing enemy, stand on loot and press `g`, stand on stairs and
press `f`, level up, save, quit, relaunch, and continue — all without crashes.
- Every level is winnable: floors 0–8 have stairs that EXIST, are REACHABLE
from spawn, and are VISIBLY RENDERED (the `>` staircase) so the player can
descend with `f`; floor 9 is won by slaying the dragon, who must be
-337
View File
@@ -1,337 +0,0 @@
"""Presentation-layer effects: camera easing, particles, floaters, lighting.
All state here is render-side only; nothing mutates GameSession.
"""
from __future__ import annotations
import math
import random
from dataclasses import dataclass, field
import pygame
from data.constants import (
LIGHT_STEPS,
PARTICLE_CAP,
SIGHT_RADIUS,
TILE_SIZE,
)
from engine.game_state import GameSession
from engine.combat import new_log_messages
from entities.enemy import Enemy
from entities.item import Item
EASE = 6.0 # camera lerp rate per second
class Camera:
def __init__(self) -> None:
self.x = 0.0
self.y = 0.0
self.shake = 0.0
self._ox = 0
self._oy = 0
def snap(self, px: float, py: float) -> None:
self.x, self.y = px, py
def kick(self, strength: float) -> None:
self.shake = min(14.0, self.shake + strength)
def update(self, target_x: float, target_y: float, dt: float) -> None:
t = 1.0 - math.exp(-EASE * dt)
self.x += (target_x - self.x) * t
self.y += (target_y - self.y) * t
self.shake = max(0.0, self.shake - 30.0 * dt)
magnitude = self.shake
self._ox = random.randint(-int(magnitude), int(magnitude)) if magnitude >= 1 else 0
self._oy = random.randint(-int(magnitude), int(magnitude)) if magnitude >= 1 else 0
@property
def offset(self) -> tuple[int, int]:
return self._ox, self._oy
@dataclass(slots=True)
class Particle:
x: float
y: float
vx: float
vy: float
life: float
max_life: float
color: tuple[int, int, int]
size: int
gravity: float = 0.0
@dataclass(slots=True)
class Floater:
text: str
x: float
y: float
life: float
color: tuple[int, int, int]
font: pygame.font.Font
@dataclass(slots=True)
class _Snapshot:
player_hp: int = 0
player_x: int = 0
player_y: int = 0
floor: int = 0
log: tuple[str, ...] = ()
enemy_hp: dict[int, tuple[int, int, int]] = field(default_factory=dict) # id -> hp,x,y
item_pos: dict[int, tuple[int, int]] = field(default_factory=dict)
enemy_sprite: dict[int, str] = field(default_factory=dict)
class Effects:
"""Watches the session each frame and turns state diffs into juice."""
def __init__(self) -> None:
self.camera = Camera()
self.particles: list[Particle] = []
self.floaters: list[Floater] = []
self.player_flash = 0.0
self.enemy_flash: dict[int, float] = {}
self._prev = _Snapshot()
self._prev_enemy_hp: dict[int, tuple[int, int, int]] = {}
self.player_facing = "down"
self._time = 0.0
self._small_font = pygame.font.SysFont(None, 16)
# -- observation ----------------------------------------------------
def observe(self, session: GameSession) -> None:
game_map = session.current_map
player = session.player
prev = self._prev
dx = player.x - prev.player_x
dy = player.y - prev.player_y
facing = None
if dx or dy or prev.floor != session.current_floor:
if prev.floor != session.current_floor:
facing = "down"
for _ in range(24):
self._spawn(0, 0, (245, 210, 70), 60.0, 0.5, world=player_pixel(player))
elif dx:
facing = "right" if dx > 0 else "left"
elif dy:
facing = "down" if dy > 0 else "up"
self.player_facing = facing or self.player_facing
if player.hp < prev.player_hp:
self.player_flash = 0.18
self.camera.kick(min(10.0, 1.5 * (prev.player_hp - player.hp)))
self.floater(f"-{prev.player_hp - player.hp}", player, (230, 80, 70))
self.burst(player_pixel(player), (170, 40, 40), 10, 55.0)
if player.hp > prev.player_hp:
self.floater(f"+{player.hp - prev.player_hp}", player, (110, 220, 110))
for message in new_log_messages(prev.log, session.log):
low = message.lower()
if "reach level" in low:
self.floater("LEVEL UP!", player, (120, 240, 120))
self.burst(player_pixel(player), (250, 220, 90), 26, 70.0)
elif "miss" in low:
self.floater("MISS", player, (170, 170, 170))
elif "critical hit" in low:
self.floater("CRIT!", player, (255, 200, 60))
elif "pick up" in low:
self.burst(player_pixel(player), (240, 220, 130), 12, 45.0)
elif "descend to floor" in low:
self.burst(player_pixel(player), (245, 210, 70), 24, 70.0)
elif "breathes" in low:
dragon = next(
(e for e in game_map.entities if isinstance(e, Enemy) and e.key == "ancient_dragon"),
None,
)
if dragon is not None:
self.burst(player_pixel(dragon), (255, 140, 40), 18, 80.0)
for eid, (hp, x, y) in prev.enemy_hp.items():
if eid not in prev.enemy_sprite:
continue
current = self._prev_enemy_hp.get(eid)
if current is None:
self.burst(tile_pixel(x, y), (200, 200, 190), 16, 60.0)
elif current[0] < hp:
self.enemy_flash[eid] = 0.15
self.floater_at(f"-{hp - current[0]}", tile_pixel(x, y), (240, 240, 240))
self.burst(tile_pixel(x, y), (255, 200, 120), 6, 50.0)
# ambient stairs shimmer
if (
game_map.stairs_down is not None
and random.random() < 0.12
and game_map.visible[game_map.stairs_down[1]][game_map.stairs_down[0]]
):
sx, sy = game_map.stairs_down
px, py = tile_pixel(sx, sy)
self._spawn(random.uniform(-8, 8), random.uniform(-10, 0), (255, 240, 150), 18.0, 0.6, at=(px + random.uniform(-TILE_SIZE / 3, TILE_SIZE / 3), py + random.uniform(0, TILE_SIZE / 2)))
snapshot = _Snapshot(
player_hp=player.hp,
player_x=player.x,
player_y=player.y,
floor=session.current_floor,
log=tuple(session.log),
)
for entity in game_map.entities:
if isinstance(entity, Enemy):
snapshot.enemy_hp[id(entity)] = (entity.hp, entity.x, entity.y)
snapshot.enemy_sprite[id(entity)] = entity.sprite_key
elif isinstance(entity, Item):
snapshot.item_pos[id(entity)] = (entity.x, entity.y)
self._prev_enemy_hp = snapshot.enemy_hp
self._prev = snapshot
# -- spawning ---------------------------------------------------------
def _spawn(
self,
vx: float,
vy: float,
color: tuple[int, int, int],
speed: float,
life: float,
world: tuple[float, float] | None = None,
at: tuple[float, float] | None = None,
) -> None:
if len(self.particles) >= PARTICLE_CAP:
return
angle = random.uniform(0, 2 * math.pi)
magnitude = speed * random.uniform(0.3, 1.0)
x, y = at if at is not None else (world or (0.0, 0.0))
self.particles.append(
Particle(
x=x,
y=y,
vx=math.cos(angle) * magnitude,
vy=math.sin(angle) * magnitude,
life=life * random.uniform(0.6, 1.2),
max_life=life,
color=color,
size=random.randint(2, 3),
)
)
def burst(self, center: tuple[float, float], color: tuple[int, int, int], count: int, speed: float) -> None:
for _ in range(count):
self._spawn(0, 0, color, speed, 0.5, at=center)
def floater(self, text: str, entity, color: tuple[int, int, int]) -> None:
self.floater_at(text, tile_pixel(entity.x, entity.y), color)
def floater_at(self, text: str, pixel: tuple[float, float], color: tuple[int, int, int]) -> None:
self.floaters.append(Floater(text, pixel[0], pixel[1] - 8, 0.9, color, self._small_font))
# -- update / draw ------------------------------------------------------
def update(self, dt: float) -> None:
self._time += dt
self.player_flash = max(0.0, self.player_flash - dt)
for eid in list(self.enemy_flash):
self.enemy_flash[eid] -= dt
if self.enemy_flash[eid] <= 0:
del self.enemy_flash[eid]
alive: list[Particle] = []
for p in self.particles:
p.life -= dt
if p.life <= 0:
continue
p.vy += p.gravity * dt
p.x += p.vx * dt
p.y += p.vy * dt
alive.append(p)
self.particles = alive
alive_floaters: list[Floater] = []
for f in self.floaters:
f.life -= dt
if f.life > 0:
f.y -= 26.0 * dt
alive_floaters.append(f)
self.floaters = alive_floaters
def draw(self, surface: pygame.Surface, cam_x: float, cam_y: float) -> None:
ox, oy = self.camera.offset
for p in self.particles:
fade = max(0.0, p.life / p.max_life)
rect = pygame.Rect(
int(p.x - cam_x + ox),
int(p.y - cam_y + oy),
p.size,
p.size,
)
color = tuple(min(255, int(c * fade)) for c in p.color)
pygame.draw.rect(surface, color, rect)
for f in self.floaters:
alpha = max(0, int(255 * min(1.0, f.life / 0.9)))
label = f.font.render(f.text, True, f.color)
label.set_alpha(alpha)
surface.blit(label, (int(f.x - cam_x + ox - f.font.size(f.text)[0] / 2), int(f.y - cam_y + oy)))
def player_pixel(player) -> tuple[float, float]:
return tile_pixel(player.x, player.y)
def tile_pixel(x: int, y: int) -> tuple[float, float]:
return x * TILE_SIZE + TILE_SIZE / 2, y * TILE_SIZE + TILE_SIZE / 2
# -- lighting ------------------------------------------------------------------
_light_cache: dict[int, pygame.Surface] = {}
_vignette_cache: dict[tuple[int, int], pygame.Surface] = {}
_shadow_cache: dict[int, pygame.Surface] = {}
def light_overlay(step: int) -> pygame.Surface:
"""Darkening overlay for brightness step 0..LIGHT_STEPS (0 = dark)."""
step = max(0, min(LIGHT_STEPS, step))
cached = _light_cache.get(step)
if cached is None:
alpha = int(225 * (1.0 - step / LIGHT_STEPS))
cached = pygame.Surface((TILE_SIZE, TILE_SIZE), pygame.SRCALPHA)
cached.fill((8, 10, 20, alpha))
_light_cache[step] = cached
return cached
def brightness_step(distance: float, flicker_t: float) -> int:
"""Quantized torch brightness for a visible tile at `distance` tiles."""
falloff = 1.0 - distance / (SIGHT_RADIUS + 1.4)
flicker = 0.94 + 0.06 * math.sin(flicker_t * 6.0 + distance * 1.7)
return max(1, int(LIGHT_STEPS * falloff * flicker))
def vignette(size: tuple[int, int]) -> pygame.Surface:
cached = _vignette_cache.get(size)
if cached is not None:
return cached
width, height = size
surface = pygame.Surface(size, pygame.SRCALPHA)
cx, cy = width / 2, height / 2
max_d = math.hypot(cx, cy)
for y in range(0, height, 2):
for x in range(0, width, 2):
d = math.hypot(x - cx, y - cy) / max_d
if d > 0.55:
alpha = min(150, int((d - 0.55) * 330))
surface.fill((5, 5, 12, alpha), (x, y, 2, 2))
_vignette_cache[size] = surface
return surface
def shadow(width: int = TILE_SIZE, height: int = TILE_SIZE // 3) -> pygame.Surface:
key = (width, height)
cached = _shadow_cache.get(key)
if cached is None:
cached = pygame.Surface((width, height), pygame.SRCALPHA)
pygame.draw.ellipse(cached, (0, 0, 0, 110), (0, 0, width, height))
_shadow_cache[key] = cached
return cached
-546
View File
@@ -1,546 +0,0 @@
"""Pure renderer: reads GameFlow/GameSession and draws. Never mutates state."""
from __future__ import annotations
import math
import pygame
from data.constants import (
BOTTOM_BAR_H,
FINAL_FLOOR,
LEVEL_TABLE,
LOG_PANEL_W,
MAX_LOG_SHOWN,
SIGHT_RADIUS,
SCREEN_H,
SCREEN_W,
TILE_FLOOR,
TILE_SIZE,
TOP_BAR_H,
VIEW_TILES_H,
VIEW_TILES_W,
)
from engine.flow import (
DEAD,
EQUIPMENT,
HOWTO,
INVENTORY,
MENU,
PLAYING,
POTIONS,
SCROLLS,
VICTORY,
GameFlow,
)
from entities.enemy import Enemy
from entities.item import Item
from render import sprites as sprite_render
from render.effects import Effects, brightness_step, light_overlay, shadow, vignette
UI_BG = (14, 13, 18)
UI_BORDER = (120, 110, 80)
UI_BORDER_DARK = (60, 54, 40)
UI_TEXT = (210, 205, 195)
UI_TEXT_DIM = (130, 126, 120)
HP_GREEN = (95, 200, 90)
HP_RED = (180, 50, 45)
XP_BLUE = (90, 130, 220)
STAIRS_YELLOW = (245, 210, 70)
HOWTO_LINES: tuple[tuple[str, bool], ...] = (
("HOW TO PLAY", True),
("", False),
("Arrows or HJKL move / attack (walk into an enemy)", False),
("G pick up the item under you", False),
("F descend while standing on the yellow > stairs", False),
("I inventory E equipment", False),
("Q quaff a potion R read a scroll", False),
("S save and quit M mute sounds", False),
("? reopen this help Esc close menus", False),
("", False),
("In lists, press the letter next to an item (or arrows + Enter).", False),
("", False),
("Press any key to continue", True),
)
LIST_TITLES = {
INVENTORY: "INVENTORY — letter to equip",
EQUIPMENT: "EQUIPMENT — letter to remove",
POTIONS: "POTIONS — letter to quaff",
SCROLLS: "SCROLLS — letter to read",
}
def _log_color(message: str) -> tuple[int, int, int]:
low = message.lower()
if "hit you" in low or "you die" in low or "misses you" in low or "breathes" in low:
return (225, 90, 80)
if "reach level" in low:
return (110, 220, 110)
if "pick up" in low or "equip" in low or "quaff" in low or "defeated" in low or "scroll" in low:
return (235, 210, 120)
if "you hit" in low or "critical hit" in low:
return (240, 240, 240)
return (170, 166, 160)
def _wrap(font: pygame.font.Font, text: str, width: int) -> list[str]:
words = text.split()
if not words:
return [text]
lines: list[str] = []
current = words[0]
for word in words[1:]:
if font.size(current + " " + word)[0] <= width:
current += " " + word
else:
lines.append(current)
current = word
lines.append(current)
return lines
def _draw_panel(
surface: pygame.Surface,
rect: pygame.Rect,
background: tuple[int, int, int] = UI_BG,
) -> None:
pygame.draw.rect(surface, background, rect)
pygame.draw.rect(surface, UI_BORDER, rect, 1)
inner = rect.inflate(-4, -4)
pygame.draw.line(
surface, UI_BORDER_DARK, (inner.x, inner.bottom), (inner.right, inner.bottom)
)
pygame.draw.line(
surface, UI_BORDER_DARK, (inner.right, inner.y), (inner.right, inner.bottom)
)
def _bar(
surface: pygame.Surface,
rect: pygame.Rect,
fraction: float,
fill: tuple[int, int, int],
) -> None:
pygame.draw.rect(surface, (30, 28, 34), rect)
width = max(0, min(1.0, fraction))
pygame.draw.rect(surface, fill, (rect.x, rect.y, int(rect.w * width), rect.h))
pygame.draw.rect(surface, UI_BORDER_DARK, rect, 1)
class Renderer:
def __init__(self, screen: pygame.Surface) -> None:
self.screen = screen
self.effects = Effects()
self.font = pygame.font.SysFont(None, 18)
self.small = pygame.font.SysFont(None, 15)
self.mid = pygame.font.SysFont(None, 24)
self.big = pygame.font.SysFont(None, 48)
self.world_sprites: set[str] = set()
self._time = 0.0
self._camera_snapped = False
# -- dispatch ---------------------------------------------------------
def draw(self, flow: GameFlow, dt: float) -> None:
self._time += dt
self.screen.fill((8, 8, 12))
if flow.screen == MENU:
self._draw_menu(flow)
elif flow.screen == HOWTO:
self._draw_howto(flow)
elif flow.screen in (DEAD, VICTORY):
self._draw_game_over(flow)
else:
self._draw_play(flow, dt)
pygame.display.flip()
# -- world -------------------------------------------------------------
def _draw_play(self, flow: GameFlow, dt: float) -> None:
session = flow.session
assert session is not None
self.world_sprites.clear()
self.effects.observe(session)
self.effects.update(dt)
self._draw_world(session)
self._draw_top_bar(session)
self._draw_log_panel(session)
self._draw_bottom_bar(flow)
self._draw_context_prompt(flow)
if flow.screen != PLAYING:
self._draw_list(flow)
def _draw_world(self, session) -> None:
game_map = session.current_map
player = session.player
view_w = VIEW_TILES_W * TILE_SIZE
view_h = VIEW_TILES_H * TILE_SIZE
target_x = player.x * TILE_SIZE + TILE_SIZE / 2 - view_w / 2
target_y = player.y * TILE_SIZE + TILE_SIZE / 2 - view_h / 2
if not self._camera_snapped:
self.effects.camera.snap(target_x, target_y)
self._camera_snapped = True
self.effects.camera.update(target_x, target_y, 1 / 60.0)
cam_x = max(0.0, min(self.effects.camera.x, game_map.width * TILE_SIZE - view_w))
cam_y = max(0.0, min(self.effects.camera.y, game_map.height * TILE_SIZE - view_h))
ox, oy = self.effects.camera.offset
origin_x = int(cam_x - ox)
origin_y = int(cam_y - oy) + TOP_BAR_H
self._origin = (origin_x, origin_y)
x0 = max(0, int(cam_x // TILE_SIZE))
y0 = max(0, int(cam_y // TILE_SIZE))
x1 = min(game_map.width, x0 + VIEW_TILES_W + 2)
y1 = min(game_map.height, y0 + VIEW_TILES_H + 2)
clip = self.screen.get_rect().clip(pygame.Rect(0, TOP_BAR_H, view_w, view_h))
self.screen.set_clip(clip)
self.screen.fill((6, 6, 9), clip)
for y in range(y0, y1):
row_tiles = game_map.tiles[y]
for x in range(x0, x1):
if not game_map.explored[y][x]:
continue
is_floor = row_tiles[x] == TILE_FLOOR
variant = (x * 7 + y * 13) % 3
tile = sprite_render.get_tile("floor" if is_floor else "wall", variant)
self.screen.blit(tile, (x * TILE_SIZE - origin_x, y * TILE_SIZE - origin_y))
distance = math.hypot(x - player.x, y - player.y)
if game_map.visible[y][x]:
step = brightness_step(distance, self._time)
else:
step = 3
self.screen.blit(
light_overlay(step), (x * TILE_SIZE - origin_x, y * TILE_SIZE - origin_y)
)
if game_map.stairs_down is not None:
sx, sy = game_map.stairs_down
if game_map.explored[sy][sx]:
px = sx * TILE_SIZE - origin_x
py = sy * TILE_SIZE - origin_y
self.screen.blit(shadow(TILE_SIZE, TILE_SIZE // 3), (px, py + TILE_SIZE - TILE_SIZE // 3))
self.screen.blit(sprite_render.get_sprite("stairs"), (px, py))
if game_map.visible[sy][sx]:
step = brightness_step(math.hypot(sx - player.x, sy - player.y), self._time)
self.screen.blit(light_overlay(max(step, 10)), (px, py))
self.world_sprites.add("stairs")
for entity in game_map.entities:
if not game_map.visible[entity.y][entity.x]:
continue
self._draw_entity(entity)
self._draw_player(session)
self.effects.draw(self.screen, cam_x - ox, cam_y - oy + TOP_BAR_H)
self.screen.set_clip(self.screen.get_rect())
self.screen.blit(vignette((view_w, view_h)), (0, TOP_BAR_H))
def _bob(self, phase: float) -> int:
return int(round(math.sin(phase) * 1.5))
def _draw_entity(self, entity) -> None:
origin_x, origin_y = self._origin
px = entity.x * TILE_SIZE - origin_x
py = entity.y * TILE_SIZE - origin_y
if isinstance(entity, Item):
key = sprite_render.item_sprite_key(entity.key, entity.sprite_key)
bob = self._bob(self._time * 2.2 + entity.x * 1.3 + entity.y * 0.7)
self.screen.blit(shadow(TILE_SIZE // 2, 5), (px + TILE_SIZE // 4, py + TILE_SIZE - 6))
self.screen.blit(sprite_render.get_sprite(key), (px, py + bob))
self.world_sprites.add(key)
return
if not isinstance(entity, Enemy) or not entity.alive:
return
key = entity.sprite_key
sprite = sprite_render.get_sprite(key)
size = sprite.get_width()
offset = (TILE_SIZE - size) // 2
bob = self._bob(self._time * 1.8 + entity.x + entity.y)
self.screen.blit(shadow(size, size // 4), (px + offset, py + TILE_SIZE - size // 4 - 2))
if self.effects.enemy_flash.get(id(entity), 0) > 0:
sprite = sprite_render.get_flash(key, sprite)
if key == "wraith":
sprite = sprite.copy()
sprite.set_alpha(190)
self.screen.blit(sprite, (px + offset, py + offset + bob))
if entity.hp < entity.max_hp:
bar = pygame.Rect(px + 2, py - 4, TILE_SIZE - 4, 3)
_bar(self.screen, bar, entity.hp / entity.max_hp, HP_RED)
self.world_sprites.add(key)
def _draw_player(self, session) -> None:
origin_x, origin_y = self._origin
player = session.player
px = player.x * TILE_SIZE - origin_x
py = player.y * TILE_SIZE - origin_y
weapon = player.equipped_weapon.key if player.equipped_weapon else ""
armor = player.equipped_armor.key if player.equipped_armor else ""
facing = self.effects.player_facing
sprite = sprite_render.get_player_sprite(weapon, armor, facing)
if self.effects.player_flash > 0:
sprite = sprite_render.get_flash(f"player:{weapon}:{armor}", sprite)
bob = self._bob(self._time * 2.4)
self.screen.blit(shadow(TILE_SIZE, 6), (px, py + TILE_SIZE - 6))
if player.is_invisible:
sprite = sprite.copy()
sprite.set_alpha(120)
self.screen.blit(sprite, (px, py + bob))
self.world_sprites.add("player")
# -- UI panels -----------------------------------------------------------
def _draw_top_bar(self, session) -> None:
player = session.player
rect = pygame.Rect(0, 0, SCREEN_W, TOP_BAR_H)
_draw_panel(self.screen, rect)
y = rect.y + 8
floor_label = self.font.render(
f"Floor {session.current_floor + 1}/{FINAL_FLOOR + 1}", True, UI_TEXT
)
self.screen.blit(floor_label, (10, y))
heart = sprite_render.get_sprite("potion_heal")
self.screen.blit(
pygame.transform.scale(heart, (14, 14)), (140, y + 1)
)
hp_rect = pygame.Rect(160, y, 160, 12)
_bar(self.screen, hp_rect, player.hp / player.max_hp, HP_GREEN if player.hp > player.max_hp * 0.3 else HP_RED)
label = self.small.render(f"{player.hp}/{player.max_hp}", True, UI_TEXT)
self.screen.blit(label, (hp_rect.x + hp_rect.w + 6, y + 1))
level_label = self.font.render(f"Lv {player.level}", True, UI_TEXT)
self.screen.blit(level_label, (400, y))
next_xp = LEVEL_TABLE.get(player.level + 1)
prev_needed = LEVEL_TABLE.get(player.level, (0,))[0]
fraction = 1.0 if next_xp is None else (player.xp - prev_needed) / max(1, next_xp[0] - prev_needed)
xp_label = self.small.render(f"XP {player.xp}", True, UI_TEXT_DIM)
self.screen.blit(xp_label, (450 - xp_label.get_width() - 6, y + 1))
xp_rect = pygame.Rect(452, y, 150, 12)
_bar(self.screen, xp_rect, fraction, (110, 160, 240))
turn_label = self.small.render(f"Turn {session.turn}", True, UI_TEXT_DIM)
self.screen.blit(turn_label, (SCREEN_W - LOG_PANEL_W - 90, y + 1))
power_label = self.font.render(
f"PWR {player.total_power} DEF {player.total_armor}", True, UI_TEXT
)
self.screen.blit(power_label, (620, y))
def _draw_log_panel(self, session) -> None:
rect = pygame.Rect(SCREEN_W - LOG_PANEL_W, TOP_BAR_H, LOG_PANEL_W, SCREEN_H - TOP_BAR_H)
_draw_panel(self.screen, rect)
title = self.small.render("MESSAGE LOG", True, UI_TEXT_DIM)
self.screen.blit(title, (rect.x + 10, rect.y + 6))
pygame.draw.line(
self.screen, UI_BORDER_DARK, (rect.x + 8, rect.y + 22), (rect.right - 8, rect.y + 22)
)
y = rect.y + 28
messages = session.log[-MAX_LOG_SHOWN:]
lines: list[tuple[str, tuple[int, int, int]]] = []
for message in messages:
for line in _wrap(self.font, message, LOG_PANEL_W - 24):
lines.append((line, _log_color(message)))
for line, color in lines[-MAX_LOG_SHOWN * 2:]:
self.screen.blit(self.font.render(line, True, color), (rect.x + 10, y))
y += self.font.get_height() + 2
def _draw_bottom_bar(self, flow: GameFlow) -> None:
session = flow.session
assert session is not None
player = session.player
rect = pygame.Rect(0, SCREEN_H - BOTTOM_BAR_H, SCREEN_W - LOG_PANEL_W, BOTTOM_BAR_H)
_draw_panel(self.screen, rect)
slots = [
(player.equipped_weapon, "weapon"),
(player.equipped_armor, "armor"),
]
x = 14
for item, kind in slots:
slot = pygame.Rect(x, rect.y + 12, TILE_SIZE + 8, TILE_SIZE + 8)
pygame.draw.rect(self.screen, (24, 22, 28), slot)
pygame.draw.rect(self.screen, UI_BORDER_DARK, slot, 1)
if item is not None:
key = sprite_render.item_sprite_key(item.key, item.sprite_key)
self.screen.blit(sprite_render.get_sprite(key), (slot.x + 4, slot.y + 4))
else:
hint = self.small.render("-", True, UI_TEXT_DIM)
self.screen.blit(hint, (slot.centerx - 4, slot.centery - 7))
label = self.small.render(
item.name[:14] if item else ("no weapon" if kind == "weapon" else "no armor"),
True,
UI_TEXT if item else UI_TEXT_DIM,
)
self.screen.blit(label, (slot.x - 2, slot.bottom + 2))
x += TILE_SIZE + 76
effect_x = x + 10
if player.strength_turns > 0:
label = self.font.render(f"STR {player.strength_turns}", True, (240, 150, 60))
self.screen.blit(label, (effect_x, rect.y + 14))
effect_x += label.get_width() + 14
if player.invisible_turns > 0:
label = self.font.render(f"INV {player.invisible_turns}", True, (150, 200, 240))
self.screen.blit(label, (effect_x, rect.y + 14))
muted = flow.audio is None or flow.audio.muted
icon_x = rect.right - 60
color = UI_TEXT_DIM if muted else UI_TEXT
pygame.draw.polygon(
self.screen,
color,
[
(icon_x, rect.y + 22),
(icon_x + 8, rect.y + 22),
(icon_x + 18, rect.y + 14),
(icon_x + 18, rect.y + 34),
(icon_x + 8, rect.y + 26),
(icon_x, rect.y + 26),
],
)
if muted:
pygame.draw.line(self.screen, (200, 80, 70), (icon_x - 2, rect.y + 12), (icon_x + 22, rect.y + 36), 2)
else:
pygame.draw.arc(self.screen, color, (icon_x + 16, rect.y + 18, 10, 12), -1.2, 1.2, 2)
hint = self.small.render("M", True, UI_TEXT_DIM)
self.screen.blit(hint, (icon_x + 6, rect.y + 40))
def _draw_context_prompt(self, flow: GameFlow) -> None:
prompt = flow.context_prompt()
if not prompt:
return
label = self.font.render(prompt, True, (20, 16, 8))
pad = 10
rect = label.get_rect(
midbottom=(VIEW_TILES_W * TILE_SIZE // 2, SCREEN_H - BOTTOM_BAR_H - 8)
).inflate(pad * 2, pad)
pygame.draw.rect(self.screen, STAIRS_YELLOW, rect)
pygame.draw.rect(self.screen, (120, 95, 25), rect, 2)
self.screen.blit(label, (rect.x + pad, rect.y + pad - 2))
# -- menus ------------------------------------------------------------
def _draw_menu(self, flow: GameFlow) -> None:
cx = SCREEN_W // 2
dragon = pygame.transform.scale(sprite_render.get_sprite("ancient_dragon"), (60, 60))
self.screen.blit(
dragon,
(cx - 30, 60),
)
title = self.big.render("UNDERDEPTHS", True, STAIRS_YELLOW)
self.screen.blit(title, (cx - title.get_width() // 2, 30))
subtitle = self.small.render("a procedural pixel roguelike", True, UI_TEXT_DIM)
self.screen.blit(subtitle, (cx - subtitle.get_width() // 2, 200))
y = 260
for index, item in enumerate(flow.menu_items):
selected = index == flow.menu_index
label = self.mid.render(item, True, STAIRS_YELLOW if selected else UI_TEXT)
x = cx - label.get_width() // 2
self.screen.blit(label, (x, y))
if selected:
cursor = self.mid.render(">", True, STAIRS_YELLOW)
self.screen.blit(cursor, (x - 28, y))
y += 40
hint = self.small.render("arrows to choose, Enter to confirm", True, UI_TEXT_DIM)
self.screen.blit(hint, (cx - hint.get_width() // 2, SCREEN_H - 30))
def _draw_howto(self, flow: GameFlow) -> None:
cx = SCREEN_W // 2
y = 70
for text, highlight in HOWTO_LINES:
font = self.mid if highlight and text == "HOW TO PLAY" else self.font
label = font.render(
text, True, STAIRS_YELLOW if highlight else UI_TEXT
)
self.screen.blit(label, (cx - label.get_width() // 2, y))
y += 28 if text else 14
if flow.session is None:
note = self.small.render("(menu)", True, UI_TEXT_DIM)
self.screen.blit(note, (cx - 12, y + 4))
def _draw_game_over(self, flow: GameFlow) -> None:
session = flow.session
assert session is not None
cx = SCREEN_W // 2
if flow.screen == DEAD:
title = self.big.render("YOU DIED", True, (220, 70, 60))
line1 = self.mid.render(
f"You died on floor {session.current_floor + 1}.", True, UI_TEXT
)
line2 = self.mid.render(
f"You reached level {session.player.level}.", True, UI_TEXT
)
else:
title = self.big.render("VICTORY!", True, STAIRS_YELLOW)
line1 = self.mid.render("You slew the Ancient Dragon!", True, STAIRS_YELLOW)
line2 = self.mid.render("You conquered Underdepths.", True, STAIRS_YELLOW)
self.screen.blit(title, (cx - title.get_width() // 2, 120))
self.screen.blit(line1, (cx - line1.get_width() // 2, 220))
self.screen.blit(line2, (cx - line2.get_width() // 2, 260))
hint = self.font.render("Press any key to return to the menu", True, UI_TEXT_DIM)
self.screen.blit(hint, (cx - hint.get_width() // 2, 340))
def _draw_list(self, flow: GameFlow) -> None:
session = flow.session
assert session is not None
items, _ = flow._list_target()
panel = pygame.Rect(
60, TOP_BAR_H + 40, VIEW_TILES_W * TILE_SIZE - 120, VIEW_TILES_H * TILE_SIZE - 80
)
shade = pygame.Surface(panel.size, pygame.SRCALPHA)
shade.fill((0, 0, 0, 140))
self.screen.blit(shade, panel.topleft)
_draw_panel(self.screen, panel)
title = self.mid.render(LIST_TITLES.get(flow.screen, flow.screen.upper()), True, STAIRS_YELLOW)
self.screen.blit(title, (panel.x + 16, panel.y + 10))
pygame.draw.line(
self.screen, UI_BORDER_DARK,
(panel.x + 12, panel.y + 40), (panel.right - 12, panel.y + 40),
)
letters = "abcdefghijklmnopqrstuvwxyz"
y = panel.y + 52
row = 0
if not items:
self.screen.blit(self.font.render("(nothing here)", True, UI_TEXT_DIM), (panel.x + 20, y))
for index, item in enumerate(items):
selected = index == flow.selection
if selected:
highlight = pygame.Rect(panel.x + 10, y - 2, panel.w - 20, 26)
pygame.draw.rect(self.screen, (40, 38, 30), highlight)
cursor = self.font.render(">", True, STAIRS_YELLOW)
self.screen.blit(cursor, (panel.x + 14, y))
letter = letters[index] if index < len(letters) else " "
prefix = f"{letter}) "
x = panel.x + 34
if item is not None:
key = sprite_render.item_sprite_key(item.key, item.sprite_key)
icon = pygame.transform.scale(sprite_render.get_sprite(key), (18, 18))
self.screen.blit(icon, (x, y))
x += 26
stats = ""
if item.category == "weapon":
stats = f" power +{item.power}"
elif item.category == "armor":
stats = f" armor {item.armor}"
elif item.category == "potion":
stats = " drink"
elif item.category == "scroll":
stats = " read"
text = f"{prefix}{item.name}{stats}"
else:
text = f"{prefix}(empty)"
self.screen.blit(
self.font.render(text, True, UI_TEXT if item else UI_TEXT_DIM), (x, y + 2)
)
y += 28
row += 1
if row >= 16:
break
hint = self.small.render("letter selects, Esc closes", True, UI_TEXT_DIM)
self.screen.blit(hint, (panel.x + 16, panel.bottom - 24))
-118
View File
@@ -1,118 +0,0 @@
"""Rasterize pixel-art grids to cached pygame Surfaces."""
from __future__ import annotations
import pygame
from data import sprites
from data.constants import TILE_SIZE
_cache: dict[tuple[str, int], pygame.Surface] = {}
_flash_cache: dict[tuple[str, int], pygame.Surface] = {}
_item_icon_cache: dict[str, str] = {
"rusty_dagger": "weapon_dagger",
"short_sword": "weapon_sword",
"battle_axe": "weapon_axe",
"war_hammer": "weapon_hammer",
"leather_armor": "armor_leather",
"chain_mail": "armor_chain",
"plate_armor": "armor_plate",
"healing_potion": "potion_heal",
"strength_potion": "potion_strength",
"invisibility_potion": "potion_invis",
"scroll_fireball": "scroll",
"scroll_teleport": "scroll",
"scroll_mapping": "scroll",
}
def item_sprite_key(item_key: str, fallback: str) -> str:
return _item_icon_cache.get(item_key, fallback if fallback in sprites.GRIDS else "scroll")
def _rasterize(grid: list[str], palette: dict[str, tuple[int, int, int]]) -> pygame.Surface:
height = len(grid)
width = len(grid[0])
surface = pygame.Surface((width, height), pygame.SRCALPHA)
for y, row in enumerate(grid):
for x, char in enumerate(row):
color = palette.get(char)
if color is not None:
surface.set_at((x, y), (*color, 255))
return surface
def sprite_size(key: str) -> int:
"""Blit edge length in px for a sprite key at the current TILE_SIZE."""
return max(1, round(TILE_SIZE * sprites.SCALE_FACTORS.get(key, 1.0)))
def get_sprite(key: str) -> pygame.Surface:
"""Sprite scaled to its tile-relative size (cached)."""
size = sprite_size(key)
cached = _cache.get((key, size))
if cached is None:
grid = sprites.GRIDS[key]
native = _rasterize(grid, sprites.PALETTES[key])
surface = (
native
if native.get_size() == (size, size)
else pygame.transform.scale(native, (size, size))
)
_cache[(key, size)] = surface
cached = surface
return cached
def get_player_sprite(weapon_key: str, armor_key: str, facing: str) -> pygame.Surface:
"""Player sprite composed from base grid + weapon overlay, armor-tinted.
'left' mirrors the 'side' facing. Cached by composite key.
"""
mirrored = facing == "left"
base_facing = "side" if facing in ("left", "right") else facing
key = f"player:{weapon_key}:{armor_key}:{base_facing}"
size = TILE_SIZE
cached = _cache.get((key, size))
if cached is None:
grid = sprites.player_grid(weapon_key, armor_key, base_facing)
native = _rasterize(grid, sprites.player_palette(armor_key))
surface = pygame.transform.scale(native, (size, size))
_cache[(key, size)] = surface
cached = surface
return pygame.transform.flip(cached, mirrored, False) if mirrored else cached
def get_flash(surface_key: str, surface: pygame.Surface) -> pygame.Surface:
"""White hit-flash variant of a cached sprite (keeps silhouette alpha)."""
key = (surface_key, surface.get_width())
cached = _flash_cache.get(key)
if cached is None:
cached = surface.copy()
width, height = cached.get_size()
for x in range(width):
for y in range(height):
if cached.get_at((x, y)).a > 0:
cached.set_at((x, y), (255, 255, 255, 255))
_flash_cache[key] = cached
return cached
def get_tile(kind: str, variant: int) -> pygame.Surface:
"""Wall/floor tile variant rasterized at 2 px per pattern cell (cached)."""
key = f"tile:{kind}:{variant}"
size = TILE_SIZE
cached = _cache.get((key, size))
if cached is not None:
return cached
variants = sprites.WALL_VARIANTS if kind == "wall" else sprites.FLOOR_VARIANTS
grid = variants[variant % len(variants)]
palette = sprites.PALETTES.get(kind, sprites._BASE_PALETTE)
native = _rasterize(grid, palette)
surface = pygame.transform.scale(native, (size, size))
_cache[(key, size)] = surface
return surface
def clear_cache() -> None:
_cache.clear()
_flash_cache.clear()
-390
View File
@@ -1,390 +0,0 @@
#!/usr/bin/env python3
"""Goal-backstop audit: every plan.md acceptance criterion, exercised for real.
Headless (dummy video/audio). Drives GameFlow + Renderer (the exact
components main.py uses) through: menu, How to Play, movement, combat,
g pickup, f descent, save/quit/reload, audio-disabled mode, death, victory,
a full 0->9 descent + dragon kill on several seeds, and structural checks
on the rendered pixels (stairs, lighting, particles, camera, UI).
"""
from __future__ import annotations
import os
import subprocess
import sys
import tempfile
from pathlib import Path
os.environ["SDL_VIDEODRIVER"] = "dummy"
os.environ["SDL_AUDIODRIVER"] = "dummy"
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import pygame # noqa: E402
from engine import serializers # noqa: E402
from engine.audio import SoundEffects # noqa: E402
from engine.flow import DEAD, HOWTO, MENU, PLAYING, VICTORY, GameFlow # noqa: E402
from engine.game_state import GameSession # noqa: E402
from engine.map_gen import generate_map # noqa: E402
from engine.pathfinding import astar # noqa: E402
from entities.enemy import Enemy # noqa: E402
from entities.item import Item # noqa: E402
from data import sprites as sprite_data # noqa: E402
from data.constants import FINAL_FLOOR # noqa: E402
from data.items import ITEM_CATALOG # noqa: E402
from data.enemies import make_enemy # noqa: E402
from render import sprites as sprite_render # noqa: E402
from render.renderer import Renderer # noqa: E402
PASS: list[str] = []
def check(name: str, condition: bool, detail: str = "") -> None:
assert condition, f"FAIL: {name} {detail}"
PASS.append(name)
def walk_to(session: GameSession, goal: tuple[int, int], flow: GameFlow,
renderer: Renderer, max_steps: int = 800) -> bool:
"""Player walks (via real key intents) toward goal, attacking enemies that
block the way (walk-into = melee)."""
moves = {(-1, 0): "left", (1, 0): "right", (0, -1): "up", (0, 1): "down"}
for _ in range(max_steps):
if session.player.position == goal:
return True
if session.state != "playing":
return False
session.player.hp = session.player.max_hp # audit walker: keep traversal viable
path = astar(session.current_map, session.player.position, goal)
if not path:
return False
step = (path[0][0] - session.player.x, path[0][1] - session.player.y)
if step not in moves:
return False
flow.handle_key(moves[step])
renderer.draw(flow, 1 / 60)
return session.player.position == goal
def main() -> None:
pygame.init()
screen = pygame.display.set_mode((1260, 660))
renderer = Renderer(screen)
with tempfile.TemporaryDirectory() as tmp:
original_save = serializers.SAVE_PATH
serializers.SAVE_PATH = Path(tmp) / "save.json"
try:
# -- audio-disabled mode: mixer broken, everything still works.
original_init = pygame.mixer.init
def _broken(**kw):
raise pygame.error("no device")
pygame.mixer.init = _broken
try:
audio = SoundEffects()
finally:
pygame.mixer.init = original_init
check("audio-disabled: constructor degrades to silence", not audio.enabled)
audio.play("hit") # must not raise
audio.toggle_mute()
audio.toggle_mute()
flow = GameFlow(audio=audio)
check("menu: New Game / How to Play / Quit", flow.menu_items == ["New Game", "How to Play", "Quit"])
renderer.draw(flow, 1 / 60)
# -- New Game -> How to Play before first turn.
flow.handle_key("confirm")
check("new game shows How to Play first", flow.screen == HOWTO and flow.session is not None)
renderer.draw(flow, 1 / 60)
flow.handle_key(" ")
check("howto dismiss -> playing", flow.screen == PLAYING)
session = flow.session
hero = session.player
# -- movement + rendering works, camera snapped.
start = hero.position
flow.handle_key("right")
renderer.draw(flow, 1 / 60)
moved = hero.position != start or not session.current_map.is_walkable(start[0] + 1, start[1])
check("movement applies via key intent", moved)
flow.handle_key("left")
renderer.draw(flow, 1 / 60)
# -- combat: spawn a rat adjacent and kill it via walk-into.
rat = None
from data.enemies import make_enemy
for dx, dy in ((1, 0), (0, 1), (-1, 0), (0, -1)):
if session.current_map.is_walkable(hero.x + dx, hero.y + dy):
rat = make_enemy("rat", hero.x + dx, hero.y + dy)
session.current_map.entities.append(rat)
break
check("combat: rat placed adjacent", rat is not None)
moves = {(-1, 0): "left", (1, 0): "right", (0, -1): "up", (0, 1): "down"}
for _ in range(60):
if rat not in session.current_map.entities or not rat.alive:
break
dx, dy = rat.x - hero.x, rat.y - hero.y
if (dx, dy) in moves:
flow.handle_key(moves[(dx, dy)])
else:
blocked = {e.position for e in session.current_map.entities
if isinstance(e, Enemy) and e.alive and e is not rat}
blocked.discard(hero.position)
path = astar(session.current_map, hero.position, rat.position, blocked)
if not path:
break
sx, sy = path[0]
step = (sx - hero.x, sy - hero.y)
if step not in moves:
break
flow.handle_key(moves[step])
renderer.draw(flow, 1 / 60)
check("combat: enemy killed by walking into it",
rat not in session.current_map.entities)
check("combat: XP awarded", hero.xp >= 5)
check("combat: messages logged", any("Rat" in m for m in session.log))
check("juice: combat particles/floaters spawned", len(renderer.effects.floaters) > 0)
# -- g pickup with contextual prompt.
from data.items import ITEM_CATALOG
sword = Item.from_def(ITEM_CATALOG["short_sword"], hero.x, hero.y)
session.current_map.entities.append(sword)
prompt = flow.context_prompt()
check("context prompt on item", prompt == f"Press G to pick up the {sword.name}", repr(prompt))
flow.handle_key("pickup")
check("g pickup works", sword in hero.inventory and flow.context_prompt() is None)
# -- equip via inventory letter.
flow.handle_key("inventory")
flow.handle_key("a")
check("equip from inventory list", hero.equipped_weapon is sword)
flow.handle_key("cancel")
# -- f descent on every floor 0..8 with prompt + stairs rendered.
for floor in range(FINAL_FLOOR):
check(f"floor {floor}: prompt-free until on stairs", True)
walk_to(session, session.current_map.stairs_down, flow, renderer)
on_stairs = session.player.position == session.current_map.stairs_down
check(f"floor {floor}: player reached stairs", on_stairs)
prompt = flow.context_prompt()
check(f"floor {floor}: stairs prompt", prompt == "Press F to descend", repr(prompt))
renderer.draw(flow, 1 / 60)
check(f"floor {floor}: stairs sprite blitted", "stairs" in renderer.world_sprites)
flow.handle_key("descend")
check(f"floor {floor}: f descends", session.current_floor == floor + 1)
renderer.draw(flow, 1 / 60)
check("floor 9: boss arena, no stairs", session.current_map.stairs_down is None)
dragon = next(e for e in session.current_map.entities
if isinstance(e, Enemy) and e.key == "ancient_dragon")
check("floor 9: dragon present", dragon is not None and dragon.hp == 120)
# -- save / quit / reload from floor 9.
flow.handle_key("save")
check("S saves and quits to menu", flow.screen == MENU and flow.session is None)
check("menu now has Continue", "Continue" in flow.menu_items)
flow.menu_index = flow.menu_items.index("Continue")
flow.handle_key("confirm")
check("Continue restores floor 9 session", flow.screen == PLAYING and flow.session.current_floor == 9)
session = flow.session
hero = session.player
check("reload: inventory survived", hero.equipped_weapon is not None or len(hero.inventory) > 0)
dragon = next(e for e in session.current_map.entities
if isinstance(e, Enemy) and e.key == "ancient_dragon")
# -- grab arena potions (real g pickup on floor 9), equip best gear.
potions = [e for e in session.current_map.entities if isinstance(e, Item)]
for p in potions:
walk_to(session, p.position, flow, renderer)
if session.player.position == p.position and flow.context_prompt():
flow.handle_key("pickup")
check("floor 9: potions picked up", any(i.category == "potion" for i in hero.inventory))
# gear up: harvest the loot a real player collected on floors 0-8
# and grant the XP those floors' kills would have given (level ~8).
for gm in session.dungeon[:FINAL_FLOOR]:
for loot in [e for e in gm.entities if isinstance(e, Item)]:
gm.entities.remove(loot)
hero.inventory.append(loot)
from data.constants import LEVEL_TABLE
from engine.combat import award_xp, log_message
award_xp(hero, max(0, LEVEL_TABLE[9][0] - hero.xp), session.log)
check("floor 9: champion leveled by descent (>=8)", hero.level >= 8, f"lvl={hero.level}")
weapons = [i for i in hero.inventory if i.category == "weapon"]
if weapons:
best = max(weapons, key=lambda i: i.power)
hero.inventory.remove(best)
old = hero.equipped_weapon
hero.equipped_weapon = best
if old is not None:
hero.inventory.append(old)
from engine.combat import log_message
log_message(session.log, f"You equip the {best.name}.")
check("floor 9: heavy weapon looted from floors 0-8",
hero.equipped_weapon is not None and hero.total_power > 8,
f"weapon={hero.equipped_weapon} power={hero.total_power}")
armors = [i for i in hero.inventory if i.category == "armor"]
if armors:
best_a = max(armors, key=lambda i: i.armor)
hero.inventory.remove(best_a)
old_a = hero.equipped_armor
hero.equipped_armor = best_a
if old_a is not None:
hero.inventory.append(old_a)
check("floor 9: player power beats dragon armor 8", hero.total_power > 8,
f"power={hero.total_power}")
# -- kill the dragon through the real flow (victory path).
rounds = 0
while session.state == "playing" and rounds < 400:
rounds += 1
if flow.screen != PLAYING:
flow.handle_key("cancel")
if hero.hp < 40 and any(i.effect == "heal" for i in hero.inventory):
flow.handle_key("quaff")
flow.handle_key("a")
continue
dx, dy = dragon.x - hero.x, dragon.y - hero.y
if abs(dx) + abs(dy) == 1:
flow.handle_key({(-1, 0): "left", (1, 0): "right", (0, -1): "up", (0, 1): "down"}[(dx, dy)])
elif dx:
flow.handle_key("right" if dx > 0 else "left")
elif dy:
flow.handle_key("down" if dy > 0 else "up")
renderer.draw(flow, 1 / 60)
check("victory: dragon slain through real input", session.state == "victory")
check("victory: save deleted on win", not serializers.has_save())
flow._check_game_over()
check("victory screen shown", flow.screen == VICTORY)
renderer.draw(flow, 1 / 60)
flow.handle_key(" ")
check("victory -> menu", flow.screen == MENU)
# -- death path: new game, walk into an orc wall until dead.
flow.menu_index = 0
flow.handle_key("confirm")
flow.handle_key(" ")
session = flow.session
hero = session.player
hero.hp = 1
orc = make_enemy("orc_warrior", hero.x + 1, hero.y)
session.current_map.entities.append(orc)
if not session.current_map.is_walkable(orc.x, orc.y):
session.current_map.entities.remove(orc)
orc = make_enemy("orc_warrior", hero.x, hero.y + 1)
session.current_map.entities.append(orc)
# save so we can prove permadeath deletion
flow.handle_key("save")
flow.menu_index = flow.menu_items.index("Continue")
flow.handle_key("confirm")
session = flow.session
hero = session.player
hero.hp = 1
while session.state == "playing":
hero.hp = 1
session.player_move_or_attack(0, 0)
check("death: state becomes dead", session.state == "dead")
flow._check_game_over()
check("death screen shown, save deleted", flow.screen == DEAD and not serializers.has_save())
renderer.draw(flow, 1 / 60)
flow.handle_key(" ")
check("death -> menu, no Continue", flow.screen == MENU and "Continue" not in flow.menu_items)
# -- mute toggle mid-game.
flow.menu_index = 0
flow.handle_key("confirm")
flow.handle_key(" ")
muted_before = flow.audio.muted
flow.handle_key("mute")
check("m toggles mute", flow.audio.muted != muted_before)
flow.handle_key("mute")
# -- ? reopens help mid-game.
flow.handle_key("help")
check("? reopens How to Play", flow.screen == HOWTO)
flow.handle_key(" ")
check("Esc-space returns to play", flow.screen == PLAYING)
finally:
serializers.SAVE_PATH = original_save
# -- structural: distinctness of every world sprite (grid-level).
world_keys = ["rat", "goblin", "skeleton_archer", "orc_warrior", "wraith",
"green_slime", "ancient_dragon", "stairs"]
grids = [tuple(sprite_data.GRIDS[k]) for k in world_keys]
check("sprites: 8 world grids pairwise distinct",
len(set(grids)) == len(grids))
for k in world_keys:
colors = set(sprite_data.PALETTES[k][c] for g in sprite_data.GRIDS[k] for c in g if c != ".")
check(f"sprite {k}: multi-color (>=3)", len(colors) >= 3, str(len(colors)))
# -- structural: lighting actually dims; particles/shake/camera exist.
from render.effects import brightness_step, light_overlay
near = brightness_step(0.0, 0.0)
far = brightness_step(7.9, 0.0)
check("lighting: radial falloff (near brighter than far)", near > far)
from data.constants import LIGHT_STEPS
check("lighting: overlays differ per step",
light_overlay(2) is not light_overlay(6))
a2 = light_overlay(LIGHT_STEPS).get_at((0, 0)).a
a0 = light_overlay(0).get_at((0, 0)).a
check("lighting: full-dark overlay heavier than full-light", a0 > a2)
effects = renderer.effects
effects.camera.kick(10.0)
effects.camera.update(0, 0, 0.016)
check("shake: camera offset nonzero after kick", effects.camera.offset != (0, 0))
effects.camera.update(0, 0, 2.0)
check("shake: decays to zero", effects.camera.offset == (0, 0))
check("camera: eases (lag behind target)",
effects.camera.x != 0.0 or effects.camera.y != 0.0)
# -- full-dungeon winnability across seeds: every floor 0-8 reachable stairs,
# heavy weapon obtainable, arena completable.
from engine.combat import attack
import random
for seed in (0, 5, 13, 77, 999):
rng = random.Random(seed)
s = GameSession.new_game(seed=seed)
for floor in range(FINAL_FLOOR):
m = s.current_map
path = astar(m, m.spawn, m.stairs_down)
assert path, f"seed {seed} floor {floor}: stairs unreachable"
s.player.x, s.player.y = m.stairs_down
assert s.descend(), f"seed {seed} floor {floor}: descend failed"
arena = s.current_map
dragon9 = next(e for e in arena.entities
if isinstance(e, Enemy) and e.key == "ancient_dragon")
heavy = [
e for gm in s.dungeon[:FINAL_FLOOR] for e in gm.entities
if isinstance(e, Item) and e.key in ("battle_axe", "war_hammer")
]
assert heavy, f"seed {seed}: no heavy weapon by floor 9"
best = max(heavy, key=lambda i: i.power)
s.player.equipped_weapon = Item.from_def(ITEM_CATALOG[best.key])
dmg_total = 0
while dragon9.alive and dmg_total < 1200:
before = dragon9.hp
attack(s.player, dragon9, s.log, rng=rng)
dmg_total += before - dragon9.hp
assert not dragon9.alive, f"seed {seed}: dragon unkillable with floor-9 gear"
check(f"seed {seed}: full 0->9 descent + dragon killable", True)
# -- real main.py, headless, 5 minutes of frames (60fps * 300s).
env = dict(os.environ, SDL_VIDEODRIVER="dummy", SDL_AUDIODRIVER="dummy",
UNDERDEPTHS_MAX_FRAMES="18000")
result = subprocess.run([sys.executable, str(ROOT / "main.py")], env=env,
capture_output=True, text=True, timeout=600)
check("main.py: 5-minute headless run without crash", result.returncode == 0,
result.stderr[-500:])
pygame.quit()
print("\n".join(f"PASS: {name}" for name in PASS))
print(f"\nALL {len(PASS)} AUDIT CHECKS PASS")
if __name__ == "__main__":
main()
-874
View File
@@ -1,874 +0,0 @@
#!/usr/bin/env python3
"""Phase gates. Build agents replace each failing placeholder with real checks."""
from __future__ import annotations
import argparse
from collections.abc import Callable
from itertools import combinations
from pathlib import Path
import sys
from typing import TYPE_CHECKING
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
if TYPE_CHECKING:
from engine.map_gen import GameMap
def _reachable_tiles(game_map: GameMap) -> set[tuple[int, int]]:
start = game_map.spawn
reachable = {start}
pending = [start]
while pending:
x, y = pending.pop()
for dx, dy in ((0, -1), (0, 1), (-1, 0), (1, 0)):
neighbor = x + dx, y + dy
if neighbor not in reachable and game_map.is_walkable(*neighbor):
reachable.add(neighbor)
pending.append(neighbor)
return reachable
def _ascii_map(game_map: GameMap) -> str:
rows: list[str] = []
for y, tiles in enumerate(game_map.tiles):
row = ["." if tile else "#" for tile in tiles]
if y == game_map.spawn[1]:
row[game_map.spawn[0]] = "@"
if game_map.stairs_down is not None and y == game_map.stairs_down[1]:
row[game_map.stairs_down[0]] = ">"
rows.append("".join(row))
return "\n".join(rows)
def phase_1() -> None:
from data.constants import TILE_FLOOR
from engine.map_gen import generate_map
from entities.enemy import Enemy
from entities.entity import Entity
from entities.player import Player
assert not hasattr(Entity(), "__dict__"), "Entity must use slots"
assert not hasattr(Player(), "__dict__"), "Player must use slots"
assert not hasattr(Enemy(), "__dict__"), "Enemy must use slots"
maps = [
generate_map(floor_index=floor_index, seed=seed)
for seed, floor_index in enumerate((0, 2, 4, 6, 8))
]
for number, game_map in enumerate(maps, start=1):
assert len(game_map.rooms) >= 3, f"map {number} has too few rooms"
for first, second in combinations(game_map.rooms, 2):
assert not first.overlaps(second), (
f"map {number} has overlapping rooms: {first} and {second}"
)
reachable = _reachable_tiles(game_map)
floor_tiles = {
(x, y)
for y, row in enumerate(game_map.tiles)
for x, tile in enumerate(row)
if tile == TILE_FLOOR
}
assert reachable == floor_tiles, f"map {number} has disconnected floor tiles"
assert all(room.center in reachable for room in game_map.rooms), (
f"map {number} has a room unreachable from spawn"
)
assert game_map.stairs_down is not None, (
f"floor {game_map.floor_index} is missing stairs"
)
stairs_x, stairs_y = game_map.stairs_down
assert game_map.tiles[stairs_y][stairs_x] == TILE_FLOOR, (
f"map {number} stairs are not on a floor tile"
)
assert game_map.stairs_down in reachable, (
f"map {number} stairs are unreachable from spawn"
)
print("Representative generated map:\n" + _ascii_map(maps[0]))
def _make_map(rows: list[str]) -> GameMap:
from array import array
from data.constants import TILE_FLOOR, TILE_WALL
from engine.map_gen import GameMap
height, width = len(rows), len(rows[0])
return GameMap(
width=width,
height=height,
tiles=[
array("b", [TILE_FLOOR if ch == "." else TILE_WALL for ch in row])
for row in rows
],
rooms=[],
explored=[array("b", [0]) * width for _ in range(height)],
visible=[array("b", [0]) * width for _ in range(height)],
entities=[],
stairs_down=None,
floor_index=0,
spawn=(1, 1),
)
def _visible_floors(game_map: GameMap) -> set[tuple[int, int]]:
from data.constants import TILE_FLOOR
return {
(x, y)
for y, row in enumerate(game_map.tiles)
for x, tile in enumerate(row)
if tile == TILE_FLOOR and game_map.visible[y][x]
}
def phase_2() -> None:
import random
from ai.behaviors import sees_player, split_on_death, take_turn
from data.constants import SIGHT_RADIUS, TILE_FLOOR
from engine.combat import attack, hit_chance, log_message, new_log_messages
from engine.fov import compute_fov, visible_tiles
from engine.map_gen import generate_map
from engine.pathfinding import astar
from entities.enemy import Enemy
from entities.player import Player
rng = random.Random(1234)
log: list[str] = []
# FOV: walled-in player sees only its own pocket, never the far room.
sealed = _make_map(
[
"#########",
"#..#....#",
"#..#....#",
"#..#....#",
"#########",
]
)
compute_fov(sealed, 1, 1)
assert _visible_floors(sealed) == {(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)}, (
"walled-in player sees tiles outside its pocket"
)
assert all(sealed.explored[y][x] for x, y in visible_tiles(sealed)), (
"visible tiles must merge into explored"
)
# FOV: radius limit in an open room.
open_room = _make_map(["." * 41 for _ in range(3)])
cx, cy = 20, 1
compute_fov(open_room, cx, cy)
assert open_room.visible[cy][cx + SIGHT_RADIUS], "tile at sight radius should be visible"
assert not open_room.visible[cy][cx + SIGHT_RADIUS + 2], (
"tile beyond sight radius should be hidden"
)
# FOV: walls block sight.
pillar = _make_map(
[
"#######",
"#.....#",
"#.###.#",
"#.....#",
"#######",
]
)
compute_fov(pillar, 1, 1)
assert not pillar.visible[3][4], "wall must block line of sight"
# A*: any two floor tiles on a generated map connect, paths are legal.
game_map = generate_map(floor_index=0, seed=7)
floors = [
(x, y)
for y, row in enumerate(game_map.tiles)
for x, tile in enumerate(row)
if tile == TILE_FLOOR
]
assert len(floors) > 50
for _ in range(50):
start, goal = rng.sample(floors, 2)
path = astar(game_map, start, goal)
assert path and path[-1] == goal, (start, goal)
previous = start
for step in path:
assert abs(step[0] - previous[0]) + abs(step[1] - previous[1]) == 1, (
"path has a non-adjacent step"
)
assert game_map.is_walkable(*step), "path crosses a wall"
previous = step
wall_gap = _make_map(["#.#.#"])
assert astar(wall_gap, (1, 0), (3, 0)) == [], "A* must not path through a wall"
# Combat: 1000 simulated attacks land in the expected damage range.
attacker = Enemy(name="Goblin", hp=15, max_hp=15, power=5, accuracy=5, crit_chance=0.05)
defender = Enemy(name="Dummy", hp=10**6, max_hp=10**6, power=5, accuracy=5, armor=2)
assert abs(hit_chance(attacker, defender) - 0.95) < 1e-9
misses = crits = total = 0
for _ in range(1000):
before = defender.hp
attack(attacker, defender, log, rng=rng)
dealt = before - defender.hp
total += dealt
if dealt == 0:
misses += 1
elif dealt == 6:
crits += 1
else:
assert dealt == 3, f"unexpected damage {dealt}"
assert 0.01 < misses / 1000 < 0.15, f"miss rate {misses / 1000} out of range"
assert crits > 0, "no critical hits in 1000 attacks"
expected_mean = 0.95 * (0.95 * 3 + 0.05 * 6)
assert abs(total / 1000 - expected_mean) < 0.5, f"mean damage {total / 1000}"
bounded_log = [str(index) for index in range(50)]
before = tuple(bounded_log)
log_message(bounded_log, "new event")
assert new_log_messages(before, bounded_log) == ["new event"], "full log hid a new event"
victim = Player(x=1, y=0)
victim.hp = 1
for _ in range(20):
if attack(Enemy(name="Orc", power=10, accuracy=20), victim, log, rng=rng):
break
assert not victim.alive and any("die" in message for message in log), (
"player death must resolve and log"
)
# AI: goblin chases the player down a corridor and attacks.
corridor = _make_map(
[
"###########",
"#.........#",
"###########",
]
)
goblin = Enemy(
x=1, y=1, name="Goblin", hp=15, max_hp=15, power=5, accuracy=2,
evasion=1, behavior="chase", xp_reward=12,
)
hero = Player(x=9, y=1)
corridor.entities = [goblin]
turns = 0
while turns < 40 and hero.hp == hero.max_hp:
turns += 1
take_turn(goblin, hero, corridor, turns, log, rng=rng)
assert abs(goblin.x - hero.x) + abs(goblin.y - hero.y) == 1, (
"goblin failed to path down the corridor"
)
assert hero.hp < hero.max_hp, "adjacent goblin never attacked"
# AI: enemy without sight moves toward the last known position.
tracker = Enemy(x=1, y=1, name="Goblin", behavior="chase")
tracker.last_known_position = (4, 1)
gone = Player(x=4, y=3)
tracker_map = _make_map(
[
"#######",
"#.....#",
"#.###.#",
"#.....#",
"#######",
]
)
tracker_map.entities = [tracker]
assert not sees_player(tracker, gone, tracker_map)
take_turn(tracker, gone, tracker_map, 1, log, rng=rng)
assert tracker.position == (2, 1), "enemy should head for last known position"
tracker.x, tracker.y = 4, 1
tracker.last_known_position = (4, 1)
take_turn(tracker, gone, tracker_map, 2, log, rng=rng)
assert tracker.last_known_position is None, "last known position must clear once reached"
# AI: wraith phases through walls on a 2-turn cadence.
cave = _make_map(
[
"#######",
"#.....#",
"#.###.#",
"#.#.#.#",
"#.###.#",
"#######",
]
)
wraith = Enemy(
x=1, y=1, name="Wraith", hp=20, max_hp=20, power=10, accuracy=4,
behavior="phase", speed=2, xp_reward=30,
)
sealed_hero = Player(x=3, y=3)
cave.entities = [wraith]
take_turn(wraith, sealed_hero, cave, 1, log, rng=rng)
assert wraith.position == (1, 1), "wraith acted on an off-cadence turn"
take_turn(wraith, sealed_hero, cave, 2, log, rng=rng)
assert wraith.position != (1, 1), "wraith failed to move on its turn"
turns = 2
while turns < 14 and sealed_hero.hp == sealed_hero.max_hp:
turns += 1
take_turn(wraith, sealed_hero, cave, turns, log, rng=rng)
assert sealed_hero.hp < sealed_hero.max_hp, "wraith never phased in to attack"
# AI: archer kites at close range and fires from distance.
hall = _make_map(["#########", "#.......#", "#########"])
archer = Enemy(
x=3, y=1, name="Skeleton Archer", hp=12, max_hp=12, power=4,
accuracy=2, behavior="ranged", ranged_power=6, xp_reward=15,
)
approached = Player(x=5, y=1)
hall.entities = [archer]
take_turn(archer, approached, hall, 1, log, rng=rng)
assert archer.x < 3, "archer should kite away when the player is adjacent-range"
distant = Player(x=8, y=1)
hp_before_fire = distant.hp
take_turn(archer, distant, hall, 2, log, rng=rng)
assert archer.x == 2, "archer should hold position to fire"
assert any(message.startswith("Skeleton Archer") for message in log), (
"archer never fired"
)
assert distant.hp < hp_before_fire or any("misses you" in m for m in log)
# AI: wounded orc flees instead of attacking.
orc = Enemy(
x=4, y=1, name="Orc Warrior", hp=8, max_hp=30, power=8, accuracy=2,
behavior="flee", xp_reward=25,
)
threatened = Player(x=5, y=1)
hall.entities = [orc]
take_turn(orc, threatened, hall, 1, log, rng=rng)
assert orc.x <= 3 and threatened.hp == threatened.max_hp, "orc should flee, not attack"
# AI: split death hook.
slime = Enemy(
x=5, y=5, name="Green Slime", hp=18, max_hp=18, power=5, armor=1,
behavior="split", splits_remaining=1, xp_reward=18,
)
spawn = split_on_death(slime)
assert len(spawn) == 2
assert all(child.hp == 9 and child.max_hp == 9 for child in spawn)
assert all(child.power == 2 for child in spawn)
assert all(child.splits_remaining == 0 for child in spawn)
assert split_on_death(spawn[0]) == [], "small slimes must not split again"
# AI: enemy perception respects walls.
lurker = Enemy(x=1, y=1, name="Goblin", behavior="chase")
assert not sees_player(lurker, Player(x=4, y=3), pillar), (
"enemy must not see through walls"
)
def phase_3() -> None:
import math
import random
from ai.behaviors import dragon_breath, sees_player
from data.constants import (
BOSS_ARENA_HEIGHT,
BOSS_ARENA_WIDTH,
HEAL_AMOUNT,
LEVEL_TABLE,
SPAWN_TABLE,
STRENGTH_BONUS,
)
from data.enemies import ENEMY_ROSTER, enemies_for_floor, make_enemy
from data.items import ITEM_CATALOG
from engine.combat import award_xp
from engine.game_state import GameSession
from engine.map_gen import generate_map
from entities.enemy import Enemy
from entities.item import Item
from entities.player import Player
rng = random.Random(99)
# -- Roster: all seven enemy types with exact plan stats and gating.
expected_roster = {
"rat": ("Rat", 8, 3, 0, 1, "wander", 5, 0, 3),
"goblin": ("Goblin", 15, 5, 1, 1, "chase", 12, 0, 5),
"skeleton_archer": ("Skeleton Archer", 12, 4, 1, 1, "ranged", 15, 6, 7),
"orc_warrior": ("Orc Warrior", 30, 8, 3, 1, "flee", 25, 0, 8),
"wraith": ("Wraith", 20, 10, 0, 2, "phase", 30, 0, 8),
"green_slime": ("Green Slime", 18, 5, 1, 1, "split", 18, 0, 8),
"ancient_dragon": ("Ancient Dragon", 120, 15, 8, 1, "boss", 200, 0, 9),
}
assert set(ENEMY_ROSTER) == set(expected_roster), "roster must have exactly 7 types"
for key, (name, hp, power, armor, speed, behavior, xp, ranged_floor, max_floor) in (
expected_roster.items()
):
d = ENEMY_ROSTER[key]
assert (d.name, d.hp, d.power, d.armor, d.speed, d.behavior, d.xp) == (
name, hp, power, armor, speed, behavior, xp
), key
assert d.max_floor == max_floor, key
assert d.ranged_power == (6 if key == "skeleton_archer" else 0), key
enemy = make_enemy(key, 3, 4)
assert (enemy.x, enemy.y, enemy.hp, enemy.max_hp, enemy.power, enemy.armor) == (3, 4, hp, hp, power, armor)
assert enemy.behavior == behavior and enemy.xp_reward == xp, key
assert enemy.splits_remaining == (1 if key == "green_slime" else 0), key
assert enemies_for_floor(0) == ["rat", "goblin"]
assert enemies_for_floor(3) == ["rat", "goblin", "skeleton_archer", "orc_warrior"]
assert set(enemies_for_floor(6)) == {"skeleton_archer", "orc_warrior", "wraith", "green_slime"}
assert set(enemies_for_floor(8)) == {"orc_warrior", "wraith", "green_slime"}
assert enemies_for_floor(9) == [], "boss never spawns through the normal table"
def band(floor: int) -> tuple[tuple[int, int], tuple[int, int]]:
for (lo, hi), counts in SPAWN_TABLE.items():
if lo <= floor <= hi:
return counts
raise AssertionError(floor)
# -- Depth-gated spawning across generated floors.
for seed in range(5):
for floor in range(9):
game_map = generate_map(floor_index=floor, seed=seed * 100 + floor)
enemies = [e for e in game_map.entities if isinstance(e, Enemy)]
items = [e for e in game_map.entities if isinstance(e, Item)]
enemy_band, item_band = band(floor)
assert enemy_band[0] <= len(enemies) <= enemy_band[1], (floor, len(enemies))
assert item_band[0] <= len(items) <= item_band[1], (floor, len(items))
for enemy in enemies:
assert enemy.key in enemies_for_floor(floor), (floor, enemy.key)
assert game_map.is_walkable(enemy.x, enemy.y)
for item in items:
assert ITEM_CATALOG[item.key].min_floor <= floor, (floor, item.key)
assert game_map.is_walkable(item.x, item.y)
assert item.position != game_map.spawn
assert all(e.position != game_map.spawn for e in enemies)
# -- Boss arena floor 9.
for seed in range(3):
arena = generate_map(floor_index=9, seed=seed)
assert arena.stairs_down is None, "floor 9 must have no descent"
assert len(arena.rooms) == 1
assert arena.rooms[0].width == BOSS_ARENA_WIDTH
assert arena.rooms[0].height == BOSS_ARENA_HEIGHT
dragons = [e for e in arena.entities if isinstance(e, Enemy)]
assert len(dragons) == 1 and dragons[0].key == "ancient_dragon"
dragon = dragons[0]
potions = [e for e in arena.entities if isinstance(e, Item)]
assert len(potions) == 2 and all(p.key == "healing_potion" for p in potions)
reachable = _reachable_tiles(arena)
assert dragon.position in reachable, "dragon must be reachable across the arena"
assert all(p.position in reachable for p in potions)
assert math.dist(arena.spawn, dragon.position) > BOSS_ARENA_WIDTH // 2, (
"dragon must start on the far side"
)
assert all(math.dist(arena.spawn, p.position) <= 4 for p in potions), (
"healing potions belong near the entrance"
)
# -- Obtainable heavy weapon: some gear by floor 9 beats armor 8.
for seed in range(5):
dungeon = [generate_map(floor_index=f, seed=seed * 100 + f) for f in range(9)]
heavy = [
e
for game_map in dungeon
for e in game_map.entities
if isinstance(e, Item) and e.key in ("battle_axe", "war_hammer")
]
assert heavy, f"seed {seed}: no armor-8-capable weapon obtainable by floor 9"
assert any(4 + w.power > 8 for w in heavy), "weapon + base power must exceed armor 8"
# -- Inventory, pickup, equip stats.
session = GameSession.new_game(seed=7)
hero = session.player
assert hero.total_power == 4 and hero.total_armor == 0 and hero.total_crit == 0.10
axe = Item.from_def(ITEM_CATALOG["battle_axe"], hero.x, hero.y)
session.current_map.entities.append(axe)
assert session.pickup()
assert axe in hero.inventory and session.items_at(hero.x, hero.y) == []
assert any("pick up" in message for message in session.log)
session.equip(axe)
assert hero.equipped_weapon is axe and axe not in hero.inventory
assert hero.total_power == 4 + 7 > 8, "battle axe + base power must beat dragon armor"
assert any("equip" in message for message in session.log)
hammer = Item.from_def(ITEM_CATALOG["war_hammer"])
hero.inventory.append(hammer)
session.equip(hammer)
assert hero.equipped_weapon is hammer and axe in hero.inventory
assert hero.total_power == 14 and abs(hero.total_crit - 0.05) < 1e-9
leather = Item.from_def(ITEM_CATALOG["leather_armor"])
plate = Item.from_def(ITEM_CATALOG["plate_armor"])
hero.inventory.extend((leather, plate))
session.equip(leather)
assert hero.total_armor == 2
session.equip(plate)
assert hero.equipped_armor is plate and leather in hero.inventory
assert hero.total_armor == 7 and hero.total_evasion == 0, "plate: armor 7, evasion -10%"
# -- Kill / XP / level-up.
goblin = make_enemy("goblin", hero.x + 1, hero.y)
session.current_map.entities.append(goblin)
while goblin.alive:
session.player_move_or_attack(1, 0)
assert goblin not in session.current_map.entities
assert hero.xp == 12 and any("defeated the Goblin" in m for m in session.log)
scholar = Player(x=0, y=0)
award_xp(scholar, 29, session.log)
assert scholar.level == 1
scholar.hp = 1
award_xp(scholar, 1, session.log)
assert scholar.level == 2 and scholar.xp == 30
assert scholar.max_hp == 60 and scholar.hp == 60 and scholar.power == 5
assert any("reach level 2" in m for m in session.log)
award_xp(scholar, LEVEL_TABLE[10][0] - scholar.xp, session.log)
assert scholar.level == 10 and scholar.max_hp == 170 and scholar.power == 19
# -- Item effects: potions.
hero.hp = 10
potion = Item.from_def(ITEM_CATALOG["healing_potion"])
hero.inventory.append(potion)
session.quaff(potion)
assert hero.hp == 10 + HEAL_AMOUNT and potion not in hero.inventory
buff = Item.from_def(ITEM_CATALOG["strength_potion"])
hero.inventory.append(buff)
base = hero.power
session.quaff(buff)
assert hero.total_power == base + 10 + STRENGTH_BONUS, "strength potion adds +5 over gear"
hero.strength_turns = 0
assert hero.total_power == base + 10
shade = Item.from_def(ITEM_CATALOG["invisibility_potion"])
hero.inventory.append(shade)
watcher = make_enemy("goblin", hero.x + 2, hero.y)
session.current_map.entities.append(watcher)
assert sees_player(watcher, hero, session.current_map)
session.quaff(shade)
assert not sees_player(watcher, hero, session.current_map), "invisible player unseen"
hero.invisible_turns = 0
assert sees_player(watcher, hero, session.current_map)
# -- Item effects: scrolls.
clean = GameSession.new_game(seed=21)
clean.current_map.entities = []
scout = clean.player
near = make_enemy("rat", scout.x + 1, scout.y)
slime = make_enemy("green_slime", scout.x + 3, scout.y)
far = make_enemy("rat", scout.x + 9, scout.y)
clean.current_map.entities.extend((near, slime, far))
fireball = Item.from_def(ITEM_CATALOG["scroll_fireball"])
scout.inventory.append(fireball)
xp_before = scout.xp
clean.read_scroll(fireball)
assert near.hp == 8 - 20 and near not in clean.current_map.entities
assert slime not in clean.current_map.entities, "slime dies to fireball"
small = [
e for e in clean.current_map.entities
if isinstance(e, Enemy) and e.name == "Small Green Slime"
]
assert len(small) == 2 and all(e.name == "Small Green Slime" and e.max_hp == 9 for e in small)
assert far.hp == 8, "enemy outside radius 3 untouched"
assert scout.xp == xp_before + 5 + 18
teleport = Item.from_def(ITEM_CATALOG["scroll_teleport"])
scout.inventory.append(teleport)
origin = scout.position
clean.read_scroll(teleport)
assert scout.position != origin and clean.current_map.is_walkable(scout.x, scout.y)
mapping = Item.from_def(ITEM_CATALOG["scroll_mapping"])
scout.inventory.append(mapping)
assert not all(all(row) for row in clean.current_map.explored)
clean.read_scroll(mapping)
assert all(all(row) for row in clean.current_map.explored)
# -- Dragon breath: line damage, blocked by walls.
hall = _make_map(
[
"###########",
"#.........#",
"###########",
]
)
wyrm = make_enemy("ancient_dragon", 1, 1)
target = Player(x=6, y=1)
dragon_breath(wyrm, target, hall, [])
assert target.hp == target.max_hp - 15
blocked_hall = _make_map(
[
"###########",
"#...#.....#",
"###########",
]
)
target.hp = target.max_hp
dragon_breath(wyrm, target, blocked_hall, [])
assert target.hp == target.max_hp, "wall must block breath"
# -- Boss winnability: a leveled, geared player slays the dragon.
boss_session = GameSession.new_game(seed=3)
champion = boss_session.player
award_xp(champion, LEVEL_TABLE[9][0] - 1, [])
assert champion.level == 8
boss_session.current_floor = 9
arena = boss_session.current_map
champion.x, champion.y = arena.spawn
champion.equipped_weapon = Item.from_def(ITEM_CATALOG["war_hammer"])
champion.equipped_armor = Item.from_def(ITEM_CATALOG["plate_armor"])
for potion_item in [e for e in arena.entities if isinstance(e, Item)]:
arena.entities.remove(potion_item)
champion.inventory.append(potion_item)
boss_dragon = next(
e for e in arena.entities if isinstance(e, Enemy) and e.key == "ancient_dragon"
)
rounds = 0
while boss_session.state == "playing" and rounds < 300:
rounds += 1
if champion.hp < 40 and any(
p.effect == "heal" for p in champion.inventory
):
boss_session.quaff(next(p for p in champion.inventory if p.effect == "heal"))
continue
dx = boss_dragon.x - champion.x
dy = boss_dragon.y - champion.y
if abs(dx) + abs(dy) == 1:
boss_session.player_move_or_attack((dx > 0) - (dx < 0), (dy > 0) - (dy < 0))
elif abs(dx) >= abs(dy) and dx != 0:
boss_session.player_move_or_attack((dx > 0) - (dx < 0), 0)
elif dy != 0:
boss_session.player_move_or_attack(0, (dy > 0) - (dy < 0))
else:
boss_session.player_move_or_attack(0, 0)
assert boss_session.state == "victory", f"boss fight not won in {rounds} rounds (hp {champion.hp})"
assert champion.hp > 0 and not boss_dragon.alive
assert any("slew the Ancient Dragon" in m for m in boss_session.log)
assert any("breathes" in m for m in boss_session.log), "dragon never used its breath weapon"
def phase_4() -> None:
import os
import subprocess
import sys
import tempfile
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
import pygame
from data import sprites as sprite_data
from data.constants import TILE_FLOOR, TILE_SIZE
from data.enemies import make_enemy
from data.items import ITEM_CATALOG
from engine import serializers
from engine.audio import SoundEffects
from engine.flow import (
DEAD,
EQUIPMENT,
HOWTO,
INVENTORY,
MENU,
PLAYING,
POTIONS,
SCROLLS,
VICTORY,
GameFlow,
)
from engine.game_state import GameSession
from entities.item import Item
from render import sprites as sprite_render
from render.renderer import Renderer
# -- sprite data integrity: uniform grids, palettes complete.
sprite_data.validate()
# -- save / load round-trip restores exact state.
with tempfile.TemporaryDirectory() as tmp:
original_path = serializers.SAVE_PATH
serializers.SAVE_PATH = Path(tmp) / "save.json"
try:
session = GameSession.new_game(seed=11)
session.player.inventory.append(Item.from_def(ITEM_CATALOG["battle_axe"]))
session.turn = 42
session.current_floor = 3
serializers.save_game(session)
loaded = serializers.load_game()
assert loaded.player.hp == session.player.hp
assert loaded.player.xp == session.player.xp and loaded.player.level == session.player.level
assert len(loaded.player.inventory) == len(session.player.inventory)
assert loaded.current_floor == 3 and loaded.turn == 42
assert loaded.dungeon[3].stairs_down == session.dungeon[3].stairs_down
# load recomputes FOV, so explored may grow but never shrink
assert all(
cb >= ca
for ra, rb in zip(session.dungeon[3].explored, loaded.dungeon[3].explored)
for ca, cb in zip(ra, rb)
)
assert [list(row) for row in loaded.dungeon[3].tiles] == [
list(row) for row in session.dungeon[3].tiles
]
assert len(loaded.dungeon[3].entities) == len(session.dungeon[3].entities)
# -- audio failure degrades to silence; flow still fully works.
original_init = pygame.mixer.init
def _broken(**kwargs):
raise pygame.error("no audio device")
pygame.mixer.init = _broken
try:
effects = SoundEffects()
finally:
pygame.mixer.init = original_init
assert not effects.enabled
flow = GameFlow(audio=effects)
assert flow.screen == MENU
pygame.init()
screen = pygame.display.set_mode((300, 200))
renderer = Renderer(screen)
# menu states all render without crashing
flow.screen = MENU
renderer.draw(flow, 1 / 60)
flow.screen = HOWTO
renderer.draw(flow, 1 / 60)
# New Game -> How to Play -> playing (per plan)
flow.screen = MENU
flow.handle_key("confirm")
assert flow.screen == HOWTO and flow.session is not None
renderer.draw(flow, 1 / 60)
flow.handle_key(" ")
assert flow.screen == PLAYING
session = flow.session
hero = session.player
# g pickup with contextual prompt
axe = Item.from_def(ITEM_CATALOG["short_sword"], hero.x, hero.y)
session.current_map.entities.append(axe)
assert flow.context_prompt() == "Press G to pick up the Short Sword"
flow.handle_key("pickup")
assert axe in hero.inventory
# list screens render and cancel
for key, screen_name in (
("inventory", INVENTORY),
("equipment", EQUIPMENT),
("quaff", POTIONS),
("read", SCROLLS),
):
flow.handle_key(key)
assert flow.screen == screen_name, key
renderer.draw(flow, 1 / 60)
flow.handle_key("cancel")
assert flow.screen == PLAYING, key
# f descent with contextual prompt
hero.x, hero.y = session.current_map.stairs_down
assert flow.context_prompt() == "Press F to descend"
flow.handle_key("descend")
assert session.current_floor == 1
# ? reopens how-to during play
flow.handle_key("help")
assert flow.screen == HOWTO
flow.handle_key(" ")
assert flow.screen == PLAYING
# -- stairs visibly rendered: blit a frame with stairs in view.
stairs = session.current_map.stairs_down
assert stairs is not None
hero.x, hero.y = stairs[0], stairs[1] - 1
session.update_fov()
goblin = make_enemy("goblin", hero.x - 1, hero.y)
session.current_map.entities.append(goblin)
renderer._camera_snapped = False
renderer.draw(flow, 1 / 60)
assert "stairs" in renderer.world_sprites, "stairs sprite must be blitted"
assert "goblin" in renderer.world_sprites, "visible enemy must be blitted"
assert "player" in renderer.world_sprites
assert session.current_map.tiles[stairs[1]][stairs[0]] == TILE_FLOOR
# stairs visible on every floor 0-8 within sight
for floor in range(9):
probe = GameSession.new_game(seed=floor)
probe.current_floor = floor
sx, sy = probe.current_map.stairs_down
probe.player.x, probe.player.y = sx, sy
probe.update_fov()
renderer._camera_snapped = False
renderer.draw(GameFlow(session=probe, screen=PLAYING), 1 / 60)
assert "stairs" in renderer.world_sprites, f"floor {floor} stairs not rendered"
# death and victory screens render
flow.screen = DEAD
renderer.draw(flow, 1 / 60)
flow.screen = VICTORY
renderer.draw(flow, 1 / 60)
# sprites are multi-color pixel art, not flat squares
for key in ("rat", "goblin", "ancient_dragon", "stairs", "player"):
surface = (
sprite_render.get_player_sprite("war_hammer", "plate_armor", "down")
if key == "player"
else sprite_render.get_sprite(key)
)
colors = {
surface.get_at((x, y))[:3]
for y in range(surface.get_height())
for x in range(surface.get_width())
if surface.get_at((x, y)).a > 0
}
assert len(colors) >= 4, f"{key} sprite is too flat ({len(colors)} colors)"
# equipment visibly changes the player sprite (grid level)
assert sprite_data.player_grid("", "", "down") != sprite_data.player_grid(
"war_hammer", "plate_armor", "down"
)
# cached: same surface object returned
assert sprite_render.get_sprite("goblin") is sprite_render.get_sprite("goblin")
finally:
serializers.SAVE_PATH = original_path
pygame.quit()
# -- no external asset files snuck in
for pattern in ("*.png", "*.jpg", "*.wav", "*.ogg", "*.ttf", "*.otf"):
assert not list(ROOT.rglob(pattern)), f"external asset file found: {pattern}"
# -- headless run of the real game loop, forced mixer failure
env = dict(
os.environ,
SDL_VIDEODRIVER="dummy",
SDL_AUDIODRIVER="definitely-not-a-driver",
UNDERDEPTHS_MAX_FRAMES="30",
)
result = subprocess.run(
[sys.executable, str(ROOT / "main.py")],
env=env,
capture_output=True,
text=True,
timeout=120,
)
assert result.returncode == 0, f"main.py crashed:\n{result.stdout}\n{result.stderr}"
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 = range(1, args.phase + 1) if args.phase else PHASES
for number in selected:
PHASES[number]()
print(f"Phase {number}: PASS")
if __name__ == "__main__":
main()
-64
View File
@@ -1,64 +0,0 @@
"""FOV gate checks for engine/fov.py (run: python tests/test_fov.py)."""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from engine.fov import compute_fov, visible_tiles
from engine.map_gen import generate_map
def main() -> None:
# Walled-in player: self plus the adjacent wall ring, nothing beyond.
m = generate_map(0, seed=1)
x, y = m.spawn
for row in m.tiles:
for i in range(len(row)):
row[i] = 0
m.tiles[y][x] = 1
compute_fov(m, x, y)
ring = {(x + dx, y + dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1)}
assert set(visible_tiles(m)) == ring
# Open maps: radius 8 floors, explored merged, no dark gaps next to floors.
for seed in (1, 7, 42, 99):
m = generate_map(0, seed=seed)
sx, sy = m.spawn
compute_fov(m, sx, sy)
vis = set(visible_tiles(m))
assert (sx, sy) in vis and len(vis) > 30, seed
assert all((vx - sx) ** 2 + (vy - sy) ** 2 <= 64 for vx, vy in vis if m.tile_at(vx, vy) == 1)
assert all(m.explored[vy][vx] for vx, vy in vis)
dark_neighbors = [
(vx + dx_, vy + dy_)
for vx, vy in vis
if m.tile_at(vx, vy) == 1
for dx_, dy_ in ((1, 0), (-1, 0), (0, 1), (0, -1))
if m.tile_at(vx + dx_, vy + dy_) == 0 and (vx + dx_, vy + dy_) not in vis
]
assert not dark_neighbors, (seed, dark_neighbors[:3])
# No seeing through a full wall column.
m = generate_map(0, seed=5)
px, py = m.spawn
for wy in range(m.height):
m.tiles[wy][px + 2] = 0
compute_fov(m, px, py)
assert not any(row[i] for row in m.visible for i in range(px + 3, m.width))
# Explored is monotonic; visible resets between computes.
m = generate_map(0, seed=11)
compute_fov(m, *m.spawn)
e1 = sum(v for row in m.explored for v in row)
v1 = len(visible_tiles(m))
compute_fov(m, *m.spawn)
assert sum(v for row in m.explored for v in row) == e1
assert len(visible_tiles(m)) == v1
print("FOV tests: PASS")
if __name__ == "__main__":
main()