504 lines
18 KiB
Python
504 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""Underdepths gate suite.
|
|
|
|
Each phase_N() is a verification gate run by orchestrate.sh after the matching
|
|
build phase. Gates import the game modules lazily (inside the function) so a
|
|
phase-N gate does not require modules built in later phases.
|
|
|
|
Run: python tests/smoke.py --phase N (single gate)
|
|
python tests/smoke.py --all (all gates, in order)
|
|
Exit 0 == pass, non-zero == fail (AssertionError or raised exception).
|
|
|
|
This file is also the API CONTRACT: orchestrate.sh's build prompts instruct the
|
|
dispatched agents to produce exactly the module/function names imported below.
|
|
"""
|
|
import argparse
|
|
import os
|
|
import random
|
|
import sys
|
|
|
|
# Headless-safe: force dummy drivers BEFORE any pygame import so gates never
|
|
# need a real display. Phase 4's audio test monkeypatches mixer init directly.
|
|
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
|
|
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
sys.path.insert(0, ROOT)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# small helpers
|
|
# --------------------------------------------------------------------------- #
|
|
def _rooms_overlap(a, b):
|
|
"""True if two Rect room footprints share any tile (touching edges is OK)."""
|
|
return (a.x < b.x + b.w) and (b.x < a.x + a.w) and (a.y < b.y + b.h) and (b.y < a.y + a.h)
|
|
|
|
|
|
def _floor_reachable(gmap):
|
|
"""4-dir flood fill: True if every floor tile is reachable from the first
|
|
room's center (i.e. the dungeon is fully connected)."""
|
|
start = None
|
|
if gmap.rooms:
|
|
cx, cy = gmap.rooms[0].center()
|
|
if 0 <= cx < gmap.width and 0 <= cy < gmap.height and gmap.tiles[cy][cx] == 1:
|
|
start = (cx, cy)
|
|
if start is None:
|
|
# fall back to first floor tile
|
|
for y in range(gmap.height):
|
|
for x in range(gmap.width):
|
|
if gmap.tiles[y][x] == 1:
|
|
start = (x, y)
|
|
break
|
|
if start:
|
|
break
|
|
assert start is not None, "map has no floor tiles"
|
|
|
|
total_floor = sum(row.count(1) for row in gmap.tiles)
|
|
seen = {start}
|
|
stack = [start]
|
|
while stack:
|
|
x, y = stack.pop()
|
|
for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
|
|
if 0 <= nx < gmap.width and 0 <= ny < gmap.height:
|
|
if (nx, ny) not in seen and gmap.tiles[ny][nx] == 1:
|
|
seen.add((nx, ny))
|
|
stack.append((nx, ny))
|
|
return len(seen) == total_floor
|
|
|
|
|
|
def _ascii(gmap):
|
|
glyph = {0: "#", 1: "."}
|
|
lines = []
|
|
for y in range(min(gmap.height, 25)):
|
|
lines.append("".join(glyph.get(gmap.tiles[y][x], "?") for x in range(min(gmap.width, 80))))
|
|
return "\n".join(lines)
|
|
|
|
|
|
def _make_box_map(width, height, floor_only=False):
|
|
"""A GameMap filled with walls (or floors) for controlled FOV/A* tests."""
|
|
from engine.map_gen import GameMap
|
|
|
|
fill = 1 if floor_only else 0
|
|
tiles = [[fill for _ in range(width)] for _ in range(height)]
|
|
m = GameMap(
|
|
width=width,
|
|
height=height,
|
|
tiles=tiles,
|
|
rooms=[],
|
|
explored=[[False] * width for _ in range(height)],
|
|
visible=[[False] * width for _ in range(height)],
|
|
entities=[],
|
|
stairs_down=None,
|
|
floor_index=0,
|
|
)
|
|
return m
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# PHASE 1 — procedural dungeon generation
|
|
# --------------------------------------------------------------------------- #
|
|
def phase_1():
|
|
from data.constants import MAP_W, MAP_H
|
|
from engine.map_gen import generate_dungeon
|
|
|
|
assert MAP_W == 80 and MAP_H == 50, "map must be 80x50"
|
|
|
|
for fi in range(5):
|
|
rng = random.Random(1000 + fi)
|
|
m = generate_dungeon(fi, rng)
|
|
assert m.width == MAP_W and m.height == MAP_H, f"floor {fi}: wrong dimensions"
|
|
assert len(m.rooms) >= 3, f"floor {fi}: only {len(m.rooms)} rooms (need >=3)"
|
|
# no room footprints overlap
|
|
for i in range(len(m.rooms)):
|
|
for j in range(i + 1, len(m.rooms)):
|
|
assert not _rooms_overlap(m.rooms[i], m.rooms[j]), f"floor {fi}: rooms {i},{j} overlap"
|
|
# fully connected
|
|
assert _floor_reachable(m), f"floor {fi}: not all floor tiles reachable"
|
|
# border is all walls
|
|
for x in range(MAP_W):
|
|
assert m.tiles[0][x] == 0 and m.tiles[MAP_H - 1][x] == 0, f"floor {fi}: border not wall"
|
|
for y in range(MAP_H):
|
|
assert m.tiles[y][0] == 0 and m.tiles[y][MAP_W - 1] == 0, f"floor {fi}: border not wall"
|
|
# stairs present on a floor tile (floors 0-8 carry stairs; floor 9 is boss arena)
|
|
assert m.stairs_down is not None, f"floor {fi}: no stairs_down"
|
|
sx, sy = m.stairs_down
|
|
assert m.tiles[sy][sx] == 1, f"floor {fi}: stairs not on a floor tile"
|
|
# determinism: same seed reproduces same layout
|
|
rng2 = random.Random(1000 + fi)
|
|
m2 = generate_dungeon(fi, rng2)
|
|
assert m2.tiles == m.tiles, f"floor {fi}: generation not deterministic for given rng"
|
|
|
|
# two different seeds must (almost certainly) differ
|
|
a = generate_dungeon(0, random.Random(1))
|
|
b = generate_dungeon(0, random.Random(2))
|
|
assert a.tiles != b.tiles, "different seeds produced identical maps"
|
|
|
|
print("[phase1] sample floor 0:")
|
|
print(_ascii(generate_dungeon(0, random.Random(7))))
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# PHASE 2 — FOV, A*, combat, AI
|
|
# --------------------------------------------------------------------------- #
|
|
def _test_fov():
|
|
from data.constants import SIGHT_RADIUS
|
|
from engine.fov import compute_fov
|
|
|
|
assert SIGHT_RADIUS == 8, "sight radius must be 8"
|
|
# player walled in on all sides -> only its own tile visible
|
|
m = _make_box_map(7, 7)
|
|
cx = cy = 3
|
|
m.tiles[cy][cx] = 1 # single floor tile, surrounded by walls
|
|
vis = compute_fov(m, cx, cy, SIGHT_RADIUS)
|
|
assert vis == {(cx, cy)}, f"walled-in player should see only self, got {vis}"
|
|
|
|
# open room: visible set symmetric and within radius (Chebyshev <= radius)
|
|
m = _make_box_map(21, 21, floor_only=True)
|
|
vis = compute_fov(m, 10, 10, SIGHT_RADIUS)
|
|
assert (10, 10) in vis
|
|
for (x, y) in vis:
|
|
assert max(abs(x - 10), abs(y - 10)) <= SIGHT_RADIUS, "FOV exceeds radius"
|
|
# an open floor should reveal many tiles around the center
|
|
assert len(vis) > 40, f"open-room FOV too small: {len(vis)} tiles"
|
|
|
|
# a wall blocks sight beyond it
|
|
m = _make_box_map(11, 5, floor_only=True)
|
|
m.tiles[2][5] = 0 # wall column at x=5, y=2 directly right of center(5,2)
|
|
# place wall right next to center to occlude the far side
|
|
m2 = _make_box_map(11, 3, floor_only=True)
|
|
m2.tiles[1][6] = 0 # wall immediately east of (5,1)
|
|
vis2 = compute_fov(m2, 5, 1, SIGHT_RADIUS)
|
|
assert (7, 1) not in vis2, "wall should block line of sight"
|
|
|
|
|
|
def _test_astar():
|
|
from engine.pathfinding import astar
|
|
|
|
m = _make_box_map(10, 10, floor_only=True)
|
|
# straight path
|
|
p = astar(m, (1, 1), (8, 1))
|
|
assert p is not None and p[0] == (1, 1) and p[-1] == (8, 1), f"bad straight path: {p}"
|
|
# every step adjacent and on floor
|
|
for (x, y) in p:
|
|
assert m.tiles[y][x] == 1, "path crosses a wall"
|
|
for i in range(1, len(p)):
|
|
assert abs(p[i][0] - p[i - 1][0]) + abs(p[i][1] - p[i - 1][1]) == 1, "non-adjacent step"
|
|
|
|
# path around a wall barrier
|
|
m.tiles[4][3] = m.tiles[4][4] = m.tiles[4][5] = m.tiles[4][6] = 0 # vertical wall with gap
|
|
p2 = astar(m, (2, 2), (7, 2))
|
|
assert p2 is not None, "no path around barrier"
|
|
for (x, y) in p2:
|
|
assert m.tiles[y][x] == 1, "path crosses barrier"
|
|
|
|
# no path when fully blocked
|
|
for x in range(10):
|
|
m.tiles[4][x] = 0
|
|
assert astar(m, (2, 2), (7, 7)) is None, "expected no path through full wall"
|
|
|
|
|
|
def _test_combat():
|
|
from entities.enemy import make_enemy
|
|
from entities.player import Player
|
|
from engine.combat import attack
|
|
|
|
attacker = Player(x=0, y=0)
|
|
hits = misses = crits = 0
|
|
total_dmg = 0
|
|
max_possible = 2 * (attacker.effective_power) # crit doubles
|
|
for _ in range(1000):
|
|
defender = make_enemy("Goblin", 0, 0) # fresh defender each swing
|
|
defender.hp = defender.max_hp
|
|
res = attack(attacker, defender, log=[])
|
|
if res["hit"]:
|
|
hits += 1
|
|
assert res["damage"] >= 0
|
|
assert res["damage"] <= max_possible, f"damage {res['damage']} exceeds max {max_possible}"
|
|
total_dmg += res["damage"]
|
|
if res["crit"]:
|
|
crits += 1
|
|
else:
|
|
misses += 1
|
|
assert res["damage"] == 0
|
|
assert hits > 0 and misses > 0, "combat never both hit and missed over 1000 swings"
|
|
assert crits > 0, "no critical hits over 1000 swings"
|
|
avg = total_dmg / hits if hits else 0
|
|
# goblin armor 1, player power ~4 -> per-hit roughly 3, crits 6; allow a band
|
|
assert 1 <= avg <= max_possible, f"average damage {avg} out of expected band"
|
|
|
|
|
|
def _test_ai():
|
|
from entities.enemy import make_enemy
|
|
from entities.player import Player
|
|
from engine.game_state import GameSession
|
|
from engine.map_gen import GameMap
|
|
from ai.behaviors import enemy_turn
|
|
|
|
# vertical corridor at x=3, y=1..5, walls elsewhere
|
|
w = h = 7
|
|
tiles = [[0] * w for _ in range(h)]
|
|
for y in range(1, 6):
|
|
tiles[y][3] = 1
|
|
cmap = GameMap(
|
|
width=w, height=h, tiles=tiles, rooms=[],
|
|
explored=[[False] * w for _ in range(h)],
|
|
visible=[[False] * w for _ in range(h)],
|
|
entities=[], stairs_down=None, floor_index=0,
|
|
)
|
|
player = Player(x=3, y=1)
|
|
goblin = make_enemy("Goblin", 3, 5)
|
|
cmap.entities = [goblin]
|
|
sess = GameSession(player=player, dungeon=[cmap], current_floor=0,
|
|
log=[], turn=0, state="playing")
|
|
start_dist = abs(goblin.y - player.y)
|
|
moved_closer = False
|
|
for _ in range(20):
|
|
enemy_turn(goblin, sess)
|
|
sess.turn += 1
|
|
d = abs(goblin.y - player.y)
|
|
if d < start_dist:
|
|
moved_closer = True
|
|
if d <= 1:
|
|
break # reached melee range
|
|
assert moved_closer, "chase enemy never moved closer to the player"
|
|
# after enough turns it should be adjacent (and attacking) -> player took damage
|
|
assert abs(goblin.y - player.y) <= 1, "chase enemy failed to close distance"
|
|
# keep going a few turns: adjacent goblin should hit the player eventually
|
|
hurt = False
|
|
start_hp = player.hp
|
|
for _ in range(30):
|
|
enemy_turn(goblin, sess)
|
|
sess.turn += 1
|
|
if player.hp < start_hp:
|
|
hurt = True
|
|
break
|
|
assert hurt, "adjacent enemy never landed a hit on the player"
|
|
|
|
|
|
def phase_2():
|
|
_test_fov()
|
|
_test_astar()
|
|
_test_combat()
|
|
_test_ai()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# PHASE 3 — content: enemies, items/equipment, XP/leveling
|
|
# --------------------------------------------------------------------------- #
|
|
def _test_enemy_roster():
|
|
from data.enemies import ENEMIES, enemies_for_floor
|
|
from entities.enemy import make_enemy
|
|
|
|
expected = {"Rat", "Goblin", "Skeleton Archer", "Orc Warrior",
|
|
"Wraith", "Green Slime", "Ancient Dragon"}
|
|
assert set(ENEMIES.keys()) == expected, f"roster mismatch: {set(ENEMIES)}"
|
|
|
|
# every kind buildable and mirrors its roster entry
|
|
for kind, stats in ENEMIES.items():
|
|
e = make_enemy(kind, 0, 0)
|
|
assert e.hp == stats["hp"], f"{kind} hp mismatch"
|
|
assert e.max_hp == stats["hp"], f"{kind} max_hp mismatch"
|
|
assert e.behavior == stats["behavior"], f"{kind} behavior mismatch"
|
|
assert e.xp_value == stats["xp"], f"{kind} xp mismatch"
|
|
|
|
# hard checks against the plan's roster table (guards wrong data)
|
|
rat = make_enemy("Rat", 0, 0)
|
|
assert rat.hp == 8 and rat.behavior == "wander" and rat.xp_value == 5
|
|
gob = make_enemy("Goblin", 0, 0)
|
|
assert gob.behavior == "chase"
|
|
arch = make_enemy("Skeleton Archer", 0, 0)
|
|
assert arch.behavior == "ranged" and ENEMIES["Skeleton Archer"]["ranged_power"] == 6
|
|
orc = make_enemy("Orc Warrior", 0, 0)
|
|
assert orc.behavior == "flee" and orc.hp == 30
|
|
wraith = make_enemy("Wraith", 0, 0)
|
|
assert wraith.behavior == "phase" and ENEMIES["Wraith"]["speed"] == 2
|
|
slime = make_enemy("Green Slime", 0, 0)
|
|
assert slime.behavior == "split" and getattr(slime, "can_split", False) is True
|
|
dragon = make_enemy("Ancient Dragon", 0, 0)
|
|
assert dragon.hp == 120 and dragon.xp_value == 200 and dragon.behavior == "chase"
|
|
|
|
# floor gating: floor 0 must not spawn wraiths/orcs/dragon
|
|
deep = set(enemies_for_floor(0))
|
|
assert "Rat" in deep and "Wraith" not in deep and "Ancient Dragon" not in deep
|
|
# dragon only on floor 9
|
|
assert "Ancient Dragon" in set(enemies_for_floor(9))
|
|
|
|
|
|
def _test_equipment():
|
|
from entities.player import Player
|
|
from entities.item import make_item
|
|
|
|
p = Player(x=0, y=0)
|
|
base_power = p.effective_power
|
|
base_armor = p.effective_armor
|
|
|
|
sword = make_item("Short Sword")
|
|
assert sword.kind == "weapon" and sword.power == 4
|
|
p.equip_item(sword)
|
|
assert p.weapon is sword
|
|
assert p.effective_power == base_power + 4, "weapon power not applied"
|
|
|
|
chain = make_item("Chain Mail")
|
|
assert chain.kind == "armor" and chain.armor == 4
|
|
p.equip_item(chain)
|
|
assert p.armor_item is chain
|
|
assert p.effective_armor == base_armor + 4, "armor not applied"
|
|
|
|
# re-equipping returns the old item to inventory
|
|
axe = make_item("Battle Axe")
|
|
p.equip_item(axe)
|
|
assert p.weapon is axe
|
|
assert sword in p.inventory
|
|
|
|
|
|
def _test_progression():
|
|
from entities.enemy import make_enemy
|
|
from entities.player import Player
|
|
from engine.combat import attack
|
|
|
|
p = Player(x=0, y=0)
|
|
start_level = p.level
|
|
start_power = p.effective_power
|
|
p.xp = 29 # one kill away from level 2 (threshold 30)
|
|
|
|
gob = make_enemy("Goblin", 0, 0)
|
|
gob.hp = 1
|
|
gob.max_hp = 1
|
|
# Loop the swing until the 1-hp goblin dies: combat hit chance is ~90%, so a
|
|
# single roll is not guaranteed. The kill is just setup; the level-up
|
|
# assertions below are what this gate actually verifies.
|
|
for _ in range(20):
|
|
attack(p, gob, log=[])
|
|
if gob.hp <= 0:
|
|
break
|
|
assert gob.hp <= 0
|
|
p.gain_xp(gob.xp_value, log=[]) # +12 -> 41 >= 30 -> level 2
|
|
|
|
assert p.level == start_level + 1, "level did not advance past threshold"
|
|
assert p.hp == p.max_hp, "level-up must fully heal"
|
|
assert p.effective_power > start_power, "level-up must increase power"
|
|
|
|
|
|
def phase_3():
|
|
_test_enemy_roster()
|
|
_test_equipment()
|
|
_test_progression()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# PHASE 4 — save/load, pickup, descend, audio safety
|
|
# --------------------------------------------------------------------------- #
|
|
def _test_save_load():
|
|
import tempfile
|
|
from engine.game_state import new_game
|
|
from engine.serializers import save_session, load_session
|
|
|
|
sess = new_game(seed=12345)
|
|
# mutate a little so equality is meaningful
|
|
sess.player.hp = 13
|
|
sess.turn = 7
|
|
sess.log.append("probe message")
|
|
|
|
path = os.path.join(tempfile.mkdtemp(), "save.json")
|
|
save_session(sess, path)
|
|
loaded = load_session(path)
|
|
|
|
from engine.serializers import session_to_dict
|
|
assert session_to_dict(loaded) == session_to_dict(sess), "save/load state not equal"
|
|
assert loaded.player.hp == 13 and loaded.turn == 7
|
|
assert "probe message" in loaded.log
|
|
|
|
|
|
def _test_pickup():
|
|
from engine.game_state import new_game
|
|
from entities.item import make_item
|
|
from engine import actions
|
|
|
|
sess = new_game(seed=1)
|
|
m = sess.current_map
|
|
px, py = sess.player.x, sess.player.y
|
|
item = make_item("Healing Potion")
|
|
item.x, item.y = px, py
|
|
m.entities.append(item)
|
|
inv_before = len(sess.player.inventory)
|
|
actions.pickup(sess)
|
|
assert item in sess.player.inventory, "pickup did not move item into inventory"
|
|
assert item not in m.entities, "pickup did not remove item from the map"
|
|
assert len(sess.player.inventory) == inv_before + 1
|
|
|
|
|
|
def _test_descend():
|
|
from engine.game_state import new_game
|
|
from engine import actions
|
|
|
|
sess = new_game(seed=1)
|
|
# put the player squarely on the stairs of the current floor
|
|
sx, sy = sess.current_map.stairs_down
|
|
sess.player.x, sess.player.y = sx, sy
|
|
floor_before = sess.current_floor
|
|
actions.descend(sess)
|
|
assert sess.current_floor == floor_before + 1, "descend did not advance floor"
|
|
|
|
|
|
def _test_audio_safety():
|
|
import pygame
|
|
from engine.audio import Audio
|
|
|
|
# 1) forced mixer-init failure must not raise
|
|
real_init = pygame.mixer.init
|
|
|
|
def boom(*a, **k):
|
|
raise OSError("simulated no audio device")
|
|
|
|
pygame.mixer.init = boom
|
|
try:
|
|
aud = Audio() # must swallow the failure
|
|
assert aud.enabled is False, "Audio should be disabled when mixer init fails"
|
|
# playing while disabled must be a silent no-op, never raise
|
|
aud.play("hit")
|
|
aud.toggle_mute()
|
|
aud.toggle_mute()
|
|
finally:
|
|
pygame.mixer.init = real_init
|
|
|
|
# 2) no asset files required: Audio builds sounds in memory (skip if real
|
|
# mixer unavailable in CI). We only assert the class never touches disk.
|
|
import inspect
|
|
src = inspect.getsource(Audio)
|
|
assert ".wav" not in src and ".ogg" not in src, "Audio must not load asset files"
|
|
|
|
|
|
def phase_4():
|
|
_test_save_load()
|
|
_test_pickup()
|
|
_test_descend()
|
|
_test_audio_safety()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
PHASES = {1: phase_1, 2: phase_2, 3: phase_3, 4: phase_4}
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="Underdepths gate suite")
|
|
ap.add_argument("--phase", type=int, choices=[1, 2, 3, 4])
|
|
ap.add_argument("--all", action="store_true")
|
|
args = ap.parse_args()
|
|
|
|
if args.all:
|
|
for n in (1, 2, 3, 4):
|
|
print(f"\n=== PHASE {n} ===")
|
|
PHASES[n]()
|
|
print(f"PHASE {n} OK")
|
|
print("\nALL PHASES OK")
|
|
return
|
|
|
|
if args.phase is None:
|
|
ap.error("specify --phase N or --all")
|
|
PHASES[args.phase]()
|
|
print(f"PHASE {args.phase} OK")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|