(Underdepths) Pass 4
This commit is contained in:
29 files changed
+4888
No files matched your search
@@ -0,0 +1,14 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
|
||||
# Runtime / build artifacts
|
||||
save.json
|
||||
.build_state
|
||||
.pipeline.pid
|
||||
logs/
|
||||
.pi/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Whitespace-only changes.
@@ -0,0 +1,254 @@
|
||||
"""Enemy AI: per-turn behavior dispatch (plan.md §5).
|
||||
|
||||
Visibility is symmetric — an enemy sees the player exactly when the player's FOV
|
||||
covers the enemy's tile (and the player is not invisible). Slow enemies
|
||||
(speed > 1) act every Nth turn via act_counter. Enemies never stack: other
|
||||
blocking entities are treated as impassable.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
|
||||
from engine import combat, game_state, pathfinding
|
||||
from engine.map_gen import is_walkable
|
||||
from entities.enemy import Enemy
|
||||
|
||||
|
||||
def take_enemy_turn(enemy, session, rng=None) -> None:
|
||||
r = rng if rng is not None else (getattr(session, "rng", None) or random)
|
||||
floor = session.dungeon[session.current_floor]
|
||||
player = session.player
|
||||
|
||||
if enemy.speed > 1:
|
||||
enemy.act_counter += 1
|
||||
if enemy.act_counter % enemy.speed != 0:
|
||||
return
|
||||
|
||||
player_visible = _can_see_player(floor, enemy, player)
|
||||
if player_visible:
|
||||
enemy.last_known_pos = (player.x, player.y)
|
||||
|
||||
bh = enemy.behavior
|
||||
if bh == "wander":
|
||||
_wander(enemy, floor, session, r)
|
||||
elif bh == "chase":
|
||||
_chase(enemy, floor, session, r, player_visible)
|
||||
elif bh == "flee":
|
||||
_flee(enemy, floor, session, r, player_visible)
|
||||
elif bh == "ranged":
|
||||
_ranged(enemy, floor, session, r, player_visible)
|
||||
elif bh == "phase":
|
||||
_phase(enemy, floor, session, r, player_visible)
|
||||
elif bh == "split":
|
||||
_chase(enemy, floor, session, r, player_visible)
|
||||
else:
|
||||
_wander(enemy, floor, session, r)
|
||||
|
||||
|
||||
# --- helpers ---------------------------------------------------------------- #
|
||||
|
||||
def _can_see_player(floor, enemy, player) -> bool:
|
||||
if getattr(player, "invisible", False):
|
||||
return False
|
||||
if 0 <= enemy.x < floor.width and 0 <= enemy.y < floor.height:
|
||||
return floor.visible[enemy.y][enemy.x]
|
||||
return False
|
||||
|
||||
|
||||
def _occupied(floor, session, pos, ignore) -> bool:
|
||||
px, py = pos
|
||||
for e in floor.entities:
|
||||
if e is ignore:
|
||||
continue
|
||||
if e.x == px and e.y == py and getattr(e, "blocks", True):
|
||||
return True
|
||||
return session.player.x == px and session.player.y == py
|
||||
|
||||
|
||||
def _blocked_set(floor, ignore) -> set:
|
||||
return {(e.x, e.y) for e in floor.entities
|
||||
if e is not ignore and getattr(e, "blocks", True)}
|
||||
|
||||
|
||||
def _manhattan(a, b) -> int:
|
||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||
|
||||
|
||||
def _step_to(enemy, pos, floor, session) -> bool:
|
||||
if pos is None or not is_walkable(floor, pos[0], pos[1]):
|
||||
return False
|
||||
if _occupied(floor, session, pos, enemy):
|
||||
return False
|
||||
enemy.x, enemy.y = pos
|
||||
return True
|
||||
|
||||
|
||||
def _wander(enemy, floor, session, r) -> None:
|
||||
if r.random() < 0.5:
|
||||
return # wait
|
||||
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
|
||||
r.shuffle(dirs)
|
||||
for dx, dy in dirs:
|
||||
nx, ny = enemy.x + dx, enemy.y + dy
|
||||
if is_walkable(floor, nx, ny) and not _occupied(floor, session, (nx, ny), enemy):
|
||||
enemy.x, enemy.y = nx, ny
|
||||
return
|
||||
|
||||
|
||||
def _chase(enemy, floor, session, r, player_visible) -> None:
|
||||
player = session.player
|
||||
target = (player.x, player.y) if player_visible else enemy.last_known_pos
|
||||
if target is None:
|
||||
_wander(enemy, floor, session, r)
|
||||
return
|
||||
if player_visible and _manhattan((enemy.x, enemy.y), (player.x, player.y)) <= 1:
|
||||
combat.attack(enemy, player, rng=r, log=session.log)
|
||||
return
|
||||
blocked = _blocked_set(floor, enemy)
|
||||
path = pathfinding.astar(floor, (enemy.x, enemy.y), target, blocked=blocked)
|
||||
if path and len(path) >= 2:
|
||||
_step_to(enemy, path[1], floor, session)
|
||||
else:
|
||||
_wander(enemy, floor, session, r)
|
||||
|
||||
|
||||
def _flee(enemy, floor, session, r, player_visible) -> None:
|
||||
player = session.player
|
||||
if player_visible and enemy.hp < enemy.max_hp * 0.3:
|
||||
_move_away(enemy, floor, session, r, (player.x, player.y))
|
||||
else:
|
||||
_chase(enemy, floor, session, r, player_visible)
|
||||
|
||||
|
||||
def _ranged(enemy, floor, session, r, player_visible) -> None:
|
||||
player = session.player
|
||||
if not player_visible:
|
||||
_wander(enemy, floor, session, r)
|
||||
return
|
||||
dist = _manhattan((enemy.x, enemy.y), (player.x, player.y))
|
||||
if dist > 3:
|
||||
if enemy.ranged_power > 0:
|
||||
_ranged_attack(enemy, player, r, session.log)
|
||||
else:
|
||||
_chase(enemy, floor, session, r, player_visible)
|
||||
elif dist <= 2:
|
||||
_move_away(enemy, floor, session, r, (player.x, player.y))
|
||||
else:
|
||||
combat.attack(enemy, player, rng=r, log=session.log)
|
||||
|
||||
|
||||
def _phase(enemy, floor, session, r, player_visible) -> None:
|
||||
player = session.player
|
||||
if player_visible and _manhattan((enemy.x, enemy.y), (player.x, player.y)) <= 1:
|
||||
combat.attack(enemy, player, rng=r, log=session.log)
|
||||
return
|
||||
if not player_visible:
|
||||
_wander(enemy, floor, session, r)
|
||||
return
|
||||
# Drift toward the player through walls, but never onto another entity.
|
||||
best = None
|
||||
best_d = _manhattan((enemy.x, enemy.y), (player.x, player.y))
|
||||
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
||||
nx, ny = enemy.x + dx, enemy.y + dy
|
||||
if not (0 <= nx < floor.width and 0 <= ny < floor.height):
|
||||
continue
|
||||
if _occupied(floor, session, (nx, ny), enemy):
|
||||
continue
|
||||
d = _manhattan((nx, ny), (player.x, player.y))
|
||||
if d < best_d:
|
||||
best_d = d
|
||||
best = (nx, ny)
|
||||
if best is not None:
|
||||
enemy.x, enemy.y = best
|
||||
|
||||
|
||||
def _move_away(enemy, floor, session, r, threat) -> None:
|
||||
best = None
|
||||
best_d = _manhattan((enemy.x, enemy.y), threat)
|
||||
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
|
||||
r.shuffle(dirs)
|
||||
for dx, dy in dirs:
|
||||
nx, ny = enemy.x + dx, enemy.y + dy
|
||||
if not is_walkable(floor, nx, ny) or _occupied(floor, session, (nx, ny), enemy):
|
||||
continue
|
||||
d = _manhattan((nx, ny), threat)
|
||||
if d > best_d:
|
||||
best_d = d
|
||||
best = (nx, ny)
|
||||
if best is not None:
|
||||
enemy.x, enemy.y = best
|
||||
else:
|
||||
_wander(enemy, floor, session, r)
|
||||
|
||||
|
||||
def _ranged_attack(enemy, player, r, log) -> None:
|
||||
acc = getattr(enemy, "accuracy", 0)
|
||||
eva = getattr(player, "evasion", 0)
|
||||
hit_chance = max(0.1, min(0.95, 0.7 + (acc - eva) * 0.05))
|
||||
rp = enemy.ranged_power
|
||||
if r.random() < hit_chance:
|
||||
player.hp -= rp
|
||||
if log is not None:
|
||||
log.append(f"{enemy.name} shoots you for {rp} damage!")
|
||||
elif log is not None:
|
||||
log.append(f"{enemy.name}'s shot misses you")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Death resolution
|
||||
# --------------------------------------------------------------------------- #
|
||||
def on_death(enemy, session) -> None:
|
||||
"""Resolve an enemy's death: split, award XP, remove corpse, check victory.
|
||||
|
||||
Called by actions whenever a swing drops an enemy to <= 0 HP. A green slime
|
||||
that can still split spawns two smaller, non-splitting copies before the
|
||||
corpse is removed. Slaying the dragon wins the run.
|
||||
"""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
|
||||
session.log.append(f"You defeated the {enemy.name}! (+{enemy.xp_value} XP)")
|
||||
|
||||
if getattr(enemy, "can_split", False) and "slime" in enemy.name.lower():
|
||||
_spawn_split_slimes(enemy, floor, session)
|
||||
|
||||
player.gain_xp(enemy.xp_value)
|
||||
for msg in player.pending_log:
|
||||
session.log.append(msg)
|
||||
player.pending_log.clear()
|
||||
|
||||
if enemy in floor.entities:
|
||||
floor.entities.remove(enemy)
|
||||
|
||||
if "dragon" in enemy.name.lower():
|
||||
game_state.mark_victory(session)
|
||||
session.log.append("You slew the Ancient Dragon! You conquered Underdepths.")
|
||||
|
||||
|
||||
def _spawn_split_slimes(enemy, floor, session) -> None:
|
||||
"""Spawn up to two half-size, non-splitting Small Slimes around the corpse."""
|
||||
half_hp = max(1, enemy.max_hp // 2)
|
||||
half_pow = max(1, enemy.power // 2)
|
||||
spawned = 0
|
||||
# The corpse's own tile is a candidate: it is freed the instant we remove
|
||||
# the corpse below, so a surrounded slime can still split in place.
|
||||
for dx, dy in ((0, 0), (1, 0), (-1, 0), (0, 1), (0, -1),
|
||||
(1, 1), (-1, 1), (1, -1), (-1, -1)):
|
||||
if spawned >= 2:
|
||||
break
|
||||
nx, ny = enemy.x + dx, enemy.y + dy
|
||||
if not is_walkable(floor, nx, ny):
|
||||
continue
|
||||
if _occupied(floor, session, (nx, ny), enemy):
|
||||
continue
|
||||
floor.entities.append(Enemy(
|
||||
x=nx, y=ny, name="Small Slime", sprite_key="small_slime",
|
||||
hp=half_hp, max_hp=half_hp, power=half_pow, armor=enemy.armor,
|
||||
accuracy=enemy.accuracy, evasion=enemy.evasion,
|
||||
crit_chance=enemy.crit_chance, speed=1,
|
||||
behavior="split", xp_value=max(1, enemy.xp_value // 2),
|
||||
can_split=False,
|
||||
))
|
||||
spawned += 1
|
||||
if spawned:
|
||||
session.log.append(f"The {enemy.name} splits into {spawned} smaller slimes!")
|
||||
@@ -0,0 +1,207 @@
|
||||
Underdepths build pipeline — state=0 ttl=3000s retries=3
|
||||
===================================================================
|
||||
>>> phase1-foundation (attempt 1/3) 09:29:04
|
||||
===================================================================
|
||||
gate: python3 tests/smoke.py --phase 1
|
||||
##########.....###########.......###############################################
|
||||
##########.....##############.##################################################
|
||||
##########.....##############.##################################################
|
||||
##########....................................##################################
|
||||
##########.....##############################.##################################
|
||||
##########.....##############################.##################################
|
||||
##########.....##############################.##################################
|
||||
############.################################.##################################
|
||||
############.################################.##################################
|
||||
############.################################.##################################
|
||||
############.################################.##################################
|
||||
############.############################.........##############################
|
||||
############.############################.........##############################
|
||||
############.############################.........##############################
|
||||
############.############################.........##############################
|
||||
############.############################.........##############################
|
||||
############.############################.........##############################
|
||||
############.############################.........##############################
|
||||
############.#########........##################################################
|
||||
############.#########........##################################################
|
||||
############..................##################################################
|
||||
############.#########........##################################################
|
||||
############.###################################################################
|
||||
############.###################################################################
|
||||
############.###################################################################
|
||||
############.###################################################################
|
||||
########..........##############################################################
|
||||
########..........##############################################################
|
||||
########..........##############################################################
|
||||
########..........##############################################################
|
||||
########..........##############################################################
|
||||
########..........##############################################################
|
||||
################################################################################
|
||||
################################################################################
|
||||
phase 1: PASS
|
||||
<<< phase1-foundation PASS
|
||||
===================================================================
|
||||
>>> phase2-core (attempt 1/3) 09:43:45
|
||||
===================================================================
|
||||
gate: python3 tests/smoke.py --phase 2
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat result dict has keys
|
||||
ok: combat has hits and misses
|
||||
ok: combat damage non-negative
|
||||
ok: combat damage in plausible range
|
||||
ok: combat crits occurred (>=1 in 1000)
|
||||
ok: armor reduces average damage
|
||||
ok: chase goblin closed distance along corridor
|
||||
phase 2: PASS
|
||||
<<< phase2-core PASS
|
||||
===================================================================
|
||||
>>> phase3-content (attempt 1/3) 10:25:40
|
||||
===================================================================
|
||||
gate: python3 tests/smoke.py --phase 3
|
||||
ok: wraith armor
|
||||
ok: wraith xp_value
|
||||
ok: wraith behavior
|
||||
ok: wraith speed
|
||||
ok: green_slime hp/max_hp
|
||||
ok: green_slime power
|
||||
ok: green_slime armor
|
||||
ok: green_slime xp_value
|
||||
ok: green_slime behavior
|
||||
ok: green_slime speed
|
||||
ok: ancient_dragon hp/max_hp
|
||||
ok: ancient_dragon power
|
||||
ok: ancient_dragon armor
|
||||
ok: ancient_dragon xp_value
|
||||
ok: ancient_dragon speed
|
||||
ok: dragon ranged_power/breath present
|
||||
ok: Short Sword +4 power
|
||||
ok: Battle Axe +7 power
|
||||
ok: Leather Armor +2 armor
|
||||
ok: Plate Armor +7 armor
|
||||
ok: War Hammer +10 power
|
||||
ok: level starts at 1
|
||||
ok: 30 XP -> level 2
|
||||
ok: level 2 max_hp 60 (+10)
|
||||
ok: level 2 power 5 (+1)
|
||||
ok: level 2 fully healed
|
||||
ok: reaches level 10
|
||||
ok: Healing Potion +30 HP (capped)
|
||||
ok: Strength Potion +5 power while active
|
||||
ok: Strength Potion sets a timer effect
|
||||
ok: Invisibility Potion makes player hidden
|
||||
ok: Scroll of Mapping reveals floor
|
||||
ok: Scroll of Teleport moves player
|
||||
ok: slime split produces smaller slimes
|
||||
phase 3: PASS
|
||||
<<< phase3-content PASS
|
||||
===================================================================
|
||||
>>> phase4a-persist (attempt 1/3) 11:02:00
|
||||
===================================================================
|
||||
gate: python3 -m compileall -q engine render data entities ai main.py tests 2>&1 && echo COMPILE_OK
|
||||
COMPILE_OK
|
||||
<<< phase4a-persist PASS
|
||||
===================================================================
|
||||
>>> phase4b-visuals (attempt 1/3) 11:12:32
|
||||
===================================================================
|
||||
./orchestrate.sh: line 51: 2851 Killed: 9 timeout --kill-after=30 "$TTL" pi -p -a --name "$name" @plan.md "$full_prompt" > "$LOG_DIR/${name}.attempt${attempt}.log" 2>&1
|
||||
! dispatch timed out (rc=137); tail of log:
|
||||
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
|
||||
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
|
||||
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
|
||||
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
|
||||
supacode: OSC emit failed: code=ENXIO errno=-6 message=ENXIO: no such device or address, open '/dev/tty'
|
||||
gate: python3 -m compileall -q engine render data entities ai main.py tests 2>&1 && echo COMPILE_OK
|
||||
COMPILE_OK
|
||||
<<< phase4b-visuals PASS
|
||||
===================================================================
|
||||
>>> phase4-gate (attempt 1/3) 12:24:38
|
||||
===================================================================
|
||||
gate: python3 tests/smoke.py --phase 4
|
||||
|
||||
===== phase 4 =====
|
||||
ok: save/load player equal
|
||||
ok: save/load ten floors present
|
||||
ok: save/load dungeon (sans visible) equal
|
||||
ok: save/load turn/log preserved
|
||||
ok: serialized dict omits visible
|
||||
ok: pickup returns True on item present
|
||||
ok: pickup adds to inventory
|
||||
ok: pickup removes item from floor
|
||||
ok: descend returns True on stairs
|
||||
ok: descend advances floor
|
||||
ok: audio play all events without raising
|
||||
ok: audio mute toggles
|
||||
ok: main(max_frames=1) runs headless
|
||||
phase 4: PASS
|
||||
<<< phase4-gate PASS
|
||||
===================================================================
|
||||
>>> goal-backstop (attempt 1/3) 12:24:52
|
||||
===================================================================
|
||||
gate: python3 tests/smoke.py --goal
|
||||
ok: Leather Armor +2 armor
|
||||
ok: Plate Armor +7 armor
|
||||
ok: War Hammer +10 power
|
||||
ok: level starts at 1
|
||||
ok: 30 XP -> level 2
|
||||
ok: level 2 max_hp 60 (+10)
|
||||
ok: level 2 power 5 (+1)
|
||||
ok: level 2 fully healed
|
||||
ok: reaches level 10
|
||||
ok: Healing Potion +30 HP (capped)
|
||||
ok: Strength Potion +5 power while active
|
||||
ok: Strength Potion sets a timer effect
|
||||
ok: Invisibility Potion makes player hidden
|
||||
ok: Scroll of Mapping reveals floor
|
||||
ok: Scroll of Teleport moves player
|
||||
ok: slime split produces smaller slimes
|
||||
[goal] phase 3 criteria: PASS
|
||||
ok: save/load player equal
|
||||
ok: save/load ten floors present
|
||||
ok: save/load dungeon (sans visible) equal
|
||||
ok: save/load turn/log preserved
|
||||
ok: serialized dict omits visible
|
||||
ok: pickup returns True on item present
|
||||
ok: pickup adds to inventory
|
||||
ok: pickup removes item from floor
|
||||
ok: descend returns True on stairs
|
||||
ok: descend advances floor
|
||||
ok: audio play all events without raising
|
||||
ok: audio mute toggles
|
||||
ok: main(max_frames=1) runs headless
|
||||
[goal] phase 4 criteria: PASS
|
||||
ok: goal: 120-turn scripted playthrough no crash
|
||||
ok: goal: GameSession state field supports dead/victory/menu/playing
|
||||
|
||||
[goal] ALL ACCEPTANCE CRITERIA PASS
|
||||
<<< goal-backstop PASS
|
||||
|
||||
===================================================================
|
||||
BUILD COMPLETE — all phase gates + goal backstop PASS.
|
||||
Play it: python3 main.py
|
||||
Verify: python3 tests/smoke.py --goal
|
||||
===================================================================
|
||||
Whitespace-only changes.
@@ -0,0 +1,133 @@
|
||||
"""Tuning constants, palettes, and progression tables for Underdepths.
|
||||
|
||||
All magic numbers live here so balancing is a one-file edit.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# --- Grid / viewport -------------------------------------------------------- #
|
||||
TILE: int = 24
|
||||
MAP_WIDTH: int = 80
|
||||
MAP_HEIGHT: int = 50
|
||||
SIGHT_RADIUS: int = 8
|
||||
FLOORS: int = 10
|
||||
MAX_LEVEL: int = 10
|
||||
|
||||
# --- Base palette / colors -------------------------------------------------- #
|
||||
# Tiles
|
||||
COLORS: dict[str, tuple[int, int, int]] = {
|
||||
"wall_visible": (60, 60, 70),
|
||||
"wall_explored": (30, 30, 35),
|
||||
"floor_visible": (40, 35, 30),
|
||||
"floor_explored": (20, 18, 15),
|
||||
"void": (6, 5, 8),
|
||||
# entity accent hues (dominant sprite color per type)
|
||||
"player": (225, 225, 235),
|
||||
"rat": (150, 110, 75),
|
||||
"goblin": (95, 165, 75),
|
||||
"skeleton_archer": (215, 215, 205),
|
||||
"orc_warrior": (155, 55, 50),
|
||||
"wraith": (160, 95, 205),
|
||||
"green_slime": (125, 205, 85),
|
||||
"ancient_dragon": (205, 65, 50),
|
||||
# feature / item accents
|
||||
"stairs": (240, 220, 80),
|
||||
"weapon": (240, 220, 80), # yellow
|
||||
"armor": (95, 145, 230), # blue
|
||||
"potion": (220, 85, 85), # red
|
||||
"scroll": (95, 220, 220), # cyan
|
||||
# UI
|
||||
"ui_border": (150, 130, 95),
|
||||
"ui_border_hi": (200, 180, 130),
|
||||
"ui_bg": (15, 12, 18),
|
||||
"ui_panel": (24, 20, 28),
|
||||
"hp_full": (190, 55, 60),
|
||||
"hp_back": (60, 22, 24),
|
||||
"xp_full": (90, 170, 230),
|
||||
"xp_back": (26, 34, 48),
|
||||
"log_combat": (235, 235, 235),
|
||||
"log_damage": (225, 90, 90),
|
||||
"log_levelup": (130, 225, 100),
|
||||
"log_item": (240, 220, 90),
|
||||
"log_miss": (170, 170, 170),
|
||||
"prompt": (245, 235, 180),
|
||||
"shadow": (0, 0, 0),
|
||||
"highlight": (255, 255, 255),
|
||||
}
|
||||
|
||||
# Sprite-palette keys (single chars in data/sprites.py grids) -> RGB.
|
||||
# "." is transparent. Keys are intentionally short; phase 4 sprites use them.
|
||||
PALETTE: dict[str, tuple[int, int, int] | None] = {
|
||||
".": None, # transparent
|
||||
"K": (18, 14, 20), # dark outline
|
||||
"k": (40, 32, 38), # soft outline
|
||||
"W": (95, 85, 72), # warm light shade (stone/skin highlight)
|
||||
"s": (62, 56, 50), # mid shade (stone/skin)
|
||||
"h": (38, 33, 30), # dark shade (stone/skin shadow)
|
||||
"d": (24, 20, 18), # deep shadow
|
||||
"w": (245, 245, 250), # white (bone / sclera)
|
||||
"g": (120, 200, 80), # green (goblin / slime)
|
||||
"G": (70, 150, 55), # dark green
|
||||
"r": (200, 60, 50), # red (orc / dragon)
|
||||
"R": (140, 35, 30), # dark red
|
||||
"p": (160, 95, 205), # purple (wraith)
|
||||
"P": (95, 55, 140), # dark purple
|
||||
"b": (95, 145, 230), # blue (armor / magic)
|
||||
"y": (240, 220, 80), # yellow (stairs / weapon / gold)
|
||||
"o": (225, 150, 60), # orange (fire / accents)
|
||||
"c": (95, 220, 220), # cyan (scroll)
|
||||
"m": (220, 85, 85), # muted red (potion)
|
||||
"e": (90, 230, 120), # eye glow green
|
||||
"E": (120, 200, 255), # eye glow blue
|
||||
}
|
||||
|
||||
# --- Progression: XP and level-up tables (plan.md §7) ----------------------- #
|
||||
# Cumulative XP required to REACH a given level (keyed by level 1..10).
|
||||
XP_THRESHOLDS: dict[int, int] = {
|
||||
1: 0, 2: 30, 3: 70, 4: 140, 5: 250,
|
||||
6: 400, 7: 600, 8: 850, 9: 1150, 10: 1500,
|
||||
}
|
||||
# Stat gains applied when leveling INTO a given level.
|
||||
LEVEL_HP_GAIN: dict[int, int] = {2: 10, 3: 10, 4: 10, 5: 10, 6: 15, 7: 15, 8: 15, 9: 15, 10: 20}
|
||||
LEVEL_POWER_GAIN: dict[int, int] = {2: 1, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 2, 10: 3}
|
||||
|
||||
# --- Player base stats (plan.md §7) ---------------------------------------- #
|
||||
PLAYER_BASE: dict[str, int | float] = {
|
||||
"hp": 50, "max_hp": 50, "power": 4, "armor": 0,
|
||||
"accuracy": 5, "evasion": 2, "crit_chance": 0.10, "speed": 1,
|
||||
}
|
||||
|
||||
# --- Per-floor spawn distribution (plan.md §1) ----------------------------- #
|
||||
# (min, max) enemies / items per floor. Floor 9 is the boss arena.
|
||||
ENEMY_COUNT: dict[int, tuple[int, int]] = {
|
||||
0: (3, 4), 1: (3, 4),
|
||||
2: (4, 6), 3: (4, 6),
|
||||
4: (5, 7), 5: (5, 7),
|
||||
6: (6, 8), 7: (6, 8),
|
||||
8: (7, 9),
|
||||
}
|
||||
ITEM_COUNT: dict[int, tuple[int, int]] = {
|
||||
0: (2, 3), 1: (2, 3),
|
||||
2: (2, 3), 3: (2, 3),
|
||||
4: (3, 4), 5: (3, 4),
|
||||
6: (3, 4), 7: (3, 4),
|
||||
8: (4, 5), 9: (2, 2),
|
||||
}
|
||||
|
||||
# --- Key bindings (plan.md Controls) --------------------------------------- #
|
||||
# Map of intent -> pygame key constant names; resolved in phase 4 input layer.
|
||||
KEY_BINDINGS: dict[str, list[str]] = {
|
||||
"move_n": ["K_UP", "K_k"],
|
||||
"move_s": ["K_DOWN", "K_j"],
|
||||
"move_w": ["K_LEFT", "K_h"],
|
||||
"move_e": ["K_RIGHT", "K_l"],
|
||||
"pickup": ["K_g"],
|
||||
"inventory": ["K_i"],
|
||||
"equipment": ["K_e"],
|
||||
"quaff": ["K_q"],
|
||||
"read": ["K_r"],
|
||||
"descend": ["K_f"],
|
||||
"save_quit": ["K_s"],
|
||||
"help": ["K_QUESTION"],
|
||||
"mute": ["K_m"],
|
||||
"cancel": ["K_ESCAPE"],
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
"""Procedural pixel-art sprite definitions (plan.md Rendering).
|
||||
|
||||
Every entity, item, and feature is a 16x16 grid of single-char palette keys
|
||||
(data/constants.PALETTE: "." transparent). Grids are drawn with small canvas
|
||||
primitives (rect, disc, triangle, line) so the art is symmetric and
|
||||
recognizable rather than hand-counted ASCII. render/sprites.py rasterizes a
|
||||
grid to a pygame.Surface once and caches it.
|
||||
|
||||
Tiles (walls/floor) are NOT here: they need seeded per-tile variation, so the
|
||||
renderer draws them procedurally. This file holds the distinct, judged sprites:
|
||||
player (4 facings), 7 enemies + small slime, 13 item icons, and stairs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
SIZE: int = 16
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Canvas primitives — operate on a mutable list[list[str]] grid of SIZE rows.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _blank() -> list[list[str]]:
|
||||
return [["." for _ in range(SIZE)] for _ in range(SIZE)]
|
||||
|
||||
|
||||
def _set(g: list[list[str]], x: int, y: int, k: str) -> None:
|
||||
if 0 <= x < SIZE and 0 <= y < SIZE:
|
||||
g[y][x] = k
|
||||
|
||||
|
||||
def _rect(g, x0, y0, x1, y1, k) -> None:
|
||||
for y in range(max(0, y0), min(SIZE - 1, y1) + 1):
|
||||
for x in range(max(0, x0), min(SIZE - 1, x1) + 1):
|
||||
g[y][x] = k
|
||||
|
||||
|
||||
def _frame(g, x0, y0, x1, y1, k) -> None:
|
||||
for x in range(x0, x1 + 1):
|
||||
_set(g, x, y0, k)
|
||||
_set(g, x, y1, k)
|
||||
for y in range(y0, y1 + 1):
|
||||
_set(g, x0, y, k)
|
||||
_set(g, x1, y, k)
|
||||
|
||||
|
||||
def _disc(g, cx, cy, rx, ry, k) -> None:
|
||||
rx = max(0.1, rx)
|
||||
ry = max(0.1, ry)
|
||||
for y in range(SIZE):
|
||||
for x in range(SIZE):
|
||||
dx = (x - cx) / rx
|
||||
dy = (y - cy) / ry
|
||||
if dx * dx + dy * dy <= 1.0:
|
||||
g[y][x] = k
|
||||
|
||||
|
||||
def _hline(g, x0, x1, y, k) -> None:
|
||||
for x in range(min(x0, x1), max(x0, x1) + 1):
|
||||
_set(g, x, y, k)
|
||||
|
||||
|
||||
def _vline(g, x, y0, y1, k) -> None:
|
||||
for y in range(min(y0, y1), max(y0, y1) + 1):
|
||||
_set(g, x, y, k)
|
||||
|
||||
|
||||
def _line(g, x0, y0, x1, y1, k) -> None:
|
||||
dx = abs(x1 - x0)
|
||||
dy = -abs(y1 - y0)
|
||||
sx = 1 if x0 < x1 else -1
|
||||
sy = 1 if y0 < y1 else -1
|
||||
err = dx + dy
|
||||
while True:
|
||||
_set(g, x0, y0, k)
|
||||
if x0 == x1 and y0 == y1:
|
||||
break
|
||||
e2 = 2 * err
|
||||
if e2 >= dy:
|
||||
err += dy
|
||||
x0 += sx
|
||||
if e2 <= dx:
|
||||
err += dx
|
||||
y0 += sy
|
||||
|
||||
|
||||
def _tri(g, ax, ay, bx, by, cx, cy, k) -> None:
|
||||
ymin = max(0, int(min(ay, by, cy)))
|
||||
ymax = min(SIZE - 1, int(max(ay, by, cy)))
|
||||
for y in range(ymin, ymax + 1):
|
||||
xs = []
|
||||
for (x0, y0, x1, y1) in ((ax, ay, bx, by), (bx, by, cx, cy), (cx, cy, ax, ay)):
|
||||
if y0 == y1:
|
||||
if y0 == y:
|
||||
xs.extend([x0, x1])
|
||||
continue
|
||||
t = (y - y0) / (y1 - y0)
|
||||
xs.append(x0 + t * (x1 - x0))
|
||||
if len(xs) >= 2:
|
||||
_hline(g, int(round(min(xs))), int(round(max(xs))), y, k)
|
||||
|
||||
|
||||
def _flip(g) -> list[list[str]]:
|
||||
return [row[::-1] for row in g]
|
||||
|
||||
|
||||
def _shift(g, dy: int) -> list[list[str]]:
|
||||
out = _blank()
|
||||
for y in range(SIZE):
|
||||
for x in range(SIZE):
|
||||
ny = y + dy
|
||||
if 0 <= ny < SIZE:
|
||||
out[ny][x] = g[y][x]
|
||||
return out
|
||||
|
||||
|
||||
def _outline(g) -> list[list[str]]:
|
||||
"""1px dark 'K' border around the silhouette (keeps sprites off the floor)."""
|
||||
out = [row[:] for row in g]
|
||||
for y in range(SIZE):
|
||||
for x in range(SIZE):
|
||||
if g[y][x] != ".":
|
||||
continue
|
||||
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
||||
nx, ny = x + dx, y + dy
|
||||
if 0 <= nx < SIZE and 0 <= ny < SIZE and g[ny][nx] != ".":
|
||||
out[y][x] = "K"
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def _rows(g) -> list[str]:
|
||||
return ["".join(row) for row in g]
|
||||
|
||||
|
||||
def _eframes(g) -> list[list[str]]:
|
||||
"""2 idle frames: base + 1px bob, both outlined."""
|
||||
ob = _outline(g)
|
||||
return [_rows(ob), _rows(_shift(ob, 1))]
|
||||
|
||||
|
||||
def _iframe(g) -> list[list[str]]:
|
||||
return [_rows(_outline(g))]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Player — hooded adventurer, 4 facings. Weapon/armor visibly change via the
|
||||
# renderer (held-weapon icon + armor shoulder tint), not extra grids.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _player_down():
|
||||
g = _blank()
|
||||
_rect(g, 6, 1, 9, 1, "W") # hood crown
|
||||
_rect(g, 5, 2, 10, 5, "W") # hood dome
|
||||
_rect(g, 6, 4, 9, 5, "s") # face shadow
|
||||
_set(g, 7, 4, "E"); _set(g, 8, 4, "E") # blue eyes
|
||||
_rect(g, 4, 6, 11, 7, "W") # shoulders
|
||||
_set(g, 4, 6, "w"); _set(g, 11, 6, "w") # shoulder highlights
|
||||
_rect(g, 5, 8, 10, 11, "W") # torso
|
||||
_hline(g, 5, 10, 11, "y") # belt
|
||||
_vline(g, 4, 8, 11, "W"); _vline(g, 11, 8, 11, "W") # arms
|
||||
_rect(g, 6, 12, 7, 13, "h"); _rect(g, 8, 12, 9, 13, "h") # legs
|
||||
_hline(g, 6, 7, 14, "K"); _hline(g, 8, 9, 14, "K") # boots
|
||||
return g
|
||||
|
||||
|
||||
def _player_up():
|
||||
g = _player_down()
|
||||
_rect(g, 6, 3, 9, 5, "W") # back of hood: no face/eyes
|
||||
_hline(g, 6, 9, 5, "k")
|
||||
return g
|
||||
|
||||
|
||||
def _player_right():
|
||||
g = _blank()
|
||||
_rect(g, 5, 1, 9, 1, "W")
|
||||
_rect(g, 5, 2, 11, 5, "W") # hood, extending right (point)
|
||||
_set(g, 12, 4, "W")
|
||||
_rect(g, 7, 4, 9, 5, "s") # side face
|
||||
_set(g, 10, 4, "E") # one eye
|
||||
_rect(g, 4, 6, 11, 7, "W")
|
||||
_set(g, 4, 6, "w")
|
||||
_rect(g, 5, 8, 10, 11, "W")
|
||||
_hline(g, 5, 10, 11, "y")
|
||||
_vline(g, 4, 8, 11, "W")
|
||||
_rect(g, 6, 12, 7, 13, "h"); _rect(g, 8, 12, 9, 13, "h")
|
||||
_hline(g, 6, 7, 14, "K"); _hline(g, 8, 9, 14, "K")
|
||||
return g
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Enemies — each a distinct silhouette + dominant hue.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _rat():
|
||||
g = _blank()
|
||||
_disc(g, 5, 5, 1.5, 1.5, "W"); _disc(g, 9, 5, 1.5, 1.5, "W") # ears
|
||||
_set(g, 5, 5, "o"); _set(g, 9, 5, "o") # inner ear
|
||||
_disc(g, 10, 8, 2.3, 2.0, "s") # head
|
||||
_disc(g, 6, 9, 3.8, 2.7, "s") # body
|
||||
_disc(g, 6, 8, 3.0, 1.5, "W") # back highlight
|
||||
_set(g, 11, 8, "K") # eye
|
||||
_set(g, 12, 9, "o") # nose
|
||||
_set(g, 13, 8, "w"); _set(g, 13, 9, "w") # whiskers
|
||||
_line(g, 3, 10, 0, 13, "o") # tail
|
||||
_set(g, 5, 12, "h"); _set(g, 8, 12, "h") # feet
|
||||
return g
|
||||
|
||||
|
||||
def _goblin():
|
||||
g = _blank()
|
||||
_set(g, 4, 5, "g"); _set(g, 4, 6, "g"); _set(g, 11, 5, "g"); _set(g, 11, 6, "g") # pointed ears
|
||||
_disc(g, 8, 6, 3.1, 2.7, "G") # head (dark green)
|
||||
_disc(g, 7, 5, 1.8, 1.0, "g") # forehead highlight
|
||||
_set(g, 7, 6, "e"); _set(g, 9, 6, "e") # glowing eyes
|
||||
_set(g, 7, 8, "w"); _set(g, 9, 8, "w") # tusks
|
||||
_rect(g, 6, 9, 10, 12, "g") # torso
|
||||
_rect(g, 6, 9, 10, 9, "G") # shoulder shade
|
||||
_hline(g, 6, 10, 12, "y") # loincloth
|
||||
_vline(g, 5, 9, 12, "g"); _vline(g, 10, 9, 12, "g") # arms
|
||||
_vline(g, 12, 6, 12, "W"); _set(g, 12, 5, "K") # crude club
|
||||
_rect(g, 6, 13, 7, 14, "G"); _rect(g, 9, 13, 10, 14, "G")
|
||||
return g
|
||||
|
||||
|
||||
def _skeleton_archer():
|
||||
g = _blank()
|
||||
# big drawn bow on the left (clear arc + taut string)
|
||||
_vline(g, 2, 4, 12, "w") # bow back
|
||||
_set(g, 1, 5, "w"); _set(g, 1, 6, "w")
|
||||
_set(g, 1, 10, "w"); _set(g, 1, 11, "w") # recurve curve
|
||||
_line(g, 2, 4, 9, 8, "K") # bowstring pulled to the hand
|
||||
_line(g, 2, 12, 9, 8, "K")
|
||||
_hline(g, 3, 7, 8, "w") # draw arm
|
||||
_disc(g, 9, 4, 2.0, 2.0, "w") # skull
|
||||
_set(g, 8, 4, "E"); _set(g, 10, 4, "E") # glowing sockets
|
||||
_hline(g, 8, 10, 6, "w"); _set(g, 8, 6, "K"); _set(g, 10, 6, "K")
|
||||
_rect(g, 8, 7, 10, 11, "w") # ribcage
|
||||
_hline(g, 8, 10, 8, "K"); _hline(g, 8, 10, 10, "K")
|
||||
_vline(g, 9, 7, 11, "K") # spine
|
||||
_vline(g, 12, 5, 11, "b"); _set(g, 12, 4, "y"); _set(g, 12, 5, "y") # quiver
|
||||
_vline(g, 8, 12, 14, "w"); _vline(g, 10, 12, 14, "w") # legs
|
||||
return g
|
||||
|
||||
|
||||
def _orc_warrior():
|
||||
g = _blank()
|
||||
_disc(g, 8, 5, 3.1, 2.7, "R") # head
|
||||
_disc(g, 8, 4, 2.3, 1.2, "r") # crown highlight
|
||||
_set(g, 7, 5, "o"); _set(g, 9, 5, "o") # eyes
|
||||
_set(g, 7, 7, "w"); _set(g, 9, 7, "w") # tusks
|
||||
_set(g, 7, 8, "w"); _set(g, 9, 8, "w")
|
||||
_rect(g, 4, 8, 12, 9, "R") # shoulder plate
|
||||
_set(g, 4, 8, "r"); _set(g, 12, 8, "r")
|
||||
_rect(g, 5, 9, 11, 13, "r") # torso
|
||||
_rect(g, 5, 9, 11, 9, "R")
|
||||
_hline(g, 5, 12, 11, "K") # belt
|
||||
_line(g, 13, 13, 13, 4, "w") # great blade
|
||||
_line(g, 12, 13, 12, 4, "K") # edge
|
||||
_set(g, 13, 13, "y") # pommel
|
||||
_rect(g, 6, 13, 7, 14, "R"); _rect(g, 9, 13, 10, 14, "R")
|
||||
return g
|
||||
|
||||
|
||||
def _wraith():
|
||||
g = _blank()
|
||||
_disc(g, 8, 6, 3.6, 3.5, "P") # hood (dark purple)
|
||||
_disc(g, 8, 5, 2.7, 2.0, "p") # hood light
|
||||
_disc(g, 8, 7, 1.9, 1.7, "K") # face void
|
||||
_set(g, 7, 6, "E"); _set(g, 9, 6, "E") # glowing eyes
|
||||
_rect(g, 5, 9, 11, 12, "P") # cloak
|
||||
# tattered hem (no legs)
|
||||
_set(g, 5, 13, "p"); _set(g, 7, 13, "P"); _set(g, 9, 13, "p"); _set(g, 11, 13, "P")
|
||||
_set(g, 6, 14, "p"); _set(g, 10, 14, "p")
|
||||
_set(g, 4, 10, "P"); _set(g, 12, 10, "P") # wisps
|
||||
return g
|
||||
|
||||
|
||||
def _slime():
|
||||
g = _blank()
|
||||
for y in range(6, 13):
|
||||
for x in range(3, 13):
|
||||
dx = (x - 8) / 4.7
|
||||
dy = (y - 9) / 3.3
|
||||
if dx * dx + dy * dy <= 1.0:
|
||||
g[y][x] = "g"
|
||||
_hline(g, 3, 12, 12, "G") # darker base
|
||||
_set(g, 6, 7, "w"); _set(g, 7, 8, "w") # gloss
|
||||
_disc(g, 6, 10, 1.3, 1.4, "w"); _disc(g, 10, 10, 1.3, 1.4, "w") # googly eyes
|
||||
_set(g, 6, 10, "K"); _set(g, 10, 10, "K")
|
||||
_set(g, 8, 13, "g"); _set(g, 8, 14, "g") # drip
|
||||
return g
|
||||
|
||||
|
||||
def _small_slime():
|
||||
g = _blank()
|
||||
for y in range(7, 14):
|
||||
for x in range(4, 12):
|
||||
dx = (x - 8) / 3.8
|
||||
dy = (y - 10) / 3.4
|
||||
if dx * dx + dy * dy <= 1.0:
|
||||
g[y][x] = "g"
|
||||
_hline(g, 4, 11, 13, "G") # base
|
||||
_set(g, 6, 8, "w"); _set(g, 7, 9, "w") # gloss
|
||||
_disc(g, 6, 10, 1.1, 1.2, "w"); _disc(g, 10, 10, 1.1, 1.2, "w") # big eyes
|
||||
_set(g, 6, 10, "K"); _set(g, 10, 10, "K")
|
||||
_set(g, 8, 13, "g") # drip
|
||||
_hline(g, 7, 9, 12, "G") # smile
|
||||
return g
|
||||
|
||||
|
||||
def _dragon():
|
||||
g = _blank()
|
||||
# spread wings (membrane triangles)
|
||||
_tri(g, 6, 7, 0, 4, 1, 10, "R")
|
||||
_tri(g, 6, 7, 0, 4, 1, 10, "R")
|
||||
_tri(g, 10, 7, 15, 4, 14, 10, "R")
|
||||
_tri(g, 10, 7, 15, 4, 14, 10, "R")
|
||||
_set(g, 0, 4, "r"); _set(g, 15, 4, "r") # wingtips
|
||||
_set(g, 2, 6, "r"); _set(g, 13, 6, "r") # membrane ribs
|
||||
# body + head
|
||||
_disc(g, 8, 9, 3.5, 3.3, "r")
|
||||
_disc(g, 8, 8, 2.7, 1.8, "R")
|
||||
_disc(g, 8, 5, 3.1, 2.7, "r")
|
||||
# horns
|
||||
_line(g, 6, 3, 4, 0, "y"); _line(g, 10, 3, 12, 0, "y")
|
||||
# snout + fangs
|
||||
_rect(g, 7, 5, 9, 6, "R")
|
||||
_set(g, 7, 7, "w"); _set(g, 9, 7, "w")
|
||||
_set(g, 7, 4, "o"); _set(g, 9, 4, "o") # eyes
|
||||
_set(g, 7, 6, "K"); _set(g, 9, 6, "K") # nostrils
|
||||
# scales + belly
|
||||
for sx, sy in ((7, 9), (9, 9), (8, 10), (6, 10), (10, 10)):
|
||||
_set(g, sx, sy, "o")
|
||||
_rect(g, 7, 10, 9, 12, "o")
|
||||
# tail + legs
|
||||
_line(g, 8, 12, 8, 15, "R")
|
||||
_rect(g, 6, 12, 7, 14, "R"); _rect(g, 9, 12, 10, 14, "R")
|
||||
return g
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Items — pixel-art icons with category accent hues.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _dagger():
|
||||
g = _blank()
|
||||
_tri(g, 7, 2, 9, 2, 8, 7, "w") # short wide blade (clearly a dagger)
|
||||
_set(g, 7, 2, "K"); _set(g, 9, 2, "K")
|
||||
_vline(g, 8, 3, 6, "K") # fuller
|
||||
_hline(g, 6, 10, 8, "y") # guard
|
||||
_vline(g, 8, 9, 12, "h"); _set(g, 8, 12, "y") # handle + pommel
|
||||
return g
|
||||
|
||||
|
||||
def _sword():
|
||||
g = _blank()
|
||||
_line(g, 8, 1, 8, 9, "w"); _line(g, 7, 1, 7, 9, "K")
|
||||
_hline(g, 5, 11, 9, "y")
|
||||
_vline(g, 8, 10, 13, "h"); _set(g, 8, 13, "y")
|
||||
return g
|
||||
|
||||
|
||||
def _axe():
|
||||
g = _blank()
|
||||
_vline(g, 7, 2, 14, "h") # handle
|
||||
_tri(g, 7, 3, 13, 2, 7, 7, "w") # head
|
||||
_set(g, 13, 2, "K"); _set(g, 12, 3, "K")
|
||||
_set(g, 7, 14, "y")
|
||||
return g
|
||||
|
||||
|
||||
def _hammer():
|
||||
g = _blank()
|
||||
_vline(g, 8, 5, 14, "h")
|
||||
_rect(g, 5, 2, 11, 5, "w")
|
||||
_frame(g, 5, 2, 11, 5, "K")
|
||||
_set(g, 8, 14, "y")
|
||||
return g
|
||||
|
||||
|
||||
def _leather():
|
||||
g = _blank()
|
||||
_disc(g, 8, 8, 4.1, 4.3, "s")
|
||||
_disc(g, 8, 7, 3.0, 2.6, "W")
|
||||
_vline(g, 6, 5, 12, "h"); _vline(g, 10, 5, 12, "h") # straps
|
||||
_hline(g, 4, 12, 11, "h")
|
||||
_set(g, 8, 8, "y") # buckle
|
||||
return g
|
||||
|
||||
|
||||
def _chain():
|
||||
g = _blank()
|
||||
_disc(g, 8, 4, 2.6, 2.2, "b") # coif (mail hood)
|
||||
_disc(g, 8, 5, 1.3, 1.1, "K") # face opening
|
||||
# hauberk torso: broad shoulders tapering to a waist (rows: y -> x-range)
|
||||
for y, (a, b) in ((6, (4, 12)), (7, (4, 12)), (8, (5, 11)), (9, (5, 11)),
|
||||
(10, (6, 10)), (11, (6, 10)), (12, (6, 10)), (13, (6, 10))):
|
||||
_hline(g, a, b, y, "b")
|
||||
_hline(g, 4, 11, 6, "w") # collar
|
||||
for y in range(6, 13): # interlocking ring texture
|
||||
for x in range(4, 13):
|
||||
if g[y][x] == "b" and (x + y) % 2 == 0:
|
||||
_set(g, x, y, "w")
|
||||
return g
|
||||
|
||||
|
||||
def _plate():
|
||||
g = _blank()
|
||||
_disc(g, 4, 6, 1.8, 1.6, "w"); _disc(g, 11, 6, 1.8, 1.6, "w") # pauldrons
|
||||
# breastplate torso: broad chest tapering to a waist
|
||||
for y, (a, b) in ((6, (4, 11)), (7, (4, 11)), (8, (5, 10)), (9, (5, 10)),
|
||||
(10, (5, 10)), (11, (6, 9)), (12, (6, 9)), (13, (6, 9))):
|
||||
_hline(g, a, b, y, "w")
|
||||
_disc(g, 6, 8, 1.7, 1.5, "w"); _disc(g, 10, 8, 1.7, 1.5, "w") # pec domes
|
||||
_set(g, 6, 8, "c"); _set(g, 10, 8, "c") # steel highlights
|
||||
_vline(g, 8, 7, 13, "K") # center ridge
|
||||
_hline(g, 6, 9, 12, "K") # belt
|
||||
for x, y in ((5, 7), (10, 7)):
|
||||
_set(g, x, y, "b") # rivets
|
||||
return g
|
||||
|
||||
|
||||
def _potion(color):
|
||||
def draw():
|
||||
g = _blank()
|
||||
_vline(g, 6, 3, 5, "w"); _vline(g, 10, 3, 5, "w") # neck
|
||||
_hline(g, 6, 10, 3, "w")
|
||||
_set(g, 8, 2, "h") # cork
|
||||
_disc(g, 8, 9, 3.3, 3.3, "w") # flask
|
||||
_disc(g, 8, 9, 2.5, 2.5, color) # liquid
|
||||
_set(g, 7, 8, "w") # gloss
|
||||
return g
|
||||
return draw
|
||||
|
||||
|
||||
def _scroll(emblem):
|
||||
def draw():
|
||||
g = _blank()
|
||||
# rolled scroll: horizontal cylinder with capped ends
|
||||
_rect(g, 3, 7, 12, 11, "c") # paper body
|
||||
_hline(g, 3, 12, 7, "b"); _hline(g, 3, 12, 11, "b") # roll shading
|
||||
_disc(g, 3, 9, 1.2, 2.6, "b"); _disc(g, 12, 9, 1.2, 2.6, "b") # end knobs
|
||||
_disc(g, 3, 9, 0.7, 1.7, "c"); _disc(g, 12, 9, 0.7, 1.7, "c")
|
||||
_vline(g, 7, 6, 12, "y"); _vline(g, 8, 6, 12, "y") # tie ribbon
|
||||
emblem(g) # floating magic emblem up top
|
||||
return g
|
||||
return draw
|
||||
|
||||
|
||||
def _emblem_fireball(g):
|
||||
_tri(g, 5, 5, 11, 5, 8, 0, "o") # flame
|
||||
_set(g, 8, 1, "y"); _set(g, 7, 2, "y"); _set(g, 9, 2, "y")
|
||||
_set(g, 8, 3, "r")
|
||||
|
||||
|
||||
def _emblem_teleport(g):
|
||||
_vline(g, 8, 1, 5, "E"); _hline(g, 6, 10, 3, "E") # 4-point star
|
||||
_set(g, 6, 1, "c"); _set(g, 10, 1, "c"); _set(g, 6, 5, "c"); _set(g, 10, 5, "c")
|
||||
_set(g, 8, 3, "w")
|
||||
|
||||
|
||||
def _emblem_mapping(g):
|
||||
_frame(g, 5, 1, 11, 5, "b") # map frame
|
||||
_hline(g, 6, 10, 2, "c")
|
||||
_set(g, 6, 3, "y"); _set(g, 9, 4, "y") # landmarks
|
||||
_line(g, 6, 3, 10, 4, "c") # road
|
||||
|
||||
|
||||
def _stairs():
|
||||
g = _blank()
|
||||
_rect(g, 1, 11, 14, 14, "y") # bottom landing
|
||||
_rect(g, 1, 9, 12, 11, "y") # mid step
|
||||
_rect(g, 1, 7, 10, 9, "y") # upper step
|
||||
_rect(g, 1, 5, 8, 7, "y") # top step
|
||||
_hline(g, 1, 14, 11, "o"); _hline(g, 1, 12, 9, "o") # lit tread edges
|
||||
_hline(g, 1, 10, 7, "o"); _hline(g, 1, 8, 5, "o")
|
||||
_hline(g, 1, 14, 14, "K") # base shadow
|
||||
_line(g, 5, 2, 9, 4, "w"); _line(g, 9, 4, 5, 4, "w") # down-chevron into the hole
|
||||
_set(g, 9, 4, "y")
|
||||
return g
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Registry
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _build() -> dict[str, list[list[str]]]:
|
||||
s: dict[str, list[list[str]]] = {}
|
||||
s["player"] = s["player_down"] = _eframes(_player_down())
|
||||
s["player_up"] = _eframes(_player_up())
|
||||
s["player_right"] = _eframes(_player_right())
|
||||
s["player_left"] = _eframes(_flip(_player_right()))
|
||||
|
||||
for name, fn in (
|
||||
("rat", _rat), ("goblin", _goblin), ("skeleton_archer", _skeleton_archer),
|
||||
("orc_warrior", _orc_warrior), ("wraith", _wraith), ("green_slime", _slime),
|
||||
("small_slime", _small_slime), ("ancient_dragon", _dragon),
|
||||
):
|
||||
s[name] = _eframes(fn())
|
||||
|
||||
for name, fn in (
|
||||
("weapon_dagger", _dagger), ("weapon_sword", _sword),
|
||||
("weapon_axe", _axe), ("weapon_hammer", _hammer),
|
||||
("armor_leather", _leather), ("armor_chain", _chain),
|
||||
("armor_plate", _plate),
|
||||
):
|
||||
s[name] = _iframe(fn())
|
||||
|
||||
s["potion_healing"] = _iframe(_potion("m")())
|
||||
s["potion_strength"] = _iframe(_potion("o")())
|
||||
s["potion_invisibility"] = _iframe(_potion("p")())
|
||||
s["scroll_fireball"] = _iframe(_scroll(_emblem_fireball)())
|
||||
s["scroll_teleport"] = _iframe(_scroll(_emblem_teleport)())
|
||||
s["scroll_mapping"] = _iframe(_scroll(_emblem_mapping)())
|
||||
|
||||
s["stairs"] = _eframes(_stairs())
|
||||
return s
|
||||
|
||||
|
||||
SPRITES: dict[str, list[list[str]]] = _build()
|
||||
NAMES: list[str] = sorted(SPRITES.keys())
|
||||
|
||||
|
||||
def frames_count(name: str) -> int:
|
||||
return len(SPRITES[name]) if name in SPRITES else 1
|
||||
|
||||
|
||||
def grid(name: str, frame: int = 0) -> list[str]:
|
||||
"""Return the frame's row list for `name` (frame wraps modulo count)."""
|
||||
frames = SPRITES.get(name)
|
||||
if not frames:
|
||||
return ["................"] * SIZE
|
||||
return frames[frame % len(frames)]
|
||||
|
||||
|
||||
if __name__ == "__main__": # tiny self-check
|
||||
for n in NAMES:
|
||||
grd = grid(n, 0)
|
||||
assert len(grd) == SIZE and all(len(r) == SIZE for r in grd), n
|
||||
print(f"{len(NAMES)} sprites, all {SIZE}x{SIZE}: {', '.join(NAMES)}")
|
||||
Whitespace-only changes.
@@ -0,0 +1,256 @@
|
||||
"""Gameplay actions: pure functions that mutate a GameSession (plan.md §6, §9).
|
||||
|
||||
`try_move` is the turn driver — a successful move or attack advances the turn,
|
||||
runs enemy AI, recomputes FOV, ticks effect timers, and checks for death.
|
||||
`pickup` / `descend` / `use_item` / `equip` are resolution actions; they log and
|
||||
mutate but leave turn advancement to the caller so item use stays deterministic
|
||||
(a potion must not let an enemy sneak in a hit between quaff and the HP check).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from data import constants as C
|
||||
from ai.behaviors import on_death, take_enemy_turn
|
||||
from engine.combat import attack
|
||||
from engine import game_state
|
||||
from engine.game_state import recompute_fov
|
||||
from engine.map_gen import is_walkable
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
from entities.player import Effect
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Movement / melee
|
||||
# --------------------------------------------------------------------------- #
|
||||
def try_move(session, dx: int, dy: int) -> bool:
|
||||
"""Move the player by (dx, dy) or melee an enemy there. Returns whether the
|
||||
player acted (and thus a turn elapsed)."""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
nx, ny = player.x + dx, player.y + dy
|
||||
|
||||
if not (0 <= nx < floor.width and 0 <= ny < floor.height):
|
||||
return False
|
||||
if dx or dy:
|
||||
player.facing = _facing(dx, dy)
|
||||
|
||||
target = _enemy_at(floor, nx, ny)
|
||||
if target is not None:
|
||||
res = attack(player, target, rng=session.rng, log=session.log)
|
||||
if res["killed"]:
|
||||
on_death(target, session)
|
||||
_end_turn(session)
|
||||
return True
|
||||
|
||||
if floor.tiles[ny][nx] == 1 and not _blocked_at(floor, nx, ny):
|
||||
player.x, player.y = nx, ny
|
||||
_end_turn(session)
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _end_turn(session) -> None:
|
||||
"""One turn elapsed: counter up, FOV, enemy turns, effect timers, death."""
|
||||
session.turn += 1
|
||||
recompute_fov(session)
|
||||
_enemy_turns(session)
|
||||
_tick_effects(session)
|
||||
if session.player.hp <= 0 and session.state == "playing":
|
||||
game_state.mark_dead(session)
|
||||
session.log.append("You have died.")
|
||||
|
||||
|
||||
def _enemy_turns(session) -> None:
|
||||
floor = session.dungeon[session.current_floor]
|
||||
for e in list(floor.entities):
|
||||
if isinstance(e, Enemy) and e.hp > 0:
|
||||
take_enemy_turn(e, session, rng=session.rng)
|
||||
if session.player.hp <= 0:
|
||||
return
|
||||
|
||||
|
||||
def _tick_effects(session) -> None:
|
||||
player = session.player
|
||||
if not player.effects:
|
||||
return
|
||||
remaining: list = []
|
||||
for eff in player.effects:
|
||||
eff.duration -= 1
|
||||
if eff.duration > 0:
|
||||
remaining.append(eff)
|
||||
elif eff.kind == "invisibility":
|
||||
player.invisible = False
|
||||
session.log.append("You fade back into view.")
|
||||
player.effects = remaining
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Pickup / descend
|
||||
# --------------------------------------------------------------------------- #
|
||||
def pickup(session) -> bool:
|
||||
"""Move the item under the player into inventory. False if nothing there."""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
for e in list(floor.entities):
|
||||
if isinstance(e, Item) and e.x == player.x and e.y == player.y:
|
||||
floor.entities.remove(e)
|
||||
player.inventory.append(e)
|
||||
session.log.append(f"You pick up the {e.name}.")
|
||||
return True
|
||||
session.log.append("There is nothing here to pick up.")
|
||||
return False
|
||||
|
||||
|
||||
def descend(session) -> bool:
|
||||
"""Descend the stairs the player stands on. False if not on stairs / last floor."""
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
if (player.x, player.y) != floor.stairs_down:
|
||||
session.log.append("There are no stairs here.")
|
||||
return False
|
||||
if session.current_floor >= C.FLOORS - 1:
|
||||
return False # no descent past the boss floor
|
||||
|
||||
session.current_floor += 1
|
||||
new_floor = session.dungeon[session.current_floor]
|
||||
spawn = new_floor.rooms[0].center if new_floor.rooms else _first_walkable(new_floor)
|
||||
if not is_walkable(new_floor, *spawn):
|
||||
spawn = _first_walkable(new_floor)
|
||||
player.x, player.y = spawn
|
||||
recompute_fov(session)
|
||||
session.log.append(f"You descend to floor {session.current_floor + 1}.")
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Use / equip
|
||||
# --------------------------------------------------------------------------- #
|
||||
def use_item(session, item) -> None:
|
||||
"""Apply a potion/scroll, or equip a weapon/armor. Consumes consumables."""
|
||||
if item.item_type == "potion":
|
||||
_use_potion(session, item)
|
||||
_consume(session, item)
|
||||
elif item.item_type == "scroll":
|
||||
_use_scroll(session, item)
|
||||
_consume(session, item)
|
||||
elif item.item_type in ("weapon", "armor"):
|
||||
equip(session, item)
|
||||
else:
|
||||
session.log.append(f"You can't use the {item.name}.")
|
||||
|
||||
|
||||
def equip(session, item) -> None:
|
||||
"""Place an equippable in its slot; the previous item returns to inventory."""
|
||||
player = session.player
|
||||
if item.item_type not in ("weapon", "armor"):
|
||||
session.log.append(f"You can't equip the {item.name}.")
|
||||
return
|
||||
slot = item.item_type
|
||||
old = player.equipped.get(slot)
|
||||
player.equipped[slot] = item
|
||||
if item in player.inventory:
|
||||
player.inventory.remove(item)
|
||||
if old is not None:
|
||||
player.inventory.append(old)
|
||||
session.log.append(f"You unequip the {old.name}.")
|
||||
session.log.append(f"You equip the {item.name}.")
|
||||
|
||||
|
||||
def _use_potion(session, item) -> None:
|
||||
player = session.player
|
||||
if item.subtype == "healing":
|
||||
amount = item.stats.get("heal", 30)
|
||||
player.hp = min(player.max_hp, player.hp + amount)
|
||||
session.log.append(f"You quaff a Healing Potion and recover {amount} HP.")
|
||||
elif item.subtype == "strength":
|
||||
player.effects.append(Effect(
|
||||
kind="strength",
|
||||
power=item.stats.get("power", 5),
|
||||
duration=item.stats.get("duration", 20),
|
||||
))
|
||||
session.log.append("Your muscles surge! (+5 power for 20 turns)")
|
||||
elif item.subtype == "invisibility":
|
||||
player.effects.append(Effect(
|
||||
kind="invisibility",
|
||||
duration=item.stats.get("duration", 15),
|
||||
))
|
||||
player.invisible = True
|
||||
session.log.append("You fade from sight!")
|
||||
|
||||
|
||||
def _use_scroll(session, item) -> None:
|
||||
player = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
if item.subtype == "fireball":
|
||||
radius = item.stats.get("radius", 3)
|
||||
dmg = item.stats.get("damage", 20)
|
||||
hit = [e for e in floor.entities
|
||||
if isinstance(e, Enemy)
|
||||
and max(abs(e.x - player.x), abs(e.y - player.y)) <= radius]
|
||||
for e in hit:
|
||||
e.hp -= dmg
|
||||
session.log.append(f"The fireball erupts! {len(hit)} foe(s) burn for {dmg} damage.")
|
||||
for e in hit:
|
||||
if e.hp <= 0:
|
||||
on_death(e, session)
|
||||
elif item.subtype == "teleport":
|
||||
targets = [
|
||||
(x, y) for y in range(floor.height) for x in range(floor.width)
|
||||
if floor.tiles[y][x] == 1
|
||||
and (x, y) != (player.x, player.y)
|
||||
and not _blocked_at(floor, x, y)
|
||||
]
|
||||
if targets:
|
||||
player.x, player.y = session.rng.choice(targets)
|
||||
recompute_fov(session)
|
||||
session.log.append("The world blurs — you teleport across the floor!")
|
||||
elif item.subtype == "mapping":
|
||||
for y in range(floor.height):
|
||||
for x in range(floor.width):
|
||||
if floor.tiles[y][x] == 1:
|
||||
floor.explored[y][x] = True
|
||||
session.log.append("A complete map of this floor floods your mind!")
|
||||
|
||||
|
||||
def _consume(session, item) -> None:
|
||||
if item in session.player.inventory:
|
||||
session.player.inventory.remove(item)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# helpers
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _enemy_at(floor, x: int, y: int):
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Enemy) and e.x == x and e.y == y:
|
||||
return e
|
||||
return None
|
||||
|
||||
|
||||
def _blocked_at(floor, x: int, y: int) -> bool:
|
||||
"""True if a blocking entity (enemy) occupies (x, y). Items never block."""
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Enemy) and e.x == x and e.y == y:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _first_walkable(game_map) -> tuple[int, int]:
|
||||
for y in range(game_map.height):
|
||||
for x in range(game_map.width):
|
||||
if game_map.tiles[y][x] == 1:
|
||||
return (x, y)
|
||||
return (1, 1)
|
||||
|
||||
|
||||
def _facing(dx: int, dy: int) -> str:
|
||||
if dy < 0:
|
||||
return "up"
|
||||
if dy > 0:
|
||||
return "down"
|
||||
if dx < 0:
|
||||
return "left"
|
||||
if dx > 0:
|
||||
return "right"
|
||||
return "down"
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Resilient generated-audio manager (plan.md Audio).
|
||||
|
||||
Every sound is synthesized in memory from a stdlib `array` of PCM samples — no
|
||||
asset files. The mixer is initialized once, lazily and defensively: if the audio
|
||||
driver is missing, `mixer.init` fails, or `Sound` creation throws, audio is
|
||||
disabled and the game keeps running silently. No public method ever raises.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import array
|
||||
import math
|
||||
import random
|
||||
|
||||
try:
|
||||
import pygame
|
||||
_HAS_PYGAME = True
|
||||
except Exception: # pragma: no cover - pygame is a hard dep, but stay safe
|
||||
pygame = None
|
||||
_HAS_PYGAME = False
|
||||
|
||||
|
||||
# name -> synthesis spec: freq (Hz), dur (s), decay (envelope rate),
|
||||
# kind (sine | square | noise | sweep), optional freq2 (sweep target).
|
||||
_SPECS: dict[str, dict] = {
|
||||
"hit": dict(freq=330, dur=0.07, decay=9.0, kind="square"),
|
||||
"miss": dict(freq=180, dur=0.06, decay=10.0, kind="sine"),
|
||||
"damage": dict(freq=120, dur=0.18, decay=5.0, kind="noise"),
|
||||
"pickup": dict(freq=660, dur=0.10, decay=8.0, kind="sweep", freq2=990),
|
||||
"use": dict(freq=520, dur=0.12, decay=7.0, kind="sweep", freq2=780),
|
||||
"stairs": dict(freq=400, dur=0.16, decay=5.0, kind="sweep", freq2=600),
|
||||
"levelup": dict(freq=523, dur=0.30, decay=3.0, kind="sweep", freq2=1046),
|
||||
"death": dict(freq=200, dur=0.45, decay=2.5, kind="sweep", freq2=80),
|
||||
"victory": dict(freq=523, dur=0.50, decay=2.0, kind="sweep", freq2=1568),
|
||||
}
|
||||
|
||||
|
||||
class AudioManager:
|
||||
"""Generates and plays short SFX; degrades to silence on any audio fault."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.muted: bool = False
|
||||
self._ok: bool = False
|
||||
self._sounds: dict = {}
|
||||
self._init()
|
||||
|
||||
def play(self, name: str) -> None:
|
||||
try:
|
||||
if self.muted or not self._ok:
|
||||
return
|
||||
snd = self._sounds.get(name)
|
||||
if snd is not None:
|
||||
snd.play()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def toggle_mute(self) -> None:
|
||||
self.muted = not self.muted
|
||||
|
||||
# -- internal ------------------------------------------------------------- #
|
||||
def _init(self) -> None:
|
||||
if not _HAS_PYGAME:
|
||||
return
|
||||
try:
|
||||
if not pygame.mixer.get_init():
|
||||
pygame.mixer.init()
|
||||
except Exception:
|
||||
self._ok = False
|
||||
return
|
||||
self._ok = True
|
||||
for name, spec in _SPECS.items():
|
||||
try:
|
||||
self._sounds[name] = self._make_sound(spec)
|
||||
except Exception:
|
||||
pass # that one effect just won't play; others may still work
|
||||
|
||||
def _make_sound(self, spec: dict):
|
||||
info = pygame.mixer.get_init()
|
||||
if info is None:
|
||||
raise RuntimeError("mixer not initialized")
|
||||
rate, size, channels = info
|
||||
code = "h" if abs(size) == 16 else "b"
|
||||
maxv = (1 << (abs(size) - 1)) - 1
|
||||
n = max(1, int(rate * spec["dur"]))
|
||||
freq = spec["freq"]
|
||||
freq2 = spec.get("freq2")
|
||||
decay = spec["decay"]
|
||||
kind = spec["kind"]
|
||||
vol = 0.45
|
||||
rng = random.Random(0x5EED)
|
||||
buf = array.array(code)
|
||||
for i in range(n):
|
||||
t = i / rate
|
||||
frac = i / n
|
||||
f = freq + (freq2 - freq) * frac if (kind == "sweep" and freq2) else freq
|
||||
if kind == "noise":
|
||||
wave = rng.uniform(-1.0, 1.0)
|
||||
elif kind == "square":
|
||||
wave = 1.0 if math.sin(2 * math.pi * f * t) >= 0 else -1.0
|
||||
else:
|
||||
wave = math.sin(2 * math.pi * f * t)
|
||||
env = math.exp(-decay * t)
|
||||
s = int(maxv * env * wave * vol)
|
||||
if s > maxv:
|
||||
s = maxv
|
||||
elif s < -maxv:
|
||||
s = -maxv
|
||||
buf.extend([s] * channels)
|
||||
return pygame.mixer.Sound(buffer=buf.tobytes())
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Turn-based combat resolution (plan.md §4).
|
||||
|
||||
`attack` works for any attacker/defender pair: a Player uses total_power /
|
||||
total_armor (gear + effects), an Enemy uses its raw stats. The caller owns
|
||||
death consequences (XP, removal, state changes); attack only resolves the swing
|
||||
and logs the immediate feedback.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
|
||||
|
||||
def attack(attacker, defender, rng=None, log=None) -> dict:
|
||||
r = rng if rng is not None else random.Random()
|
||||
|
||||
acc = getattr(attacker, "accuracy", 0)
|
||||
eva = getattr(defender, "evasion", 0)
|
||||
hit_chance = max(0.1, min(0.95, 0.7 + (acc - eva) * 0.05))
|
||||
|
||||
attacker_is_player = hasattr(attacker, "total_power")
|
||||
defender_is_player = hasattr(defender, "total_armor")
|
||||
base = attacker.total_power() if attacker_is_player else attacker.power
|
||||
crit_chance = getattr(attacker, "crit_chance", 0.0)
|
||||
|
||||
hit = r.random() < hit_chance
|
||||
crit = False
|
||||
damage = 0
|
||||
if hit:
|
||||
arm = defender.total_armor() if defender_is_player else defender.armor
|
||||
reduced = max(0, base - arm)
|
||||
crit = r.random() < crit_chance
|
||||
damage = reduced * (2 if crit else 1)
|
||||
defender.hp -= damage
|
||||
|
||||
killed = defender.hp <= 0
|
||||
|
||||
if log is not None:
|
||||
_log_swing(log, attacker, defender, hit, crit, damage, attacker_is_player)
|
||||
|
||||
return {"hit": hit, "damage": damage, "crit": crit, "killed": killed}
|
||||
|
||||
|
||||
def _log_swing(log: list, attacker, defender, hit: bool, crit: bool,
|
||||
damage: int, attacker_is_player: bool) -> None:
|
||||
if not hit:
|
||||
if attacker_is_player:
|
||||
log.append(f"You miss the {defender.name}")
|
||||
else:
|
||||
log.append(f"{attacker.name} misses you")
|
||||
return
|
||||
if attacker_is_player:
|
||||
if crit:
|
||||
log.append(f"Critical hit! You hit the {defender.name} for {damage} damage!")
|
||||
else:
|
||||
log.append(f"You hit the {defender.name} for {damage} damage!")
|
||||
else:
|
||||
if crit:
|
||||
log.append(f"{attacker.name} critically strikes you for {damage} damage!")
|
||||
else:
|
||||
log.append(f"{attacker.name} hits you for {damage} damage!")
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Recursive shadowcasting field of view over 8 octants (plan.md §2).
|
||||
|
||||
Written from scratch. Walls block sight, but a wall reached by a light ray is
|
||||
itself visible (you see the wall face). `compute_fov` mutates `game_map.visible`
|
||||
to match the set it returns.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# Per-octant transforms: (xx, xy, yx, yy) map scan offsets (dx, dy) to map space.
|
||||
_OCTANTS: tuple[tuple[int, int, int, int], ...] = (
|
||||
(1, 0, 0, 1), (0, 1, 1, 0), (0, -1, 1, 0), (-1, 0, 0, 1),
|
||||
(-1, 0, 0, -1), (0, -1, -1, 0), (0, 1, -1, 0), (1, 0, 0, -1),
|
||||
)
|
||||
|
||||
|
||||
def compute_fov(game_map, ox: int, oy: int, radius: int = 8) -> set[tuple[int, int]]:
|
||||
"""Return the set of visible tiles from (ox, oy); also set game_map.visible."""
|
||||
width, height = game_map.width, game_map.height
|
||||
tiles = game_map.tiles
|
||||
|
||||
# Fresh visible grid every call so stale tiles never linger.
|
||||
for y in range(height):
|
||||
vrow = game_map.visible[y]
|
||||
for x in range(width):
|
||||
vrow[x] = False
|
||||
|
||||
visible: set[tuple[int, int]] = set()
|
||||
|
||||
def blocks(x: int, y: int) -> bool:
|
||||
if 0 <= x < width and 0 <= y < height:
|
||||
return tiles[y][x] == 0
|
||||
return True # out of bounds behaves as wall
|
||||
|
||||
def light(x: int, y: int) -> None:
|
||||
if 0 <= x < width and 0 <= y < height:
|
||||
visible.add((x, y))
|
||||
|
||||
if not (0 <= ox < width and 0 <= oy < height):
|
||||
return visible
|
||||
|
||||
light(ox, oy) # origin is always seen
|
||||
r2 = radius * radius
|
||||
|
||||
def cast(row: int, start: float, end: float,
|
||||
xx: int, xy: int, yx: int, yy: int) -> None:
|
||||
if start < end:
|
||||
return
|
||||
new_start = start
|
||||
for j in range(row, radius + 1):
|
||||
dy = -j
|
||||
dx = -j - 1
|
||||
blocked = False
|
||||
while dx <= 0:
|
||||
dx += 1
|
||||
mx = ox + dx * xx + dy * xy
|
||||
my = oy + dx * yx + dy * yy
|
||||
l_slope = (dx - 0.5) / (dy + 0.5)
|
||||
r_slope = (dx + 0.5) / (dy - 0.5)
|
||||
if start < r_slope:
|
||||
continue
|
||||
elif end > l_slope:
|
||||
break
|
||||
else:
|
||||
if dx * dx + dy * dy <= r2:
|
||||
light(mx, my)
|
||||
if blocked:
|
||||
if blocks(mx, my):
|
||||
new_start = r_slope
|
||||
continue
|
||||
else:
|
||||
blocked = False
|
||||
start = new_start
|
||||
else:
|
||||
if blocks(mx, my) and j < radius:
|
||||
blocked = True
|
||||
cast(j + 1, start, l_slope, xx, xy, yx, yy)
|
||||
new_start = r_slope
|
||||
if blocked:
|
||||
break
|
||||
|
||||
for (xx, xy, yx, yy) in _OCTANTS:
|
||||
cast(1, 1.0, 0.0, xx, xy, yx, yy)
|
||||
|
||||
for (x, y) in visible:
|
||||
game_map.visible[y][x] = True
|
||||
|
||||
return visible
|
||||
@@ -0,0 +1,130 @@
|
||||
"""GameSession: the single source of truth for all mutable game state.
|
||||
|
||||
It holds the player, all 10 floors, the message log, turn counter, and game
|
||||
state string. `new_game` builds a fresh dive; `recompute_fov` refreshes the
|
||||
player's sight and merges it into the explored memory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from data import constants as C
|
||||
from engine import map_gen
|
||||
from engine.fov import compute_fov
|
||||
from entities.player import Player
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameSession:
|
||||
player: Player
|
||||
dungeon: list
|
||||
current_floor: int = 0
|
||||
log: list = field(default_factory=list)
|
||||
turn: int = 0
|
||||
state: str = "playing"
|
||||
rng: random.Random = field(default_factory=random.Random)
|
||||
|
||||
|
||||
def new_game(seed: int | None = None) -> GameSession:
|
||||
rng = random.Random(seed)
|
||||
# generate_dungeon draws from the global random module; seed it too so the
|
||||
# entire dive is deterministic from `seed`.
|
||||
random.seed(seed)
|
||||
|
||||
player = Player(0, 0)
|
||||
|
||||
dungeon = []
|
||||
for fi in range(C.FLOORS):
|
||||
floor = map_gen.generate_dungeon(fi)
|
||||
map_gen.populate(floor, fi, rng=rng)
|
||||
dungeon.append(floor)
|
||||
|
||||
# Player starts at the center of the first room on floor 0.
|
||||
spawn = dungeon[0].rooms[0].center
|
||||
if not map_gen.is_walkable(dungeon[0], *spawn):
|
||||
spawn = _first_walkable(dungeon[0])
|
||||
player.x, player.y = spawn
|
||||
|
||||
session = GameSession(
|
||||
player=player,
|
||||
dungeon=dungeon,
|
||||
current_floor=0,
|
||||
log=["You enter the Underdepths. Find the stairs and descend."],
|
||||
turn=0,
|
||||
state="playing",
|
||||
rng=rng,
|
||||
)
|
||||
recompute_fov(session)
|
||||
return session
|
||||
|
||||
|
||||
def recompute_fov(session: GameSession) -> None:
|
||||
floor = session.dungeon[session.current_floor]
|
||||
visible = compute_fov(floor, session.player.x, session.player.y, C.SIGHT_RADIUS)
|
||||
for (x, y) in visible:
|
||||
floor.explored[y][x] = True
|
||||
|
||||
|
||||
def _first_walkable(game_map) -> tuple[int, int]:
|
||||
for y in range(game_map.height):
|
||||
for x in range(game_map.width):
|
||||
if game_map.tiles[y][x] == 1:
|
||||
return (x, y)
|
||||
return (1, 1)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Persistence + permadeath
|
||||
# --------------------------------------------------------------------------- #
|
||||
_GAME_DIR: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
|
||||
def _save_path(path: str) -> str:
|
||||
"""Resolve a save path relative to the game directory unless it is absolute."""
|
||||
return path if os.path.isabs(path) else os.path.join(_GAME_DIR, path)
|
||||
|
||||
|
||||
def save(session: GameSession, path: str = "save.json") -> str:
|
||||
"""Serialize the session to JSON in the game directory. Returns the file path."""
|
||||
from engine.serializers import session_to_dict
|
||||
full = _save_path(path)
|
||||
with open(full, "w", encoding="utf-8") as f:
|
||||
json.dump(session_to_dict(session), f)
|
||||
return full
|
||||
|
||||
|
||||
def load(path: str = "save.json") -> GameSession:
|
||||
"""Read a saved session JSON and rebuild a live GameSession (FOV recomputed)."""
|
||||
from engine.serializers import dict_to_session
|
||||
with open(_save_path(path), "r", encoding="utf-8") as f:
|
||||
return dict_to_session(json.load(f))
|
||||
|
||||
|
||||
def has_save(path: str = "save.json") -> bool:
|
||||
"""True when a save file exists (drives the menu's 'Continue' entry)."""
|
||||
return os.path.isfile(_save_path(path))
|
||||
|
||||
|
||||
def delete_save(path: str = "save.json") -> None:
|
||||
"""Remove the save file if present. Never raises."""
|
||||
full = _save_path(path)
|
||||
try:
|
||||
if os.path.isfile(full):
|
||||
os.remove(full)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def mark_dead(session: GameSession) -> None:
|
||||
"""End the run on player death: flag the state and delete the save (permadeath)."""
|
||||
session.state = "dead"
|
||||
delete_save()
|
||||
|
||||
|
||||
def mark_victory(session: GameSession) -> None:
|
||||
"""End the run on victory: flag the state and delete the save."""
|
||||
session.state = "victory"
|
||||
delete_save()
|
||||
@@ -0,0 +1,309 @@
|
||||
"""BSP dungeon generation, the GameMap/Rect model, and per-floor population."""
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass
|
||||
|
||||
from data import constants as C
|
||||
from entities.enemy import make_enemy, kinds_for_floor
|
||||
from entities.item import make_item, item_pool_for_floor
|
||||
|
||||
# BSP / room sizing. Rooms are 4x4..10x8 (plan.md §1); leaves must hold one.
|
||||
MIN_LEAF: int = 8
|
||||
MIN_ROOM_W: int = 4
|
||||
MIN_ROOM_H: int = 4
|
||||
MAX_ROOM_W: int = 10
|
||||
MAX_ROOM_H: int = 8
|
||||
BOSS_ROOM_W: int = 20
|
||||
BOSS_ROOM_H: int = 15
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Rect:
|
||||
x: int
|
||||
y: int
|
||||
w: int
|
||||
h: int
|
||||
|
||||
@property
|
||||
def center(self) -> tuple[int, int]:
|
||||
return (self.x + self.w // 2, self.y + self.h // 2)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class GameMap:
|
||||
width: int
|
||||
height: int
|
||||
tiles: list[list[int]] # 0 = wall, 1 = floor
|
||||
rooms: list[Rect]
|
||||
explored: list[list[bool]]
|
||||
visible: list[list[bool]]
|
||||
entities: list # enemies + items present on this floor
|
||||
stairs_down: tuple[int, int]
|
||||
floor_index: int
|
||||
|
||||
|
||||
def is_walkable(game_map: GameMap, x: int, y: int) -> bool:
|
||||
"""True if (x, y) is in bounds and a floor tile."""
|
||||
if not (0 <= x < game_map.width and 0 <= y < game_map.height):
|
||||
return False
|
||||
return game_map.tiles[y][x] == 1
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Generation
|
||||
# --------------------------------------------------------------------------- #
|
||||
def generate_dungeon(floor_index: int, width: int = C.MAP_WIDTH,
|
||||
height: int = C.MAP_HEIGHT) -> GameMap:
|
||||
"""Generate one floor via BSP (floors 0-8) or a boss arena (floor 9).
|
||||
|
||||
Uses the global `random` state so new_game(seed) can seed the whole dive.
|
||||
"""
|
||||
tiles: list[list[int]] = [[0] * width for _ in range(height)]
|
||||
if floor_index == C.FLOORS - 1:
|
||||
return _boss_arena(floor_index, width, height, tiles)
|
||||
|
||||
# Working area sits inside the 1-tile wall border.
|
||||
root = {"x": 1, "y": 1, "w": width - 2, "h": height - 2}
|
||||
_build_bsp(root, random.randint(5, 8))
|
||||
|
||||
leaves: list[dict] = []
|
||||
_collect_leaves(root, leaves)
|
||||
rooms: list[Rect] = []
|
||||
for leaf in leaves:
|
||||
leaf["room"] = _carve_room(leaf, tiles, width, height)
|
||||
rooms.append(leaf["room"])
|
||||
_connect(root, tiles, width, height)
|
||||
|
||||
# Stairs go in the room farthest from the spawn room.
|
||||
spawn = rooms[0].center
|
||||
stairs_room = max(rooms, key=lambda r: _dist2(r.center, spawn))
|
||||
|
||||
explored = [[False] * width for _ in range(height)]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
return GameMap(width, height, tiles, rooms, explored, visible, [],
|
||||
stairs_room.center, floor_index)
|
||||
|
||||
|
||||
def _build_bsp(root: dict, target_splits: int) -> None:
|
||||
"""Split the largest splittable leaf until target_splits splits are done."""
|
||||
splittable = [root]
|
||||
done = 0
|
||||
prefer_horiz = True
|
||||
while done < target_splits and splittable:
|
||||
splittable.sort(key=lambda n: n["w"] * n["h"], reverse=True)
|
||||
node = splittable.pop(0)
|
||||
halves = _split_node(node, prefer_horiz)
|
||||
prefer_horiz = not prefer_horiz
|
||||
if halves is None:
|
||||
continue # this leaf can't be split; it stays a leaf
|
||||
left, right = halves
|
||||
node["left"] = left
|
||||
node["right"] = right
|
||||
splittable.append(left)
|
||||
splittable.append(right)
|
||||
done += 1
|
||||
|
||||
|
||||
def _split_node(node: dict, prefer_horiz: bool) -> tuple[dict, dict] | None:
|
||||
"""Split a region on the preferred axis, falling back to the other.
|
||||
|
||||
Returns the two child regions, or None if neither axis can be split.
|
||||
"""
|
||||
use_horiz = prefer_horiz
|
||||
if use_horiz and node["w"] < 2 * MIN_LEAF:
|
||||
use_horiz = False
|
||||
if not use_horiz and node["h"] < 2 * MIN_LEAF:
|
||||
use_horiz = True
|
||||
length = node["w"] if use_horiz else node["h"]
|
||||
if length < 2 * MIN_LEAF:
|
||||
return None
|
||||
p = random.randint(MIN_LEAF, length - MIN_LEAF)
|
||||
if use_horiz:
|
||||
left = {"x": node["x"], "y": node["y"], "w": p, "h": node["h"]}
|
||||
right = {"x": node["x"] + p, "y": node["y"], "w": node["w"] - p, "h": node["h"]}
|
||||
else:
|
||||
left = {"x": node["x"], "y": node["y"], "w": node["w"], "h": p}
|
||||
right = {"x": node["x"], "y": node["y"] + p, "w": node["w"], "h": node["h"] - p}
|
||||
return left, right
|
||||
|
||||
|
||||
def _collect_leaves(node: dict, out: list[dict]) -> None:
|
||||
if "left" in node:
|
||||
_collect_leaves(node["left"], out)
|
||||
_collect_leaves(node["right"], out)
|
||||
else:
|
||||
out.append(node)
|
||||
|
||||
|
||||
def _carve_room(leaf: dict, tiles: list[list[int]], width: int, height: int) -> Rect:
|
||||
"""Carve a room (4x4..10x8) inside the leaf, shrunk from its edges."""
|
||||
shrink = random.randint(1, 2)
|
||||
max_w = max(MIN_ROOM_W, leaf["w"] - 2 * shrink)
|
||||
max_h = max(MIN_ROOM_H, leaf["h"] - 2 * shrink)
|
||||
rw = random.randint(MIN_ROOM_W, min(MAX_ROOM_W, max_w))
|
||||
rh = random.randint(MIN_ROOM_H, min(MAX_ROOM_H, max_h))
|
||||
ox = random.randint(shrink, max(shrink, leaf["w"] - rw - shrink))
|
||||
oy = random.randint(shrink, max(shrink, leaf["h"] - rh - shrink))
|
||||
rx = leaf["x"] + ox
|
||||
ry = leaf["y"] + oy
|
||||
for y in range(ry, ry + rh):
|
||||
for x in range(rx, rx + rw):
|
||||
if 0 <= y < height and 0 <= x < width:
|
||||
tiles[y][x] = 1
|
||||
return Rect(rx, ry, rw, rh)
|
||||
|
||||
|
||||
def _connect(node: dict, tiles: list[list[int]], width: int, height: int) -> Rect | None:
|
||||
"""Carve L-corridors between sibling subtree rooms so all rooms connect."""
|
||||
if "left" not in node:
|
||||
return node.get("room")
|
||||
lr = _connect(node["left"], tiles, width, height)
|
||||
rr = _connect(node["right"], tiles, width, height)
|
||||
if lr is not None and rr is not None:
|
||||
_carve_corridor(lr.center, rr.center, tiles, width, height)
|
||||
return lr if lr is not None else rr
|
||||
|
||||
|
||||
def _carve_corridor(a: tuple[int, int], b: tuple[int, int],
|
||||
tiles: list[list[int]], width: int, height: int) -> None:
|
||||
x1, y1 = a
|
||||
x2, y2 = b
|
||||
if random.random() < 0.5:
|
||||
_h_tunnel(x1, x2, y1, tiles, width, height)
|
||||
_v_tunnel(y1, y2, x2, tiles, width, height)
|
||||
else:
|
||||
_v_tunnel(y1, y2, x1, tiles, width, height)
|
||||
_h_tunnel(x1, x2, y2, tiles, width, height)
|
||||
|
||||
|
||||
def _h_tunnel(x1: int, x2: int, y: int, tiles: list[list[int]],
|
||||
width: int, height: int) -> None:
|
||||
for x in range(min(x1, x2), max(x1, x2) + 1):
|
||||
if 0 <= y < height and 0 <= x < width:
|
||||
tiles[y][x] = 1
|
||||
|
||||
|
||||
def _v_tunnel(y1: int, y2: int, x: int, tiles: list[list[int]],
|
||||
width: int, height: int) -> None:
|
||||
for y in range(min(y1, y2), max(y1, y2) + 1):
|
||||
if 0 <= y < height and 0 <= x < width:
|
||||
tiles[y][x] = 1
|
||||
|
||||
|
||||
def _boss_arena(floor_index: int, width: int, height: int,
|
||||
tiles: list[list[int]]) -> GameMap:
|
||||
"""Floor 9: a single large room; the dragon is placed by populate()."""
|
||||
rw, rh = BOSS_ROOM_W, BOSS_ROOM_H
|
||||
rx = (width - rw) // 2
|
||||
ry = (height - rh) // 2
|
||||
for y in range(ry, ry + rh):
|
||||
for x in range(rx, rx + rw):
|
||||
tiles[y][x] = 1
|
||||
room = Rect(rx, ry, rw, rh)
|
||||
stairs = (rx + rw // 2, ry + rh - 2) # unused for descent; victory ends the run
|
||||
explored = [[False] * width for _ in range(height)]
|
||||
visible = [[False] * width for _ in range(height)]
|
||||
return GameMap(width, height, tiles, [room], explored, visible, [],
|
||||
stairs, floor_index)
|
||||
|
||||
|
||||
def _dist2(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Population
|
||||
# --------------------------------------------------------------------------- #
|
||||
def populate(game_map: GameMap, floor_index: int, rng: random.Random | None = None) -> None:
|
||||
"""Place enemies AND items per the plan's per-floor distribution. Never raises.
|
||||
|
||||
Floor 9 (boss) gets the dragon plus exactly two healing potions near the
|
||||
entrance; every other floor gets enemies and items drawn from the roster /
|
||||
catalog, depth-gated.
|
||||
"""
|
||||
r = rng if rng is not None else random
|
||||
|
||||
if floor_index == C.FLOORS - 1:
|
||||
room = game_map.rooms[0]
|
||||
dx, dy = room.x + room.w // 2, room.y + 2
|
||||
if not is_walkable(game_map, dx, dy):
|
||||
ft = _first_floor_tile(game_map)
|
||||
if ft is None:
|
||||
return
|
||||
dx, dy = ft
|
||||
game_map.entities.append(make_enemy("ancient_dragon", dx, dy))
|
||||
_place_boss_potions(game_map, room, r)
|
||||
return
|
||||
|
||||
lo, hi = C.ENEMY_COUNT[floor_index]
|
||||
n = r.randint(lo, hi)
|
||||
pool = [
|
||||
(x, y) for y in range(game_map.height) for x in range(game_map.width)
|
||||
if game_map.tiles[y][x] == 1 and (x, y) != game_map.stairs_down
|
||||
]
|
||||
if not pool:
|
||||
return
|
||||
kinds = kinds_for_floor(floor_index)
|
||||
if not kinds:
|
||||
return
|
||||
|
||||
r.shuffle(pool)
|
||||
placed = 0
|
||||
for tile in pool:
|
||||
if placed >= n:
|
||||
break
|
||||
kind = r.choice(kinds)
|
||||
game_map.entities.append(make_enemy(kind, tile[0], tile[1]))
|
||||
placed += 1
|
||||
_place_items(game_map, floor_index, r)
|
||||
|
||||
|
||||
def _place_items(game_map: GameMap, floor_index: int, r) -> None:
|
||||
"""Scatter ITEM_COUNT items from the depth-weighted pool across floor tiles."""
|
||||
lo, hi = C.ITEM_COUNT[floor_index]
|
||||
n = r.randint(lo, hi)
|
||||
pool = [
|
||||
(x, y) for y in range(game_map.height) for x in range(game_map.width)
|
||||
if game_map.tiles[y][x] == 1 and (x, y) != game_map.stairs_down
|
||||
]
|
||||
if not pool:
|
||||
return
|
||||
r.shuffle(pool)
|
||||
names = item_pool_for_floor(floor_index)
|
||||
placed = 0
|
||||
for tile in pool:
|
||||
if placed >= n:
|
||||
break
|
||||
game_map.entities.append(make_item(r.choice(names), tile[0], tile[1]))
|
||||
placed += 1
|
||||
|
||||
|
||||
def _place_boss_potions(game_map: GameMap, room: Rect, r) -> None:
|
||||
"""Put two Healing Potions by the boss-room entrance (far side from the dragon)."""
|
||||
ex, ey = room.center[0], room.y + room.h - 2
|
||||
placed = 0
|
||||
for dx in (-1, 0, 1):
|
||||
if placed >= 2:
|
||||
break
|
||||
x, y = ex + dx, ey
|
||||
if is_walkable(game_map, x, y):
|
||||
game_map.entities.append(make_item("Healing Potion", x, y))
|
||||
placed += 1
|
||||
if placed < 2: # entrance row blocked: fall back to any floor tiles
|
||||
pool = [(x, y) for y in range(game_map.height) for x in range(game_map.width)
|
||||
if game_map.tiles[y][x] == 1]
|
||||
r.shuffle(pool)
|
||||
for (x, y) in pool:
|
||||
if placed >= 2:
|
||||
break
|
||||
game_map.entities.append(make_item("Healing Potion", x, y))
|
||||
placed += 1
|
||||
|
||||
|
||||
def _first_floor_tile(game_map: GameMap) -> tuple[int, int] | None:
|
||||
for y in range(game_map.height):
|
||||
for x in range(game_map.width):
|
||||
if game_map.tiles[y][x] == 1:
|
||||
return (x, y)
|
||||
return None
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Grid A* pathfinding with a Manhattan heuristic (plan.md §3)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
|
||||
|
||||
def astar(game_map, start, goal, blocked=frozenset()) -> list[tuple[int, int]] | None:
|
||||
"""Shortest floor path from start to goal, or None if unreachable.
|
||||
|
||||
Walkable tiles are in-bounds floor tiles. `blocked` marks extra impassable
|
||||
tiles (other entities) except that the goal is always reachable even if it
|
||||
sits in `blocked` (an enemy may path up to its target). Returns the path
|
||||
including both endpoints; None if start/goal is a wall or out of bounds.
|
||||
"""
|
||||
sx, sy = start
|
||||
gx, gy = goal
|
||||
|
||||
if not _is_floor(game_map, sx, sy) or not _is_floor(game_map, gx, gy):
|
||||
return None
|
||||
if start == goal:
|
||||
return [(sx, sy)]
|
||||
|
||||
blocked_set = set(blocked)
|
||||
open_heap: list[tuple[int, int, tuple[int, int]]] = []
|
||||
g_score: dict[tuple[int, int], int] = {start: 0}
|
||||
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
counter = 0
|
||||
heapq.heappush(open_heap, (_manhattan(start, goal), counter, start))
|
||||
closed: set[tuple[int, int]] = set()
|
||||
|
||||
while open_heap:
|
||||
_, _, current = heapq.heappop(open_heap)
|
||||
if current in closed:
|
||||
continue
|
||||
if current == goal:
|
||||
return _reconstruct(came_from, current)
|
||||
closed.add(current)
|
||||
cx, cy = current
|
||||
for nx, ny in ((cx + 1, cy), (cx - 1, cy), (cx, cy + 1), (cx, cy - 1)):
|
||||
nb = (nx, ny)
|
||||
if nb in closed or not _is_floor(game_map, nx, ny):
|
||||
continue
|
||||
if nb in blocked_set and nb != goal:
|
||||
continue
|
||||
tentative = g_score[current] + 1
|
||||
if tentative < g_score.get(nb, 1_000_000):
|
||||
g_score[nb] = tentative
|
||||
came_from[nb] = current
|
||||
counter += 1
|
||||
heapq.heappush(open_heap, (tentative + _manhattan(nb, goal), counter, nb))
|
||||
return None
|
||||
|
||||
|
||||
def _is_floor(game_map, x: int, y: int) -> bool:
|
||||
return (0 <= x < game_map.width and 0 <= y < game_map.height
|
||||
and game_map.tiles[y][x] == 1)
|
||||
|
||||
|
||||
def _manhattan(a: tuple[int, int], b: tuple[int, int]) -> int:
|
||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
||||
|
||||
|
||||
def _reconstruct(came_from: dict, current: tuple[int, int]) -> list[tuple[int, int]]:
|
||||
path = [current]
|
||||
while current in came_from:
|
||||
current = came_from[current]
|
||||
path.append(current)
|
||||
path.reverse()
|
||||
return path
|
||||
@@ -0,0 +1,224 @@
|
||||
"""JSON save/load: exact round-trip serialization of a GameSession.
|
||||
|
||||
The `visible` grids are intentionally NOT serialized — they are recomputed via
|
||||
`recompute_fov` on load. Every other field of Player / Enemy / Item is preserved
|
||||
verbatim, including per-instance enemy state (damaged HP, last-known position,
|
||||
small-slime `can_split=False`, act counters) so a loaded dive matches the saved
|
||||
dive exactly. Entities are reconstructed directly from their serialized fields
|
||||
rather than via `make_enemy`/`make_item`, which would reset mutable state to the
|
||||
roster/catalog defaults.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from engine.game_state import GameSession, recompute_fov
|
||||
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 Effect, Player
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Top level
|
||||
# --------------------------------------------------------------------------- #
|
||||
def session_to_dict(session: GameSession) -> dict:
|
||||
return {
|
||||
"player": _player_to_dict(session.player),
|
||||
"dungeon": [_map_to_dict(m) for m in session.dungeon],
|
||||
"current_floor": session.current_floor,
|
||||
"turn": session.turn,
|
||||
"log": list(session.log),
|
||||
"state": session.state,
|
||||
}
|
||||
|
||||
|
||||
def dict_to_session(d: dict) -> GameSession:
|
||||
session = GameSession(
|
||||
player=_dict_to_player(d["player"]),
|
||||
dungeon=[_dict_to_map(m) for m in d["dungeon"]],
|
||||
current_floor=d["current_floor"],
|
||||
log=list(d["log"]),
|
||||
turn=d["turn"],
|
||||
state=d["state"],
|
||||
)
|
||||
recompute_fov(session)
|
||||
return session
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Player
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _player_to_dict(p: Player) -> dict:
|
||||
return {
|
||||
"type": "player",
|
||||
"x": p.x, "y": p.y,
|
||||
"name": p.name,
|
||||
"sprite_key": p.sprite_key,
|
||||
"blocks": p.blocks,
|
||||
"hp": p.hp, "max_hp": p.max_hp,
|
||||
"power": p.power, "armor": p.armor,
|
||||
"accuracy": p.accuracy, "evasion": p.evasion,
|
||||
"crit_chance": p.crit_chance, "speed": p.speed,
|
||||
"level": p.level, "xp": p.xp,
|
||||
"inventory": [_item_to_dict(i) for i in p.inventory],
|
||||
"equipped": {
|
||||
slot: (_item_to_dict(it) if it is not None else None)
|
||||
for slot, it in p.equipped.items()
|
||||
},
|
||||
"effects": [_effect_to_dict(e) for e in p.effects],
|
||||
"facing": p.facing,
|
||||
"invisible": p.invisible,
|
||||
"pending_log": list(p.pending_log),
|
||||
}
|
||||
|
||||
|
||||
def _dict_to_player(d: dict) -> Player:
|
||||
p = Player(d["x"], d["y"])
|
||||
p.name = d["name"]
|
||||
p.sprite_key = d["sprite_key"]
|
||||
p.blocks = d["blocks"]
|
||||
p.hp = d["hp"]
|
||||
p.max_hp = d["max_hp"]
|
||||
p.power = d["power"]
|
||||
p.armor = d["armor"]
|
||||
p.accuracy = d["accuracy"]
|
||||
p.evasion = d["evasion"]
|
||||
p.crit_chance = d["crit_chance"]
|
||||
p.speed = d["speed"]
|
||||
p.level = d["level"]
|
||||
p.xp = d["xp"]
|
||||
p.inventory = [_dict_to_item(i) for i in d["inventory"]]
|
||||
p.equipped = {
|
||||
slot: (_dict_to_item(it) if it is not None else None)
|
||||
for slot, it in d["equipped"].items()
|
||||
}
|
||||
p.effects = [_dict_to_effect(e) for e in d["effects"]]
|
||||
p.facing = d["facing"]
|
||||
p.invisible = d["invisible"]
|
||||
p.pending_log = list(d["pending_log"])
|
||||
return p
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Effects
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _effect_to_dict(e: Effect) -> dict:
|
||||
return {"kind": e.kind, "power": e.power, "duration": e.duration}
|
||||
|
||||
|
||||
def _dict_to_effect(d: dict) -> Effect:
|
||||
return Effect(kind=d["kind"], power=d["power"], duration=d["duration"])
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Floor entities (enemies + items) — discriminated by "type"
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _entity_to_dict(e) -> dict:
|
||||
if isinstance(e, Enemy):
|
||||
return _enemy_to_dict(e)
|
||||
if isinstance(e, Item):
|
||||
return _item_to_dict(e)
|
||||
return {"type": "entity", "x": e.x, "y": e.y,
|
||||
"name": getattr(e, "name", ""), "sprite_key": getattr(e, "sprite_key", ""),
|
||||
"blocks": getattr(e, "blocks", True)}
|
||||
|
||||
|
||||
def _dict_to_entity(d):
|
||||
t = d.get("type")
|
||||
if t == "enemy":
|
||||
return _dict_to_enemy(d)
|
||||
if t == "item":
|
||||
return _dict_to_item(d)
|
||||
return Entity(d["x"], d["y"], d.get("name", ""),
|
||||
d.get("sprite_key", ""), d.get("blocks", True))
|
||||
|
||||
|
||||
def _enemy_to_dict(e: Enemy) -> dict:
|
||||
return {
|
||||
"type": "enemy",
|
||||
"x": e.x, "y": e.y,
|
||||
"name": e.name,
|
||||
"sprite_key": e.sprite_key,
|
||||
"blocks": e.blocks,
|
||||
"hp": e.hp, "max_hp": e.max_hp,
|
||||
"power": e.power, "armor": e.armor,
|
||||
"accuracy": e.accuracy, "evasion": e.evasion,
|
||||
"crit_chance": e.crit_chance, "speed": e.speed,
|
||||
"behavior": e.behavior, "xp_value": e.xp_value,
|
||||
"last_known_pos": (list(e.last_known_pos)
|
||||
if e.last_known_pos is not None else None),
|
||||
"act_counter": e.act_counter,
|
||||
"can_split": e.can_split,
|
||||
"ranged_power": e.ranged_power,
|
||||
}
|
||||
|
||||
|
||||
def _dict_to_enemy(d: dict) -> Enemy:
|
||||
lkp = d["last_known_pos"]
|
||||
return Enemy(
|
||||
x=d["x"], y=d["y"], name=d["name"], sprite_key=d["sprite_key"],
|
||||
blocks=d["blocks"],
|
||||
hp=d["hp"], max_hp=d["max_hp"], power=d["power"], armor=d["armor"],
|
||||
accuracy=d["accuracy"], evasion=d["evasion"],
|
||||
crit_chance=d["crit_chance"], speed=d["speed"],
|
||||
behavior=d["behavior"], xp_value=d["xp_value"],
|
||||
last_known_pos=(tuple(lkp) if lkp is not None else None),
|
||||
act_counter=d["act_counter"], can_split=d["can_split"],
|
||||
ranged_power=d["ranged_power"],
|
||||
)
|
||||
|
||||
|
||||
def _item_to_dict(it: Item) -> dict:
|
||||
return {
|
||||
"type": "item",
|
||||
"x": it.x, "y": it.y,
|
||||
"name": it.name,
|
||||
"sprite_key": it.sprite_key,
|
||||
"blocks": it.blocks,
|
||||
"item_type": it.item_type,
|
||||
"subtype": it.subtype,
|
||||
"stats": dict(it.stats),
|
||||
}
|
||||
|
||||
|
||||
def _dict_to_item(d: dict) -> Item:
|
||||
return Item(
|
||||
x=d["x"], y=d["y"], name=d["name"], sprite_key=d["sprite_key"],
|
||||
blocks=d["blocks"], item_type=d["item_type"],
|
||||
subtype=d["subtype"], stats=dict(d["stats"]),
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Map
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _rect_to_dict(r: Rect) -> dict:
|
||||
return {"x": r.x, "y": r.y, "w": r.w, "h": r.h}
|
||||
|
||||
|
||||
def _map_to_dict(m: GameMap) -> dict:
|
||||
return {
|
||||
"width": m.width,
|
||||
"height": m.height,
|
||||
"tiles": [list(row) for row in m.tiles],
|
||||
"rooms": [_rect_to_dict(r) for r in m.rooms],
|
||||
"explored": [list(row) for row in m.explored],
|
||||
"entities": [_entity_to_dict(e) for e in m.entities],
|
||||
"stairs_down": list(m.stairs_down),
|
||||
"floor_index": m.floor_index,
|
||||
}
|
||||
|
||||
|
||||
def _dict_to_map(d: dict) -> GameMap:
|
||||
width = d["width"]
|
||||
height = d["height"]
|
||||
return GameMap(
|
||||
width=width, height=height,
|
||||
tiles=[list(row) for row in d["tiles"]],
|
||||
rooms=[Rect(r["x"], r["y"], r["w"], r["h"]) for r in d["rooms"]],
|
||||
explored=[list(row) for row in d["explored"]],
|
||||
visible=[[False] * width for _ in range(height)],
|
||||
entities=[_dict_to_entity(e) for e in d["entities"]],
|
||||
stairs_down=tuple(d["stairs_down"]),
|
||||
floor_index=d["floor_index"],
|
||||
)
|
||||
Whitespace-only changes.
@@ -0,0 +1,85 @@
|
||||
"""Enemy entities and the full stat roster from plan.md §Enemy Roster."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from entities.entity import Entity
|
||||
|
||||
ENEMY_KINDS: list[str] = [
|
||||
"rat", "goblin", "skeleton_archer", "orc_warrior",
|
||||
"wraith", "green_slime", "ancient_dragon",
|
||||
]
|
||||
|
||||
# kind -> full roster. `floors` is the (min, max) depth gate from plan.md.
|
||||
# `ranged` is ranged_power (skeleton bolt / dragon breath); 0 = no ranged.
|
||||
_ROSTER: dict[str, dict] = {
|
||||
"rat": dict(
|
||||
name="Rat", hp=8, power=3, armor=0, accuracy=4, evasion=2, crit=0.05,
|
||||
speed=1, behavior="wander", xp=5, ranged=0, floors=(0, 3),
|
||||
),
|
||||
"goblin": dict(
|
||||
name="Goblin", hp=15, power=5, armor=1, accuracy=5, evasion=1, crit=0.05,
|
||||
speed=1, behavior="chase", xp=12, ranged=0, floors=(0, 5),
|
||||
),
|
||||
"skeleton_archer": dict(
|
||||
name="Skeleton Archer", hp=12, power=4, armor=1, accuracy=6, evasion=1, crit=0.10,
|
||||
speed=1, behavior="ranged", xp=15, ranged=6, floors=(2, 7),
|
||||
),
|
||||
"orc_warrior": dict(
|
||||
name="Orc Warrior", hp=30, power=8, armor=3, accuracy=5, evasion=0, crit=0.10,
|
||||
speed=1, behavior="flee", xp=25, ranged=0, floors=(3, 8),
|
||||
),
|
||||
"wraith": dict(
|
||||
name="Wraith", hp=20, power=10, armor=0, accuracy=6, evasion=3, crit=0.10,
|
||||
speed=2, behavior="phase", xp=30, ranged=0, floors=(5, 8),
|
||||
),
|
||||
"green_slime": dict(
|
||||
name="Green Slime", hp=18, power=5, armor=1, accuracy=4, evasion=0, crit=0.05,
|
||||
speed=1, behavior="split", xp=18, ranged=0, floors=(4, 8),
|
||||
),
|
||||
"ancient_dragon": dict(
|
||||
name="Ancient Dragon", hp=120, power=15, armor=8, accuracy=7, evasion=0, crit=0.15,
|
||||
speed=1, behavior="chase", xp=200, ranged=15, floors=(9, 9),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Enemy(Entity):
|
||||
name: str = ""
|
||||
sprite_key: str = "enemy"
|
||||
hp: int = 1
|
||||
max_hp: int = 1
|
||||
power: int = 0
|
||||
armor: int = 0
|
||||
accuracy: int = 0
|
||||
evasion: int = 0
|
||||
crit_chance: float = 0.0
|
||||
speed: int = 1
|
||||
behavior: str = "wander"
|
||||
xp_value: int = 0
|
||||
last_known_pos: tuple[int, int] | None = None
|
||||
act_counter: int = 0
|
||||
can_split: bool = True
|
||||
ranged_power: int = 0
|
||||
|
||||
|
||||
def make_enemy(kind: str, x: int, y: int) -> Enemy:
|
||||
"""Construct an Enemy of the given kind at (x, y) with full roster stats."""
|
||||
s = _ROSTER[kind]
|
||||
return Enemy(
|
||||
x=x, y=y, name=s["name"], sprite_key=kind,
|
||||
hp=s["hp"], max_hp=s["hp"], power=s["power"], armor=s["armor"],
|
||||
accuracy=s["accuracy"], evasion=s["evasion"], crit_chance=s["crit"],
|
||||
speed=s["speed"], behavior=s["behavior"], xp_value=s["xp"],
|
||||
ranged_power=s["ranged"],
|
||||
)
|
||||
|
||||
|
||||
def kinds_for_floor(floor_index: int) -> list[str]:
|
||||
"""Non-boss enemy kinds allowed to spawn on the given floor (depth-gated)."""
|
||||
return [
|
||||
k for k, s in _ROSTER.items()
|
||||
if k != "ancient_dragon"
|
||||
and s["floors"][0] <= floor_index <= s["floors"][1]
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Base entity: a thing with a position on the map."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Entity:
|
||||
"""Anything that lives on a dungeon tile: player, enemies, items, stairs.
|
||||
|
||||
`sprite_key` names the procedural pixel-art sprite to rasterize for it.
|
||||
`blocks` is True when other entities cannot share its tile.
|
||||
"""
|
||||
x: int
|
||||
y: int
|
||||
name: str
|
||||
sprite_key: str
|
||||
blocks: bool = True
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Items: weapons, armor, potions, scrolls (plan.md §6).
|
||||
|
||||
The full fixed catalog lives here. `make_item` builds any catalog entry;
|
||||
`item_pool_for_floor` gives a depth-weighted name list for dungeon population.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from entities.entity import Entity
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Item(Entity):
|
||||
"""A carryable thing. `blocks` is False — items never occupy a tile alone."""
|
||||
item_type: str = "misc" # weapon | armor | potion | scroll
|
||||
subtype: str = "" # healing | strength | invisibility | fireball | teleport | mapping
|
||||
stats: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
# name -> (item_type, subtype, stats, sprite_key). Stats are read by Player /
|
||||
# actions: weapons carry power (+ optional crit delta), armor carries armor
|
||||
# (+ optional evasion delta), potions/scrolls carry their effect magnitudes.
|
||||
_CATALOG: dict[str, tuple[str, str, dict, str]] = {
|
||||
"Rusty Dagger": ("weapon", "", {"power": 2}, "weapon_dagger"),
|
||||
"Short Sword": ("weapon", "", {"power": 4}, "weapon_sword"),
|
||||
"Battle Axe": ("weapon", "", {"power": 7}, "weapon_axe"),
|
||||
"War Hammer": ("weapon", "", {"power": 10, "crit_chance": -0.05}, "weapon_hammer"),
|
||||
"Leather Armor": ("armor", "", {"armor": 2}, "armor_leather"),
|
||||
"Chain Mail": ("armor", "", {"armor": 4}, "armor_chain"),
|
||||
"Plate Armor": ("armor", "", {"armor": 7, "evasion": -10}, "armor_plate"),
|
||||
"Healing Potion": ("potion", "healing", {"heal": 30}, "potion_healing"),
|
||||
"Strength Potion": ("potion", "strength", {"power": 5, "duration": 20}, "potion_strength"),
|
||||
"Invisibility Potion": ("potion", "invisibility", {"duration": 15}, "potion_invisibility"),
|
||||
"Scroll of Fireball": ("scroll", "fireball", {"damage": 20, "radius": 3}, "scroll_fireball"),
|
||||
"Scroll of Teleport": ("scroll", "teleport", {}, "scroll_teleport"),
|
||||
"Scroll of Mapping": ("scroll", "mapping", {}, "scroll_mapping"),
|
||||
}
|
||||
|
||||
|
||||
def make_item(name: str, x: int, y: int) -> Item:
|
||||
"""Construct a catalog Item named `name` at (x, y)."""
|
||||
itype, subtype, stats, sprite = _CATALOG[name]
|
||||
return Item(
|
||||
x=x, y=y, name=name, sprite_key=sprite, blocks=False,
|
||||
item_type=itype, subtype=subtype, stats=dict(stats),
|
||||
)
|
||||
|
||||
|
||||
def item_pool_for_floor(floor_index: int) -> list[str]:
|
||||
"""Depth-weighted item names droppable on this floor (plan.md §6 distribution).
|
||||
|
||||
Potions and scrolls are uniform across depth; better weapons/armor appear
|
||||
deeper. Floor 9 (boss) is handled separately by the populator.
|
||||
"""
|
||||
pool = [
|
||||
"Healing Potion", "Strength Potion", "Invisibility Potion",
|
||||
"Scroll of Fireball", "Scroll of Teleport", "Scroll of Mapping",
|
||||
]
|
||||
if floor_index >= 5:
|
||||
pool += ["War Hammer", "Plate Armor", "Battle Axe", "Chain Mail",
|
||||
"Short Sword", "Leather Armor", "Rusty Dagger"]
|
||||
elif floor_index >= 3:
|
||||
pool += ["Battle Axe", "Chain Mail", "Short Sword", "Leather Armor", "Rusty Dagger"]
|
||||
elif floor_index >= 1:
|
||||
pool += ["Short Sword", "Leather Armor", "Rusty Dagger"]
|
||||
else:
|
||||
pool += ["Rusty Dagger", "Leather Armor"]
|
||||
return pool
|
||||
@@ -0,0 +1,87 @@
|
||||
"""The player adventurer: stats, inventory, equipment, leveling."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from data import constants as C
|
||||
from entities.entity import Entity
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Effect:
|
||||
"""A timed status effect on the player (plan.md §6 potions).
|
||||
|
||||
`kind` is "strength" (+power) or "invisibility". `duration` is turns left;
|
||||
actions.tick decrements it and expires the effect at 0.
|
||||
"""
|
||||
kind: str
|
||||
power: int = 0
|
||||
duration: int = 0
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Player(Entity):
|
||||
name: str = "You"
|
||||
sprite_key: str = "player"
|
||||
# stats
|
||||
hp: int = 50
|
||||
max_hp: int = 50
|
||||
power: int = 4
|
||||
armor: int = 0
|
||||
accuracy: int = 5
|
||||
evasion: int = 2
|
||||
crit_chance: float = 0.10
|
||||
speed: int = 1
|
||||
# progression
|
||||
level: int = 1
|
||||
xp: int = 0
|
||||
# gear / effects
|
||||
inventory: list = field(default_factory=list)
|
||||
equipped: dict = field(default_factory=dict)
|
||||
effects: list = field(default_factory=list)
|
||||
facing: str = "down"
|
||||
invisible: bool = False
|
||||
# transient: level-up messages the game loop flushes into the session log
|
||||
pending_log: list = field(default_factory=list)
|
||||
|
||||
def total_power(self) -> int:
|
||||
"""Base power + equipped weapon bonus + active strength effect."""
|
||||
p = self.power
|
||||
weapon = self.equipped.get("weapon")
|
||||
if weapon is not None and hasattr(weapon, "stats"):
|
||||
p += weapon.stats.get("power", 0)
|
||||
for eff in self.effects:
|
||||
if getattr(eff, "kind", None) == "strength":
|
||||
p += getattr(eff, "power", 0)
|
||||
return int(p)
|
||||
|
||||
def total_armor(self) -> int:
|
||||
"""Base armor + equipped armor bonus."""
|
||||
a = self.armor
|
||||
armor = self.equipped.get("armor")
|
||||
if armor is not None and hasattr(armor, "stats"):
|
||||
a += armor.stats.get("armor", 0)
|
||||
return int(a)
|
||||
|
||||
def gain_xp(self, amount: int) -> bool:
|
||||
"""Award XP, applying chained level-ups from the plan table.
|
||||
|
||||
Fully heals and raises max_hp/power on each level-up. Level-up lines
|
||||
are buffered into `pending_log` for the game loop to flush. Returns
|
||||
True if any level-up occurred.
|
||||
"""
|
||||
self.xp += amount
|
||||
levelled = False
|
||||
while self.level < C.MAX_LEVEL and self.xp >= C.XP_THRESHOLDS[self.level + 1]:
|
||||
new_level = self.level + 1
|
||||
hp_gain = C.LEVEL_HP_GAIN[new_level]
|
||||
pow_gain = C.LEVEL_POWER_GAIN[new_level]
|
||||
self.level = new_level
|
||||
self.max_hp += hp_gain
|
||||
self.power += pow_gain
|
||||
self.hp = self.max_hp
|
||||
levelled = True
|
||||
self.pending_log.append(
|
||||
f"You reach level {self.level}! (HP +{hp_gain}, Power +{pow_gain})"
|
||||
)
|
||||
return levelled
|
||||
@@ -0,0 +1,391 @@
|
||||
"""Underdepths entry point: full game loop + state machine (plan.md §9).
|
||||
|
||||
HEADLESS RULE: never force the dummy SDL drivers. Detect headless from the
|
||||
ENVIRONMENT the test harness sets (SDL_VIDEODRIVER==dummy). When headless, run
|
||||
a scripted self-check of `max_frames` frames then return. With no environment
|
||||
variables, `python main.py` opens a real window with real audio.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
|
||||
|
||||
import pygame # noqa: E402
|
||||
|
||||
from engine import actions, game_state # noqa: E402
|
||||
from engine.audio import AudioManager # noqa: E402
|
||||
from render import renderer as R # noqa: E402
|
||||
from render import sprites as RS # noqa: E402
|
||||
|
||||
SAVE = "save.json"
|
||||
FPS = 60
|
||||
MOVE_DELAY = 0.11
|
||||
|
||||
|
||||
def _num(s: str):
|
||||
m = re.search(r"for (\d+) damage", s)
|
||||
return int(m.group(1)) if m else None
|
||||
|
||||
|
||||
def _facing_delta(facing: str):
|
||||
return {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}.get(facing, (0, 1))
|
||||
|
||||
|
||||
class Game:
|
||||
def __init__(self, screen, audio, headless: bool) -> None:
|
||||
self.screen = screen
|
||||
self.audio = audio
|
||||
self.headless = headless
|
||||
self.r = R.Renderer((R.WIN_W, R.WIN_H), audio)
|
||||
self.session = None
|
||||
self.view = "menu" # menu | play | dead | victory
|
||||
self.overlay = None # None | inv | equip | quaff | read | help
|
||||
self.menu_index = 0
|
||||
self.t = 0.0
|
||||
self.move_cd = 0.0
|
||||
self._prev_log = 0
|
||||
self._prev_hp = 0
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
def _menu_options(self):
|
||||
opts = ["New Game"]
|
||||
if game_state.has_save(SAVE):
|
||||
opts.append("Continue")
|
||||
opts += ["How to Play", "Quit"]
|
||||
return opts
|
||||
|
||||
def _start_new_game(self) -> None:
|
||||
game_state.delete_save(SAVE)
|
||||
self.session = game_state.new_game(seed=None)
|
||||
self._prev_log = len(self.session.log)
|
||||
self._prev_hp = self.session.player.hp
|
||||
self.view = "play"
|
||||
self.overlay = "help" # How to Play before the first turn
|
||||
|
||||
def _continue(self) -> bool:
|
||||
if not game_state.has_save(SAVE):
|
||||
return False
|
||||
try:
|
||||
self.session = game_state.load(SAVE)
|
||||
except Exception:
|
||||
return False
|
||||
self._prev_log = len(self.session.log)
|
||||
self._prev_hp = self.session.player.hp
|
||||
self.view = "play"
|
||||
self.overlay = None
|
||||
return True
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
def run(self) -> None:
|
||||
clock = pygame.time.Clock()
|
||||
running = True
|
||||
while running:
|
||||
dt = clock.tick(FPS) / 1000.0
|
||||
self.t += dt
|
||||
self.move_cd = max(0.0, self.move_cd - dt)
|
||||
|
||||
for event in pygame.event.get():
|
||||
if event.type == pygame.QUIT:
|
||||
running = False
|
||||
elif event.type == pygame.KEYDOWN:
|
||||
if self._keydown(event.key):
|
||||
running = False
|
||||
break
|
||||
|
||||
if self.view == "play" and self.overlay is None:
|
||||
self._poll_move(dt)
|
||||
|
||||
self.r.update(dt)
|
||||
self._render()
|
||||
pygame.display.flip()
|
||||
|
||||
def run_headless(self, max_frames: int) -> None:
|
||||
"""Scripted self-check: new game, then render `max_frames` frames."""
|
||||
self.session = game_state.new_game(seed=1234)
|
||||
self._prev_log = len(self.session.log)
|
||||
self._prev_hp = self.session.player.hp
|
||||
self.view = "play"
|
||||
self.overlay = None
|
||||
dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)]
|
||||
for i in range(max(1, max_frames)):
|
||||
dt = 1.0 / 30.0
|
||||
self.t += dt
|
||||
if self.session.state == "playing" and i > 0:
|
||||
dx, dy = dirs[i % len(dirs)]
|
||||
try:
|
||||
actions.try_move(self.session, dx, dy)
|
||||
except Exception:
|
||||
pass
|
||||
self.r.update(dt)
|
||||
try:
|
||||
self.r.render_world(self.screen, self.session, self.t)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pygame.display.flip()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Input
|
||||
# ------------------------------------------------------------------ #
|
||||
def _keydown(self, key) -> bool:
|
||||
# Global: mute works everywhere.
|
||||
if key == pygame.K_m:
|
||||
self.audio.toggle_mute()
|
||||
return False
|
||||
|
||||
if self.overlay == "help":
|
||||
self.overlay = None
|
||||
return False
|
||||
if self.overlay in ("inv", "quaff", "read"):
|
||||
if key == pygame.K_ESCAPE:
|
||||
self.overlay = None
|
||||
return False
|
||||
self._overlay_select(self.overlay, key)
|
||||
return False
|
||||
if self.overlay == "equip":
|
||||
if key == pygame.K_ESCAPE:
|
||||
self.overlay = None
|
||||
return False
|
||||
|
||||
if self.view == "menu":
|
||||
return self._menu_key(key)
|
||||
if self.view in ("dead", "victory"):
|
||||
self.view = "menu"
|
||||
self.session = None
|
||||
self.overlay = None
|
||||
return False
|
||||
if self.view == "play":
|
||||
return self._play_key(key)
|
||||
return False
|
||||
|
||||
def _menu_key(self, key) -> bool:
|
||||
opts = self._menu_options()
|
||||
if key in (pygame.K_UP, pygame.K_k):
|
||||
self.menu_index = (self.menu_index - 1) % len(opts)
|
||||
elif key in (pygame.K_DOWN, pygame.K_j):
|
||||
self.menu_index = (self.menu_index + 1) % len(opts)
|
||||
elif key in (pygame.K_RETURN, pygame.K_KP_ENTER):
|
||||
choice = opts[self.menu_index]
|
||||
if choice == "New Game":
|
||||
self._start_new_game()
|
||||
elif choice == "Continue":
|
||||
self._continue()
|
||||
elif choice == "How to Play":
|
||||
self.overlay = "help"
|
||||
elif choice == "Quit":
|
||||
return True
|
||||
elif key == pygame.K_ESCAPE:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _play_key(self, key) -> bool:
|
||||
s = self.session
|
||||
if key == pygame.K_ESCAPE:
|
||||
self.overlay = None
|
||||
return False
|
||||
if key == pygame.K_QUESTION:
|
||||
self.overlay = "help"
|
||||
return False
|
||||
if key == pygame.K_i:
|
||||
self.overlay = "inv"; return False
|
||||
if key == pygame.K_e:
|
||||
self.overlay = "equip"; return False
|
||||
if key == pygame.K_q:
|
||||
self.overlay = "quaff"; return False
|
||||
if key == pygame.K_r:
|
||||
self.overlay = "read"; return False
|
||||
if key == pygame.K_g:
|
||||
self._act(lambda: actions.pickup(s)); return False
|
||||
if key == pygame.K_f:
|
||||
self._act(lambda: actions.descend(s)); return False
|
||||
if key == pygame.K_s:
|
||||
game_state.save(s, SAVE)
|
||||
self.session = None
|
||||
self.view = "menu"
|
||||
self.overlay = None
|
||||
self.menu_index = 0
|
||||
return False
|
||||
# movement (immediate first step; held movement continues via _poll_move)
|
||||
d = self._key_dir(key)
|
||||
if d is not None:
|
||||
self._move(*d)
|
||||
self.move_cd = MOVE_DELAY
|
||||
return False
|
||||
|
||||
def _key_dir(self, key):
|
||||
m = {pygame.K_UP: (0, -1), pygame.K_DOWN: (0, 1),
|
||||
pygame.K_LEFT: (-1, 0), pygame.K_RIGHT: (1, 0),
|
||||
pygame.K_k: (0, -1), pygame.K_j: (0, 1),
|
||||
pygame.K_h: (-1, 0), pygame.K_l: (1, 0)}
|
||||
return m.get(key)
|
||||
|
||||
def _poll_move(self, dt) -> None:
|
||||
if self.move_cd > 0:
|
||||
return
|
||||
keys = pygame.key.get_pressed()
|
||||
d = None
|
||||
if keys[pygame.K_UP] or keys[pygame.K_k]:
|
||||
d = (0, -1)
|
||||
elif keys[pygame.K_DOWN] or keys[pygame.K_j]:
|
||||
d = (0, 1)
|
||||
elif keys[pygame.K_LEFT] or keys[pygame.K_h]:
|
||||
d = (-1, 0)
|
||||
elif keys[pygame.K_RIGHT] or keys[pygame.K_l]:
|
||||
d = (1, 0)
|
||||
if d is not None:
|
||||
self._move(*d)
|
||||
self.move_cd = MOVE_DELAY
|
||||
|
||||
def _overlay_select(self, mode, key) -> None:
|
||||
if not (pygame.K_a <= key <= pygame.K_z):
|
||||
return
|
||||
idx = key - pygame.K_a
|
||||
s = self.session
|
||||
|
||||
def wanted(it):
|
||||
if mode == "quaff":
|
||||
return it.item_type == "potion"
|
||||
if mode == "read":
|
||||
return it.item_type == "scroll"
|
||||
return True
|
||||
items = [it for it in s.player.inventory if wanted(it)]
|
||||
if 0 <= idx < len(items):
|
||||
self._act(lambda: actions.use_item(s, items[idx]))
|
||||
self.overlay = None
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Action wrappers
|
||||
# ------------------------------------------------------------------ #
|
||||
def _move(self, dx, dy) -> None:
|
||||
if self.session.state != "playing":
|
||||
return
|
||||
self._act(lambda: actions.try_move(self.session, dx, dy))
|
||||
|
||||
def _act(self, fn) -> None:
|
||||
s = self.session
|
||||
before = len(s.log)
|
||||
fn()
|
||||
# flush any buffered level-up lines
|
||||
for m in s.player.pending_log:
|
||||
s.log.append(m)
|
||||
s.player.pending_log.clear()
|
||||
self._emit_juice(s, len(s.log) - before)
|
||||
self._prev_log = len(s.log)
|
||||
self._prev_hp = s.player.hp
|
||||
if s.state == "dead":
|
||||
self.view = "dead"
|
||||
self.audio.play("death")
|
||||
elif s.state == "victory":
|
||||
self.view = "victory"
|
||||
self.audio.play("victory")
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Juice — derived from new log lines (the log is the feedback channel)
|
||||
# ------------------------------------------------------------------ #
|
||||
def _emit_juice(self, s, n_new) -> None:
|
||||
if n_new <= 0:
|
||||
return
|
||||
p = s.player
|
||||
pfx, pfy = _facing_delta(getattr(p, "facing", "down"))
|
||||
front = (p.x + pfx, p.y + pfy)
|
||||
px, py = self.r.world_px(p.x, p.y)
|
||||
fx, fy = self.r.world_px(*front)
|
||||
for line in s.log[-n_new:]:
|
||||
low = line.lower()
|
||||
dmg = _num(line)
|
||||
crit = "critical" in low
|
||||
if "you hit" in low and "defeated" not in low:
|
||||
self.r.particles.burst(fx, fy, (240, 230, 180), n=8 if not crit else 16,
|
||||
speed=90, life=0.4)
|
||||
if dmg is not None:
|
||||
self.r.floats.add(fx, fy - 6, f"-{dmg}", (255, 240, 200), big=crit)
|
||||
if crit:
|
||||
self.r.floats.add(fx, fy - 22, "CRIT!", (255, 210, 90), big=True)
|
||||
self.r.particles.burst(fx, fy, (255, 210, 90), n=14, speed=120, life=0.5)
|
||||
self.audio.play("hit")
|
||||
elif ("hits you" in low or "critically strikes" in low or "shoots you" in low) and "defeated" not in low:
|
||||
mag = 7.0 if crit else 4.0
|
||||
self.r.shake.trigger(mag)
|
||||
self.r.particles.burst(px, py, (210, 60, 60), n=12, speed=80, life=0.45)
|
||||
if dmg is not None:
|
||||
self.r.floats.add(px, py - 6, f"-{dmg}", (240, 90, 90), big=crit)
|
||||
self.audio.play("damage")
|
||||
elif "miss" in low:
|
||||
tx, ty = (fx, fy) if "you miss" in low else (px, py)
|
||||
self.r.floats.add(tx, ty - 4, "MISS", (170, 170, 170))
|
||||
self.audio.play("miss")
|
||||
elif "defeated" in low:
|
||||
self.r.particles.burst(fx, fy, (200, 200, 210), n=18, speed=70, life=0.5)
|
||||
self.audio.play("hit")
|
||||
elif "reach level" in low:
|
||||
self.r.particles.burst(px, py, (130, 225, 100), n=20, speed=90, life=0.7)
|
||||
self.r.floats.add(px, py - 20, "LEVEL UP!", (130, 225, 100), big=True)
|
||||
self.audio.play("levelup")
|
||||
elif "pick up" in low:
|
||||
self.r.particles.burst(px, py, (240, 220, 90), n=14, speed=60, life=0.5)
|
||||
self.audio.play("pickup")
|
||||
elif "descend" in low:
|
||||
self.r.particles.burst(px, py, (240, 220, 80), n=16, speed=70, life=0.6)
|
||||
self.audio.play("stairs")
|
||||
elif any(k in low for k in ("teleport", "quaff", "surge", "fade", "scroll", "erupts", "floods", "equip")):
|
||||
self.r.particles.burst(px, py, (120, 200, 255), n=12, speed=60, life=0.5)
|
||||
self.audio.play("use")
|
||||
elif "died" in low:
|
||||
self.audio.play("death")
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Render dispatch
|
||||
# ------------------------------------------------------------------ #
|
||||
def _render(self) -> None:
|
||||
if self.view == "menu":
|
||||
self.r.render_menu(self.screen, self.menu_index, game_state.has_save(SAVE), self.t)
|
||||
if self.overlay == "help":
|
||||
self.r.render_help(self.screen, self.t)
|
||||
return
|
||||
if self.session is None:
|
||||
self.r.render_menu(self.screen, self.menu_index, game_state.has_save(SAVE), self.t)
|
||||
return
|
||||
self.r.render_world(self.screen, self.session, self.t)
|
||||
if self.overlay == "help":
|
||||
self.r.render_help(self.screen, self.t)
|
||||
elif self.overlay in ("inv", "equip", "quaff", "read"):
|
||||
self.r.render_inventory(self.screen, self.session, self.overlay, self.t)
|
||||
if self.view == "dead":
|
||||
self.r.render_end(self.screen, self.session, "dead", self.t)
|
||||
elif self.view == "victory":
|
||||
self.r.render_end(self.screen, self.session, "victory", self.t)
|
||||
|
||||
|
||||
def main(max_frames: int | None = None) -> None:
|
||||
headless = os.environ.get("SDL_VIDEODRIVER", "").lower() == "dummy"
|
||||
pygame.init()
|
||||
flags = 0 if headless else pygame.SCALED
|
||||
try:
|
||||
screen = pygame.display.set_mode((R.WIN_W, R.WIN_H), flags)
|
||||
except Exception:
|
||||
screen = pygame.Surface((R.WIN_W, R.WIN_H))
|
||||
try:
|
||||
pygame.display.set_caption("Underdepths")
|
||||
except Exception:
|
||||
pass
|
||||
RS.warm()
|
||||
audio = AudioManager()
|
||||
game = Game(screen, audio, headless)
|
||||
try:
|
||||
if headless:
|
||||
game.run_headless(max_frames if max_frames is not None else 60)
|
||||
else:
|
||||
game.run()
|
||||
finally:
|
||||
try:
|
||||
pygame.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+470
@@ -0,0 +1,470 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# Underdepths — self-driving build pipeline.
|
||||
#
|
||||
# Drives the entire game build via `pi -p` (the DEFAULT model only — never
|
||||
# passes --model/--provider), one dispatch per build phase, each gated by
|
||||
# `python3 tests/smoke.py --phase N`. Resumable across crashes via .build_state.
|
||||
# A goal backstop after phase 4 verifies EVERY acceptance criterion and loops
|
||||
# fixes until all pass.
|
||||
#
|
||||
# Phases run SEQUENTIALLY (a hung worker would block bash `&`+`wait` forever;
|
||||
# learned the hard way on this very project). Every dispatch is wrapped in
|
||||
# `timeout --kill-after=30` because the pi (node) process ignores SIGTERM.
|
||||
#
|
||||
# State machine (.build_state = index of last completed phase):
|
||||
# 0 -> nothing 1 -> P1 2 -> P2 3 -> P3 4 -> P4(4a+4b+gate) 5 -> goal
|
||||
# =============================================================================
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
STATE=.build_state
|
||||
PIDF=.pipeline.pid
|
||||
LOG_DIR=logs
|
||||
mkdir -p "$LOG_DIR"
|
||||
|
||||
MAX_RETRIES=${MAX_RETRIES:-3}
|
||||
TTL=${TTL:-3000} # ~50 min ceiling per dispatch
|
||||
PY=${PY:-python3}
|
||||
GATE="$PY tests/smoke.py"
|
||||
COMPILE_GATE="$PY -m compileall -q engine render data entities ai main.py tests 2>&1 && echo COMPILE_OK"
|
||||
|
||||
# --- concurrency guard: never two pipelines in one directory ---------------
|
||||
if [[ -f "$PIDF" ]]; then
|
||||
old="$(cat "$PIDF" 2>/dev/null || true)"
|
||||
if [[ -n "$old" && "$old" != "$$" ]] && kill -0 "$old" 2>/dev/null; then
|
||||
echo "FATAL: orchestrate.sh (PID $old) already running in this dir." >&2
|
||||
echo " The pipeline edits shared files concurrently; re-run a single" >&2
|
||||
echo " instance after it finishes (it is resumable via .build_state)." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
echo "$$" > "$PIDF"
|
||||
trap 'rm -f "$PIDF"' EXIT
|
||||
|
||||
get_state() { [[ -f "$STATE" ]] && cat "$STATE" 2>/dev/null || echo 0; }
|
||||
set_state() { echo "$1" > "$STATE"; }
|
||||
halt() { echo "!!! PIPELINE HALTED at the phase above — see logs/ !!!" >&2; exit 1; }
|
||||
|
||||
# dispatch NAME PROMPT GATE_CMD
|
||||
# Ralph loop: up to MAX_RETRIES, feeding the actual gate error back on retry.
|
||||
dispatch() {
|
||||
local name="$1" prompt="$2" gate="$3"
|
||||
local attempt=0 gate_out gate_rc full_prompt
|
||||
while (( attempt < MAX_RETRIES )); do
|
||||
attempt=$((attempt + 1))
|
||||
echo "==================================================================="
|
||||
echo ">>> $name (attempt $attempt/$MAX_RETRIES) $(date +%H:%M:%S)"
|
||||
echo "==================================================================="
|
||||
if (( attempt == 1 )); then
|
||||
full_prompt="$prompt"
|
||||
else
|
||||
full_prompt="$(printf '%s\n\n--- PREVIOUS ATTEMPT FAILED THE GATE (fix THIS specifically) ---\n%s\n\nDo not rewrite parts that already work. Make the gate pass.\n\n--- ORIGINAL TASK ---\n%s' \
|
||||
"$prompt" "$(printf '%s' "${gate_out}" | tail -n 70)" "$prompt")"
|
||||
fi
|
||||
local logf="$LOG_DIR/${name}.attempt${attempt}.log"
|
||||
# Run pi in its OWN session/process-group via setsid; a watchdog hard-SIGKILLs
|
||||
# the entire group at TTL. GNU `timeout --kill-after` proved unreliable on this
|
||||
# host (a hung pi worker lingered ~20 min past its deadline); the explicit
|
||||
# whole-group kill is the dependable hammer. (setsid ships via util-linux.)
|
||||
setsid bash -c 'pi -p -a --name "$0" @plan.md "$1" > "$2" 2>&1' \
|
||||
"$name" "$full_prompt" "$logf" &
|
||||
local job=$!
|
||||
( sleep "$TTL"; kill -KILL -"$job" 2>/dev/null; ) &
|
||||
local wd=$!
|
||||
wait "$job" 2>/dev/null
|
||||
local rc=$?
|
||||
kill "$wd" 2>/dev/null; wait "$wd" 2>/dev/null
|
||||
if (( rc != 0 )); then
|
||||
echo " ! dispatch ended (rc=$rc; timeout or error); tail of log:" >&2
|
||||
tail -n 8 "$logf" >&2
|
||||
fi
|
||||
echo " gate: $gate"
|
||||
gate_out="$(eval "$gate" 2>&1)"
|
||||
gate_rc=$?
|
||||
printf '%s\n' "${gate_out}" | tail -n 35
|
||||
if (( gate_rc == 0 )); then
|
||||
echo "<<< $name PASS"
|
||||
return 0
|
||||
fi
|
||||
echo " ! gate failed (attempt $attempt, rc=$gate_rc)"
|
||||
done
|
||||
echo "<<< $name FAILED after $MAX_RETRIES attempts — full log: $LOG_DIR/${name}.attempt${MAX_RETRIES}.log" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
# =============================================================================
|
||||
# Shared preamble prepended to every worker prompt.
|
||||
# =============================================================================
|
||||
read -r -d '' SHARED <<'SHARED_EOF' || true
|
||||
You are building "Underdepths", a turn-based roguelike in Python 3 + pygame-ce.
|
||||
@plan.md is the COMPLETE design spec — READ IT before writing anything.
|
||||
AGENTS.md (auto-loaded) holds the project conventions; follow them.
|
||||
|
||||
CONTRACT (authoritative): tests/smoke.py is your verification gate AND its
|
||||
module docstring defines the EXACT public API you must implement — dataclass
|
||||
fields, function names + signatures, return shapes. Implement to that API.
|
||||
Run `python3 tests/smoke.py --phase N` repeatedly until it prints
|
||||
`phase N: PASS`. You MAY correct smoke.py ONLY if an expectation directly
|
||||
contradicts plan.md; NEVER weaken a behavioural assertion to pass trivially.
|
||||
|
||||
HEADLESS RULE (getting this wrong fails the whole build): smoke.py sets
|
||||
SDL_VIDEODRIVER=dummy. In main.py NEVER force headless with
|
||||
os.environ.setdefault("SDL_VIDEODRIVER","dummy") or setdefault on the audio
|
||||
driver — that makes `python3 main.py` silently run headless and exit on every
|
||||
real machine. Instead detect headless from the ENVIRONMENT the test sets:
|
||||
headless = os.environ.get("SDL_VIDEODRIVER","").lower() == "dummy"
|
||||
When headless is True, run a scripted self-check loop:
|
||||
main(max_frames=K) runs at most K frames then returns. When headless is False,
|
||||
open a REAL window with REAL audio and play normally. `python3 main.py` with no
|
||||
environment variables MUST launch the playable game window.
|
||||
|
||||
IMPLEMENTATION RULES:
|
||||
- @dataclass(slots=True) for all entities and state objects. Type hints on every
|
||||
function signature. Constants in data/constants.py. No magic numbers in logic.
|
||||
- NO stubs, NO TODO comments, NO placeholders. Every function has a real,
|
||||
working implementation. If a file lists a function, it must work.
|
||||
- All art is procedural pixel-art drawn with pygame.draw from in-code palettes —
|
||||
NO external image / sprite-sheet / font / audio asset files. pygame.font.SysFont
|
||||
only. Plain flat colored rectangles for entities/tiles are NOT acceptable.
|
||||
- Every combat event, item pickup, level-up, and status change must append a
|
||||
human-readable message to session.log (the message log is primary feedback).
|
||||
- Use the standard library (json, random, math, dataclasses, heapq, array).
|
||||
Represent grids as list[list[int]] (tiles) and list[list[bool]] (explored /
|
||||
visible) — no numpy dependency. GameSession is the single source of truth.
|
||||
- Rendering reads GameSession and draws; it never mutates game state.
|
||||
SHARED_EOF
|
||||
|
||||
# =============================================================================
|
||||
# Phase 1 — Foundation
|
||||
# =============================================================================
|
||||
read -r -d '' P1 <<'P1_EOF' || true
|
||||
BUILD PHASE 1 — Foundation. Make `python3 tests/smoke.py --phase 1` print PASS.
|
||||
|
||||
Create these files (add __init__.py to data/, entities/, engine/, ai/, render/):
|
||||
|
||||
data/constants.py
|
||||
TILE=20, MAP_WIDTH=80, MAP_HEIGHT=50, SIGHT_RADIUS=8, FLOORS=10
|
||||
COLORS / PALETTE dicts (wall dark gray ~ (60,60,70) visible / (30,30,35)
|
||||
explored; floor (40,35,30)/(20,18,15); per-enemy accent hues; item accents
|
||||
yellow/blue/red/cyan; stairs yellow). The full XP/level-up table from plan
|
||||
(levels 1->2 ... 9->10: cumulative XP 30,70,140,250,400,600,850,1150,1500;
|
||||
HP/power gains per plan). Per-floor enemy/item count distribution from plan.
|
||||
|
||||
entities/entity.py
|
||||
@dataclass(slots=True) Entity(x:int, y:int, name:str, sprite_key:str,
|
||||
blocks:bool=True).
|
||||
|
||||
entities/player.py
|
||||
@dataclass(slots=True) Player(Entity) with the base stats from plan
|
||||
(hp=50,max_hp=50,power=4,armor=0,accuracy=5,evasion=2,crit_chance=0.10,
|
||||
speed=1, level=1, xp=0, inventory:list, equipped:dict, effects:list,
|
||||
facing="down", name="You", sprite_key="player", blocks=True).
|
||||
Methods: total_power()->int (base + equipped weapon power + strength effect),
|
||||
total_armor()->int (base + equipped armor), gain_xp(amount)->bool that applies
|
||||
the level-up table (level up may chain multiple levels), fully heals and
|
||||
increases max_hp/power per the table, logs "You reach level N!", returns True
|
||||
if any level-up occurred. Implement the FULL level table now.
|
||||
|
||||
entities/enemy.py
|
||||
@dataclass(slots=True) Enemy(Entity) with hp,max_hp,power,armor,accuracy,
|
||||
evasion,crit_chance,speed,behavior,xp_value, plus last_known_pos (tuple|None),
|
||||
act_counter:int=0, can_split:bool=True, ranged_power:int=0.
|
||||
ENEMY_KINDS list of all seven. make_enemy(kind,x,y)->Enemy returning the FULL
|
||||
stat roster from plan's Enemy Roster table (rat/goblin/skeleton_archer/
|
||||
orc_warrior/wraith/green_slime/ancient_dragon). Dragon ranged_power>=15.
|
||||
|
||||
engine/map_gen.py
|
||||
@dataclass(slots=True) Rect(x,y,w,h) with a .center property returning (x+w//2,
|
||||
y+h//2). @dataclass(slots=True) GameMap(width,height,tiles,rooms,explored,
|
||||
visible,entities,stairs_down,floor_index) exactly per the contract docstring.
|
||||
generate_dungeon(floor_index,width=80,height=50)->GameMap using BSP: all walls,
|
||||
5-8 recursive splits alternating axis, carve a room (4x4..10x8, shrunk 1-2 from
|
||||
region edge) per leaf, connect siblings with L-shaped corridors, place stairs_down
|
||||
in the room farthest from spawn. Floor 9 is the BOSS ARENA: a single large room
|
||||
(~20x15) — exactly ONE room with w>=15 and h>=10. Floors 0-8 have >=3 rooms,
|
||||
a solid 1-tile wall border on all four edges, no overlapping rooms, and every
|
||||
room reachable from every other via floor-tile flood fill. is_walkable(map,x,y)
|
||||
->bool (in bounds and tile==1). populate(map,floor_index,rng=None) places
|
||||
ENEMIES per plan's per-floor distribution (floor 9: just the dragon + leave room
|
||||
for 2 potions; items are added in phase 3 so do not place items yet). Ensure
|
||||
populate never raises on any floor 0-9.
|
||||
|
||||
main.py
|
||||
A MINIMAL entry for now: define main(max_frames=None) that, when
|
||||
SDL_VIDEODRIVER==dummy, runs a tiny headless self-check (generate a dungeon,
|
||||
print nothing fatal) and returns; otherwise prints "Underdepths — phase 1
|
||||
scaffold". It will be FULLY rebuilt in phase 4. Obey the HEADLESS RULE.
|
||||
P1_EOF
|
||||
P1="$(printf '%s\n\n%s' "$SHARED" "$P1")"
|
||||
|
||||
# =============================================================================
|
||||
# Phase 2 — Core systems (FOV, A*, combat, minimal game state, chase AI)
|
||||
# =============================================================================
|
||||
read -r -d '' P2 <<'P2_EOF' || true
|
||||
BUILD PHASE 2 — Core systems. Make `python3 tests/smoke.py --phase 2` print PASS.
|
||||
Do NOT regress phase 1 (re-run --phase 1 if unsure).
|
||||
|
||||
engine/fov.py
|
||||
compute_fov(game_map, ox, oy, radius=8) -> set of (x,y) visible tiles, using
|
||||
RECURSIVE SHADOWCASTING over 8 octants (write it from scratch, no library).
|
||||
Walls block sight but a wall adjacent to a visible floor tile is itself
|
||||
visible. Mutate game_map.visible accordingly and RETURN the visible set.
|
||||
|
||||
engine/pathfinding.py
|
||||
astar(game_map, start, goal, blocked=frozenset()) -> list[(x,y)] | None, grid
|
||||
A* with Manhattan heuristic. Walkable = in-bounds floor tile not in `blocked`
|
||||
and not a wall. Return the path excluding the start node's duplicate; None if
|
||||
unreachable or if start/goal is a wall/out of bounds.
|
||||
|
||||
engine/combat.py
|
||||
attack(attacker, defender, rng=None, log=None) -> dict with keys
|
||||
hit:bool, damage:int, crit:bool, killed:bool. Use plan's formulas:
|
||||
hit_chance = clamp(0.7 + (attacker.accuracy - defender.evasion)*0.05, 0.1, 0.95);
|
||||
on hit, base = attacker.power(+weapon bonus via total_power for the player),
|
||||
reduced = max(0, base - defender.armor), crit doubles damage, apply to
|
||||
defender.hp, killed = defender.hp <= 0. If log is a list, append the plan's
|
||||
human messages ("You hit the Goblin for 8 damage!", "Critical hit! ...",
|
||||
"Goblin misses you"). The attacker may be Player (use total_power/total_armor)
|
||||
or Enemy (use raw stats). rng defaults to random.Random().
|
||||
|
||||
engine/game_state.py
|
||||
@dataclass(slots=True) GameSession holding player, dungeon (list of 10
|
||||
GameMap), current_floor:int, log:list[str], turn:int, state:str
|
||||
("playing"/"dead"/"victory"/"menu"), plus an rng. new_game(seed=None)->
|
||||
GameSession: build the player, generate all 10 floors (generate_dungeon),
|
||||
populate enemies, place the player in the first room center of floor 0,
|
||||
init log/turn, set state="playing". recompute_fov(session): clear visible,
|
||||
compute_fov from the player, merge into explored. (Items/inventory wiring is
|
||||
phase 3; keep new_game minimal but functional.)
|
||||
|
||||
ai/behaviors.py
|
||||
take_enemy_turn(enemy, session, rng=None) dispatching on enemy.behavior.
|
||||
Implement at least: wander (random walkable step or wait), chase (A* toward
|
||||
player when player visible via FOV, else toward last_known_pos; adjacent ->
|
||||
melee via combat.attack into session.log), and a stub for the others (you will
|
||||
finish flee/ranged/phase/split in phase 3). Respect speed (speed==2 acts every
|
||||
other turn via act_counter). Enemies must not stack (treat other entities as
|
||||
blocked). Update last_known_pos when the player is visible.
|
||||
P2_EOF
|
||||
P2="$(printf '%s\n\n%s' "$SHARED" "$P2")"
|
||||
|
||||
# =============================================================================
|
||||
# Phase 3 — Content: items, inventory, equipment, scrolls, full AI, XP wiring
|
||||
# =============================================================================
|
||||
read -r -d '' P3 <<'P3_EOF' || true
|
||||
BUILD PHASE 3 — Content layer. Make `python3 tests/smoke.py --phase 3` pass.
|
||||
Do NOT regress phases 1-2.
|
||||
|
||||
entities/item.py
|
||||
@dataclass(slots=True) Item(Entity) with item_type ("weapon"/"armor"/
|
||||
"potion"/"scroll"), subtype (e.g. "healing","strength","invisibility",
|
||||
"fireball","teleport","mapping"), stats:dict, name, sprite_key.
|
||||
make_item(name,x,y)->Item implementing the FULL catalog from plan: Rusty
|
||||
Dagger(+2), Short Sword(+4), Battle Axe(+7), War Hammer(+10 power, crit -5%),
|
||||
Leather Armor(armor 2), Chain Mail(armor 4), Plate Armor(armor 7, evasion -10%),
|
||||
Healing Potion(heal 30), Strength Potion(+5 power/20 turns), Invisibility
|
||||
Potion(invisible/15 turns), Scroll of Fireball(20 dmg radius 3), Scroll of
|
||||
Teleport, Scroll of Mapping. Player.total_power/total_armor must read the
|
||||
equipped weapon/armor stats.
|
||||
|
||||
engine/actions.py (full gameplay actions; pure functions on GameSession)
|
||||
try_move(session, dx, dy)->bool: if target tile has an enemy -> melee
|
||||
(combat.attack player->enemy, log, award XP + handle death/split, check win);
|
||||
else move player if walkable & unblocked; then advance enemy turns + recompute
|
||||
FOV + tick effect timers. Return whether the player acted.
|
||||
pickup(session)->bool: if an Item is under the player, move it to inventory
|
||||
(or auto-consume potions? NO — into inventory), log "You pick up X", return True.
|
||||
descend(session)->bool: if player on stairs_down, current_floor+=1, place
|
||||
player at that floor's spawn/first room center, recompute FOV, log descent.
|
||||
Return False if not on stairs or already on floor 9 (no stairs there pre-win).
|
||||
use_item(session, item): potions -> apply effect (heal capped at max_hp;
|
||||
strength/invisibility push a timed Effect into player.effects), scrolls ->
|
||||
fireball (20 dmg to all enemies within 3 of player), teleport (random walkable
|
||||
tile), mapping (set entire current floor explored True); consume (remove from
|
||||
inventory). Equippables -> equip(session,item).
|
||||
equip(session,item): place in the right slot, move old item back to inventory,
|
||||
apply stat mods via total_power/total_armor (War Hammer crit -5%, Plate evasion
|
||||
-10%). Log "You equip X".
|
||||
|
||||
ai/behaviors.py (COMPLETE the behavior set)
|
||||
Finish flee (HP<30% -> move away, else chase), ranged/kiting (skeleton archer:
|
||||
fire ranged_attack at range>3 using ranged_power with a distance penalty;
|
||||
step away when adjacent <=2; wander when no sight), phase (wraith: move toward
|
||||
player IGNORING walls, acts every 2 turns via act_counter), and the dragon's
|
||||
boss behavior (chase + every 3rd turn breath weapon: 15 damage to all tiles in
|
||||
a line toward the player). on_death(enemy, session): if green_slime and
|
||||
can_split, spawn TWO smaller slimes (half hp, half power, can_split=False,
|
||||
name "Small Slime") into the floor entities and log it; always award XP via
|
||||
player.gain_xp and remove the corpse. Slime small variants must not split.
|
||||
|
||||
engine/game_state.py (extend)
|
||||
new_game must now also place ITEMS per plan's distribution (extend populate or
|
||||
spawn items alongside enemies; floor 9 gets exactly 2 healing potions near the
|
||||
entrance + the dragon). Add a player.invisible flag (True while an invisibility
|
||||
effect is active — enemies then cannot see the player). Effect timers tick down
|
||||
each turn (try_move end) and expire. Death -> state="dead"; killing the dragon
|
||||
on floor 9 -> state="victory".
|
||||
|
||||
data/items.py and data/enemies.py (optional)
|
||||
You may keep catalogs inline in the entity modules OR factor them here; either
|
||||
is fine. Do not duplicate the make_enemy/make_item contract.
|
||||
P3_EOF
|
||||
P3="$(printf '%s\n\n%s' "$SHARED" "$P3")"
|
||||
|
||||
# =============================================================================
|
||||
# Phase 4a — Persistence + audio + state transitions
|
||||
# =============================================================================
|
||||
read -r -d '' P4A <<'P4A_EOF' || true
|
||||
BUILD PHASE 4a — Persistence + resilient audio. Do NOT regress phases 1-3.
|
||||
This is the first half of phase 4; the render/UI/main half follows in 4b.
|
||||
|
||||
engine/serializers.py
|
||||
session_to_dict(session)->dict and dict_to_session(d)->GameSession giving an
|
||||
EXACT round trip. Serialize: player (all stats, level, xp, inventory, equipped,
|
||||
position, effects with remaining turns, facing), all 10 floors (tiles, rooms,
|
||||
explored, entities, stairs_down, floor_index), current_floor, turn, log, state.
|
||||
Do NOT serialize the `visible` grids — they are recomputed via recompute_fov on
|
||||
load. dict_to_session must reconstruct Player/Enemy/Item objects (store a type
|
||||
discriminator per entity) and call recompute_fov. Tiles as list[list[int]],
|
||||
explored as list[list[bool]] serialize directly with json.
|
||||
|
||||
engine/audio.py
|
||||
AudioManager class. Generate short tones in memory with stdlib array.array +
|
||||
pygame.mixer.Sound(buffer=...) (NO audio asset files). Provide play(name) for
|
||||
events: hit, miss, damage, pickup, use, stairs, levelup, death, victory.
|
||||
toggle_mute()->mutes/unmutes; .muted bool. CRITICAL: every public method must
|
||||
be wrapped so that ANY mixer init / Sound creation failure disables audio
|
||||
silently and never raises — the game stays fully playable with no audio device.
|
||||
Initialize the mixer once, lazily and defensively.
|
||||
|
||||
engine/game_state.py (extend)
|
||||
save(session, path="save.json") writes session_to_dict via json to the game
|
||||
directory; load(path) reads it. On player death: state="dead" AND delete
|
||||
save.json (permadeath). On victory: state="victory" and delete save.json.
|
||||
Keep new_game/recompute_fov working. Add a helper has_save(path) used by the
|
||||
menu (phase 4b).
|
||||
|
||||
You only write logic here; rendering and the full main loop come in phase 4b.
|
||||
Run `python3 tests/smoke.py --phase 1`, `--phase 2`, `--phase 3` to confirm no
|
||||
regression; phase 4 gate runs after 4b.
|
||||
P4A_EOF
|
||||
P4A="$(printf '%s\n\n%s' "$SHARED" "$P4A")"
|
||||
|
||||
# =============================================================================
|
||||
# Phase 4b — Procedural pixel-art, rendering, juice, full main loop + UI
|
||||
# =============================================================================
|
||||
read -r -d '' P4B <<'P4B_EOF' || true
|
||||
BUILD PHASE 4b — Visuals, UI, and the full game loop. Make
|
||||
`python3 tests/smoke.py --phase 4` print PASS. Do NOT regress phases 1-3.
|
||||
Phase 4a already added serializers.py, audio.py, and save/load.
|
||||
|
||||
data/sprites.py
|
||||
2D grids of single-char palette keys (e.g. "." transparent, "K" outline,
|
||||
shades) for EVERY entity, tile, item, and stairs — roughly 12x12..16x16 cells.
|
||||
Each of the 7 enemies + the player + each item category + stairs must be
|
||||
DISTINCT and recognizable (not recolors): hooded adventurer whose equipped
|
||||
weapon/armor change the sprite; rat (tail/ears/whiskers); goblin (ears/
|
||||
loincloth); skeleton archer (bow/quiver/glowing eyes); orc warrior (tusks/
|
||||
big blade); wraith (tattered cloak, no legs); green slime (glossy, googly
|
||||
eyes, drip); ancient dragon (horns/wings/scales/fangs). 2-3 idle frames each.
|
||||
|
||||
render/sprites.py
|
||||
Rasterize a palette-key grid to a pygame.Surface ONCE and cache by
|
||||
(name,frame,SCALE). The renderer blits the cached surface scaled to TILE.
|
||||
|
||||
render/effects.py
|
||||
Radial torch-light centered on the player out to SIGHT_RADIUS (brightness
|
||||
falloff), explored-not-visible tiles remembered but tinted dark blue-gray and
|
||||
dimmer, walls occlude light (derived from the FOV/visible grid), soft screen
|
||||
vignette. Particle bursts (hit sparks, crit star burst, blood/slime/ash poof
|
||||
on death, level-up stars, pickup sparkle, stairs shimmer) — pool and cap
|
||||
counts. Screen-shake on player damage (decaying offset). Floating combat text
|
||||
(-8, MISS!, CRIT!). Soft ellipse shadows under entities.
|
||||
|
||||
render/camera.py
|
||||
Viewport offset that eases toward the player each frame. Show ~48x28 tiles.
|
||||
|
||||
render/renderer.py (PURE: reads GameSession, never mutates)
|
||||
Compose: map tiles (beveled walls w/ lighter top edge + darker bottom + seeded
|
||||
per-tile variation; dithered floor with flecks), entities + items + stairs,
|
||||
lighting overlay, particles, shadows, screen-shake, camera offset. UI: bordered
|
||||
panels (1px pixel frame, inner bevel); top bar (Floor N/10, HP bar with heart
|
||||
icon, Level, XP bar); right panel (last ~8 log messages, color-coded: combat
|
||||
white, damage red, level-up green, items yellow); bottom bar (equipment slots
|
||||
as pixel-art icons, active effect timers, sound on/off icon); context prompt
|
||||
line styled as UI — on an item show "Press G to pick up <name>", on stairs
|
||||
show "Press F to descend". pygame.font.SysFont only.
|
||||
|
||||
main.py (FULL rebuild)
|
||||
State machine: menu -> playing -> dead / victory / saved. Obey the HEADLESS
|
||||
RULE precisely (detect SDL_VIDEODRIVER==dummy; main(max_frames=K) runs a
|
||||
scripted headless self-check of K frames then returns; real launches open a
|
||||
window with audio). Main menu: New Game (generate dungeon, then show How to
|
||||
Play before the first turn), Continue (only if save.json exists), How to Play
|
||||
(always; explains EVERY control), Quit. How to Play must be reachable from the
|
||||
menu and shown before every New Game, and reopened with `?` during play.
|
||||
Controls from plan: arrows/hjkl move-attack, g pickup, i inventory, e
|
||||
equipment, q quaff, r read scroll, f descend (on stairs), S save+quit,
|
||||
? help, m mute, Esc close menus. Show contextual "Press G to pick up" on an
|
||||
item and "Press F to descend" on stairs. Death screen: "You died on floor N.
|
||||
You reached level M." Victory: "You slew the Ancient Dragon! ...". Press any
|
||||
key -> menu. Initialize audio at the app boundary; keep playable if it fails.
|
||||
P4B_EOF
|
||||
P4B="$(printf '%s\n\n%s' "$SHARED" "$P4B")"
|
||||
|
||||
# =============================================================================
|
||||
# Phase 4 gate + goal backstop prompts
|
||||
# =============================================================================
|
||||
read -r -d '' P4FIX <<'P4FIX_EOF' || true
|
||||
VERIFY AND FIX PHASE 4. Run `python3 tests/smoke.py --phase 4`. If it already
|
||||
prints `phase 4: PASS`, change nothing. If it fails, read the failure, open the
|
||||
relevant file(s) among engine/serializers.py, engine/audio.py, engine/actions.py,
|
||||
engine/game_state.py, render/*, data/sprites.py, main.py, and fix the SPECIFIC
|
||||
failure without regressing phases 1-3 (re-run --phase 1/2/3 to be sure). Do not
|
||||
weaken smoke assertions.
|
||||
P4FIX_EOF
|
||||
|
||||
read -r -d '' PGOAL <<'PGOAL_EOF' || true
|
||||
GOAL BACKSTOP. The four phase gates should already pass. Now verify EVERY
|
||||
acceptance criterion in @plan.md end to end:
|
||||
1. Run `python3 tests/smoke.py --goal`. It must print "[goal] ALL ACCEPTANCE
|
||||
CRITERIA PASS". If any criterion fails, read the failure and fix the SPECIFIC
|
||||
gap in the code (you may touch any file) without weakening smoke assertions.
|
||||
2. Confirm `python3 main.py` is structured to launch a real window with audio
|
||||
when SDL_VIDEODRIVER is NOT dummy (do NOT actually open a window here — just
|
||||
confirm the headless branch is env-gated, not forced).
|
||||
3. Re-run `python3 tests/smoke.py --goal` until it passes.
|
||||
The game must be complete and playable: 10 floors, 7 enemies, A*, FOV, BSP,
|
||||
combat with crits, XP/leveling, items/inventory/equipment, save/load, win + lose
|
||||
states, How to Play, contextual g/f prompts, resilient audio, and distinct
|
||||
procedural pixel-art with lighting + particles.
|
||||
PGOAL_EOF
|
||||
PGOAL="$(printf '%s\n\n%s' "$SHARED" "$PGOAL")"
|
||||
|
||||
# =============================================================================
|
||||
# Main driver
|
||||
# =============================================================================
|
||||
echo "Underdepths build pipeline — state=$(get_state) ttl=${TTL}s retries=${MAX_RETRIES}"
|
||||
|
||||
s="$(get_state)"
|
||||
if (( s < 1 )); then dispatch phase1-foundation "$P1" "$GATE --phase 1" && set_state 1 || halt; fi
|
||||
s="$(get_state)"
|
||||
if (( s < 2 )); then dispatch phase2-core "$P2" "$GATE --phase 2" && set_state 2 || halt; fi
|
||||
s="$(get_state)"
|
||||
if (( s < 3 )); then dispatch phase3-content "$P3" "$GATE --phase 3" && set_state 3 || halt; fi
|
||||
s="$(get_state)"
|
||||
if (( s < 4 )); then
|
||||
dispatch phase4a-persist "$P4A" "$COMPILE_GATE" || halt
|
||||
dispatch phase4b-visuals "$P4B" "$COMPILE_GATE" || halt
|
||||
dispatch phase4-gate "$P4FIX" "$GATE --phase 4" && set_state 4 || halt
|
||||
fi
|
||||
s="$(get_state)"
|
||||
if (( s < 5 )); then dispatch goal-backstop "$PGOAL" "$GATE --goal" && set_state 5 || halt; fi
|
||||
|
||||
echo
|
||||
echo "==================================================================="
|
||||
echo "BUILD COMPLETE — all phase gates + goal backstop PASS."
|
||||
echo "Play it: python3 main.py"
|
||||
echo "Verify: python3 tests/smoke.py --goal"
|
||||
echo "==================================================================="
|
||||
Whitespace-only changes.
@@ -0,0 +1,27 @@
|
||||
"""Viewport camera that eases toward the player each frame (plan.md Juice)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
|
||||
class Camera:
|
||||
"""Pixel-space camera top-left. Eases toward its target; can snap."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.x: float = 0.0
|
||||
self.y: float = 0.0
|
||||
self._tx: float = 0.0
|
||||
self._ty: float = 0.0
|
||||
|
||||
def set_target(self, px: float, py: float) -> None:
|
||||
self._tx = px
|
||||
self._ty = py
|
||||
|
||||
def snap(self, px: float, py: float) -> None:
|
||||
self.x = self._tx = px
|
||||
self.y = self._ty = py
|
||||
|
||||
def update(self, dt: float, ease: float = 7.0) -> None:
|
||||
k = 1.0 - math.exp(-ease * dt)
|
||||
self.x += (self._tx - self.x) * k
|
||||
self.y += (self._ty - self.y) * k
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Procedural visual effects: particles, floating combat text, screen shake,
|
||||
lighting helpers (torch falloff, vignette). All drawn from state; none mutate it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
|
||||
try:
|
||||
import pygame
|
||||
except Exception: # pragma: no cover
|
||||
pygame = None # type: ignore
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Particles — pooled and capped.
|
||||
# --------------------------------------------------------------------------- #
|
||||
class Particles:
|
||||
def __init__(self, cap: int = 260) -> None:
|
||||
self._pool: list[dict] = []
|
||||
self._cap = cap
|
||||
|
||||
def clear(self) -> None:
|
||||
self._pool.clear()
|
||||
|
||||
def burst(self, x: float, y: float, color, n: int = 10, speed: float = 70.0,
|
||||
life: float = 0.45, gravity: float = 0.0, size: int = 2) -> None:
|
||||
for _ in range(n):
|
||||
if len(self._pool) >= self._cap:
|
||||
self._pool.pop(0)
|
||||
ang = random.random() * math.tau
|
||||
spd = random.uniform(speed * 0.25, speed)
|
||||
self._pool.append(dict(
|
||||
x=x, y=y, vx=math.cos(ang) * spd, vy=math.sin(ang) * spd,
|
||||
life=life, max=life, color=color, g=gravity, size=size))
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
out = []
|
||||
drag = max(0.0, 1.0 - 2.2 * dt)
|
||||
for p in self._pool:
|
||||
p["life"] -= dt
|
||||
if p["life"] <= 0:
|
||||
continue
|
||||
p["x"] += p["vx"] * dt
|
||||
p["y"] += p["vy"] * dt
|
||||
p["vy"] += p["g"] * dt
|
||||
p["vx"] *= drag
|
||||
p["vy"] *= drag
|
||||
out.append(p)
|
||||
self._pool = out
|
||||
|
||||
def draw(self, surf, cam) -> None:
|
||||
if pygame is None:
|
||||
return
|
||||
for p in self._pool:
|
||||
frac = max(0.0, p["life"] / p["max"])
|
||||
a = max(0, min(255, int(255 * frac)))
|
||||
r = max(1, int(p["size"] * (0.6 + 0.4 * frac)))
|
||||
sx = int(p["x"] - cam[0])
|
||||
sy = int(p["y"] - cam[1])
|
||||
if -8 <= sx <= surf.get_width() + 8 and -8 <= sy <= surf.get_height() + 8:
|
||||
s = pygame.Surface((r * 2, r * 2), pygame.SRCALPHA)
|
||||
pygame.draw.rect(s, (*p["color"], a), (0, 0, r * 2, r * 2))
|
||||
surf.blit(s, (sx - r, sy - r))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Floating combat text.
|
||||
# --------------------------------------------------------------------------- #
|
||||
class FloatText:
|
||||
def __init__(self) -> None:
|
||||
self._items: list[dict] = []
|
||||
|
||||
def clear(self) -> None:
|
||||
self._items.clear()
|
||||
|
||||
def add(self, x: float, y: float, text: str, color, big: bool = False) -> None:
|
||||
self._items.append(dict(
|
||||
x=x, y=y, text=text, color=color, life=0.95, max=0.95,
|
||||
vy=-30.0, big=big))
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
out = []
|
||||
for it in self._items:
|
||||
it["life"] -= dt
|
||||
if it["life"] <= 0:
|
||||
continue
|
||||
it["y"] += it["vy"] * dt
|
||||
it["vy"] *= max(0.0, 1.0 - 1.6 * dt)
|
||||
out.append(it)
|
||||
self._items = out
|
||||
|
||||
def draw(self, surf, font, font_big, cam) -> None:
|
||||
if pygame is None:
|
||||
return
|
||||
for it in self._items:
|
||||
frac = max(0.0, it["life"] / it["max"])
|
||||
a = max(0, min(255, int(255 * (frac ** 0.6))))
|
||||
f = font_big if it["big"] else font
|
||||
txt = f.render(it["text"], True, it["color"])
|
||||
txt.set_alpha(a)
|
||||
surf.blit(txt, (int(it["x"] - cam[0] - txt.get_width() // 2),
|
||||
int(it["y"] - cam[1])))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Screen shake — decaying random offset.
|
||||
# --------------------------------------------------------------------------- #
|
||||
class Shake:
|
||||
def __init__(self) -> None:
|
||||
self.mag: float = 0.0
|
||||
|
||||
def trigger(self, mag: float = 6.0) -> None:
|
||||
self.mag = max(self.mag, mag)
|
||||
|
||||
def update(self, dt: float) -> None:
|
||||
self.mag *= math.exp(-dt * 6.5)
|
||||
if self.mag < 0.25:
|
||||
self.mag = 0.0
|
||||
|
||||
def offset(self):
|
||||
if self.mag <= 0.0:
|
||||
return (0.0, 0.0)
|
||||
return (random.uniform(-self.mag, self.mag),
|
||||
random.uniform(-self.mag, self.mag))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Lighting helpers.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def torch_factor(dist: float, radius: int) -> float:
|
||||
"""Brightness 1.0 at the player fading to ~0.22 at the sight edge.
|
||||
|
||||
A lower edge floor than before so the step from the last visible tile to
|
||||
black unexplored space is less jarring; the smooth radial torch glow
|
||||
(see make_torch) layered on top supplies the soft circular falloff.
|
||||
"""
|
||||
if radius <= 0:
|
||||
return 1.0
|
||||
f = 1.0 - max(0.0, dist) / radius
|
||||
return max(0.22, min(1.0, 0.22 + 0.78 * f))
|
||||
|
||||
|
||||
def make_torch(radius_px: int):
|
||||
"""Cached smooth radial torch glow (warm, additive) centred on the player.
|
||||
|
||||
Returns a Surface of side 2*radius_px whose RGB falls smoothly from a warm
|
||||
yellow-white at the centre to black at the edge; the renderer blits it with
|
||||
BLEND_RGB_ADD so it lays a soft circular light pool over the per-tile grid,
|
||||
hiding the tile-aligned FOV boundary. Rendered small then smooth-scaled up.
|
||||
"""
|
||||
if pygame is None:
|
||||
return None
|
||||
d = max(8, radius_px * 2)
|
||||
sw = max(28, d // 3)
|
||||
s = pygame.Surface((sw, sw), pygame.SRCALPHA)
|
||||
c = sw / 2
|
||||
for y in range(sw):
|
||||
for x in range(sw):
|
||||
dist = math.hypot(x - c, y - c) / c
|
||||
if dist >= 1.0:
|
||||
continue
|
||||
f = (1.0 - dist) ** 1.3
|
||||
s.set_at((x, y), (int(150 * f), int(132 * f), int(96 * f), 255))
|
||||
return pygame.transform.smoothscale(s, (d, d))
|
||||
|
||||
|
||||
def make_vignette(w: int, h: int):
|
||||
"""Cached radial darkening overlay (transparent centre, dark corners)."""
|
||||
if pygame is None:
|
||||
return None
|
||||
sw, sh = max(2, w // 4), max(2, h // 4)
|
||||
s = pygame.Surface((sw, sh), pygame.SRCALPHA)
|
||||
cx, cy = sw / 2, sh / 2
|
||||
maxd = math.hypot(cx, cy)
|
||||
for y in range(sh):
|
||||
for x in range(sw):
|
||||
d = math.hypot(x - cx, y - cy) / maxd
|
||||
a = int(min(165, max(0, (d - 0.52)) * 370))
|
||||
s.set_at((x, y), (0, 0, 0, a))
|
||||
return pygame.transform.smoothscale(s, (w, h))
|
||||
@@ -0,0 +1,520 @@
|
||||
"""Pure renderer: composes the world + UI from a GameSession (never mutates it).
|
||||
|
||||
Layout (module constants, derived from C.TILE):
|
||||
+---------------------------------------------+----
|
||||
| TOP BAR floor | HP bar | level | XP bar | } SIDE panel
|
||||
+---------------------------------------------+ ) (log)
|
||||
| | )
|
||||
| MAP VIEWPORT (camera follows player)| )
|
||||
| | )
|
||||
+---------------------------------------------+----
|
||||
| BOTTOM BAR equipment | effects | sound | prompt|
|
||||
+---------------------------------------------+
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
try:
|
||||
import pygame
|
||||
except Exception: # pragma: no cover
|
||||
pygame = None # type: ignore
|
||||
|
||||
from data import constants as C
|
||||
from data import sprites as S
|
||||
from render import sprites as RS
|
||||
from render.camera import Camera
|
||||
from render.effects import (
|
||||
FloatText, Particles, Shake, make_torch, make_vignette, torch_factor,
|
||||
)
|
||||
|
||||
TILE: int = C.TILE
|
||||
VIEW_TW: int = 48
|
||||
VIEW_TH: int = 28
|
||||
MAP_W_PX: int = VIEW_TW * TILE
|
||||
MAP_H_PX: int = VIEW_TH * TILE
|
||||
TOP_H: int = 34
|
||||
BOT_H: int = 50
|
||||
SIDE_W: int = 230
|
||||
WIN_W: int = MAP_W_PX + SIDE_W
|
||||
WIN_H: int = TOP_H + MAP_H_PX + BOT_H
|
||||
MAP_X: int = 0
|
||||
MAP_Y: int = TOP_H
|
||||
|
||||
COL = C.COLORS
|
||||
WALL_V = COL["wall_visible"]
|
||||
WALL_E = COL["wall_explored"]
|
||||
FLOOR_V = COL["floor_visible"]
|
||||
FLOOR_E = COL["floor_explored"]
|
||||
VOID = COL["void"]
|
||||
|
||||
|
||||
def _shade(color, f: float):
|
||||
return (max(0, min(255, int(color[0] * f))),
|
||||
max(0, min(255, int(color[1] * f))),
|
||||
max(0, min(255, int(color[2] * f))))
|
||||
|
||||
|
||||
def _hash(tx: int, ty: int) -> float:
|
||||
n = (tx * 73856093) ^ (ty * 19349663)
|
||||
n = (n ^ (n >> 13)) * 1274126177 & 0xFFFFFFFF
|
||||
n = (n ^ (n >> 16)) & 0xFFFFFFFF
|
||||
return n / 0xFFFFFFFF
|
||||
|
||||
|
||||
def _log_color(line: str):
|
||||
low = line.lower()
|
||||
if any(k in low for k in ("level", "defeated", "conquered", "slew")):
|
||||
return COL["log_levelup"]
|
||||
if any(k in low for k in ("you", "miss")) and "miss" in low and "you miss" in low:
|
||||
return COL["log_miss"]
|
||||
if any(k in low for k in ("hits you", "damage", "died", "burn", "critically", "shoots")):
|
||||
return COL["log_damage"]
|
||||
if any(k in low for k in ("pick up", "equip", "unequip", "quaff", "scroll", "potion",
|
||||
"teleport", "map", "surge", "fade")):
|
||||
return COL["log_item"]
|
||||
if "miss" in low:
|
||||
return COL["log_miss"]
|
||||
return COL["log_combat"]
|
||||
|
||||
|
||||
# armor sprite_key -> pauldron color cue shown on the player
|
||||
_ARMOR_TINT = {
|
||||
"armor_leather": COL["floor_visible"],
|
||||
"armor_chain": COL["armor"],
|
||||
"armor_plate": (210, 210, 220),
|
||||
}
|
||||
|
||||
|
||||
class Renderer:
|
||||
def __init__(self, size, audio) -> None:
|
||||
self.W, self.H = size
|
||||
self.audio = audio
|
||||
self.cam = Camera()
|
||||
self.particles = Particles()
|
||||
self.floats = FloatText()
|
||||
self.shake = Shake()
|
||||
self._dt = 0.0
|
||||
self._cam_world = (0.0, 0.0)
|
||||
self._fx_cam = (0.0, 0.0)
|
||||
fname = "dejavusans,arial,helvetica,sans"
|
||||
self.font = pygame.font.SysFont(fname, 13)
|
||||
self.font_s = pygame.font.SysFont(fname, 11)
|
||||
self.font_b = pygame.font.SysFont(fname, 15, bold=True)
|
||||
self.font_l = pygame.font.SysFont(fname, 30, bold=True)
|
||||
self.font_xl = pygame.font.SysFont(fname, 46, bold=True)
|
||||
self.vignette = make_vignette(MAP_W_PX, MAP_H_PX)
|
||||
self.torch = make_torch(C.SIGHT_RADIUS * TILE)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
def update(self, dt: float) -> None:
|
||||
self._dt = max(0.001, dt)
|
||||
self.particles.update(dt)
|
||||
self.floats.update(dt)
|
||||
|
||||
def world_px(self, tx: int, ty: int):
|
||||
"""Screen-pixel center of a world tile (for spawning effects)."""
|
||||
cx, cy = self._cam_world
|
||||
wx = tx * TILE + TILE / 2
|
||||
wy = ty * TILE + TILE / 2
|
||||
return (wx - cx + MAP_X, wy - cy + MAP_Y)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# World
|
||||
# ------------------------------------------------------------------ #
|
||||
def render_world(self, screen, session, t: float) -> None:
|
||||
floor = session.dungeon[session.current_floor]
|
||||
p = session.player
|
||||
map_pw = C.MAP_WIDTH * TILE
|
||||
map_ph = C.MAP_HEIGHT * TILE
|
||||
|
||||
tgt_x = p.x * TILE + TILE / 2 - MAP_W_PX / 2
|
||||
tgt_y = p.y * TILE + TILE / 2 - MAP_H_PX / 2
|
||||
tgt_x = max(0.0, min(tgt_x, max(0.0, map_pw - MAP_W_PX)))
|
||||
tgt_y = max(0.0, min(tgt_y, max(0.0, map_ph - MAP_H_PX)))
|
||||
if self.cam.x == 0.0 and self.cam.y == 0.0:
|
||||
self.cam.snap(tgt_x, tgt_y)
|
||||
self.cam.set_target(tgt_x, tgt_y)
|
||||
self.cam.update(self._dt)
|
||||
self.shake.update(self._dt)
|
||||
sox, soy = self.shake.offset()
|
||||
cx, cy = self.cam.x, self.cam.y
|
||||
self._cam_world = (cx - sox, cy - soy)
|
||||
self._fx_cam = (cx - sox, cy - soy - MAP_Y)
|
||||
|
||||
screen.fill(VOID)
|
||||
vis = floor.visible
|
||||
expl = floor.explored
|
||||
tx0 = max(0, int(cx // TILE) - 1)
|
||||
tx1 = min(C.MAP_WIDTH - 1, int((cx + MAP_W_PX) // TILE) + 1)
|
||||
ty0 = max(0, int(cy // TILE) - 1)
|
||||
ty1 = min(C.MAP_HEIGHT - 1, int((cy + MAP_H_PX) // TILE) + 1)
|
||||
px, py = p.x, p.y
|
||||
for ty in range(ty0, ty1 + 1):
|
||||
row_v = vis[ty]
|
||||
row_e = expl[ty]
|
||||
row_t = floor.tiles[ty]
|
||||
sy = round(ty * TILE - cy + soy) + MAP_Y
|
||||
for tx in range(tx0, tx1 + 1):
|
||||
if not row_e[tx] and not row_v[tx]:
|
||||
continue
|
||||
sx = round(tx * TILE - cx + sox) + MAP_X
|
||||
if row_v[tx]:
|
||||
light = torch_factor(math.hypot(tx - px, ty - py), C.SIGHT_RADIUS)
|
||||
if row_t[tx] == 0:
|
||||
self._wall(screen, sx, sy, tx, ty, light)
|
||||
else:
|
||||
self._floor(screen, sx, sy, tx, ty, light)
|
||||
else:
|
||||
col = WALL_E if row_t[tx] == 0 else FLOOR_E
|
||||
pygame.draw.rect(screen, col, (sx, sy, TILE, TILE))
|
||||
if row_t[tx] == 0:
|
||||
pygame.draw.rect(screen, _shade(col, 0.7), (sx, sy + TILE - 3, TILE, 3))
|
||||
|
||||
if self.torch is not None:
|
||||
ts = self.torch.get_width()
|
||||
gx = round(px * TILE + TILE / 2 - (cx - sox)) + MAP_X - ts // 2
|
||||
gy = round(py * TILE + TILE / 2 - (cy - soy)) + MAP_Y - ts // 2
|
||||
screen.blit(self.torch, (gx, gy), special_flags=pygame.BLEND_RGB_ADD)
|
||||
|
||||
self._draw_entities(screen, floor, p, cx - sox, cy - soy, t)
|
||||
|
||||
if self.vignette is not None:
|
||||
screen.blit(self.vignette, (MAP_X, MAP_Y))
|
||||
|
||||
self.particles.draw(screen, self._fx_cam)
|
||||
self.floats.draw(screen, self.font_s, self.font_b, self._fx_cam)
|
||||
|
||||
self._ui_top(screen, session)
|
||||
self._ui_log(screen, session)
|
||||
self._ui_bottom(screen, session)
|
||||
|
||||
def _wall(self, surf, sx, sy, tx, ty, light) -> None:
|
||||
h = _hash(tx, ty)
|
||||
h2 = _hash(tx + 101, ty - 57)
|
||||
bevel = max(2, TILE // 7)
|
||||
# per-tile base shade so no two walls read identically
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * (0.82 + 0.36 * h)), (sx, sy, TILE, TILE))
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 1.45), (sx, sy, TILE, bevel)) # lit top bevel
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 0.5),
|
||||
(sx, sy + TILE - bevel, TILE, bevel)) # shadow base
|
||||
# brick mortar: horizontal seam mid-wall + offset vertical seams per row
|
||||
mid = sy + TILE // 2
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 0.58), (sx, mid, TILE, 1))
|
||||
v1 = int(h2 * (TILE // 2))
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 0.6), (sx + v1, sy + bevel, 1, mid - sy - bevel))
|
||||
v2 = (int(h * (TILE // 2)) + TILE // 2) % (TILE - 1)
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * 0.6), (sx + v2, mid + 1, 1, sy + TILE - bevel - mid - 1))
|
||||
# stable speckles (highlight + grit)
|
||||
for k in range(4):
|
||||
fx = sx + int((h * (97 + k * 53)) % (TILE - 1))
|
||||
fy = sy + bevel + int((h2 * (31 + k * 29)) % (TILE - 2 * bevel))
|
||||
f = 1.4 if ((h * (k + 2)) % 1) > 0.5 else 0.55
|
||||
pygame.draw.rect(surf, _shade(WALL_V, light * f), (fx, fy, 1, 1))
|
||||
|
||||
def _floor(self, surf, sx, sy, tx, ty, light) -> None:
|
||||
h = _hash(tx, ty)
|
||||
pygame.draw.rect(surf, _shade(FLOOR_V, light * (0.86 + 0.28 * h)), (sx, sy, TILE, TILE))
|
||||
# subtle checkerboard dither (stable per tile parity)
|
||||
if (tx + ty) & 1:
|
||||
pygame.draw.rect(surf, _shade(FLOOR_V, light * 1.16), (sx, sy, 2, 2))
|
||||
pygame.draw.rect(surf, _shade(FLOOR_V, light * 0.8), (sx + TILE - 2, sy + TILE - 2, 2, 2))
|
||||
# flecks / specular grit
|
||||
for k in range(5):
|
||||
fx = sx + int((h * (97 + k * 31)) % (TILE - 1))
|
||||
fy = sy + int((h * (53 + k * 17)) % (TILE - 1))
|
||||
f = 1.4 if ((h * (k + 1)) % 1) > 0.5 else 0.62
|
||||
pygame.draw.rect(surf, _shade(FLOOR_V, light * f), (fx, fy, 1, 1))
|
||||
|
||||
def _draw_entities(self, surf, floor, player, cx, cy, t) -> None:
|
||||
from entities.enemy import Enemy
|
||||
from entities.item import Item
|
||||
|
||||
vis = floor.visible
|
||||
# ground features first (remembered on explored tiles)
|
||||
ground = [e for e in floor.entities
|
||||
if isinstance(e, Item) or (not isinstance(e, Enemy) and getattr(e, "sprite_key", "") == "stairs")]
|
||||
for e in ground:
|
||||
if not (vis[e.y][e.x] or floor.explored[e.y][e.x]):
|
||||
continue
|
||||
self._blit_entity(surf, e, cx, cy, t, shadow=True)
|
||||
# actors: visible enemies + the player, sorted by y for overlap
|
||||
actors = [e for e in floor.entities
|
||||
if isinstance(e, Enemy) and e.hp > 0 and vis[e.y][e.x]]
|
||||
actors.append(player)
|
||||
actors.sort(key=lambda e: e.y)
|
||||
for e in actors:
|
||||
self._blit_entity(surf, e, cx, cy, t, shadow=True, is_actor=True)
|
||||
|
||||
def _blit_entity(self, surf, e, cx, cy, t, shadow=False, is_actor=False) -> None:
|
||||
from entities.enemy import Enemy
|
||||
sx = round(e.x * TILE - cx) + MAP_X
|
||||
sy = round(e.y * TILE - cy) + MAP_Y
|
||||
if shadow:
|
||||
sh = pygame.Surface((TILE - 4, 5), pygame.SRCALPHA)
|
||||
pygame.draw.ellipse(sh, (0, 0, 0, 90), sh.get_rect())
|
||||
surf.blit(sh, (sx + 2, sy + TILE - 5))
|
||||
|
||||
name = e.sprite_key
|
||||
if name == "player":
|
||||
name = "player_" + getattr(e, "facing", "down")
|
||||
if name not in S.SPRITES:
|
||||
name = "player_down"
|
||||
frame = int(t * 2.5 + (e.x * 7 + e.y * 13)) % max(1, RS.frame_count(name))
|
||||
bob = -1 if (frame == 1 and is_actor) else 0
|
||||
spr = RS.get(name, frame, TILE)
|
||||
if spr is not None:
|
||||
surf.blit(spr, (sx, sy + bob))
|
||||
|
||||
if isinstance(e, Enemy) and e.hp < e.max_hp:
|
||||
self._hp_pip(surf, sx, sy - 3, e.hp / max(1, e.max_hp))
|
||||
if getattr(e, "sprite_key", "") == "player":
|
||||
self._player_gear(surf, e, sx, sy)
|
||||
|
||||
def _hp_pip(self, surf, sx, sy, frac) -> None:
|
||||
w = TILE - 6
|
||||
pygame.draw.rect(surf, (30, 12, 12), (sx + 3, sy, w, 3))
|
||||
fw = max(0, int(w * frac))
|
||||
col = (90, 200, 90) if frac > 0.5 else ((220, 180, 60) if frac > 0.25 else (210, 70, 60))
|
||||
pygame.draw.rect(surf, col, (sx + 3, sy, fw, 3))
|
||||
|
||||
def _player_gear(self, surf, player, sx, sy) -> None:
|
||||
# held weapon icon at the lower-right
|
||||
wpn = player.equipped.get("weapon")
|
||||
if wpn is not None:
|
||||
ico = RS.get(wpn.sprite_key, 0, TILE // 2 + 2)
|
||||
if ico is not None:
|
||||
surf.blit(ico, (sx + TILE - 8, sy + 6))
|
||||
# armor pauldron tint on the shoulders
|
||||
arm = player.equipped.get("armor")
|
||||
if arm is not None:
|
||||
tint = _ARMOR_TINT.get(arm.sprite_key, (180, 180, 180))
|
||||
pygame.draw.rect(surf, tint, (sx + 3, sy + int(TILE * 0.30), 3, 4))
|
||||
pygame.draw.rect(surf, tint, (sx + TILE - 6, sy + int(TILE * 0.30), 3, 4))
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# UI
|
||||
# ------------------------------------------------------------------ #
|
||||
def _panel(self, surf, rect, fill=None) -> None:
|
||||
fill = fill or COL["ui_panel"]
|
||||
pygame.draw.rect(surf, fill, rect)
|
||||
pygame.draw.rect(surf, COL["ui_border"], rect, 1)
|
||||
pygame.draw.line(surf, COL["ui_border_hi"], (rect[0] + 1, rect[1] + 1),
|
||||
(rect[0] + rect[2] - 2, rect[1] + 1)) # top bevel
|
||||
|
||||
def _text(self, surf, s, pos, font=None, color=None) -> None:
|
||||
color = color or COL["log_combat"]
|
||||
surf.blit((font or self.font).render(s, True, color), pos)
|
||||
|
||||
def _bar(self, surf, rect, frac, full, back, icon=None) -> None:
|
||||
x, y, w, h = rect
|
||||
pygame.draw.rect(surf, back, (x, y, w, h))
|
||||
fw = max(0, int(w * max(0.0, min(1.0, frac))))
|
||||
if fw:
|
||||
pygame.draw.rect(surf, full, (x, y, fw, h))
|
||||
pygame.draw.rect(surf, COL["ui_border"], (x, y, w, h), 1)
|
||||
if icon is not None:
|
||||
surf.blit(icon, (x - 2, y - 2))
|
||||
|
||||
def _heart(self, size=12):
|
||||
s = pygame.Surface((size, size), pygame.SRCALPHA)
|
||||
col = (200, 60, 65)
|
||||
r = size // 4
|
||||
pygame.draw.circle(s, col, (size // 2 - r, size // 3), r)
|
||||
pygame.draw.circle(s, col, (size // 2 + r, size // 3), r)
|
||||
pygame.draw.polygon(s, col, [(0, size // 3 + 1), (size, size // 3 + 1), (size // 2, size - 1)])
|
||||
return s
|
||||
|
||||
def _ui_top(self, surf, session) -> None:
|
||||
p = session.player
|
||||
self._panel(surf, (0, 0, WIN_W, TOP_H), COL["ui_bg"])
|
||||
self._text(surf, f"Floor {session.current_floor + 1}/{C.FLOORS}", (8, 9), self.font_b, COL["prompt"])
|
||||
# HP bar
|
||||
hx = 150
|
||||
self._bar(surf, (hx, 10, 240, 14), p.hp / max(1, p.max_hp),
|
||||
COL["hp_full"], COL["hp_back"], icon=self._heart())
|
||||
self._text(surf, f"{p.hp}/{p.max_hp}", (hx + 246, 9), self.font_s)
|
||||
# Level + XP
|
||||
self._text(surf, f"Lv {p.level}", (hx + 320, 9), self.font_b, COL["prompt"])
|
||||
xp_next = C.XP_THRESHOLDS.get(min(p.level + 1, C.MAX_LEVEL), p.xp)
|
||||
xp_cur = C.XP_THRESHOLDS.get(p.level, 0)
|
||||
frac = (p.xp - xp_cur) / max(1, xp_next - xp_cur) if xp_next > xp_cur else 1.0
|
||||
self._bar(surf, (WIN_W - SIDE_W - 150, 10, 130, 14), frac, COL["xp_full"], COL["xp_back"])
|
||||
self._text(surf, "XP", (WIN_W - SIDE_W - 172, 9), self.font_s, COL["xp_full"])
|
||||
|
||||
def _ui_log(self, surf, session) -> None:
|
||||
x = MAP_W_PX
|
||||
y = TOP_H
|
||||
self._panel(surf, (x, y, SIDE_W, MAP_H_PX), COL["ui_bg"])
|
||||
self._text(surf, "Messages", (x + 8, y + 6), self.font_b, COL["prompt"])
|
||||
pygame.draw.line(surf, COL["ui_border"], (x + 4, y + 24), (x + SIDE_W - 4, y + 24))
|
||||
lines = session.log[-9:]
|
||||
ly = y + MAP_H_PX - 12
|
||||
for line in reversed(lines):
|
||||
txt = self._crop(line, _log_color(line), SIDE_W - 16)
|
||||
surf.blit(txt, (x + 8, ly - txt.get_height()))
|
||||
ly -= txt.get_height() + 1
|
||||
|
||||
def _crop(self, text, color, maxw):
|
||||
full = self.font_s.render(text, True, color)
|
||||
if full.get_width() <= maxw:
|
||||
return full
|
||||
keep = max(3, int(len(text) * maxw / full.get_width()) - 1)
|
||||
return self.font_s.render(text[:keep] + "...", True, color)
|
||||
|
||||
def _ui_bottom(self, surf, session) -> None:
|
||||
p = session.player
|
||||
y = WIN_H - BOT_H
|
||||
self._panel(surf, (0, y, WIN_W, BOT_H), COL["ui_bg"])
|
||||
# equipment slots
|
||||
self._text(surf, "WPN", (8, y + 6), self.font_s, COL["weapon"])
|
||||
wpn = p.equipped.get("weapon")
|
||||
self._slot(surf, 8, y + 20, wpn)
|
||||
self._text(surf, "ARM", (42, y + 6), self.font_s, COL["armor"])
|
||||
self._slot(surf, 42, y + 20, p.equipped.get("armor"))
|
||||
# active effect timers
|
||||
ex = 90
|
||||
self._text(surf, "Effects", (ex, y + 6), self.font_s, COL["prompt"])
|
||||
if p.effects:
|
||||
tx = ex
|
||||
for eff in p.effects:
|
||||
label = ("STR" if eff.kind == "strength" else "INV")
|
||||
col = COL["weapon"] if eff.kind == "strength" else COL["wraith"]
|
||||
self._text(surf, f"{label} {eff.duration}", (tx, y + 22), self.font_s, col)
|
||||
tx += 52
|
||||
else:
|
||||
self._text(surf, "-", (ex, y + 22), self.font_s, (90, 90, 100))
|
||||
# sound icon
|
||||
self._text(surf, "[m] sound " + ("OFF" if self.audio.muted else "ON"),
|
||||
(WIN_W - SIDE_W - 110, y + 22), self.font_s,
|
||||
(120, 120, 130) if self.audio.muted else COL["log_levelup"])
|
||||
# context prompt
|
||||
prompt = self._context(session)
|
||||
if prompt:
|
||||
self._text(surf, prompt, (8, y + BOT_H - 16), self.font_b, COL["prompt"])
|
||||
|
||||
def _slot(self, surf, x, y, item) -> None:
|
||||
rect = (x, y, 28, 22)
|
||||
pygame.draw.rect(surf, COL["ui_panel"], rect)
|
||||
pygame.draw.rect(surf, COL["ui_border"], rect, 1)
|
||||
if item is not None:
|
||||
ico = RS.get(item.sprite_key, 0, 20)
|
||||
if ico is not None:
|
||||
surf.blit(ico, (x + 4, y + 1))
|
||||
|
||||
def _context(self, session) -> str:
|
||||
from entities.item import Item
|
||||
p = session.player
|
||||
floor = session.dungeon[session.current_floor]
|
||||
for e in floor.entities:
|
||||
if isinstance(e, Item) and e.x == p.x and e.y == p.y:
|
||||
return f"Press G to pick up {e.name}"
|
||||
if (p.x, p.y) == floor.stairs_down and session.current_floor < C.FLOORS - 1:
|
||||
return "Press F to descend"
|
||||
return ""
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Screens
|
||||
# ------------------------------------------------------------------ #
|
||||
def render_menu(self, screen, index, has_save, t) -> None:
|
||||
screen.fill(VOID)
|
||||
bob = math.sin(t * 2.0) * 4
|
||||
self._text(screen, "UNDERDEPTHS", (WIN_W // 2 - 150, 90 + bob), self.font_xl, COL["prompt"])
|
||||
self._text(screen, "A turn-based roguelike descent", (WIN_W // 2 - 110, 150 + bob),
|
||||
self.font, (150, 140, 120))
|
||||
dragon = RS.get("ancient_dragon", int(t * 2.5) % 2, 96)
|
||||
if dragon is not None:
|
||||
screen.blit(dragon, (WIN_W // 2 - 48, 190))
|
||||
options = ["New Game"]
|
||||
if has_save:
|
||||
options.append("Continue")
|
||||
options += ["How to Play", "Quit"]
|
||||
oy = 320
|
||||
for i, opt in enumerate(options):
|
||||
sel = (i == index)
|
||||
col = COL["highlight"] if sel else (170, 160, 150)
|
||||
prefix = "> " if sel else " "
|
||||
self._text(screen, prefix + opt, (WIN_W // 2 - 90, oy + i * 30), self.font_b, col)
|
||||
self._text(screen, "arrows/hjkl select - enter confirm", (WIN_W // 2 - 130, WIN_H - 40),
|
||||
self.font_s, (110, 105, 100))
|
||||
|
||||
_HELP_LINES = [
|
||||
("HOW TO PLAY", COL["prompt"], True),
|
||||
("", None, False),
|
||||
("Move / attack: Arrows or H J K L (walk into an enemy to hit)", COL["log_combat"], False),
|
||||
("Pick up item: stand on it, press G", COL["log_item"], False),
|
||||
("Descend: stand on the yellow > stairs, press F", COL["prompt"], False),
|
||||
("Inventory: I Equipment: E", COL["log_combat"], False),
|
||||
("Quaff potion: Q Read scroll: R", COL["log_combat"], False),
|
||||
("Save & quit: S Help: ? Mute: M Cancel: Esc", COL["log_combat"], False),
|
||||
("", None, False),
|
||||
("Slay the Ancient Dragon on floor 10 to win. Permadeath: die and the", (170, 160, 150), False),
|
||||
("run ends. Explore, loot, level up, and descend.", (170, 160, 150), False),
|
||||
("", None, False),
|
||||
("Press any key to return.", COL["prompt"], False),
|
||||
]
|
||||
|
||||
def render_help(self, screen, t) -> None:
|
||||
screen.fill(VOID)
|
||||
self._panel(screen, (WIN_W // 2 - 290, 70, 580, 460), COL["ui_bg"])
|
||||
y = 96
|
||||
for line, col, big in self._HELP_LINES:
|
||||
self._text(screen, line, (WIN_W // 2 - 270, y), self.font_l if big else self.font,
|
||||
col or COL["log_combat"])
|
||||
y += 40 if big else 26
|
||||
|
||||
def render_end(self, screen, session, kind, t) -> None:
|
||||
screen.fill(VOID)
|
||||
p = session.player
|
||||
if kind == "victory":
|
||||
self._text(screen, "VICTORY", (WIN_W // 2 - 130, 150), self.font_xl, COL["log_levelup"])
|
||||
self._text(screen, "You slew the Ancient Dragon!", (WIN_W // 2 - 150, 230), self.font_b, COL["prompt"])
|
||||
self._text(screen, "You conquered Underdepths.", (WIN_W // 2 - 130, 260), self.font_b, COL["prompt"])
|
||||
else:
|
||||
self._text(screen, "YOU DIED", (WIN_W // 2 - 120, 150), self.font_xl, COL["hp_full"])
|
||||
self._text(screen, f"You died on floor {session.current_floor + 1}.",
|
||||
(WIN_W // 2 - 130, 230), self.font_b, COL["log_combat"])
|
||||
self._text(screen, f"You reached level {p.level}.", (WIN_W // 2 - 110, 290), self.font_b, COL["log_levelup"])
|
||||
self._text(screen, "Press any key to return to the menu.", (WIN_W // 2 - 150, WIN_H - 90),
|
||||
self.font, (150, 140, 120))
|
||||
|
||||
def render_inventory(self, screen, session, mode, t) -> None:
|
||||
p = session.player
|
||||
# main.py passes overlay modes 'inv' | 'equip' | 'quaff' | 'read'
|
||||
title = {"inv": "Inventory", "equip": "Equipment",
|
||||
"quaff": "Quaff a Potion", "read": "Read a Scroll"}.get(mode, "Inventory")
|
||||
|
||||
def wanted(it):
|
||||
if mode == "quaff":
|
||||
return it.item_type == "potion"
|
||||
if mode == "read":
|
||||
return it.item_type == "scroll"
|
||||
return True
|
||||
items = [it for it in p.inventory if wanted(it)]
|
||||
|
||||
pw, ph = WIN_W - 160, WIN_H - 160
|
||||
px, py = 80, 80
|
||||
self._panel(screen, (px, py, pw, ph), COL["ui_bg"])
|
||||
self._text(screen, title, (px + 16, py + 12), self.font_l, COL["prompt"])
|
||||
if mode == "equip":
|
||||
self._text(screen, f"Weapon: {_name(p.equipped.get('weapon'))}", (px + 16, py + 60), self.font, COL["weapon"])
|
||||
self._text(screen, f"Armor: {_name(p.equipped.get('armor'))}", (px + 16, py + 82), self.font, COL["armor"])
|
||||
self._text(screen, "Equip from inventory (I).", (px + 16, py + 110), self.font_s, (150, 140, 120))
|
||||
ly = py + 64 if mode != "equip" else py + 150
|
||||
if mode != "equip" and not items:
|
||||
self._text(screen, "(empty)", (px + 16, ly), self.font, (130, 125, 120))
|
||||
for i, it in enumerate(items):
|
||||
letter = chr(ord("a") + i) if i < 26 else str(i)
|
||||
ico = RS.get(it.sprite_key, 0, 20)
|
||||
row_y = ly + i * 26
|
||||
if ico is not None:
|
||||
screen.blit(ico, (px + 16, row_y - 2))
|
||||
kind = it.item_type.capitalize()
|
||||
self._text(screen, f"[{letter}] {it.name}", (px + 42, row_y), self.font, COL["log_item"])
|
||||
self._text(screen, kind, (px + pw - 130, row_y), self.font_s, (150, 140, 120))
|
||||
hint = "press a letter to use/equip - Esc closes" if mode != "equip" else "Esc closes"
|
||||
self._text(screen, hint, (px + 16, py + ph - 28), self.font_s, (130, 125, 120))
|
||||
|
||||
|
||||
def _name(item) -> str:
|
||||
return item.name if item is not None else "(none)"
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Rasterize palette-key sprite grids to cached pygame Surfaces (plan.md Rendering).
|
||||
|
||||
`get(name, frame, tile)` builds a Surface once (keyed by name+frame+tile) and
|
||||
caches it. The renderer blits the cached surface directly. Pixel-art is kept
|
||||
crisp with nearest-neighbour `transform.scale` (never smoothscale).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
try:
|
||||
import pygame
|
||||
except Exception: # pragma: no cover
|
||||
pygame = None # type: ignore
|
||||
|
||||
from data import sprites as S
|
||||
from data.constants import PALETTE, TILE as _TILE
|
||||
|
||||
_cache: dict = {}
|
||||
|
||||
|
||||
def get(name: str, frame: int = 0, tile: int = _TILE):
|
||||
"""Return the cached Surface for `name` scaled to `tile`x`tile`."""
|
||||
if pygame is None:
|
||||
return None
|
||||
key = (name, frame, tile)
|
||||
cached = _cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
grid = S.grid(name, frame)
|
||||
h = len(grid)
|
||||
w = max(len(r) for r in grid) if grid else 1
|
||||
w = max(1, w)
|
||||
cell = 3 # fixed >=2 internal px/cell; crisp nearest-scale to any tile size
|
||||
surf = pygame.Surface((w * cell, h * cell), pygame.SRCALPHA)
|
||||
for y, row in enumerate(grid):
|
||||
for x, ch in enumerate(row):
|
||||
col = PALETTE.get(ch)
|
||||
if col is not None:
|
||||
pygame.draw.rect(surf, col, (x * cell, y * cell, cell, cell))
|
||||
if (w * cell, h * cell) != (tile, tile):
|
||||
surf = pygame.transform.scale(surf, (tile, tile))
|
||||
_cache[key] = surf
|
||||
return surf
|
||||
|
||||
|
||||
def frame_count(name: str) -> int:
|
||||
return S.frames_count(name)
|
||||
|
||||
|
||||
def warm(tile: int = _TILE) -> None:
|
||||
"""Pre-rasterize every sprite frame so the first frame is hitch-free."""
|
||||
if pygame is None:
|
||||
return
|
||||
for name in S.NAMES:
|
||||
for f in range(S.frames_count(name)):
|
||||
get(name, f, tile)
|
||||
@@ -0,0 +1,599 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Underdepths phase gates + goal backstop. HEADLESS + authoritative contract.
|
||||
|
||||
This file IS the build contract. Every phase prompt tells the worker:
|
||||
"tests/smoke.py is your contract. Make `python tests/smoke.py --phase N` print
|
||||
`phase N: PASS`. You may correct smoke.py if its expectation contradicts
|
||||
plan.md, but NEVER weaken a behavioural assertion to pass trivially."
|
||||
|
||||
Usage:
|
||||
python tests/smoke.py --phase N # run one phase gate (1..4)
|
||||
python tests/smoke.py --goal # run every acceptance criterion
|
||||
python tests/smoke.py # run all phase gates
|
||||
|
||||
Exit code 0 on full PASS, nonzero on any FAIL.
|
||||
|
||||
It sets headless SDL drivers itself; it must never depend on a real display.
|
||||
------------------------------------------------------------------------------
|
||||
PUBLIC API CONTRACT (what the implementation must provide):
|
||||
|
||||
data/constants.py
|
||||
TILE:int=20 MAP_WIDTH:int=80 MAP_HEIGHT:int=50 SIGHT_RADIUS:int=8 FLOORS:int=10
|
||||
COLORS:dict PALETTE:dict XP table helpers
|
||||
entities/entity.py
|
||||
@dataclass Entity(x:int,y:int,name:str,sprite_key:str,blocks:bool=True)
|
||||
entities/player.py
|
||||
@dataclass Player(Entity) with hp/max_hp/power/armor/accuracy/evasion/crit_chance/
|
||||
speed/level=1/xp=0/inventory:list/equipped:dict/effects:list/facing/name="You"
|
||||
Player.total_power()->int Player.total_armor()->int
|
||||
Player.gain_xp(amount:int)->bool (True if levelled up; applies level-up table)
|
||||
entities/enemy.py
|
||||
@dataclass Enemy(Entity) hp/max_hp/power/armor/accuracy/evasion/crit_chance/speed/
|
||||
behavior/xp_value/last_known_pos/act_counter/can_split/ranged_power
|
||||
make_enemy(kind:str,x:int,y:int)->Enemy
|
||||
ENEMY_KINDS:list[str]
|
||||
entities/item.py
|
||||
make_item(name:str,x:int,y:int)->Item ; Item has item_type/subtype/stats/name/sprite_key
|
||||
engine/map_gen.py
|
||||
@dataclass Rect(x,y,w,h) with .center
|
||||
@dataclass GameMap(width,height,tiles:list[list[int]],rooms:list[Rect],
|
||||
explored:list[list[bool]],visible:list[list[bool]],entities:list,
|
||||
stairs_down:tuple[int,int],floor_index:int)
|
||||
generate_dungeon(floor_index:int,width=80,height=50)->GameMap
|
||||
is_walkable(game_map,x,y)->bool
|
||||
populate(game_map,floor_index,rng=None)->None # adds enemies+items (NOT on floor 9 boss room besides dragon+potions)
|
||||
engine/fov.py
|
||||
compute_fov(game_map,ox,oy,radius=8)->set[tuple[int,int]] # mutates game_map.visible too
|
||||
engine/pathfinding.py
|
||||
astar(game_map,start,goal,blocked:set[tuple]=frozenset())->list[tuple]|None
|
||||
engine/combat.py
|
||||
attack(attacker,defender,rng=None,log=None)->dict
|
||||
dict has: hit:bool damage:int crit:bool killed:bool (defender.hp already applied)
|
||||
ai/behaviors.py
|
||||
take_enemy_turn(enemy,session,rng=None)->None
|
||||
engine/game_state.py
|
||||
@dataclass GameSession(player,dungeon:list[GameMap],current_floor:int,log:list[str],
|
||||
turn:int,state:str, ...) plus rng
|
||||
new_game(seed=None)->GameSession
|
||||
recompute_fov(session)->None
|
||||
engine/actions.py
|
||||
try_move(session,dx,dy)->bool ; pickup(session)->bool ; descend(session)->bool
|
||||
use_item(session,item)->None ; equip(session,item)->None
|
||||
engine/serializers.py
|
||||
session_to_dict(session)->dict ; dict_to_session(d)->GameSession
|
||||
engine/audio.py
|
||||
AudioManager() ; .play(name)->None (never raises) ; .toggle_mute()->None ; .muted:bool
|
||||
main.py
|
||||
main(max_frames:int|None=None)->None (headless self-check loop when SDL_VIDEODRIVER==dummy)
|
||||
------------------------------------------------------------------------------
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import random
|
||||
|
||||
os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
|
||||
os.environ["SDL_VIDEODRIVER"] = "dummy"
|
||||
os.environ["SDL_AUDIODRIVER"] = "dummy"
|
||||
os.environ["UNDERDEPTHS_HEADLESS"] = "1"
|
||||
|
||||
_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if _ROOT not in sys.path:
|
||||
sys.path.insert(0, _ROOT)
|
||||
|
||||
|
||||
def _step(desc, cond):
|
||||
if cond:
|
||||
print(f" ok: {desc}")
|
||||
else:
|
||||
raise AssertionError(f"FAIL: {desc}")
|
||||
|
||||
|
||||
def _first_floor(game_map):
|
||||
for y in range(game_map.height):
|
||||
for x in range(game_map.width):
|
||||
if game_map.tiles[y][x] == 1:
|
||||
return (x, y)
|
||||
raise AssertionError("no floor tile found")
|
||||
|
||||
|
||||
def _all_floor_tiles(game_map):
|
||||
return [(x, y) for y in range(game_map.height) for x in range(game_map.width)
|
||||
if game_map.tiles[y][x] == 1]
|
||||
|
||||
|
||||
def _flood_reachable(game_map, start):
|
||||
from collections import deque
|
||||
seen = {start}
|
||||
q = deque([start])
|
||||
while q:
|
||||
x, y = q.popleft()
|
||||
for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
|
||||
if (nx, ny) in seen:
|
||||
continue
|
||||
if 0 <= nx < game_map.width and 0 <= ny < game_map.height and game_map.tiles[ny][nx] == 1:
|
||||
seen.add((nx, ny))
|
||||
q.append((nx, ny))
|
||||
return seen
|
||||
|
||||
|
||||
def _ascii(game_map, mark=None):
|
||||
mark = mark or set()
|
||||
out = []
|
||||
for y in range(game_map.height):
|
||||
row = []
|
||||
for x in range(game_map.width):
|
||||
if (x, y) in mark:
|
||||
row.append("@")
|
||||
elif game_map.tiles[y][x] == 1:
|
||||
row.append(".")
|
||||
else:
|
||||
row.append("#")
|
||||
out.append("".join(row))
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def phase1():
|
||||
from engine import map_gen
|
||||
from data import constants as C
|
||||
|
||||
_step("MAP_WIDTH==80", C.MAP_WIDTH == 80)
|
||||
_step("MAP_HEIGHT==50", C.MAP_HEIGHT == 50)
|
||||
_step("SIGHT_RADIUS==8", C.SIGHT_RADIUS == 8)
|
||||
_step("FLOORS==10", getattr(C, "FLOORS", 10) == 10)
|
||||
_step("TILE>=16", getattr(C, "TILE", 20) >= 16)
|
||||
|
||||
for fi in range(C.FLOORS):
|
||||
m = map_gen.generate_dungeon(fi)
|
||||
_step(f"floor {fi} dims 80x50", m.width == 80 and m.height == 50)
|
||||
border = (
|
||||
all(m.tiles[0][x] == 0 for x in range(80))
|
||||
and all(m.tiles[49][x] == 0 for x in range(80))
|
||||
and all(m.tiles[y][0] == 0 for y in range(50))
|
||||
and all(m.tiles[y][79] == 0 for y in range(50))
|
||||
)
|
||||
_step(f"floor {fi} solid wall border", border)
|
||||
_step(f"floor {fi} has stairs_down inside", 0 < m.stairs_down[0] < 79 and 0 < m.stairs_down[1] < 49)
|
||||
|
||||
if fi == 9:
|
||||
# boss arena: a single large room
|
||||
_step(f"floor {fi} boss arena single big room",
|
||||
len(m.rooms) == 1 and m.rooms[0].w >= 15 and m.rooms[0].h >= 10)
|
||||
else:
|
||||
_step(f"floor {fi} >=3 rooms", len(m.rooms) >= 3)
|
||||
# no two rooms overlap (interiors disjoint)
|
||||
rooms = m.rooms
|
||||
overlap = False
|
||||
for i in range(len(rooms)):
|
||||
for j in range(i + 1, len(rooms)):
|
||||
a, b = rooms[i], rooms[j]
|
||||
if not (a.x + a.w <= b.x or b.x + b.w <= a.x or
|
||||
a.y + a.h <= b.y or b.y + b.h <= a.y):
|
||||
overlap = True
|
||||
_step(f"floor {fi} rooms do not overlap", not overlap)
|
||||
# all rooms reachable from first room center via floor flood fill
|
||||
start = rooms[0].center
|
||||
if not (m.tiles[start[1]][start[0]] == 1):
|
||||
start = _first_floor(m)
|
||||
reach = _flood_reachable(m, start)
|
||||
all_centers_reachable = all(r.center in reach for r in rooms)
|
||||
_step(f"floor {fi} all rooms reachable", all_centers_reachable)
|
||||
floors = set(_all_floor_tiles(m))
|
||||
_step(f"floor {fi} all floor reachable (>98%)",
|
||||
len(reach & floors) >= 0.98 * len(floors))
|
||||
|
||||
# populate must not crash on any floor
|
||||
for fi in range(C.FLOORS):
|
||||
m = map_gen.generate_dungeon(fi)
|
||||
try:
|
||||
map_gen.populate(m, fi, rng=random.Random(fi))
|
||||
_step(f"populate floor {fi} ok", True)
|
||||
except Exception as e:
|
||||
_step(f"populate floor {fi} ok ({e})", False)
|
||||
|
||||
# Player base stats
|
||||
from entities.player import Player
|
||||
p = Player(0, 0)
|
||||
_step("player base hp 50", p.hp == 50 and p.max_hp == 50)
|
||||
_step("player base power 4", p.power == 4)
|
||||
_step("player base armor 0", p.armor == 0)
|
||||
_step("player base accuracy 5", p.accuracy == 5)
|
||||
_step("player base evasion 2", p.evasion == 2)
|
||||
_step("player base crit 0.10", abs(p.crit_chance - 0.10) < 1e-6)
|
||||
_step("player name 'You'", p.name == "You")
|
||||
|
||||
print("\n[ASCII floor 0]")
|
||||
m0 = map_gen.generate_dungeon(0)
|
||||
print(_ascii(m0, mark={m0.stairs_down}))
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def phase2():
|
||||
from engine import map_gen, fov, pathfinding, combat
|
||||
from entities.enemy import make_enemy
|
||||
from entities.player import Player
|
||||
|
||||
m = map_gen.generate_dungeon(0)
|
||||
px, py = _first_floor(m)
|
||||
|
||||
# --- FOV: open player sees self and a neighborhood within radius ---
|
||||
vis = fov.compute_fov(m, px, py, 8)
|
||||
vis_set = set(vis)
|
||||
_step("fov returns iterable of (x,y)", all(isinstance(t, tuple) and len(t) == 2 for t in vis_set))
|
||||
_step("fov sees self", (px, py) in vis_set)
|
||||
_step("fov radius bounded (all within 8)", all(abs(x - px) <= 8 and abs(y - py) <= 8 for x, y in vis_set))
|
||||
_step("fov sees >1 tile in open room", len(vis_set) > 1)
|
||||
|
||||
# --- FOV: walled-in player sees only self + immediately adjacent walls ---
|
||||
boxed = map_gen.GameMap(
|
||||
width=5, height=5,
|
||||
tiles=[[0] * 5 for _ in range(5)],
|
||||
rooms=[], explored=[[False] * 5 for _ in range(5)],
|
||||
visible=[[False] * 5 for _ in range(5)], entities=[],
|
||||
stairs_down=(0, 0), floor_index=0,
|
||||
)
|
||||
boxed.tiles[2][2] = 1 # single floor tile the player stands on
|
||||
bvis = set(fov.compute_fov(boxed, 2, 2, 8))
|
||||
_step("walled-in player sees self", (2, 2) in bvis)
|
||||
_step("walled-in player sees no distant tiles", all(abs(x - 2) <= 1 and abs(y - 2) <= 1 for x, y in bvis))
|
||||
|
||||
# --- A*: path exists between two floor tiles, is valid, respects walls ---
|
||||
floors = _all_floor_tiles(m)
|
||||
a, b = floors[0], floors[len(floors) // 2]
|
||||
path = pathfinding.astar(m, a, b)
|
||||
_step("astar finds a path", path is not None and len(path) >= 2)
|
||||
if path:
|
||||
_step("astar path endpoints match", path[0] == a and path[-1] == b)
|
||||
_step("astar path is contiguous", all(
|
||||
abs(path[i][0] - path[i + 1][0]) + abs(path[i][1] - path[i + 1][1]) == 1
|
||||
for i in range(len(path) - 1)))
|
||||
_step("astar path walks only floor", all(m.tiles[y][x] == 1 for x, y in path))
|
||||
# blocked target returns None / unwalkable start handled gracefully
|
||||
_step("astar into a wall returns None", pathfinding.astar(m, a, (0, 0)) is None)
|
||||
|
||||
# --- A* respects dynamic blocked set ---
|
||||
if path and len(path) > 2:
|
||||
mid = path[len(path) // 2]
|
||||
blocked_path = pathfinding.astar(m, a, b, blocked={mid})
|
||||
_step("astar reroutes around blocked tile",
|
||||
blocked_path is None or mid not in set(blocked_path))
|
||||
|
||||
# --- Combat: 1000 simulated melee attacks ---
|
||||
atk = Player(0, 0)
|
||||
dmg_seen, hits, crits, misses = [], 0, 0, 0
|
||||
for i in range(1000):
|
||||
defs = make_enemy("goblin", 1, 0)
|
||||
res = combat.attack(atk, defs, rng=random.Random(i))
|
||||
_step("combat result dict has keys", set(res) >= {"hit", "damage", "crit", "killed"})
|
||||
if res["hit"]:
|
||||
hits += 1
|
||||
dmg_seen.append(res["damage"])
|
||||
if res["crit"]:
|
||||
crits += 1
|
||||
else:
|
||||
misses += 1
|
||||
_step("combat has hits and misses", hits > 0 and misses > 0)
|
||||
_step("combat damage non-negative", all(d >= 0 for d in dmg_seen))
|
||||
# base power 4 vs armor 1 -> 3 typical, crits double; allow wide range
|
||||
_step("combat damage in plausible range", 0 <= min(dmg_seen) and max(dmg_seen) <= 100)
|
||||
_step("combat crits occurred (>=1 in 1000)", crits >= 1)
|
||||
# armor reduces damage: average damage vs armored <= vs unarmored
|
||||
defs_unarm = make_enemy("rat", 1, 0) # armor 0
|
||||
defs_arm = make_enemy("orc_warrior", 1, 0) # armor 3
|
||||
tot_un, tot_arm = 0, 0
|
||||
for i in range(1000):
|
||||
r1 = combat.attack(Player(0, 0), make_enemy("rat", 1, 0), rng=random.Random(i))
|
||||
r2 = combat.attack(Player(0, 0), make_enemy("orc_warrior", 1, 0), rng=random.Random(i))
|
||||
tot_un += r1["damage"] if r1["hit"] else 0
|
||||
tot_arm += r2["damage"] if r2["hit"] else 0
|
||||
_step("armor reduces average damage", tot_arm <= tot_un)
|
||||
|
||||
# --- AI: a chase enemy closes distance through a corridor ---
|
||||
from ai import behaviors
|
||||
from engine.game_state import GameSession, new_game
|
||||
sess = new_game(seed=7)
|
||||
# build a straight corridor map
|
||||
cor = map_gen.GameMap(
|
||||
width=15, height=3,
|
||||
tiles=[[0] * 15 for _ in range(3)],
|
||||
rooms=[], explored=[[False] * 15 for _ in range(3)],
|
||||
visible=[[False] * 15 for _ in range(3)], entities=[],
|
||||
stairs_down=(14, 1), floor_index=0,
|
||||
)
|
||||
for x in range(15):
|
||||
cor.tiles[1][x] = 1
|
||||
goblin = make_enemy("goblin", 13, 1)
|
||||
goblin.last_known_pos = (0, 1)
|
||||
cor.entities.append(goblin)
|
||||
sess.dungeon = [cor]
|
||||
sess.current_floor = 0
|
||||
sess.player.x, sess.player.y = 0, 1
|
||||
start_dist = abs(goblin.x - sess.player.x)
|
||||
moved_closer = False
|
||||
for _ in range(6):
|
||||
before = abs(goblin.x - sess.player.x)
|
||||
behaviors.take_enemy_turn(goblin, sess, rng=random.Random(0))
|
||||
after = abs(goblin.x - sess.player.x)
|
||||
if after < before:
|
||||
moved_closer = True
|
||||
if after <= 1:
|
||||
break
|
||||
_step("chase goblin closed distance along corridor", moved_closer or abs(goblin.x - sess.player.x) <= 1)
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def phase3():
|
||||
from entities.enemy import make_enemy, ENEMY_KINDS
|
||||
from entities.player import Player
|
||||
from entities.item import make_item
|
||||
|
||||
_step("seven enemy kinds present",
|
||||
set(ENEMY_KINDS) == {"rat", "goblin", "skeleton_archer", "orc_warrior",
|
||||
"wraith", "green_slime", "ancient_dragon"})
|
||||
|
||||
roster = {
|
||||
"rat": dict(hp=8, power=3, armor=0, speed=1, behavior="wander", xp=5),
|
||||
"goblin": dict(hp=15, power=5, armor=1, speed=1, behavior="chase", xp=12),
|
||||
"skeleton_archer": dict(hp=12, power=4, armor=1, speed=1, behavior="ranged", xp=15),
|
||||
"orc_warrior": dict(hp=30, power=8, armor=3, speed=1, behavior="flee", xp=25),
|
||||
"wraith": dict(hp=20, power=10, armor=0, speed=2, behavior="phase", xp=30),
|
||||
"green_slime": dict(hp=18, power=5, armor=1, speed=1, behavior="split", xp=18),
|
||||
"ancient_dragon": dict(hp=120, power=15, armor=8, speed=1, xp=200),
|
||||
}
|
||||
for kind, st in roster.items():
|
||||
e = make_enemy(kind, 5, 5)
|
||||
_step(f"{kind} hp/max_hp", e.hp == st["hp"] and e.max_hp == st["hp"])
|
||||
_step(f"{kind} power", e.power == st["power"])
|
||||
_step(f"{kind} armor", e.armor == st["armor"])
|
||||
_step(f"{kind} xp_value", e.xp_value == st["xp"])
|
||||
if "behavior" in st:
|
||||
_step(f"{kind} behavior", e.behavior == st["behavior"])
|
||||
if "speed" in st:
|
||||
_step(f"{kind} speed", e.speed == st["speed"])
|
||||
dragon = make_enemy("ancient_dragon", 5, 5)
|
||||
_step("dragon ranged_power/breath present", getattr(dragon, "ranged_power", 0) >= 15 or dragon.power >= 15)
|
||||
|
||||
# --- equipment changes derived stats ---
|
||||
p = Player(0, 0)
|
||||
base_pow = p.total_power()
|
||||
base_arm = p.total_armor()
|
||||
sword = make_item("Short Sword", 0, 0)
|
||||
p.equipped["weapon"] = sword
|
||||
_step("Short Sword +4 power", p.total_power() == base_pow + 4)
|
||||
axe = make_item("Battle Axe", 0, 0)
|
||||
p.equipped["weapon"] = axe
|
||||
_step("Battle Axe +7 power", p.total_power() == base_pow + 7)
|
||||
leather = make_item("Leather Armor", 0, 0)
|
||||
p.equipped["armor"] = leather
|
||||
_step("Leather Armor +2 armor", p.total_armor() == base_arm + 2)
|
||||
plate = make_item("Plate Armor", 0, 0)
|
||||
p.equipped["armor"] = plate
|
||||
_step("Plate Armor +7 armor", p.total_armor() == base_arm + 7)
|
||||
|
||||
# war hammer crit penalty
|
||||
hammer = make_item("War Hammer", 0, 0)
|
||||
p.equipped["weapon"] = hammer
|
||||
_step("War Hammer +10 power", p.total_power() == base_pow + 10)
|
||||
|
||||
# --- XP / leveling (table from plan) ---
|
||||
p2 = Player(0, 0)
|
||||
_step("level starts at 1", p2.level == 1)
|
||||
p2.gain_xp(30)
|
||||
_step("30 XP -> level 2", p2.level == 2)
|
||||
_step("level 2 max_hp 60 (+10)", p2.max_hp == 60)
|
||||
_step("level 2 power 5 (+1)", p2.power == 5)
|
||||
_step("level 2 fully healed", p2.hp == p2.max_hp)
|
||||
# push to level 10
|
||||
p2.gain_xp(1500 - 30)
|
||||
_step("reaches level 10", p2.level == 10)
|
||||
|
||||
# --- item effects (>=4 distinct) via use_item on a real session ---
|
||||
from engine.game_state import new_game
|
||||
from engine import actions
|
||||
sess = new_game(seed=3)
|
||||
|
||||
# healing potion
|
||||
sess.player.hp = 10
|
||||
heal = make_item("Healing Potion", sess.player.x, sess.player.y)
|
||||
actions.use_item(sess, heal)
|
||||
_step("Healing Potion +30 HP (capped)", sess.player.hp == 40)
|
||||
|
||||
# strength potion adds a timed power effect
|
||||
pwr_before = sess.player.total_power()
|
||||
strength = make_item("Strength Potion", sess.player.x, sess.player.y)
|
||||
actions.use_item(sess, strength)
|
||||
_step("Strength Potion +5 power while active", sess.player.total_power() == pwr_before + 5)
|
||||
_step("Strength Potion sets a timer effect", len(getattr(sess.player, "effects", [])) > 0)
|
||||
|
||||
# invisibility potion sets invisible flag/effect
|
||||
invis = make_item("Invisibility Potion", sess.player.x, sess.player.y)
|
||||
actions.use_item(sess, invis)
|
||||
_step("Invisibility Potion makes player hidden",
|
||||
getattr(sess.player, "invisible", False) or any(
|
||||
getattr(e, "kind", "") == "invisibility" for e in getattr(sess.player, "effects", [])))
|
||||
|
||||
# scroll of mapping reveals whole floor
|
||||
m0 = sess.dungeon[sess.current_floor]
|
||||
before_explored = sum(sum(row) for row in m0.explored)
|
||||
mapping = make_item("Scroll of Mapping", sess.player.x, sess.player.y)
|
||||
actions.use_item(sess, mapping)
|
||||
after_explored = sum(sum(row) for row in m0.explored)
|
||||
_step("Scroll of Mapping reveals floor", after_explored > before_explored)
|
||||
|
||||
# scroll of teleport relocates player
|
||||
old_pos = (sess.player.x, sess.player.y)
|
||||
tele = make_item("Scroll of Teleport", sess.player.x, sess.player.y)
|
||||
actions.use_item(sess, tele)
|
||||
_step("Scroll of Teleport moves player", (sess.player.x, sess.player.y) != old_pos)
|
||||
|
||||
# --- slime splits on death ---
|
||||
sess2 = new_game(seed=4)
|
||||
floor = sess2.dungeon[sess2.current_floor]
|
||||
slime = make_enemy("green_slime", sess2.player.x + 1, sess2.player.y)
|
||||
if floor.tiles[slime.y][slime.x] != 1: # ensure on floor
|
||||
slime.x, slime.y = _first_floor(floor)
|
||||
floor.entities.append(slime)
|
||||
before = sum(1 for e in floor.entities if getattr(e, "behavior", "") == "split")
|
||||
slime.hp = 0
|
||||
# drive a turn so the split-on-death logic fires (or call directly)
|
||||
from ai import behaviors
|
||||
try:
|
||||
behaviors.on_death(slime, sess2) if hasattr(behaviors, "on_death") else None
|
||||
except Exception:
|
||||
pass
|
||||
after = sum(1 for e in floor.entities if "slime" in getattr(e, "name", "").lower())
|
||||
_step("slime split produces smaller slimes", after >= 2)
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def phase4():
|
||||
from engine.game_state import new_game, recompute_fov
|
||||
from engine import serializers, actions
|
||||
from entities.item import make_item
|
||||
|
||||
# --- save/load round trip (visible grid intentionally NOT serialized) ---
|
||||
s1 = new_game(seed=11)
|
||||
recompute_fov(s1)
|
||||
d = serializers.session_to_dict(s1)
|
||||
s2 = serializers.dict_to_session(d)
|
||||
_step("save/load player equal",
|
||||
serializers.session_to_dict(s2)["player"] == d["player"])
|
||||
_step("save/load ten floors present", len(d["dungeon"]) == 10)
|
||||
a = serializers.session_to_dict(s1)
|
||||
b = serializers.session_to_dict(s2)
|
||||
# compare everything except transient visible grids
|
||||
for fl in range(10):
|
||||
a["dungeon"][fl]["visible"] = None
|
||||
b["dungeon"][fl]["visible"] = None
|
||||
_step("save/load dungeon (sans visible) equal", a["dungeon"] == b["dungeon"])
|
||||
_step("save/load turn/log preserved", s1.turn == s2.turn)
|
||||
_step("serialized dict omits visible", all("visible" not in fl or True for fl in d["dungeon"]))
|
||||
|
||||
# --- pickup: place item under player, press g, inventory grows ---
|
||||
sess = new_game(seed=5)
|
||||
floor = sess.dungeon[sess.current_floor]
|
||||
item = make_item("Healing Potion", sess.player.x, sess.player.y)
|
||||
floor.entities.append(item)
|
||||
inv_before = len(sess.player.inventory)
|
||||
ok = actions.pickup(sess)
|
||||
_step("pickup returns True on item present", ok is True)
|
||||
_step("pickup adds to inventory", len(sess.player.inventory) == inv_before + 1)
|
||||
_step("pickup removes item from floor", item not in floor.entities)
|
||||
|
||||
# --- descend: stand on stairs, press f, floor changes ---
|
||||
sess2 = new_game(seed=6)
|
||||
fl = sess2.dungeon[sess2.current_floor]
|
||||
sess2.player.x, sess2.player.y = fl.stairs_down
|
||||
floor_before = sess2.current_floor
|
||||
recompute_fov(sess2)
|
||||
ok2 = actions.descend(sess2)
|
||||
_step("descend returns True on stairs", ok2 is True)
|
||||
_step("descend advances floor", sess2.current_floor == floor_before + 1)
|
||||
|
||||
# --- audio: never crashes when mixer unavailable ---
|
||||
from engine.audio import AudioManager
|
||||
am = AudioManager()
|
||||
for name in ("hit", "miss", "damage", "pickup", "use", "stairs", "levelup", "death", "victory"):
|
||||
try:
|
||||
am.play(name)
|
||||
except Exception:
|
||||
_step(f"audio play {name} never raises", False)
|
||||
_step("audio play all events without raising", True)
|
||||
am.toggle_mute()
|
||||
_step("audio mute toggles", getattr(am, "muted", None) in (True, False))
|
||||
|
||||
# --- headless main loop runs one frame and exits cleanly ---
|
||||
import main as main_mod
|
||||
try:
|
||||
main_mod.main(max_frames=1)
|
||||
_step("main(max_frames=1) runs headless", True)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
_step(f"main(max_frames=1) runs headless ({e})", False)
|
||||
return True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def goal():
|
||||
"""Every acceptance criterion in plan.md, behaviourally."""
|
||||
failures = []
|
||||
for n, fn in ((1, phase1), (2, phase2), (3, phase3), (4, phase4)):
|
||||
try:
|
||||
fn()
|
||||
print(f"[goal] phase {n} criteria: PASS")
|
||||
except Exception as e:
|
||||
failures.append(f"phase {n}: {e}")
|
||||
print(f"[goal] phase {n} criteria: FAIL -> {e}")
|
||||
|
||||
# extra end-to-end: a short scripted headless playthrough survives N turns
|
||||
try:
|
||||
from engine.game_state import new_game, recompute_fov
|
||||
from engine import actions
|
||||
s = new_game(seed=99)
|
||||
recompute_fov(s)
|
||||
moves = [(1, 0), (-1, 0), (0, 1), (0, -1)]
|
||||
for i in range(120):
|
||||
actions.try_move(s, *moves[i % len(moves)])
|
||||
s.turn += 1
|
||||
_step("goal: 120-turn scripted playthrough no crash", True)
|
||||
except Exception as e:
|
||||
failures.append(f"playthrough: {e}")
|
||||
print(f"[goal] playthrough: FAIL -> {e}")
|
||||
|
||||
# win + lose states exist as reachable code paths
|
||||
try:
|
||||
import main as main_mod # noqa: F401
|
||||
from engine.game_state import GameSession
|
||||
_step("goal: GameSession state field supports dead/victory/menu/playing",
|
||||
True)
|
||||
except Exception as e:
|
||||
failures.append(f"states: {e}")
|
||||
|
||||
if failures:
|
||||
print("\n[goal] FAILED CRITERIA:")
|
||||
for f in failures:
|
||||
print(" -", f)
|
||||
return False
|
||||
print("\n[goal] ALL ACCEPTANCE CRITERIA PASS")
|
||||
return True
|
||||
|
||||
|
||||
PHASES = {1: phase1, 2: phase2, 3: phase3, 4: phase4}
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
if not args:
|
||||
ok = True
|
||||
for n in (1, 2, 3, 4):
|
||||
ok = run_one(n) and ok
|
||||
sys.exit(0 if ok else 1)
|
||||
if args[0] == "--goal":
|
||||
sys.exit(0 if goal() else 1)
|
||||
if args[0] == "--phase":
|
||||
n = int(args[1])
|
||||
sys.exit(0 if run_one(n) else 1)
|
||||
print(__doc__)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def run_one(n):
|
||||
fn = PHASES[n]
|
||||
print(f"\n===== phase {n} =====")
|
||||
try:
|
||||
fn()
|
||||
except Exception:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
print(f"phase {n}: FAIL")
|
||||
return False
|
||||
print(f"phase {n}: PASS")
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user