(Body Snatcher) Prepare for Pass 2

This commit is contained in:
AlexKucera committed 2026-08-12 16:03:10 +02:00
1 parent 8259ca8ddf
commit 2316e4ac39
6 files changed
+39 -1463

No files matched your search

+19 -8
View File
@@ -4,7 +4,7 @@ You are building a browser-based roguelike game called **Body Snatcher**. Read t
## The Game
You are a ghost. 1 HP. No attack. You explore a procedurally generated dungeon. To survive, you must **possess** enemies — walk into them and hold SPACE. Once inside, you control their body: their stats, their attack, their movement speed. When your host dies, you're ejected as a ghost with a countdown timer. Find a new body or die. Descend 10 floors, spend essence in shops, upgrade your abilities, reach the exit.
You are a ghost. 1 HP. No attack. You explore a procedurally generated dungeon. To survive, you must **possess** enemies — move next to them and hold SPACE. Once inside, you control their body: their stats, their attack, their movement speed. When your host dies, you're ejected as a ghost with a generous 15-second countdown timer. Find a new body or die. Descend 10 floors, spend essence in shops, upgrade your abilities, reach the exit.
## Tech Constraints
@@ -39,6 +39,9 @@ You are a ghost. 1 HP. No attack. You explore a procedurally generated dungeon.
- Tile types: floor, wall, door, exit-stairs, shop-pad, chest
- Fog of war: visible radius around player, explored-but-unseen dimmed
- HUD shows: current body HP, ghost timer (when ghost), essence count, floor number, abilities
- Before play starts, the title screen MUST show a concise controls panel explaining movement, possession/attack, facing, confirm, and pause.
- During play, the HUD MUST show a short contextual hint for SPACE (possess while ghost; current body attack/special while possessed).
- The pause and shop screens MUST show the controls needed to leave or confirm those screens.
## Player States
@@ -47,7 +50,7 @@ You are a ghost. 1 HP. No attack. You explore a procedurally generated dungeon.
- Movement: arrow keys / WASD, one tile per turn
- Cannot walk through walls (unless Ghost Tree T3 unlocked)
- Hold SPACE adjacent to enemy → possession (takes 1 turn)
- Ghost timer: 5s real-time countdown (8s with Ghost T1)
- Ghost timer: 15s real-time countdown (20s with Ghost T1)
- Timer pauses while possessing
- When timer hits 0 → game over
@@ -132,7 +135,7 @@ Each enemy is a **dual system**: it behaves one way as an opponent and different
Present 3 random upgrades from the pool below. Player picks one or skips.
### Ghost Tree
- T1: Ghost time 5s → 8s (cost: 5 essence)
- T1: Ghost time 15s → 20s (cost: 5 essence)
- T2: Possession range +1 tile, can possess from 2 tiles away (cost: 8)
- T3: Phase through walls — 1s burst, 5s cooldown (cost: 12)
- T4: Ghost Dash — quick 3-tile dash while incorporeal, 3s cooldown (cost: 15)
@@ -190,11 +193,16 @@ Present 3 random upgrades from the pool below. Player picks one or skips.
## Controls
- **WASD / Arrow Keys:** Move (one tile per turn)
- **SPACE:** Possess (ghost) / Attack (possessed) / Special (possessed)
- **Q / E:** Rotate facing (for Shielder, Turret)
- **ENTER:** Confirm in menus/shop
- **ESC:** Pause menu (Save + Quit option)
These controls must be explained on the title screen before the run starts, not only documented here:
- **WASD / Arrow Keys:** Move one tile per turn.
- **SPACE while ghost:** Possess an enemy within range. Explain that the ghost cannot attack.
- **SPACE while possessed:** Use the current host's attack or special ability. Show the current action in the HUD.
- **Q / E:** Rotate facing for directional bodies such as Shielder and Turret; activate relevant ghost upgrades when incorporeal.
- **ENTER:** Start the game and confirm a highlighted shop/menu choice.
- **ESC:** Pause or resume. The pause menu includes Save + Quit.
Keep the explanation concise and readable. This is an instructions overlay, not a separate tutorial level.
## Completion Criteria
@@ -219,6 +227,8 @@ The game MUST meet ALL of these. Do not consider yourself done until every one p
17. Fog of war renders correctly (unexplored tiles hidden, explored dimmed)
18. Audio plays (procedural tones via Web Audio API)
19. At least 3 achievements track and unlock
20. Title screen explains all controls, and gameplay/shop/pause screens show relevant contextual controls
21. Base ghost timer is 15 seconds; Ghost T1 increases it to 20 seconds
## Testability (REQUIRED)
@@ -236,6 +246,7 @@ The game MUST expose its state for automated testing:
- DO NOT add external dependencies, libraries, or frameworks.
- DO NOT use ES modules (import/export) — inline script only.
- DO NOT add a tutorial level. Start on floor 1 immediately.
- DO NOT hide controls in documentation only. They must be readable in-game before play starts.
- DO NOT write more code than needed. Bloat is penalized.
- DO NOT skip the fog of war, audio, or save/load — they are completion criteria.
- DO NOT use placeholder art or "TODO" comments. Everything must work.
+8 -6
View File
@@ -9,7 +9,7 @@ Do not delete or modify AGENTS.md.
## How to use this file
1. Copy everything between the ===== markers below
2. Open Pi in an empty directory containing ONLY AGENTS.md
2. Open Pi in a clean directory containing this base setup: `AGENTS.md`, `PROMPT.md`, and `docs/`
3. Paste as your first message
4. Hands off. Let it run.
5. Save the session jsonl when done (rule 6.2)
@@ -44,6 +44,8 @@ It must run without external packages — only Node.js builtins (`fs`, `vm`, `pa
- Grid exists and has wall + floor tiles
- GAME.input('ArrowRight') moves the ghost without error
- Ghost cannot move into walls
- Title screen visibly explains WASD/arrows, SPACE, Q/E, ENTER, and ESC before play starts
- Starting ghost timer is at least 15 seconds
### Phase 2 checks: Possession + first 3 enemies
- Spawn an enemy next to the player via GAME.spawn or debug setup
@@ -123,10 +125,10 @@ run_phase() {
}
# Phase 1: Core engine
run_phase 1 "Read AGENTS.md. Implement Phase 1 ONLY: HTML5 Canvas skeleton, game loop, grid system, tile rendering, wall collision, ghost movement (WASD/arrows), fog of war, HUD, and a static test dungeon. Expose window.GAME with {state, player, grid, input(key), start(), tick(n)} as specified in the Testability section. Do NOT implement enemies, possession, or procgen yet. Run node verify.js 1 yourself and fix any failures before finishing."
run_phase 1 "Read AGENTS.md. Implement Phase 1 ONLY: HTML5 Canvas skeleton, game loop, grid system, tile rendering, wall collision, ghost movement (WASD/arrows), 15-second ghost timer, fog of war, HUD, and a static test dungeon. The title screen must visibly explain WASD/arrows, SPACE, Q/E, ENTER, and ESC before play starts; the live HUD must show a contextual SPACE hint. Expose window.GAME with {state, player, grid, input(key), start(), tick(n)} as specified in the Testability section. Do NOT implement enemies, possession, or procgen yet. Run node verify.js 1 yourself and fix any failures before finishing."
# Phase 2: Possession + first 3 enemies
run_phase 2 "Read AGENTS.md. Implement Phase 2 ONLY: possession mechanic (SPACE on adjacent enemy), Brute/Skitterer/Sentinel with dual AI+player-kit, A* pathfinding, ghost timer, essence drops. Preserve everything from Phase 1. Run node verify.js 2 yourself and fix any failures before finishing."
run_phase 2 "Read AGENTS.md. Implement Phase 2 ONLY: possession mechanic (SPACE on adjacent enemy), Brute/Skitterer/Sentinel with dual AI+player-kit, A* pathfinding, 15-second ghost timer with 20-second Ghost T1 behavior reserved for progression, contextual HUD attack/special explanations, and essence drops. Preserve everything from Phase 1. Run node verify.js 2 yourself and fix any failures before finishing."
# Phase 3: Remaining 9 enemies
run_phase 3 "Read AGENTS.md. Implement Phase 3 ONLY: the remaining 9 enemy types (Shielder, Bomber, Healer, Phaser, Turret, Charger, Siren, Mimic, Leech). Each needs full enemy AI + player kit. Preserve everything from previous phases. Run node verify.js 3 yourself and fix any failures before finishing."
@@ -135,11 +137,11 @@ run_phase 3 "Read AGENTS.md. Implement Phase 3 ONLY: the remaining 9 enemy types
run_phase 4 "Read AGENTS.md. Implement Phase 4 ONLY: procedural dungeon generation (random walk + room carving), 10 floors with escalating enemies, between-floor shop with 3 upgrade choices, all 11 upgrades across 3 trees, save/load via localStorage. Preserve everything. Run node verify.js 4 yourself and fix any failures before finishing."
# Phase 5: Polish + audio + achievements + win/lose
run_phase 5 "Read AGENTS.md. Implement Phase 5 ONLY: Web Audio API procedural sounds, screen shake, particles, hit flashes, movement interpolation, all 8 achievements, win state (floor 10 exit), lose state (ghost timer expires), pause menu (ESC). Preserve everything. Run node verify.js 5 yourself and fix any failures before finishing."
run_phase 5 "Read AGENTS.md. Implement Phase 5 ONLY: Web Audio API procedural sounds, screen shake, particles, hit flashes, movement interpolation, all 8 achievements, win state (floor 10 exit), lose state (15-second ghost timer expires), pause menu (ESC), and complete in-game controls explanations on title, HUD, shop, and pause screens. Preserve everything. Run node verify.js 5 yourself and fix any failures before finishing."
# Final adversarial review
echo "=== ADVERSARIAL REVIEW ==="
pi -p "You are a QA reviewer. Read AGENTS.md and the complete index.html. Find bugs, missing features, and spec violations. For each issue found, fix it directly. Focus on: crashes, enemies that don't work, save/load edge cases, missing achievements, fog of war bugs. Run node verify.js 5 after fixes." || true
pi -p "You are a QA reviewer. Read AGENTS.md and the complete index.html. Find bugs, missing features, and spec violations. For each issue found, fix it directly. Focus on: crashes, enemies that don't work, save/load edge cases, missing achievements, fog of war bugs, a base ghost timer of at least 15 seconds, and readable in-game controls instructions before play plus contextual hints during play. Run node verify.js 5 after fixes." || true
# Final verification
echo "=== FINAL VERIFICATION ==="
@@ -180,7 +182,7 @@ Now: write verify.js, then build.sh, then run build.sh.
## Notes
- The directory should contain ONLY AGENTS.md when you start the Pi session
- Start the Pi session from a clean directory containing only the disclosed base setup: `AGENTS.md`, `PROMPT.md`, and `docs/`
- AGENTS.md is allowed by rule 2.2 ("Human-authored instruction text is allowed")
- AGENTS.md must be disclosed in your submission repo (rule 3.1)
- The session jsonl proves it was one prompt — save it
-67
View File
@@ -1,67 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
MAX_RETRIES=3
run_phase() {
local phase=$1
local prompt=$2
local attempt=1
local output
while [ "$attempt" -le "$MAX_RETRIES" ]; do
echo "=== Phase $phase (attempt $attempt/$MAX_RETRIES) ==="
pi -p "$prompt" || true
if output=$(node verify.js "$phase" 2>&1); then
printf '%s\n' "$output"
echo "=== Phase $phase PASSED ==="
return 0
fi
printf '%s\n' "$output"
echo "=== Phase $phase FAILED (attempt $attempt) ==="
prompt="Phase $phase of Body Snatcher failed verification. Read AGENTS.md, verify.js, and the current index.html. Fix the current implementation in place; do not rewrite working systems or merely explain. The failing output is:
$output
Run node verify.js $phase yourself and keep fixing until it exits 0."
attempt=$((attempt + 1))
done
echo "=== Phase $phase exhausted retries; targeted fix ==="
pi -p "$prompt" || true
node verify.js "$phase"
echo "=== Phase $phase PASSED after targeted fix ==="
}
COMMON="Read AGENTS.md completely, then read verify.js and the current files. Body Snatcher must remain one dependency-free index.html with inline CSS/JavaScript. Directly edit files; do not only describe code. Preserve working prior phases. Keep window.GAME's test surface synchronized with live state. Canvas and AudioContext mocks must never crash. The page must wait for GAME.start() or a user key before starting."
run_phase 1 "$COMMON
Implement Phase 1 only: HTML5 Canvas skeleton; 25x18 tile grid plus HUD; title/start flow; game loop; ghost state and timer; WASD/arrow tile movement; wall collision; fog of war; HUD; static test dungeon. Expose GAME.state, player, enemies, grid, floor, essence, upgrades, log, start(), newRun(), input(key), and tick(n). Do not implement enemies, possession, or procedural generation yet. Run node verify.js 1 and fix every failure."
run_phase 2 "$COMMON
Implement Phase 2 only: possession with Space; Brute, Skitterer, and Sentinel as dual enemy/player kits; BFS or A* wall-aware enemy movement; host death/ejection; projectiles; combat; essence drops. Preserve Phase 1. Expose deterministic GAME.spawn(type,x,y), damageEnemy(enemy,amount), and findPath(sx,sy,tx,ty) used by verify.js. Enemy objects and possessed bodies must expose maxHp, damage, speed, and special/ability. Run node verify.js 2 and fix every failure."
run_phase 3 "$COMMON
Implement Phase 3 only: add Shielder, Bomber, Healer, Phaser, Turret, Charger, Siren, Mimic, and Leech with the complete enemy AI and possessed player kit from AGENTS.md. Preserve prior systems. All 12 types must instantiate, render with their required silhouettes, possess, fight, and execute specials without errors. Give every type a distinct maxHp/damage/speed tuple as verify.js requires while retaining the specified gameplay identity. Ensure findPath routes around walls on the current GAME.grid. Run node verify.js 3 and fix every failure."
run_phase 4 "$COMMON
Implement Phase 4 only: random-room-and-corridor procedural generation; different layouts each call; exits; chests; 10 escalating floors; between-floor shop with three choices; every prerequisite-gated upgrade in all three trees; gameplay effects; save/load/autosave using bodysnatcher_save; continue-run Y/N prompt. Preserve all combat. Expose generateFloor(floor), completeFloor(), shopChoices, buyUpgrade(index), save(), and load() exactly as verify.js exercises them. Run node verify.js 4 and fix every failure."
run_phase 5 "$COMMON
Implement Phase 5 and complete the full AGENTS.md spec: procedural Web Audio tones; screen shake; particles; hit flash; 150ms movement interpolation; all eight persistent achievements; floor-10 victory; ghost-timer loss with stats; pause and Save+Quit; all controls and game feel. Audit every completion criterion, not only the harness. Expose achievements, unlockAchievement(name), and sound(name). Make GAME.tick(n) deterministic enough for the 200-tick mock stress test. Run node verify.js 5 and fix every failure."
echo "=== ADVERSARIAL REVIEW ==="
pi -p "$COMMON
Act as an adversarial QA reviewer and fixer. Read the complete AGENTS.md, verify.js, and index.html. Inspect the full game for crashes, missing completion criteria, broken enemy AI or possessed kits, procgen connectivity, save/load edge cases, achievement tracking, fog, audio mocks, shop prerequisites, controls, win/loss, and 5-minute play stability. Fix every issue directly with the smallest safe changes. Run node verify.js 5 until it passes." || true
echo "=== FINAL VERIFICATION ==="
if ! output=$(node verify.js 5 2>&1); then
printf '%s\n' "$output"
pi -p "$COMMON
Final verification failed after QA. Fix only the concrete remaining failures in index.html and rerun node verify.js 5 until it exits 0. Failure output:
$output" || true
fi
node verify.js 5
echo "=== BUILD COMPLETE: ALL GATES PASSED ==="
@@ -13,11 +13,19 @@ Browser-based roguelike. You are a ghost with 1 HP and no attack. Possess enemie
2. Enemies roam with distinct AI patterns
3. Walk into enemy + hold Space to possess
4. Control body: stats, attack, movement
5. Host dies → ejected as ghost, 5s timer
5. Host dies → ejected as ghost, 15s timer
6. Find new body or die
7. Collect essence from kills
8. Descend → shop between floors → upgrade
## Player Guidance and Forgiveness
- The title screen explains every control before the player starts: WASD/arrows to move, SPACE to possess or attack, Q/E to face, ENTER to confirm, and ESC to pause.
- The HUD names the current SPACE action so each possessed body is understandable without outside documentation.
- Shop and pause overlays show their relevant confirm/back controls.
- The base ghost timer is 15 seconds. Ghost Tree T1 raises it to 20 seconds.
- Controls guidance is an overlay, not a tutorial floor; gameplay still begins on floor 1.
## Enemy Roster (12 types — dual system: enemy AI + player kit)
| Enemy | As Enemy | As Player (possessed) |
@@ -38,7 +46,7 @@ Browser-based roguelike. You are a ghost with 1 HP and no attack. Possess enemie
## Progression: Three Ability Tracks
### Ghost Tree (enhance incorporeal form)
- T1: Ghost time 5s → 8s
- T1: Ghost time 15s → 20s
- T2: Possession range +1 tile
- T3: Phase through walls (1s burst, cooldown)
- T4: Ghost Dash (quick movement while incorporeal)
@@ -66,6 +74,8 @@ Between floors. Spend essence (dropped by kills, scaled by rarity). Choose one u
| Save/load | localStorage — save on floor transition |
| Economy/progression | Essence currency, 3-track tree, shop |
| Content pipeline | 12 enemies, 10 floors, escalating difficulty, achievements |
| Player guidance | Title controls panel, contextual HUD action hint, shop/pause help |
| Forgiveness | 15s base ghost timer, 20s with Ghost T1 |
## Tech Stack
File diff suppressed because it is too large. Load diff
-292
View File
@@ -1,292 +0,0 @@
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const phase = Number(process.argv[2] || 5);
const checks = [];
const ok = (condition, message) => {
if (!condition) throw new Error(message);
checks.push(message);
};
const value = (object, names, fallback) => {
for (const name of names) if (object && object[name] != null) return object[name];
return fallback;
};
const tileName = tile => String((tile && (tile.type ?? tile.kind ?? tile.tile)) ?? tile).toLowerCase();
const isWall = tile => /wall|#/.test(tileName(tile)) || tile === 1;
const isFloor = tile => !isWall(tile) && !/void|unknown/.test(tileName(tile));
const keyFor = (dx, dy) => dx < 0 ? 'ArrowLeft' : dx > 0 ? 'ArrowRight' : dy < 0 ? 'ArrowUp' : 'ArrowDown';
const gridRows = game => Array.isArray(game.grid?.[0]) ? game.grid : [];
const setPlayerPosition = (game, x, y) => {
game.player.x = x; game.player.y = y;
if ('tx' in game.player) game.player.tx = x;
if ('ty' in game.player) game.player.ty = y;
if ('renderX' in game.player) game.player.renderX = x;
if ('renderY' in game.player) game.player.renderY = y;
};
const position = entity => [Number(value(entity, ['x', 'col'], 0)), Number(value(entity, ['y', 'row'], 0))];
function mocks() {
const storage = new Map();
let storageWrites = 0;
let audioCalls = 0;
const noop = () => {};
const gradient = { addColorStop: noop };
const context2d = new Proxy({ canvas: null, measureText: text => ({ width: String(text).length * 8 }), createLinearGradient: () => gradient, createRadialGradient: () => gradient, createPattern: () => ({}), getImageData: () => ({ data: new Uint8ClampedArray(4) }) }, { get: (target, key) => key in target ? target[key] : noop, set: (target, key, val) => (target[key] = val, true) });
const listeners = {};
const element = tag => ({
tagName: String(tag).toUpperCase(), id: '', width: tag === 'canvas' ? 800 : 0, height: tag === 'canvas' ? 640 : 0,
style: {}, classList: { add: noop, remove: noop, toggle: noop, contains: () => false }, children: [],
appendChild(child) { this.children.push(child); return child; }, remove: noop, focus: noop,
addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, removeEventListener: noop,
getContext: () => context2d, getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 640 }),
setAttribute(name, val) { this[name] = val; }, getAttribute(name) { return this[name] ?? null; },
querySelector: () => null, querySelectorAll: () => []
});
const canvas = element('canvas');
canvas.id = 'game'; context2d.canvas = canvas;
const body = element('body'); body.appendChild(canvas);
const document = {
body, readyState: 'loading', hidden: false,
createElement: element,
getElementById: id => id === 'game' || id === 'canvas' ? canvas : null,
querySelector: selector => selector === 'canvas' || selector === '#game' || selector === '#canvas' ? canvas : null,
querySelectorAll: selector => selector === 'canvas' ? [canvas] : [],
addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, removeEventListener: noop,
dispatchEvent(event) { for (const fn of listeners[event.type] || []) fn(event); },
};
class AudioParam { setValueAtTime() { audioCalls++; } linearRampToValueAtTime() { audioCalls++; } exponentialRampToValueAtTime() { audioCalls++; } cancelScheduledValues() {} }
class AudioNode { constructor() { this.frequency = new AudioParam(); this.gain = new AudioParam(); this.type = 'sine'; } connect() { audioCalls++; return this; } disconnect() {} start() { audioCalls++; } stop() { audioCalls++; } }
class AudioContext { constructor() { audioCalls++; this.currentTime = 0; this.destination = new AudioNode(); this.state = 'running'; } createOscillator() { audioCalls++; return new AudioNode(); } createGain() { audioCalls++; return new AudioNode(); } createBiquadFilter() { return new AudioNode(); } resume() { audioCalls++; return Promise.resolve(); } close() { return Promise.resolve(); } }
const localStorage = { getItem: key => storage.has(key) ? storage.get(key) : null, setItem: (key, val) => { storageWrites++; storage.set(key, String(val)); }, removeItem: key => storage.delete(key), clear: () => storage.clear(), key: i => [...storage.keys()][i] ?? null, get length() { return storage.size; } };
let now = 1000;
const window = {
document, localStorage, AudioContext, webkitAudioContext: AudioContext, innerWidth: 800, innerHeight: 640, devicePixelRatio: 1,
performance: { now: () => (now += 16) }, navigator: { userAgent: 'verify.js' }, location: { reload: noop },
addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, removeEventListener: noop,
dispatchEvent(event) { for (const fn of listeners[event.type] || []) fn(event); },
requestAnimationFrame: fn => (window.__raf = fn, 1), cancelAnimationFrame: noop,
setTimeout: () => 1, clearTimeout: noop, setInterval: () => 1, clearInterval: noop,
confirm: () => false, alert: noop,
};
window.window = window; window.self = window; window.globalThis = window;
const sandbox = {
window, self: window, document, localStorage, AudioContext, webkitAudioContext: AudioContext,
requestAnimationFrame: window.requestAnimationFrame, cancelAnimationFrame: noop,
setTimeout: window.setTimeout, clearTimeout: noop, setInterval: window.setInterval, clearInterval: noop,
performance: window.performance, navigator: window.navigator, location: window.location,
console, Math, Date, JSON, Array, Object, String, Number, Boolean, Map, Set, WeakMap, Promise,
Uint8ClampedArray, Event: class Event { constructor(type, init = {}) { this.type = type; Object.assign(this, init); } },
KeyboardEvent: class KeyboardEvent { constructor(type, init = {}) { this.type = type; Object.assign(this, init); } },
};
sandbox.globalThis = sandbox;
return { sandbox, window, storage, metrics: { get storageWrites() { return storageWrites; }, get audioCalls() { return audioCalls; } } };
}
function boot() {
const file = path.join(__dirname, 'index.html');
ok(fs.existsSync(file), 'index.html exists');
const html = fs.readFileSync(file, 'utf8');
ok(/<canvas\b/i.test(html), 'index.html contains a canvas');
ok(/<script\b/i.test(html), 'index.html contains inline JavaScript');
ok(!/<script\b[^>]*\bsrc\s*=/i.test(html), 'no external script src attributes');
ok(!/<(?:link|img|audio|video)\b[^>]*(?:href|src)\s*=\s*["']https?:/i.test(html), 'no external asset dependencies');
ok(!/<script\b[^>]*\btype\s*=\s*["']module["']/i.test(html), 'no ES modules');
ok(!/(^|[;{}]\s*)import\s+(?:[\w*{]|["'])/m.test(html), 'no import statements');
const scripts = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map(match => match[1]);
const env = mocks();
vm.createContext(env.sandbox);
scripts.forEach((script, i) => vm.runInContext(script, env.sandbox, { filename: `index.html:inline-${i + 1}`, timeout: 3000 }));
const game = env.window.GAME || env.sandbox.GAME;
ok(game && typeof game === 'object', 'window.GAME is exposed');
ok(typeof game.start === 'function', 'GAME.start() is exposed');
ok(typeof game.input === 'function', 'GAME.input(key) is exposed');
ok(typeof game.tick === 'function', 'GAME.tick(n) is exposed');
game.start();
if (game.state === 'title') game.input('Enter');
return { ...env, game, html };
}
function adjacentFloor(game, origin = game.player) {
const rows = gridRows(game); const [x, y] = position(origin);
for (const [dx, dy] of [[1,0],[-1,0],[0,1],[0,-1]]) if (rows[y + dy] && isFloor(rows[y + dy][x + dx])) return { x: x + dx, y: y + dy, dx, dy };
for (let yy = 1; yy < rows.length - 1; yy++) for (let xx = 1; xx < rows[yy].length - 1; xx++) {
if (!isFloor(rows[yy][xx])) continue;
for (const [dx, dy] of [[1,0],[-1,0],[0,1],[0,-1]]) if (isFloor(rows[yy + dy]?.[xx + dx])) { setPlayerPosition(game, xx, yy); return { x: xx + dx, y: yy + dy, dx, dy }; }
}
throw new Error('no adjacent floor tiles available');
}
function phase1(env) {
const game = env.game;
const validStates = ['title','playing','ghost','possessed','shop','paused','won','lost','gameover','victory'];
ok(validStates.includes(String(game.state).toLowerCase()), 'GAME.state is valid');
ok(game.player && typeof game.player === 'object', 'GAME.player is exposed');
const rows = gridRows(game);
ok(rows.length > 0 && rows[0].length > 0, 'grid is a two-dimensional array');
const flat = rows.flat();
ok(flat.some(isWall), 'grid contains walls');
ok(flat.some(isFloor), 'grid contains floor tiles');
game.state = 'ghost'; if ('mode' in game.player) game.player.mode = 'ghost';
const step = adjacentFloor(game); const before = position(game.player);
game.input(keyFor(step.dx, step.dy));
const after = position(game.player);
ok(after[0] !== before[0] || after[1] !== before[1], 'Arrow/WASD input moves the ghost');
let wallCase;
for (let y = 1; y < rows.length - 1 && !wallCase; y++) for (let x = 1; x < rows[y].length - 1; x++) if (isFloor(rows[y][x])) {
for (const [dx, dy] of [[1,0],[-1,0],[0,1],[0,-1]]) if (isWall(rows[y + dy]?.[x + dx])) { wallCase = { x, y, dx, dy }; break; }
}
ok(wallCase, 'grid has a floor tile adjacent to a wall');
setPlayerPosition(game, wallCase.x, wallCase.y); game.input(keyFor(wallCase.dx, wallCase.dy));
ok(position(game.player)[0] === wallCase.x && position(game.player)[1] === wallCase.y, 'ghost cannot move through walls without upgrade');
}
function clearEnemies(game) {
ok(Array.isArray(game.enemies), 'GAME.enemies is exposed');
game.enemies.length = 0;
if (Array.isArray(game.projectiles)) game.projectiles.length = 0;
}
function spawn(game, type, x, y) {
ok(typeof game.spawn === 'function', 'GAME.spawn(type,x,y) is exposed for testing');
const before = game.enemies.length;
const result = game.spawn(type, x, y);
const enemy = result || game.enemies[game.enemies.length - 1];
ok(enemy && game.enemies.length > before, `${type} can be spawned`);
return enemy;
}
function ghostSetup(game) {
game.state = 'ghost'; clearEnemies(game);
game.player.host = null; game.player.body = null; game.player.type = 'ghost'; game.player.hp = 1;
game.player.ghostTimer = 8; game.player.timer = 8;
return adjacentFloor(game);
}
function possess(game, type) {
const spot = ghostSetup(game);
const enemy = spawn(game, type, spot.x, spot.y);
game.input('Space');
if (game.state !== 'possessed') game.input('Space');
ok(game.state === 'possessed', `${type} is possessable with Space`);
return { enemy, body: game.player.host || game.player.body || game.player };
}
function phase2(env) {
const game = env.game;
const expected = { Brute: [8,3], Skitterer: [2,1], Sentinel: [4,0] };
for (const [type, [hp, damage]] of Object.entries(expected)) {
const { body } = possess(game, type);
ok(Number(value(body, ['maxHp','maxHP','hp'])) === hp, `${type} has ${hp} HP`);
ok(Number(value(body, ['damage','attack','dmg'], 0)) === damage, `${type} has expected damage ${damage}`);
ok(value(body, ['speed','moveEvery','moveDelay']) != null, `${type} exposes movement speed`);
if (type === 'Sentinel') {
const before = game.projectiles?.length || 0; game.input('Space');
ok((game.projectiles?.length || 0) > before || /shoot|projectile|ranged/i.test(String(value(body, ['special','ability','attackType'], ''))), 'Sentinel has a projectile attack and no melee');
}
}
const { body } = possess(game, 'Brute');
body.hp = 0; game.player.hp = 0; game.tick(1);
ok(game.state === 'ghost', 'dead host ejects the player as a ghost');
ok(Number(value(game.player, ['ghostTimer','timer'], 0)) > 0, 'ejection starts a positive ghost timer');
const spot = adjacentFloor(game); const target = spawn(game, 'Skitterer', spot.x, spot.y); const essence = Number(game.essence || 0);
ok(typeof game.damageEnemy === 'function', 'GAME.damageEnemy(enemy,amount) is exposed for deterministic testing');
game.damageEnemy(target, 999);
ok(Number(game.essence || 0) > essence, 'enemy death drops and awards essence');
ok(typeof game.findPath === 'function', 'GAME.findPath() exposes enemy pathfinding');
const enemy = spawn(game, 'Brute', spot.x, spot.y); const old = position(enemy); game.state = 'ghost'; game.tick(2); const moved = position(enemy);
ok(moved[0] !== old[0] || moved[1] !== old[1] || Math.abs(old[0]-position(game.player)[0]) + Math.abs(old[1]-position(game.player)[1]) <= 1, 'enemy pathfinding advances toward the ghost');
}
const TYPES = ['Brute','Skitterer','Sentinel','Shielder','Bomber','Healer','Phaser','Turret','Charger','Siren','Mimic','Leech'];
function phase3(env) {
const game = env.game; clearEnemies(game);
const signatures = new Set();
let tile = adjacentFloor(game);
for (const type of TYPES) {
const enemy = spawn(game, type, tile.x, tile.y);
const signature = [value(enemy,['maxHp','maxHP','hp']), value(enemy,['damage','attack','dmg'],0), value(enemy,['speed','moveEvery','moveDelay'],1)].join(':');
ok(!signatures.has(signature), `${type} has a distinct HP/damage/speed kit`); signatures.add(signature);
game.enemies.splice(game.enemies.indexOf(enemy), 1);
const { body } = possess(game, type);
game.input('Space'); game.tick(1);
ok(value(body, ['special','ability','attackType','type'], type) != null, `${type} special executes without error`);
}
const originalGrid = game.grid;
const testGrid = [
['wall','wall','wall','wall','wall'],
['wall','floor','wall','floor','wall'],
['wall','floor','wall','floor','wall'],
['wall','floor','floor','floor','wall'],
['wall','wall','wall','wall','wall'],
];
game.grid = testGrid;
const route = game.findPath(1,1,3,1);
game.grid = originalGrid;
ok(Array.isArray(route) && route.length >= 6, 'pathfinder routes around blocking walls');
ok(!route.some(step => position(step)[0] === 2 && position(step)[1] < 3), 'pathfinder never routes through walls');
}
function layout(game) { return gridRows(game).map(row => row.map(tile => isWall(tile) ? '#' : tileName(tile).includes('exit') || tileName(tile).includes('stairs') ? 'E' : '.').join('')).join('\n'); }
function phase4(env) {
const game = env.game;
ok(typeof game.generateFloor === 'function', 'GAME.generateFloor(floor) is exposed');
const layouts = new Set();
for (let i = 0; i < 3; i++) {
game.generateFloor(1);
const text = layout(game); layouts.add(text);
ok(text.includes('E') || gridRows(game).flat().some(tile => /exit|stair/.test(tileName(tile))), 'generated floor contains exit stairs');
}
ok(layouts.size === 3, 'three generated dungeons have different layouts');
ok(typeof game.completeFloor === 'function', 'GAME.completeFloor() is exposed for floor transitions');
game.floor = 1; game.state = 'ghost'; game.completeFloor();
ok(game.state === 'shop', 'shop appears between floors');
ok(Array.isArray(game.shopChoices) && game.shopChoices.length === 3, 'shop presents three choices');
ok(typeof game.buyUpgrade === 'function', 'GAME.buyUpgrade(index) is exposed');
game.essence = 999; const before = JSON.stringify(game.upgrades);
game.buyUpgrade(0);
ok(JSON.stringify(game.upgrades) !== before, 'purchasing a shop choice changes upgrades');
ok(typeof game.save === 'function' && typeof game.load === 'function', 'GAME.save/load are exposed');
game.floor = 4; game.essence = 37;
if (Array.isArray(game.upgrades)) game.upgrades.push('verify_roundtrip'); else game.upgrades.verify_roundtrip = true;
const upgrades = JSON.stringify(game.upgrades); game.save();
ok(env.metrics.storageWrites > 0 && env.storage.has('bodysnatcher_save'), 'save writes bodysnatcher_save to localStorage');
game.floor = 1; game.essence = 0; game.upgrades = Array.isArray(game.upgrades) ? [] : {};
game.load();
ok(Number(game.floor) === 4 && Number(game.essence) === 37 && JSON.stringify(game.upgrades) === upgrades, 'save/load round-trip preserves floor, essence, and upgrades');
}
function phase5(env) {
const game = env.game;
ok(typeof game.newRun === 'function', 'GAME.newRun() is exposed');
game.newRun(); game.floor = 10; game.state = 'ghost'; game.completeFloor();
ok(game.state === 'won' || game.state === 'victory', 'completing floor 10 reaches the win state');
game.newRun(); game.state = 'ghost'; game.player.host = null; game.player.body = null; game.player.ghostTimer = 0; game.player.timer = 0; game.tick(1);
ok(game.state === 'lost' || game.state === 'gameover', 'expired ghost timer reaches the lose state');
const achievements = game.achievements;
ok(achievements && Object.keys(achievements).length >= 8, 'all eight achievements are defined');
ok(typeof game.unlockAchievement === 'function', 'GAME.unlockAchievement(name) is exposed');
for (const name of Object.keys(achievements).slice(0, 3)) game.unlockAchievement(name);
const unlocked = Object.values(game.achievements).filter(item => item === true || item?.unlocked).length;
ok(unlocked >= 3, 'at least three achievements can unlock');
if (typeof game.sound === 'function') game.sound('hit'); else { game.newRun(); game.input('Space'); }
ok(env.metrics.audioCalls > 0, 'Web Audio API is initialized and used');
game.newRun();
const keys = ['ArrowRight','ArrowDown','ArrowLeft','ArrowUp','Space','q','e'];
for (let i = 0; i < 200; i++) { game.input(keys[i % keys.length]); game.tick(1); }
for (let i = 0; i < 3; i++) { if (game.state === 'shop') game.input('Enter'); if (!['won','lost','gameover'].includes(game.state)) game.completeFloor(); }
ok(true, '200-tick movement/combat/transition stress test completes without errors');
}
try {
ok(Number.isInteger(phase) && phase >= 1 && phase <= 5, 'phase argument is 1 through 5');
const env = boot();
const phases = [phase1, phase2, phase3, phase4, phase5];
for (let i = 0; i < phase; i++) phases[i](env);
console.log(`PASS phase ${phase}: ${checks.length} checks`);
for (const check of checks) console.log(` ✓ ${check}`);
} catch (error) {
console.error(`FAIL phase ${phase}: ${error.message}`);
if (process.env.VERBOSE) console.error(error.stack);
process.exitCode = 1;
}