735 lines
27 KiB
Python
735 lines
27 KiB
Python
#!/usr/bin/env python3
|
|
"""Underdepths gate suite + goal-check harness.
|
|
|
|
Run from the repo root:
|
|
python tests/smoke.py --phase 0 # pipeline artifacts exist
|
|
python tests/smoke.py --phase 1 # Foundation: BSP map gen
|
|
python tests/smoke.py --phase 2 # Core systems: FOV, A*, combat, AI
|
|
python tests/smoke.py --phase 3 # Content: enemies, items, XP
|
|
python tests/smoke.py --phase 4 # Polish: save/load, menus, pickup/descent, audio
|
|
python tests/smoke.py --phase all # 1..4
|
|
python tests/smoke.py --smoke-play # headless automated playthrough
|
|
|
|
This file is HEADLESS: it forces dummy SDL drivers before importing pygame so it
|
|
runs in CI / without a display. Game logic must be drivable without a window.
|
|
|
|
=== STABLE API CONTRACT (phase sub-agents implement to this) ===
|
|
|
|
Indexing convention: tiles[y][x]; TILE_WALL=0, TILE_FLOOR=1 (see data/constants.py).
|
|
|
|
data/constants.py:
|
|
MAP_W=80, MAP_H=50, TILE_WALL=0, TILE_FLOOR=1, SIGHT_RADIUS=8
|
|
LEVEL_XP = [0,30,70,140,250,400,600,850,1150,1500] # cumulative xp to reach level i+1
|
|
LEVEL_HP_GAIN, LEVEL_POWER_GAIN lists; PLAYER_BASE stats; SPAWN tables; COLORS.
|
|
|
|
entities/entity.py:
|
|
@dataclass(slots=True) Rect: x:int,y:int,w:int,h:int # .center -> (cx,cy); .intersects(other)->bool
|
|
@dataclass(slots=True) Entity: x:int,y:int,name:str,glyph:str,color:tuple,
|
|
blocks:bool=True, is_alive:bool=True
|
|
|
|
entities/player.py:
|
|
make_player(x,y)->Player with fields: hp,max_hp,power,armor,accuracy,evasion,
|
|
crit_chance,speed,level,xp,inventory(list),weapon,armor_item,effects(dict)
|
|
methods: total_power(), total_armor(), gain_xp(amount,log), level_up(log),
|
|
equip(item,log), heal(amount)
|
|
|
|
entities/enemy.py:
|
|
make_enemy(kind:str,x,y)->Enemy with fields from data/enemies.py ENEMIES roster,
|
|
plus x,y,is_alive, last_known_pos. kinds: rat,goblin,skeleton_archer,
|
|
orc_warrior,wraith,green_slime,ancient_dragon (small_slime for split spawn).
|
|
|
|
entities/item.py:
|
|
make_item(name:str,x,y)->Item with fields: name,category('weapon'|'armor'|
|
|
'potion'|'scroll'), x,y, stats(dict), effect(dict).
|
|
|
|
engine/map_gen.py:
|
|
generate_floor(floor_index=0,width=80,height=50,seed=None)->GameMap
|
|
GameMap fields: width,height,tiles(list[list[int]]),rooms(list[Rect]),
|
|
explored(list[list[bool]]),visible(list[list[bool]]),entities(list),
|
|
stairs_down(tuple|None),floor_index
|
|
is_walkable(gm,x,y)->bool
|
|
|
|
engine/fov.py:
|
|
compute_fov(width,height,tiles,ox,oy,radius=8)->set[(x,y)]
|
|
recursive shadowcasting; walls adjacent to a visible floor are visible;
|
|
walls block sight beyond them.
|
|
|
|
engine/pathfinding.py:
|
|
astar(width,height,tiles,start,goal,blocked=frozenset())->list[(x,y)]|None
|
|
Manhattan heuristic; returns start..goal inclusive of walkable, unblocked
|
|
tiles, or None if unreachable.
|
|
|
|
engine/combat.py:
|
|
resolve_attack(attacker,defender,log=None)->dict
|
|
reads attacker.power (+ getattr(attacker,'weapon_bonus',0)), defender.armor,
|
|
attacker.accuracy, defender.evasion, attacker.crit_chance; mutates defender.hp.
|
|
returns {hit:bool,crit:bool,damage:int,killed:bool}
|
|
|
|
ai/behaviors.py:
|
|
take_enemy_turn(enemy,game_map,player,enemy_visible:set)->list[str]
|
|
one enemy action for one turn; mutates enemy/player positions & hp; returns
|
|
log lines. enemy_visible = tiles the enemy currently sees (caller computes).
|
|
|
|
data/enemies.py: ENEMIES:dict[str,dict]; make_enemy delegates here.
|
|
data/items.py: ITEMS:dict[str,dict]; CATEGORIES.
|
|
|
|
engine/game_state.py:
|
|
GameSession dataclass (single source of truth). new_game(seed=None)->GameSession.
|
|
apply_action(session, action)->result
|
|
action tuples: ('move',dx,dy) ('pickup',) ('descend',) ('save',)
|
|
('quaff',idx) ('read',idx) ('equip',idx) ('wait',)
|
|
to_dict(session)->dict ; from_dict(d)->GameSession ; save(session,path);
|
|
load(path)->GameSession
|
|
|
|
render/audio.py (or engine/audio.py):
|
|
AudioEngine with init guarded (silent fallback); play(name); toggle_mute();
|
|
enabled attribute. Must not raise when mixer unavailable.
|
|
|
|
main.py: launches game; respects SDL_VIDEODRIVER=dummy for headless.
|
|
===================================================================
|
|
"""
|
|
|
|
import os
|
|
# Force headless BEFORE any pygame import.
|
|
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
|
|
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
|
|
os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
|
|
|
|
import sys
|
|
import random
|
|
from collections import namedtuple
|
|
|
|
_REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
if _REPO not in sys.path:
|
|
sys.path.insert(0, _REPO)
|
|
|
|
_PASS = 0
|
|
_FAIL = 0
|
|
_FAILURES = []
|
|
|
|
|
|
def _ok(msg):
|
|
global _PASS
|
|
_PASS += 1
|
|
print(f" PASS: {msg}")
|
|
|
|
|
|
def _bad(msg, exc=None):
|
|
global _FAIL
|
|
_FAIL += 1
|
|
detail = f" -> {exc}" if exc is not None else ""
|
|
print(f" FAIL: {msg}{detail}")
|
|
_FAILURES.append(msg)
|
|
|
|
|
|
def _section(title):
|
|
print(f"\n=== {title} ===")
|
|
|
|
|
|
def _cheby(a, b):
|
|
return max(abs(a[0] - b[0]), abs(a[1] - b[1]))
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
def check_phase_0():
|
|
_section("Phase 0 — pipeline artifacts")
|
|
for p in ["orchestrate.sh", "tests/smoke.py", "AGENTS.md", "plan.md"]:
|
|
if os.path.exists(os.path.join(_REPO, p)):
|
|
_ok(f"{p} exists")
|
|
else:
|
|
_bad(f"{p} missing")
|
|
bs = os.path.join(_REPO, ".build_state")
|
|
if os.path.exists(bs):
|
|
try:
|
|
with open(bs) as f:
|
|
int(f.read().strip())
|
|
_ok(".build_state is an integer")
|
|
except Exception as e:
|
|
_bad(".build_state not an integer", e)
|
|
else:
|
|
_bad(".build_state missing")
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
def check_phase_1():
|
|
_section("Phase 1 — BSP dungeon generation")
|
|
try:
|
|
from engine.map_gen import generate_floor, is_walkable
|
|
except Exception as e:
|
|
_bad("import engine.map_gen", e)
|
|
return
|
|
try:
|
|
from data.constants import MAP_W, MAP_H, TILE_FLOOR, TILE_WALL
|
|
except Exception:
|
|
MAP_W, MAP_H, TILE_FLOOR, TILE_WALL = 80, 50, 1, 0
|
|
|
|
maps = []
|
|
for i in range(5):
|
|
try:
|
|
gm = generate_floor(floor_index=i, seed=1000 + i)
|
|
except TypeError:
|
|
gm = generate_floor(i)
|
|
except Exception as e:
|
|
_bad(f"generate_floor #{i}", e)
|
|
return
|
|
maps.append(gm)
|
|
try:
|
|
assert gm.width == MAP_W and gm.height == MAP_H, "map size"
|
|
assert len(gm.rooms) >= 3, f"only {len(gm.rooms)} rooms"
|
|
# tile grid shape
|
|
assert len(gm.tiles) == MAP_H and len(gm.tiles[0]) == MAP_W, "tile grid shape"
|
|
# no room overlaps (interiors)
|
|
rooms = gm.rooms
|
|
overlap = False
|
|
for a in range(len(rooms)):
|
|
for b in range(a + 1, len(rooms)):
|
|
if rooms[a].intersects(rooms[b]):
|
|
overlap = True
|
|
assert not overlap, "rooms overlap"
|
|
_ok(f"floor {i}: {len(rooms)} rooms, size ok, no overlaps")
|
|
except AssertionError as e:
|
|
_bad(f"floor {i} assertions", e)
|
|
|
|
# connectivity: all room centers reachable from first room center via floor BFS
|
|
gm = maps[0]
|
|
try:
|
|
start = gm.rooms[0].center
|
|
seen = {start}
|
|
frontier = [start]
|
|
while frontier:
|
|
x, y = frontier.pop()
|
|
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
|
nx, ny = x + dx, y + dy
|
|
if (0 <= nx < gm.width and 0 <= ny < gm.height and
|
|
(nx, ny) not in seen and gm.tiles[ny][nx] == TILE_FLOOR):
|
|
seen.add((nx, ny))
|
|
frontier.append((nx, ny))
|
|
centers = {r.center for r in gm.rooms}
|
|
missing = [c for c in centers if c not in seen]
|
|
assert not missing, f"unreachable rooms: {missing}"
|
|
_ok("all room centers reachable by flood fill")
|
|
except AssertionError as e:
|
|
_bad("connectivity", e)
|
|
except Exception as e:
|
|
_bad("connectivity", e)
|
|
|
|
# ASCII render of floor 0
|
|
try:
|
|
_render_ascii(gm)
|
|
_ok("ASCII render printed")
|
|
except Exception as e:
|
|
_bad("ASCII render", e)
|
|
|
|
|
|
def _render_ascii(gm, path=None):
|
|
glyphs = {0: "#", 1: "."}
|
|
print(" +" + "-" * gm.width + "+")
|
|
for y in range(gm.height):
|
|
row = []
|
|
for x in range(gm.width):
|
|
row.append(glyphs.get(gm.tiles[y][x], "?"))
|
|
print(" |" + "".join(row) + "|")
|
|
print(" +" + "-" * gm.width + "+")
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
def check_phase_2():
|
|
_section("Phase 2 — FOV, A*, combat, AI")
|
|
_check_fov()
|
|
_check_astar()
|
|
_check_combat()
|
|
_check_ai()
|
|
|
|
|
|
def _check_fov():
|
|
try:
|
|
from engine.fov import compute_fov
|
|
from data.constants import SIGHT_RADIUS, TILE_WALL, TILE_FLOOR
|
|
except Exception:
|
|
SIGHT_RADIUS, TILE_WALL, TILE_FLOOR = 8, 0, 1
|
|
try:
|
|
from engine.fov import compute_fov
|
|
except Exception as e:
|
|
_bad("import engine.fov", e)
|
|
return
|
|
W = H = 21
|
|
tiles = [[TILE_FLOOR] * W for _ in range(H)]
|
|
cx = cy = 10
|
|
# wall the player in completely
|
|
for dy in (-1, 0, 1):
|
|
for dx in (-1, 0, 1):
|
|
if (dx, dy) != (0, 0):
|
|
tiles[cy + dy][cx + dx] = TILE_WALL
|
|
try:
|
|
vis = compute_fov(W, H, tiles, cx, cy, radius=SIGHT_RADIUS)
|
|
assert (cx, cy) in vis, "player tile not visible"
|
|
# nothing beyond the immediate wall ring should be visible
|
|
far = [t for t in vis if _cheby(t, (cx, cy)) > 1]
|
|
assert not far, f"walls fail to occlude: {len(far)} tiles seen beyond ring"
|
|
_ok(f"FOV: walled-in player occluded (sees {len(vis)} tiles, none past ring)")
|
|
# open field: sees roughly a disc within radius
|
|
tiles2 = [[TILE_FLOOR] * W for _ in range(H)]
|
|
vis2 = compute_fov(W, H, tiles2, cx, cy, radius=SIGHT_RADIUS)
|
|
assert len(vis2) > 50, f"open FOV too small: {len(vis2)}"
|
|
assert all(_cheby(t, (cx, cy)) <= SIGHT_RADIUS for t in vis2), "exceeds radius"
|
|
_ok(f"FOV: open field sees {len(vis2)} tiles within radius")
|
|
except AssertionError as e:
|
|
_bad("FOV assertions", e)
|
|
except Exception as e:
|
|
_bad("FOV", e)
|
|
|
|
|
|
def _check_astar():
|
|
try:
|
|
from engine.pathfinding import astar
|
|
from data.constants import TILE_FLOOR, TILE_WALL
|
|
except Exception:
|
|
TILE_FLOOR, TILE_WALL = 1, 0
|
|
try:
|
|
from engine.pathfinding import astar
|
|
except Exception as e:
|
|
_bad("import engine.pathfinding", e)
|
|
return
|
|
W = H = 20
|
|
tiles = [[TILE_FLOOR] * W for _ in range(H)]
|
|
# a wall barrier with a single gap
|
|
for y in range(H):
|
|
tiles[y][10] = TILE_WALL
|
|
tiles[5][10] = TILE_FLOOR # gap
|
|
try:
|
|
start, goal = (2, 2), (17, 17)
|
|
path = astar(W, H, tiles, start, goal)
|
|
assert path is not None, "no path found through gap"
|
|
assert path[0] == start and path[-1] == goal, "path endpoints wrong"
|
|
# contiguity + walkability
|
|
for i, (x, y) in enumerate(path):
|
|
assert tiles[y][x] == TILE_FLOOR, f"path crosses wall at {(x,y)}"
|
|
if i > 0:
|
|
px, py = path[i - 1]
|
|
assert max(abs(x - px), abs(y - py)) == 1, f"non-contiguous step at {i}"
|
|
assert len(path) == len(set(path)), "path revisits a tile"
|
|
_ok(f"A*: path {start}->{goal} len {len(path)} through gap, contiguous")
|
|
# blocked goal -> None
|
|
none_path = astar(W, H, tiles, (2, 2), (10, 10), blocked={(10, 10)})
|
|
# 10,10 is a wall already; expect None or a path not crossing it
|
|
_ok("A*: handles blocked/wall target without crashing")
|
|
except AssertionError as e:
|
|
_bad("A* assertions", e)
|
|
except Exception as e:
|
|
_bad("A*", e)
|
|
|
|
|
|
def _check_combat():
|
|
try:
|
|
from engine.combat import resolve_attack
|
|
except Exception as e:
|
|
_bad("import engine.combat", e)
|
|
return
|
|
Fighter = namedtuple("Fighter", ["power", "armor", "accuracy", "evasion",
|
|
"crit_chance", "hp", "max_hp", "weapon_bonus"])
|
|
atk = Fighter(power=10, armor=0, accuracy=5, evasion=2, crit_chance=0.10,
|
|
hp=100, max_hp=100, weapon_bonus=0)
|
|
defs = []
|
|
results = []
|
|
random.seed(42)
|
|
for _ in range(1000):
|
|
d = Fighter(power=0, armor=2, accuracy=5, evasion=2, crit_chance=0.0,
|
|
hp=10_000, max_hp=10_000, weapon_bonus=0)
|
|
r = resolve_attack(atk, d)
|
|
results.append(r)
|
|
defs.append(d)
|
|
try:
|
|
n_hit = sum(1 for r in results if r["hit"])
|
|
n_crit = sum(1 for r in results if r.get("crit"))
|
|
dmg = [r["damage"] for r in results if r["hit"]]
|
|
assert 0.75 < n_hit / 1000 < 0.95, f"hit rate off: {n_hit/1000}"
|
|
assert n_crit > 0, "no crits in 1000 swings"
|
|
assert all(0 <= d <= 16 for d in dmg), "damage out of [0,16]"
|
|
mean = sum(dmg) / len(dmg) if dmg else 0
|
|
assert 6 < mean < 12, f"mean hit dmg off: {mean}"
|
|
# miss damage must be 0
|
|
assert all(r["damage"] == 0 for r in results if not r["hit"]), "miss dealt damage"
|
|
_ok(f"combat: 1000 swings, hit={n_hit}, crit={n_crit}, mean hit dmg={mean:.1f}")
|
|
except AssertionError as e:
|
|
_bad("combat assertions", e)
|
|
except Exception as e:
|
|
_bad("combat", e)
|
|
|
|
|
|
def _check_ai():
|
|
try:
|
|
from ai.behaviors import take_enemy_turn
|
|
from entities.enemy import make_enemy
|
|
except Exception as e:
|
|
_bad("import ai.behaviors / entities.enemy", e)
|
|
return
|
|
try:
|
|
from data.constants import TILE_FLOOR
|
|
except Exception:
|
|
TILE_FLOOR = 1
|
|
# 1-tall corridor, enemy at x=2, player at x=8
|
|
W, H = 12, 3
|
|
tiles = [[TILE_FLOOR] * W for _ in range(H)]
|
|
GM = namedtuple("GM", ["width", "height", "tiles"])
|
|
gm = GM(width=W, height=H, tiles=tiles)
|
|
P = namedtuple("P", ["x", "y", "hp", "max_hp"])
|
|
enemy = make_enemy("goblin", 2, 1)
|
|
player = P(x=8, y=1, hp=100, max_hp=100)
|
|
visible = {(x, 1) for x in range(W)} # enemy sees the corridor
|
|
before = enemy.x
|
|
try:
|
|
logs = take_enemy_turn(enemy, gm, player, visible)
|
|
assert enemy.x == before + 1, f"chase did not advance: {before}->{enemy.x}"
|
|
_ok(f"AI: goblin chased along corridor ({before}->{enemy.x})")
|
|
except AssertionError as e:
|
|
_bad("AI chase", e)
|
|
except Exception as e:
|
|
_bad("AI chase", e)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
def check_phase_3():
|
|
_section("Phase 3 — enemies, items, XP/leveling")
|
|
_check_enemy_roster()
|
|
_check_items_equip()
|
|
_check_xp_leveling()
|
|
|
|
|
|
def _check_enemy_roster():
|
|
try:
|
|
from data.enemies import ENEMIES
|
|
from entities.enemy import make_enemy
|
|
except Exception as e:
|
|
_bad("import data.enemies / entities.enemy", e)
|
|
return
|
|
expected_kinds = {"rat", "goblin", "skeleton_archer", "orc_warrior",
|
|
"wraith", "green_slime", "ancient_dragon"}
|
|
try:
|
|
missing = expected_kinds - set(ENEMIES)
|
|
assert not missing, f"missing enemy kinds: {missing}"
|
|
for kind, spec in ENEMIES.items():
|
|
e = make_enemy(kind, 0, 0)
|
|
for field in ("hp", "power", "armor", "behavior", "xp"):
|
|
assert hasattr(e, field), f"{kind} missing {field}"
|
|
assert e.hp == spec["hp"], f"{kind} hp {e.hp}!={spec['hp']}"
|
|
assert e.power == spec["power"], f"{kind} power mismatch"
|
|
assert e.behavior == spec["behavior"], f"{kind} behavior mismatch"
|
|
assert e.xp == spec["xp"], f"{kind} xp mismatch"
|
|
_ok(f"enemy roster: all {len(ENEMIES)} kinds spawn with correct stats")
|
|
assert "ancient_dragon" in ENEMIES and ENEMIES["ancient_dragon"]["hp"] >= 100, "boss weak"
|
|
_ok("boss dragon present with boss-scale HP")
|
|
except AssertionError as e:
|
|
_bad("enemy roster", e)
|
|
except Exception as e:
|
|
_bad("enemy roster", e)
|
|
|
|
|
|
def _check_items_equip():
|
|
try:
|
|
from entities.player import make_player
|
|
from entities.item import make_item
|
|
from data.items import ITEMS
|
|
except Exception as e:
|
|
_bad("import items/player", e)
|
|
return
|
|
try:
|
|
assert len(ITEMS) >= 11, f"item catalog too small: {len(ITEMS)}"
|
|
p = make_player(0, 0)
|
|
base_pow = p.total_power()
|
|
w = make_item("Short Sword", 0, 0)
|
|
p.equip(w)
|
|
assert p.total_power() == base_pow + 4, f"weapon equip power {p.total_power()}"
|
|
_ok(f"equip weapon: power {base_pow}->{p.total_power()}")
|
|
base_arm = p.total_armor()
|
|
a = make_item("Chain Mail", 0, 0)
|
|
p.equip(a)
|
|
assert p.total_armor() == base_arm + 4, f"armor equip {p.total_armor()}"
|
|
_ok(f"equip armor: armor {base_arm}->{p.total_armor()}")
|
|
# potions/scrolls exist with effects
|
|
cats = {make_item(n, 0, 0).category for n in ITEMS}
|
|
assert {"weapon", "armor", "potion", "scroll"} <= cats, f"categories: {cats}"
|
|
_ok(f"item categories present: {sorted(cats)}")
|
|
except AssertionError as e:
|
|
_bad("items/equip", e)
|
|
except Exception as e:
|
|
_bad("items/equip", e)
|
|
|
|
|
|
def _check_xp_leveling():
|
|
try:
|
|
from entities.player import make_player
|
|
from data.enemies import ENEMIES
|
|
except Exception as e:
|
|
_bad("import player/enemies", e)
|
|
return
|
|
try:
|
|
p = make_player(0, 0)
|
|
start_lvl = p.level
|
|
# force a level-up: gain enough xp to cross first threshold (30)
|
|
p.gain_xp(30)
|
|
assert p.level == start_lvl + 1, f"no level up: {p.level}"
|
|
assert p.hp == p.max_hp, "level up did not full heal"
|
|
_ok(f"XP: gained 30 -> level {start_lvl}->{p.level}, full heal")
|
|
# stats increased
|
|
assert p.max_hp > 50 or p.power > 4, "level-up granted no stats"
|
|
_ok("XP: level-up granted stat increases")
|
|
except AssertionError as e:
|
|
_bad("xp/leveling", e)
|
|
except Exception as e:
|
|
_bad("xp/leveling", e)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
def check_phase_4():
|
|
_section("Phase 4 — save/load, menus, pickup/descent, audio")
|
|
_check_save_load()
|
|
_check_menus()
|
|
_check_pickup_descent()
|
|
_check_audio_safety()
|
|
|
|
|
|
def _check_save_load():
|
|
try:
|
|
from engine.game_state import new_game, to_dict, from_dict, save, load
|
|
except Exception as e:
|
|
_bad("import engine.game_state", e)
|
|
return
|
|
import tempfile
|
|
try:
|
|
s = new_game(seed=7)
|
|
s.turn = 42
|
|
s.player.gain_xp(30) # mutate so we can detect round-trip
|
|
before = to_dict(s)
|
|
path = os.path.join(tempfile.gettempdir(), "underdepths_save_test.json")
|
|
save(s, path)
|
|
s2 = load(path)
|
|
after = to_dict(s2)
|
|
assert s2.turn == 42, f"turn not restored: {s2.turn}"
|
|
assert s2.player.level == s.player.level, "level not restored"
|
|
assert s2.current_floor == s.current_floor, "floor not restored"
|
|
assert s2.player.x == s.player.x and s2.player.y == s.player.y, "pos not restored"
|
|
_ok("save/load: turn, level, floor, position restored")
|
|
if os.path.exists(path):
|
|
os.remove(path)
|
|
except AssertionError as e:
|
|
_bad("save/load", e)
|
|
except Exception as e:
|
|
_bad("save/load", e)
|
|
|
|
|
|
def _check_menus():
|
|
try:
|
|
from engine.game_state import new_game, apply_action
|
|
except Exception as e:
|
|
_bad("import game_state", e)
|
|
return
|
|
try:
|
|
s = new_game(seed=1)
|
|
# state machine: playing -> dead achievable
|
|
s.player.hp = 1
|
|
# smash the player with a big hit via a helper if present
|
|
try:
|
|
s.player.hp = -1
|
|
s.recompute_state() if hasattr(s, "recompute_state") else None
|
|
except Exception:
|
|
pass
|
|
assert s.state in ("playing", "dead", "victory", "menu", "saved"), s.state
|
|
_ok(f"menus: session state readable ({s.state})")
|
|
# wait action is a no-op that advances turn
|
|
before = s.turn
|
|
apply_action(s, ("wait",))
|
|
assert s.turn == before + 1, f"wait did not advance turn: {s.turn}"
|
|
_ok("actions: ('wait',) advances turn")
|
|
except AssertionError as e:
|
|
_bad("menus/actions", e)
|
|
except Exception as e:
|
|
_bad("menus/actions", e)
|
|
|
|
|
|
def _check_pickup_descent():
|
|
try:
|
|
from engine.game_state import new_game, apply_action
|
|
from entities.item import make_item
|
|
except Exception as e:
|
|
_bad("import game_state/item", e)
|
|
return
|
|
try:
|
|
# PICKUP: place an item under the player, press g
|
|
s = new_game(seed=3)
|
|
inv_before = len(s.player.inventory)
|
|
item = make_item("Healing Potion", s.player.x, s.player.y)
|
|
s.dungeon[s.current_floor].entities.append(item)
|
|
apply_action(s, ("pickup",))
|
|
assert len(s.player.inventory) == inv_before + 1, \
|
|
f"pickup failed: inv {inv_before}->{len(s.player.inventory)}"
|
|
_ok("pickup: ('pickup',) added item to inventory")
|
|
# the floor item should be consumed
|
|
floor_items = [e for e in s.dungeon[s.current_floor].entities
|
|
if getattr(e, "category", None)]
|
|
assert item not in floor_items, "picked-up item still on floor"
|
|
_ok("pickup: item removed from floor")
|
|
except AssertionError as e:
|
|
_bad("pickup", e)
|
|
except Exception as e:
|
|
_bad("pickup", e)
|
|
|
|
try:
|
|
# DESCENT: place player on stairs, press >
|
|
s = new_game(seed=4)
|
|
floor_before = s.current_floor
|
|
stairs = s.dungeon[s.current_floor].stairs_down
|
|
assert stairs is not None, "no stairs on floor 0"
|
|
s.player.x, s.player.y = stairs
|
|
apply_action(s, ("descend",))
|
|
assert s.current_floor == floor_before + 1, \
|
|
f"descent failed: floor {floor_before}->{s.current_floor}"
|
|
_ok(f"descent: ('descend',) floor {floor_before}->{s.current_floor}")
|
|
except AssertionError as e:
|
|
_bad("descent", e)
|
|
except Exception as e:
|
|
_bad("descent", e)
|
|
|
|
|
|
def _check_audio_safety():
|
|
try:
|
|
import importlib
|
|
audio = importlib.import_module("engine.audio")
|
|
except Exception:
|
|
try:
|
|
audio = importlib.import_module("render.audio")
|
|
except Exception as e:
|
|
_bad("import audio module", e)
|
|
return
|
|
try:
|
|
AudioEngine = getattr(audio, "AudioEngine")
|
|
# Force a failing environment: dummy driver, then construct.
|
|
eng = AudioEngine()
|
|
eng.play("hit") # must not raise even if disabled
|
|
eng.play("miss")
|
|
eng.play("levelup")
|
|
eng.toggle_mute()
|
|
eng.toggle_mute()
|
|
assert hasattr(eng, "enabled"), "audio engine missing .enabled"
|
|
_ok(f"audio: plays effects without raising (enabled={eng.enabled})")
|
|
except AssertionError as e:
|
|
_bad("audio safety", e)
|
|
except Exception as e:
|
|
_bad("audio safety", e)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
def check_smoke_play():
|
|
"""Headless automated playthrough exercising the core loop end to end."""
|
|
_section("Smoke playthrough (headless)")
|
|
try:
|
|
from engine.game_state import new_game, apply_action, to_dict, from_dict
|
|
except Exception as e:
|
|
_bad("import game_state for smoke play", e)
|
|
return
|
|
try:
|
|
s = new_game(seed=99)
|
|
# explore: a few moves, no crash
|
|
for dx, dy in [(1, 0), (0, 1), (-1, 0), (1, 0), (0, -1)]:
|
|
apply_action(s, ("move", dx, dy))
|
|
_ok(f"explore: moved, turn={s.turn}, pos=({s.player.x},{s.player.y})")
|
|
|
|
# find an enemy on the floor and walk into it (combat)
|
|
fought = False
|
|
floor = s.dungeon[s.current_floor]
|
|
enemies = [e for e in floor.entities if getattr(e, "is_alive", False)
|
|
and hasattr(e, "behavior")]
|
|
if enemies:
|
|
# teleport next to it and bump
|
|
tgt = enemies[0]
|
|
s.player.x, s.player.y = tgt.x + 1, tgt.y
|
|
hp0 = tgt.hp
|
|
apply_action(s, ("move", -1, 0)) # step into enemy
|
|
fought = tgt.hp != hp0 or not tgt.is_alive
|
|
_ok(f"combat: engaged enemy (fought={fought})")
|
|
|
|
# pickup
|
|
item = None
|
|
try:
|
|
from entities.item import make_item
|
|
item = make_item("Healing Potion", s.player.x, s.player.y)
|
|
floor.entities.append(item)
|
|
apply_action(s, ("pickup",))
|
|
except Exception as e:
|
|
_bad("smoke pickup", e)
|
|
_ok("pickup: exercised")
|
|
|
|
# descend if stairs available
|
|
stairs = floor.stairs_down
|
|
if stairs:
|
|
s.player.x, s.player.y = stairs
|
|
fb = s.current_floor
|
|
apply_action(s, ("descend",))
|
|
_ok(f"descend: floor {fb}->{s.current_floor}")
|
|
else:
|
|
_ok("descend: no stairs (skipped)")
|
|
|
|
# save -> load round trip mid-play
|
|
import tempfile
|
|
path = os.path.join(tempfile.gettempdir(), "underdepths_smoke.json")
|
|
try:
|
|
from engine.game_state import save, load
|
|
save(s, path)
|
|
s2 = load(path)
|
|
assert s2.current_floor == s.current_floor, "load floor mismatch"
|
|
_ok("save/load mid-play: state preserved")
|
|
finally:
|
|
if os.path.exists(path):
|
|
os.remove(path)
|
|
|
|
# simulate death and victory states without crashing
|
|
try:
|
|
s.player.hp = -1
|
|
if hasattr(s, "check_state"):
|
|
s.check_state()
|
|
_ok(f"death path: state={getattr(s, 'state', '?')} (no crash)")
|
|
except Exception as e:
|
|
_bad("death path", e)
|
|
except Exception as e:
|
|
_bad("smoke playthrough", e)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
def main():
|
|
import argparse
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--phase", default="all",
|
|
help="0|1|2|3|4|all|play")
|
|
args = ap.parse_args()
|
|
|
|
phase = args.phase
|
|
if phase == "play":
|
|
check_smoke_play()
|
|
elif phase == "all":
|
|
for fn in (check_phase_1, check_phase_2, check_phase_3, check_phase_4):
|
|
try:
|
|
fn()
|
|
except Exception as e:
|
|
_bad(f"{fn.__name__} crashed", e)
|
|
elif phase in ("0", "1", "2", "3", "4"):
|
|
fn = {0: check_phase_0, 1: check_phase_1, 2: check_phase_2,
|
|
3: check_phase_3, 4: check_phase_4}[int(phase)]
|
|
try:
|
|
fn()
|
|
except Exception as e:
|
|
_bad(f"{fn.__name__} crashed", e)
|
|
else:
|
|
print(f"unknown phase: {phase}")
|
|
sys.exit(2)
|
|
|
|
print(f"\n==== RESULT: {_PASS} passed, {_FAIL} failed ====")
|
|
if _FAIL:
|
|
print("Failures:")
|
|
for f in _FAILURES:
|
|
print(f" - {f}")
|
|
sys.exit(1)
|
|
sys.exit(0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|