Files
agentic-labs-challenge/body-snatcher/verify.js
T
2026-08-13 15:23:35 +02:00

762 lines
38 KiB
JavaScript

#!/usr/bin/env node
'use strict';
/*
* Body Snatcher — verify.js
* Node-builtin-only test harness (fs, vm, path). No npm packages.
* Loads index.html, evals its inline <script> in a sandboxed context with
* DOM/Canvas/Audio/localStorage/rAF mocks, then asserts on window.GAME.
*
* node verify.js <phase> exit 0 = pass, exit 1 = fail (prints the failing check)
*
* This file is the build contract. The game must expose the window.GAME API
* described in AGENTS.md §Testability. Phase prompts tell the worker exactly
* which fields/behaviours this harness reads, so the gate is unambiguous.
*/
const fs = require('fs');
const vm = require('vm');
const path = require('path');
const INDEX = path.join(__dirname, 'index.html');
const PHASE = parseInt(process.argv[2] || '1', 10);
const VERBOSE = !!process.env.VERBOSE;
const ENEMY_TYPES = ['brute','skitterer','sentinel','shielder','bomber','healer','phaser','turret','charger','siren','mimic','leech'];
const VALID_STATES = ['title','playing','possessed','shop','paused','won','lost'];
let passed = 0;
function ok(msg){ passed++; if (VERBOSE) console.log(' ok: ' + msg); }
function fail(msg){ console.error('\nFAIL [phase ' + PHASE + ']: ' + msg + '\n'); process.exit(1); }
function assert(cond, msg){ if (!cond) fail(msg); ok(msg); }
function tileType(cell){
if (cell == null) return -1;
if (typeof cell === 'number') return cell;
if (typeof cell === 'object') {
if (typeof cell.type === 'number') return cell.type;
if (cell.solid) return 1;
return 0;
}
return -1;
}
function isWall(G, x, y){ return inBounds(G, x, y) && tileType(G.grid[y][x]) === 1; }
function inBounds(G, x, y){ return y >= 0 && y < G.grid.length && x >= 0 && x < G.grid[0].length; }
function manhattan(ax, ay, bx, by){ return Math.abs(ax - bx) + Math.abs(ay - by); }
/* ---- sandbox / mocks ---------------------------------------------------- */
function makeSandbox(){
const captured = []; // every piece of UI text (canvas fillText + DOM text)
const calls = { setItem: [], audioMethods: [], rafQueue: [] };
const grad = { addColorStop(){}, };
function makeCtx(canvas){
const target = { canvas, fillStyle:'#000', strokeStyle:'#000', lineWidth:1, globalAlpha:1,
font:'10px sans-serif', textAlign:'left', textBaseline:'alphabetic', lineCap:'butt',
lineJoin:'miter', miterLimit:10, globalCompositeOperation:'source-over',
shadowColor:'rgba(0,0,0,0)', shadowBlur:0, shadowOffsetX:0, shadowOffsetY:0 };
return new Proxy(target, {
get(t, p){
if (typeof p === 'symbol') return undefined;
if (p === 'measureText') return () => ({ width: 8, actualBoundingBoxAscent: 8,
actualBoundingBoxDescent: 2, actualBoundingBoxLeft: 0, actualBoundingBoxRight: 8 });
if (p === 'createLinearGradient' || p === 'createRadialGradient' || p === 'createConicGradient') return () => grad;
if (p === 'createPattern') return () => ({});
if (p === 'getImageData') return (x, y, w, h) => ({ data: new Uint8ClampedArray(Math.max(1,(w||1))*Math.max(1,(h||1))*4), width: w||1, height: h||1 });
if (p === 'createImageData') return (w, h) => ({ data: new Uint8ClampedArray(Math.max(1,(w||1))*Math.max(1,(h||1))*4), width: w||1, height: h||1 });
if (p === 'getContextAttributes') return () => ({});
if (p === 'getLineDash') return () => [];
if (p === 'getTransform') return () => ({ a:1,b:0,c:0,d:1,e:0,f:0 });
if (p === 'isPointInPath' || p === 'isPointInStroke') return () => false;
if (p === 'fillText' || p === 'strokeText') return (txt) => { if (txt != null) captured.push(String(txt)); };
if (p in t) return t[p];
t[p] = () => {};
return t[p];
},
set(t, p, v){ t[p] = v; return true; },
});
}
function makeEl(tag){
const el = { tagName:(tag||'div').toUpperCase(), nodeName:(tag||'div').toUpperCase(),
style:{}, children:[], childNodes:[], classList:{ add(){},remove(){},toggle(){},contains(){return false;} },
dataset:{}, attributes:{}, value:'', tabIndex:0,
getContext(){ return makeCtx(el); },
appendChild(c){ if (c){ el.children.push(c); el.childNodes.push(c); } return c; },
removeChild(c){ return c; }, insertBefore(c){ return c; }, replaceChild(){},
addEventListener(){}, removeEventListener(){}, dispatchEvent(){},
setAttribute(){}, getAttribute(){ return null; }, removeAttribute(){},
getBoundingClientRect(){ return { left:0, top:0, width:0, height:0, right:0, bottom:0 }; },
focus(){}, blur(){}, click(){}, remove(){}, replaceWith(){},
querySelector(){ return null; }, querySelectorAll(){ return []; },
cloneNode(){ return makeEl(tag); }, contains(){ return false; },
};
let tc = '', ih = '';
Object.defineProperty(el, 'textContent', { get(){ return tc; }, set(v){ tc = String(v); captured.push(tc); } });
Object.defineProperty(el, 'innerHTML', { get(){ return ih; }, set(v){ ih = String(v); captured.push(ih); } });
return el;
}
function makeCanvas(){
const canvas = { width:800, height:576, style:{}, tabIndex:0,
getContext(){ return makeCtx(canvas); },
addEventListener(){}, removeEventListener(){}, dispatchEvent(){},
getBoundingClientRect(){ return { left:0, top:0, width:800, height:576, right:800, bottom:576 }; },
setAttribute(){}, getAttribute(){ return null; }, removeAttribute(){},
appendChild(c){ return c; }, removeChild(c){ return c; }, focus(){}, cloneNode(){ return makeCanvas(); },
};
return canvas;
}
function makeDoc(){
const body = makeEl('body'), head = makeEl('head');
return { readyState:'complete', documentElement:makeEl('html'), body, head,
createElement(t){ t = String(t||'div').toLowerCase(); return t === 'canvas' ? makeCanvas() : makeEl(t); },
createElementNS(ns, t){ return makeEl(t); },
createTextNode(t){ const e = makeEl('#text'); e.textContent = String(t); return e; },
getElementById(){ return null; }, getElementsByTagName(){ return []; },
getElementsByClassName(){ return []; }, querySelector(){ return null; }, querySelectorAll(){ return []; },
addEventListener(){}, removeEventListener(){}, dispatchEvent(){},
createEvent(){ return { initEvent(){}, initCustomEvent(){} }; },
get defaultView(){ return sandbox; },
};
}
function makeLocalStorage(){
const store = {};
return {
getItem(k){ return Object.prototype.hasOwnProperty.call(store, k) ? store[k] : null; },
setItem(k, v){ store[k] = String(v); calls.setItem.push(String(k)); },
removeItem(k){ delete store[k]; },
clear(){ Object.keys(store).forEach(k => delete store[k]); },
key(i){ return Object.keys(store)[i] || null; },
get length(){ return Object.keys(store).length; },
_raw: store,
};
}
function makeAudio(){
const node = { connect(){ return node; }, disconnect(){}, start(){}, stop(){}, noteOn(){}, noteOff(){},
frequency:{ value:440, setValueAtTime(){}, linearRampToValueAtTime(){}, exponentialRampToValueAtTime(){} },
gain:{ value:1, setValueAtTime(){}, linearRampToValueAtTime(){}, exponentialRampToValueAtTime(){} },
type:'sine', detune:{ value:0, setValueAtTime(){} }, Q:{ value:1, setValueAtTime(){} },
delayTime:{ value:0, setValueAtTime(){} }, playbackRate:{ value:1 }, positionX:{value:0,setValueAtTime(){}}, };
const ctx = { destination:node, listener:{}, currentTime:0, sampleRate:44100, state:'running', baseLatency:0,
createOscillator(){ calls.audioMethods.push('osc'); return node; },
createGain(){ calls.audioMethods.push('gain'); return node; },
createBufferSource(){ calls.audioMethods.push('src'); return node; },
createBuffer(){ calls.audioMethods.push('buf'); return { getChannelData(){ return new Float32Array(1); }, duration:0, length:1, numberOfChannels:1, sampleRate:44100 }; },
createDynamicsCompressor(){ return node; }, createBiquadFilter(){ return node; },
createWaveShaper(){ return node; }, createDelay(){ return node; }, createPanner(){ return node; },
createAnalyser(){ return node; }, createScriptProcessor(){ return node; },
decodeAudioData(){ return Promise.resolve({ getChannelData(){ return new Float32Array(1); } }); },
resume(){ return Promise.resolve(); }, suspend(){ return Promise.resolve(); }, close(){ return Promise.resolve(); },
addEventListener(){}, removeEventListener(){}, };
return ctx;
}
const sandbox = {
console: VERBOSE ? console : { log(){}, error(){}, warn(){}, info(){}, debug(){} },
setTimeout: () => 0, clearTimeout(){}, setInterval: () => 0, clearInterval(){},
requestAnimationFrame: (cb) => { calls.rafQueue.push(cb); return calls.rafQueue.length; },
cancelAnimationFrame(){},
queueMicrotask(f){ try { f(); } catch (e) {} },
localStorage: makeLocalStorage(),
document: makeDoc(),
navigator: { userAgent:'node', platform:'node', language:'en', vendor:'node' },
location: { href:'about:blank', origin:'', protocol:'about:', host:'', hostname:'', port:'', pathname:'/index.html', search:'', hash:'', reload(){} },
performance: { now: () => Date.now(), timeOrigin: Date.now(), mark(){}, measure(){} },
devicePixelRatio: 1, innerWidth: 800, innerHeight: 576, screen: { width:800, height:600 },
matchMedia(){ return { matches:false, media:'', addEventListener(){}, removeEventListener(){}, addListener(){}, removeListener(){} }; },
customElements: { define(){} },
AudioContext: function(){ return makeAudio(); },
webkitAudioContext: function(){ return makeAudio(); },
OfflineAudioContext: function(){ return makeAudio(); },
addEventListener(){}, removeEventListener(){}, dispatchEvent(){}, postMessage(){}, alert(){}, confirm(){ return false; },
atob: (s) => Buffer.from(s, 'base64').toString('binary'),
btoa: (s) => Buffer.from(s, 'binary').toString('base64'),
TextEncoder, TextDecoder, URL, URLSearchParams,
crypto: { getRandomValues(arr){ for (let i=0;i<arr.length;i++) arr[i] = Math.floor(Math.random()*256); return arr; }, randomUUID(){ return '00000000-0000-4000-8000-000000000000'; } },
fetch(){ return Promise.resolve({ ok:true, status:200, json(){ return Promise.resolve({}); }, text(){ return Promise.resolve(''); } }); },
structuredClone: (v) => { try { return JSON.parse(JSON.stringify(v)); } catch (e) { return v; } },
Image: function(){ return makeEl('img'); },
__captured: captured, __calls: calls,
};
sandbox.window = sandbox;
sandbox.self = sandbox;
sandbox.globalThis = sandbox;
return sandbox;
}
function flushRAF(sandbox){
const q = sandbox.__calls.rafQueue.splice(0);
for (const cb of q) { try { cb && cb(); } catch (e) { /* a render error in mock ctx is non-fatal for logic checks */ } }
}
function loadGame(){
if (!fs.existsSync(INDEX)) fail('index.html not found — build phase produced no file');
const html = fs.readFileSync(INDEX, 'utf8');
// 0 = floor, 1 = wall, 2 = door, 3 = exit, 4 = shop, 5 = chest
const scriptRe = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
let m, code = '', sawScript = false, external = false;
while ((m = scriptRe.exec(html))) {
sawScript = true;
if (/\bsrc\s*=/.test(m[1] || '')) { external = true; continue; }
code += m[2] + '\n';
}
if (html.indexOf('<canvas') === -1) fail('index.html has no <canvas> element');
if (!sawScript) fail('index.html has no <script> element');
if (external) fail('index.html references an external script src= (zero-dependency rule)');
if (/\bimport\s+[\s\S]*?\bfrom\b/.test(code) || /\bexport\b/.test(code)) fail('index.html uses ES modules (forbidden — inline script only)');
const sandbox = makeSandbox();
vm.createContext(sandbox);
try { vm.runInContext(code, sandbox, { filename:'index.html' }); }
catch (e) { fail('Script threw while loading: ' + ((e && e.stack) || e)); }
const G = sandbox.window.GAME;
if (!G || typeof G !== 'object') fail('window.GAME is not defined');
return { sandbox, G, code, html };
}
/* ---- helpers that drive the game deterministically ---------------------- */
function startRun(G){
if (G.state === 'title' || G.state === 'won' || G.state === 'lost') {
if (typeof G.newRun === 'function') G.newRun();
else { try { G.input('Enter'); } catch (e) {} }
}
if (G.state === 'title') { try { G.input('Enter'); } catch (e) {} }
if (G.state !== 'playing' && G.state !== 'possessed') fail('could not enter a run (state=' + G.state + ')');
}
function tick(G, n){ n = n || 1; try { G.tick(n); } catch (e) { fail('tick(' + n + ') threw: ' + ((e && e.stack) || e)); } }
function input(G, key){ try { G.input(key); } catch (e) { fail("input('" + key + "') threw: " + ((e && e.stack) || e)); } }
function findExit(G){ for (let y=0;y<G.grid.length;y++) for (let x=0;x<G.grid[0].length;x++) if (tileType(G.grid[y][x])===3) return {x,y}; return null; }
function findAdjacentFloor(G, x, y){
for (const [dx,dy] of [[1,0],[-1,0],[0,1],[0,-1]]) { const nx=x+dx, ny=y+dy; if (inBounds(G,nx,ny) && tileType(G.grid[ny][nx])===0) return {x:nx,y:ny}; }
return null;
}
function setTile(G, x, y, type){
const sample = G.grid[0] && G.grid[0][0];
if (typeof sample === 'number') G.grid[y][x] = type;
else if (sample && typeof sample === 'object') G.grid[y][x] = Object.assign({}, sample, { type, solid: type === 1 });
else G.grid[y][x] = type;
}
function bfsPath(G, sx, sy, tx, ty){
const H = G.grid.length, W = G.grid[0].length;
const seen = Array.from({length:H}, () => new Array(W).fill(false));
const prev = Array.from({length:H}, () => new Array(W).fill(null));
const q = [[sx,sy]]; seen[sy][sx] = true;
while (q.length) {
const [x,y] = q.shift();
if (x===tx && y===ty) break;
for (const [dx,dy] of [[1,0],[-1,0],[0,1],[0,-1]]) {
const nx=x+dx, ny=y+dy;
if (nx<0||ny<0||nx>=W||ny>=H||seen[ny][nx]) continue;
if (tileType(G.grid[ny][nx])===1) continue;
seen[ny][nx]=true; prev[ny][nx]=[x,y]; q.push([nx,ny]);
}
}
if (!seen[ty][tx]) return null;
const path=[]; let cx=tx, cy=ty;
while (!(cx===sx && cy===sy)) { const p=prev[cy][cx]; if (!p) return null; path.unshift([cx,cy]); cx=p[0]; cy=p[1]; }
return path;
}
function dirKey(dx, dy){ if (dx>0) return 'ArrowRight'; if (dx<0) return 'ArrowLeft'; if (dy>0) return 'ArrowDown'; if (dy<0) return 'ArrowUp'; return null; }
/* walk the player (ghost or current host) to a tile, retrying a direction for slow hosts */
function walkTo(G, tx, ty, maxSteps){
maxSteps = maxSteps || 300;
let steps = 0;
while ((G.player.x !== tx || G.player.y !== ty) && steps < maxSteps) {
const path = bfsPath(G, G.player.x, G.player.y, tx, ty);
if (!path || !path.length) return false;
const [nx,ny] = path[0];
const key = dirKey(nx - G.player.x, ny - G.player.y);
if (!key) return false;
let guard = 0;
while ((G.player.x !== nx || G.player.y !== ny) && guard < 8) { input(G, key); guard++; if (G.state==='won'||G.state==='shop'||G.state==='lost') return G.player.x===tx && G.player.y===ty; }
steps++;
}
return G.player.x === tx && G.player.y === ty;
}
/* find a floor tile within maxDist of (x,y) with a clear straight (Bresenham) LOS */
function findTileWithLOS(G, x, y, minDist, maxDist){
const H = G.grid.length, W = G.grid[0].length;
for (let dy=-maxDist; dy<=maxDist; dy++) for (let dx=-maxDist; dx<=maxDist; dx++) {
if (dx===0 && dy===0) continue;
const d = Math.max(Math.abs(dx), Math.abs(dy));
if (d < minDist || d > maxDist) continue;
const tx=x+dx, ty=y+dy;
if (!inBounds(G,tx,ty) || tileType(G.grid[ty][tx]) !== 0) continue;
// Bresenham LOS
let clear = true, x0=x, y0=y, x1=tx, y1=ty;
let err = Math.abs(x1-x0), sx = x0<x1?1:-1, e2;
const ddx = Math.abs(x1-x0), ddy = -Math.abs(y1-y0), syy = y0<y1?1:-1;
let cx=x0, cy=y0, er = ddx+ddy;
for (;;) {
if (!(cx===x && cy===y) && tileType(G.grid[cy][cx])===1) { clear=false; break; }
if (cx===x1 && cy===y1) break;
e2 = 2*er;
if (e2 >= ddy) { er += ddy; cx += sx; }
if (e2 <= ddx) { er += ddx; cy += syy; }
}
if (clear) return { x:tx, y:ty };
}
return null;
}
function possessType(G, type){
const spot = findAdjacentFloor(G, G.player.x, G.player.y);
if (!spot) fail('no adjacent floor tile to spawn ' + type);
const e = G.spawn(type, spot.x, spot.y);
if (!e) fail('spawn(' + type + ') returned nothing');
// face/possess: one Space, then a few ticks (possession may take a turn)
input(G, ' '); for (let i=0;i<6 && G.state!=='possessed'; i++) tick(G,1);
if (G.state !== 'possessed') fail('could not possess ' + type + ' (state=' + G.state + ')');
return e;
}
/* =========================================================================
* PHASE 1 — engine, grid, ghost movement, timer, title controls, bestiary
* ========================================================================= */
function phase1(){
const { sandbox, G } = loadGame();
assert(typeof G.start === 'function', 'GAME.start() exists');
let threw = false; try { G.start(); } catch (e) { threw = true; console.error(e); }
assert(!threw, 'GAME.start() does not throw');
assert(VALID_STATES.indexOf(G.state) !== -1, 'GAME.state is valid (' + G.state + ')');
// must NOT auto-start into play
assert(G.state === 'title', 'GAME.start() leaves the game at title (no auto-start)');
assert(G.grid && G.grid.length > 0 && G.grid[0].length > 0, 'grid exists');
let walls = 0, floors = 0;
for (const row of G.grid) for (const cell of row) { const t = tileType(cell); if (t===1) walls++; else if (t===0) floors++; }
assert(walls > 0, 'grid has wall tiles (' + walls + ')');
assert(floors > 0, 'grid has floor tiles (' + floors + ')');
// ghost timer present and at least 15s at full
startRun(G);
const t = G.player && G.player.timer;
assert(typeof t === 'number', 'G.player.timer is a number');
assert(t >= 15, 'starting ghost timer >= 15 seconds (got ' + t + ')');
// movement
const bx = G.player.x, by = G.player.y;
let moved = false;
for (const d of ['ArrowRight','ArrowLeft','ArrowDown','ArrowUp']) {
input(G, d);
if (G.player.x !== bx || G.player.y !== by) { moved = true; break; }
}
assert(moved, 'ghost moves with arrow keys');
// ghost never ends on a wall tile after any input
for (const d of ['ArrowRight','ArrowLeft','ArrowDown','ArrowUp','w','a','s','d']) { input(G, d); }
assert(!isWall(G, G.player.x, G.player.y), 'ghost never stands on a wall tile');
// title controls + bestiary via captured text
G.start();
flushRAF(sandbox);
const titleText = sandbox.__captured.join(' \n').toLowerCase();
const need = ['wasd', 'arrow', 'space', 'enter', 'esc'];
const missingCtrl = need.filter(k => titleText.indexOf(k) === -1);
assert(missingCtrl.length === 0, 'title screen explains controls (missing: ' + (missingCtrl.join(',')||'none') + ')');
assert(titleText.indexOf('q') !== -1 && titleText.indexOf('e') !== -1, 'title mentions Q/E facing keys');
// bestiary reachable from title (press 'l'); lists enemies with behaviour + possessed kit
sandbox.__captured.length = 0;
input(G, 'l'); flushRAF(sandbox);
const legend = sandbox.__captured.join(' \n').toLowerCase();
const known = ['brute','skitterer','sentinel'].filter(n => legend.indexOf(n) !== -1);
assert(known.length >= 3, 'bestiary lists at least the 3 implemented enemies (' + known.join(',') + ')');
assert(/\bhp\b|health|hit\s*point/.test(legend), 'bestiary describes possessed kit (hp/damage info)');
console.log('PHASE 1 PASSED (' + passed + ' checks)');
}
/* =========================================================================
* PHASE 2 — possession, abandon, brute/skitterer/sentinel, pathfind, no friendly fire, aggro
* ========================================================================= */
function phase2(){
const { G } = loadGame();
G.start(); startRun(G);
// Brute / Skitterer / Sentinel stat contracts
const b = G.spawn('brute', G.player.x, G.player.y); // spawn fn ignores occupancy for stat read
assert((b.maxHp === 8) || (b.hp === 8), 'Brute hp 8 (maxHp=' + b.maxHp + ', hp=' + b.hp + ')');
assert(b.damage === 3, 'Brute damage 3 (got ' + b.damage + ')');
assert(b.speed >= 2, 'Brute slow movement (speed>=2, got ' + b.speed + ')');
const sk = G.spawn('skitterer', G.player.x, G.player.y);
assert((sk.maxHp === 2) || (sk.hp === 2), 'Skitterer hp 2');
assert(sk.damage === 1, 'Skitterer damage 1');
assert(sk.speed === 2, 'Skitterer moves every 2 turns (speed=2, got ' + sk.speed + ')');
const se = G.spawn('sentinel', G.player.x, G.player.y);
assert((se.maxHp === 4) || (se.hp === 4), 'Sentinel hp 4');
// possession
const spot = findAdjacentFloor(G, G.player.x, G.player.y);
assert(spot, 'adjacent floor exists for possession test');
G.spawn('brute', spot.x, spot.y);
input(G, ' '); for (let i=0;i<6 && G.state!=='possessed'; i++) tick(G,1);
assert(G.state === 'possessed', 'SPACE on adjacent enemy -> possessed');
assert(G.player.host && G.player.host.type === 'brute', 'possessed host is the brute');
assert(G.player.host.hp > 0, 'host has HP after possession');
// voluntary ABANDON (X)
const timerBeforePossess = G.player.timer;
input(G, 'x'); for (let i=0;i<3 && G.state==='possessed'; i++) tick(G,1);
assert(G.state === 'playing', 'abandon (X) returns to ghost (state=playing)');
assert(G.player.host == null, 'player.host is null after abandon');
assert(typeof G.player.timer === 'number' && G.player.timer > 0, 'ghost timer > 0 after abandon (' + G.player.timer + ')');
assert(G.player.timer <= timerBeforePossess + 0.001, 'abandon does NOT refresh the timer (resumed, not reset)');
// former host survived + lockout
const survivors = (G.enemies || []).filter(e => e.type === 'brute');
assert(survivors.length > 0, 'abandoned host survives in enemies[]');
const locked = survivors.find(e => e.lockout > 0 || e.rePossessLockout > 0 || e.pacified > 0);
assert(locked || survivors.some(e => e.x === spot.x && e.y === spot.y), 'abandoned host present (lockout field tracked if exposed)');
// re-possess lockout: trying to immediately re-possess the same host should NOT work
if (G.state === 'playing') {
input(G, ' '); for (let i=0;i<4; i++) tick(G,1);
// we do not hard-assert state here (lockout impl varies), but it must not crash — already proven by reaching here
}
// pathfinding: enemy within aggro & LOS closes distance
G.start(); startRun(G);
const los = findTileWithLOS(G, G.player.x, G.player.y, 2, 5);
if (los) {
const e = G.spawn('skitterer', los.x, los.y);
const d0 = manhattan(G.player.x, G.player.y, e.x, e.y);
let closed = false;
for (let i=0;i<12;i++) { tick(G,1); if (manhattan(G.player.x,G.player.y,e.x,e.y) < d0) { closed = true; break; } }
assert(closed, 'enemy within aggro+LOS pathfinds closer to the ghost');
} else {
// fall back: brute closes
const near = findAdjacentFloor(G, G.player.x, G.player.y);
if (near) { const e = G.spawn('brute', near.x, near.y); tick(G,4); ok('aggro/pathfind exercised via adjacent spawn'); }
}
// aggro isolation: an enemy far away with LOS blocked stays docile
G.start(); startRun(G);
const far = findTileWithLOS(G, G.player.x, G.player.y, 7, 14);
if (far) {
const e = G.spawn('brute', far.x, far.y);
const d0 = manhattan(G.player.x, G.player.y, e.x, e.y);
let minD = d0;
for (let i=0;i<10;i++) { tick(G,1); minD = Math.min(minD, manhattan(G.player.x,G.player.y,e.x,e.y)); }
assert(minD >= d0 - 2, 'far enemy (no aggro) does NOT beeline (d0=' + d0 + ', minD=' + minD + ')');
if (typeof e.aggroed !== 'undefined') assert(e.aggroed === false, 'far enemy.aggroed === false');
} else {
ok('skipped far-aggro check (no far LOS tile in this layout)');
}
// no friendly fire: two brutes adjacent, far from player, neither loses HP
G.start(); startRun(G);
const base = findTileWithLOS(G, G.player.x, G.player.y, 8, 12) || { x: G.player.x+8, y: G.player.y };
if (inBounds(G, base.x, base.y) && tileType(G.grid[base.y][base.x]) === 0) {
const e1 = G.spawn('brute', base.x, base.y);
const s2 = findAdjacentFloor(G, base.x, base.y);
if (s2) {
const e2 = G.spawn('brute', s2.x, s2.y);
const hp1 = e1.hp, hp2 = e2.hp;
for (let i=0;i<12;i++) tick(G,1);
assert(e1.hp === hp1 && e2.hp === hp2, 'enemies do NOT damage each other (hp unchanged)');
} else ok('skipped friendly-fire check (no adjacent floor)');
} else ok('skipped friendly-fire check (no open far tile)');
// Sentinel overheats: burst then a multi-turn no-fire window
G.start(); startRun(G);
const slos = findTileWithLOS(G, G.player.x, G.player.y, 3, 5);
if (slos) {
const sent = G.spawn('sentinel', slos.x, slos.y);
const beforeProj = (G.projectiles || []).length;
let fired = false, cooldownSeen = false, sinceLast = 99;
for (let i=0;i<30;i++) {
tick(G,1);
const now = (G.projectiles || []).length;
if (now > beforeProj || (sent.shotsFired != null)) { fired = true; sinceLast = 0; }
else sinceLast++;
if (fired && sinceLast >= 3) cooldownSeen = true;
if (typeof sent.overheatLeft === 'number' && sent.overheatLeft > 0) cooldownSeen = true;
}
assert(fired, 'Sentinel fires projectiles when aggroed');
assert(cooldownSeen, 'Sentinel OVERHEATS into a multi-turn no-fire window');
} else fail('no LOS tile 3-5 away for Sentinel overheat test (procgen unlucky)');
// killing a host ejects ghost with timer > 0; essence increases on kill
G.start(); startRun(G);
const enemy = possessType(G, 'brute');
// damage the host to death via self/another: easiest is set hp low and let an adjacent enemy hit, or directly tick until dead.
// We instead kill an unrelated enemy using the host's attack to confirm essence gain.
const essBefore = G.essence;
// place a weak enemy in front and attack
const facing = G.player.facing || { x:1, y:0 };
const fx = G.player.x + (facing.x != null ? facing.x : 1), fy = G.player.y + (facing.y != null ? facing.y : 0);
if (inBounds(G, fx, fy) && tileType(G.grid[fy][fx]) === 0) {
const victim = G.spawn('skitterer', fx, fy);
victim.hp = 1; victim.maxHp = 1;
for (let i=0;i<6 && (G.enemies||[]).indexOf(victim) !== -1; i++) { input(G, ' '); tick(G,1); }
if (G.essence > essBefore) ok('essence increases on kill');
else ok('essence check skipped (host attack did not connect this layout)');
} else ok('essence-on-kill check skipped (no floor in front)');
console.log('PHASE 2 PASSED (' + passed + ' checks)');
}
/* =========================================================================
* PHASE 3 — all 12 enemies, distinct stats, specials, pathfind-around-wall, AoE friendly-fire, turret overheat
* ========================================================================= */
function phase3(){
const { G } = loadGame();
G.start(); startRun(G);
// all 12 instantiable
const tuples = [];
for (const t of ENEMY_TYPES) {
let e;
try { e = G.spawn(t, G.player.x, G.player.y); } catch (err) { fail('spawn(' + t + ') threw: ' + err); }
assert(e && typeof e === 'object', 'spawn(' + t + ') returns an enemy');
const hp = e.maxHp != null ? e.maxHp : e.hp;
assert(typeof hp === 'number' && hp > 0, t + ' has positive hp');
assert(typeof e.damage === 'number', t + ' has numeric damage');
assert(typeof e.speed === 'number', t + ' has numeric speed');
tuples.push({ t, hp, dmg: e.damage, spd: e.speed });
}
// distinct (hp,damage,speed)
const seen = {};
for (const u of tuples) {
const k = u.hp + '/' + u.dmg + '/' + u.spd;
if (seen[k]) fail('two enemies share identical (hp,damage,speed): ' + seen[k] + ' & ' + u.t + ' = ' + k);
seen[k] = u.t;
}
ok('all 12 enemies have distinct (hp,damage,speed) tuples');
// each special ability executes without error when triggered (possess + Space)
for (const t of ENEMY_TYPES) {
G.start(); startRun(G);
let okSpecial = false;
try {
possessType(G, t);
input(G, ' '); tick(G, 2);
okSpecial = true;
} catch (e) { fail('special for ' + t + ' threw: ' + ((e && e.stack) || e)); }
if (!okSpecial) fail('special for ' + t + ' did not run');
ok('special ability for ' + t + ' runs without error');
}
// pathfinder navigates AROUND a wall (not through it)
G.start(); startRun(G);
const los = findTileWithLOS(G, G.player.x, G.player.y, 3, 5);
if (los) {
// drop a single wall on the direct line between enemy and player
const wx = G.player.x + Math.sign(los.x - G.player.x) * (Math.abs(los.x - G.player.x) >= 1 ? 1 : 0);
const wy = G.player.y + Math.sign(los.y - G.player.y) * (Math.abs(los.y - G.player.y) >= 1 ? 1 : 0);
const wallPlaced = (wx !== G.player.x || wy !== G.player.y) && tileType(G.grid[wy] && G.grid[wy][wx]) === 0;
if (wallPlaced) setTile(G, wx, wy, 1);
const e = G.spawn('brute', los.x, los.y);
const d0 = manhattan(G.player.x, G.player.y, e.x, e.y);
let reached = false, onWall = false;
for (let i=0;i<24;i++) {
tick(G,1);
if (isWall(G, e.x, e.y)) onWall = true;
if (manhattan(G.player.x, G.player.y, e.x, e.y) < d0) reached = true;
if (manhattan(G.player.x, G.player.y, e.x, e.y) <= 1) break;
}
assert(!onWall, 'enemy never walks through the wall tile');
assert(reached, 'enemy pathfinds AROUND the wall (distance decreased)');
} else fail('no LOS tile 3-5 away for pathfind-around-wall test');
// AoE enemies never reduce OTHER enemies' HP
// Bomber: victim adjacent to bomber + player in blast; detonate; victim HP unchanged
G.start(); startRun(G);
const center = findTileWithLOS(G, G.player.x, G.player.y, 2, 4) || findAdjacentFloor(G, G.player.x, G.player.y);
if (center) {
const victimSpot = findAdjacentFloor(G, center.x, center.y);
if (victimSpot) {
const victim = G.spawn('skitterer', victimSpot.x, victimSpot.y);
const vhp = victim.hp;
const bomber = G.spawn('bomber', center.x, center.y);
// aggro bomber by proximity + let it act / die
for (let i=0;i<20;i++) { tick(G,1); if (victim.hp !== vhp) break; }
assert(victim.hp === vhp, 'Bomber AoE does not damage other enemies');
} else ok('skipped bomber AoE check (no adjacent floor)');
} else ok('skipped bomber AoE check (no center tile)');
// Turret overheat: burst then forced downtime
G.start(); startRun(G);
const tlos = findTileWithLOS(G, G.player.x, G.player.y, 3, 6);
if (tlos) {
const turret = G.spawn('turret', tlos.x, tlos.y);
let fired = false, cooldown = false, since = 99;
for (let i=0;i<40;i++) {
const before = (G.projectiles || []).length;
tick(G,1);
const after = (G.projectiles || []).length;
if (after > before) { fired = true; since = 0; } else since++;
if (fired && since >= 3) cooldown = true;
if (typeof turret.overheatLeft === 'number' && turret.overheatLeft > 0) cooldown = true;
}
assert(fired, 'Turret fires when aggroed');
assert(cooldown, 'Turret OVERHEATS into a multi-turn no-fire window');
} else fail('no LOS tile 3-6 away for Turret overheat test');
console.log('PHASE 3 PASSED (' + passed + ' checks)');
}
/* =========================================================================
* PHASE 4 — procgen variance, exit tile, shop on transition, buy, save/load
* ========================================================================= */
function phase4(){
const { sandbox, G } = loadGame();
G.start(); startRun(G);
// exit tile exists
const ex1 = findExit(G);
assert(ex1, 'exit tile exists on the floor');
// 3 dungeons differ (wall layout)
const layouts = [];
for (let i=0;i<3;i++) {
G.start();
if (typeof G.newRun === 'function') G.newRun(); else { input(G,'Enter'); }
let sig = '';
for (const row of G.grid) for (const cell of row) sig += tileType(cell) === 1 ? '#' : '.';
layouts.push(sig);
}
const unique = new Set(layouts).size;
assert(unique >= 2, 'procedural generation produces differing layouts (' + unique + '/3 unique)');
// exit exists on each floor 1..10
let allExit = true;
for (let n=1;n<=10;n++) { try { G.setFloor(n); } catch(e){ fail('setFloor(' + n + ') threw: ' + e); } if (!findExit(G)) allExit = false; }
assert(allExit, 'every floor 1..10 has an exit tile');
// shop appears on floor transition (exit floor 2 -> shop, since floor 3 is a shop floor)
G.setFloor(2);
const ex2 = findExit(G);
if (ex2) {
const reached = walkTo(G, ex2.x, ex2.y);
if (reached && G.state === 'shop') ok('stepping on exit after a pre-shop floor opens the shop');
else {
// some designs shop on a different cadence; fall back to debug openShop
if (typeof G.openShop === 'function') { G.openShop(); assert(G.state === 'shop', 'openShop() enters shop state (walk fallback)'); }
else fail('shop did not appear on floor transition and no openShop() debug');
}
} else fail('floor 2 has no exit to test shop transition');
// shop has 3 choices; buying changes upgrades
if (typeof G.openShop === 'function') G.openShop();
assert(G.state === 'shop', 'in shop state');
const choices = G.choices || G.shopChoices || G.upgradeChoices;
assert(Array.isArray(choices) && choices.length === 3, 'shop offers exactly 3 choices (got ' + (choices && choices.length) + ')');
const upBefore = JSON.stringify(G.upgrades || {});
try { G.buy(0); } catch (e) { fail('buy(0) threw: ' + e); }
const upAfter = JSON.stringify(G.upgrades || {});
assert(upBefore !== upAfter, 'purchasing an upgrade changes GAME.upgrades');
// save writes localStorage; round-trip persists floor/essence/upgrades
G.setFloor(4);
if (typeof G.addEssence === 'function') G.addEssence(7); else if (G.essence != null) G.essence += 7;
const F = G.floor, E = G.essence, U = JSON.parse(JSON.stringify(G.upgrades || {}));
sandbox.__calls.setItem.length = 0;
try { G.save(); } catch (e) { fail('save() threw: ' + e); }
assert(sandbox.__calls.setItem.indexOf('bodysnatcher_save') !== -1, "save() calls localStorage.setItem('bodysnatcher_save')");
const blob = sandbox.localStorage.getItem('bodysnatcher_save');
assert(blob != null, 'save writes a non-null blob');
// mutate, then load, assert restored
if (G.essence != null) G.essence = 0;
try { G.load(); } catch (e) { fail('load() threw: ' + e); }
assert(G.floor === F, 'load() restores floor (' + G.floor + ' vs ' + F + ')');
assert(G.essence === E, 'load() restores essence (' + G.essence + ' vs ' + E + ')');
assert(JSON.stringify(G.upgrades || {}) === JSON.stringify(U), 'load() restores upgrades');
console.log('PHASE 4 PASSED (' + passed + ' checks)');
}
/* =========================================================================
* PHASE 5 — win, lose, achievements, audio, 200-tick stress
* ========================================================================= */
function phase5(){
const { sandbox, G } = loadGame();
const calls = sandbox.__calls;
// lose: ghost timer drains to 0
G.start(); startRun(G);
// ensure we are a ghost (abandon any host)
if (G.state === 'possessed') { input(G,'x'); tick(G,2); }
let drained = false;
for (let i=0;i<300;i++) {
tick(G,1);
if (G.state === 'lost') { drained = true; break; }
}
assert(drained, 'ghost timer expiring reaches the LOST state');
// win: reach floor 10 exit
G.start();
try { G.setFloor(10); } catch (e) { fail('setFloor(10) threw: ' + e); }
if (G.state === 'title') startRun(G);
if (G.state !== 'playing' && G.state !== 'possessed') { try { G.setFloor(10); } catch(e){} }
const ex = findExit(G);
assert(ex, 'floor 10 has an exit');
if (G.state === 'possessed') { input(G,'x'); tick(G,2); }
const reached = walkTo(G, ex.x, ex.y, 400);
if (G.state === 'won') ok('reaching floor 10 exit -> WON');
else if (!reached) fail('could not walk ghost to floor 10 exit (path blocked) — win unreachable');
else {
// landed on exit but state did not flip; nudge
tick(G, 3);
assert(G.state === 'won', 'stepping on floor 10 exit triggers win (state=' + G.state + ')');
}
// achievements: trigger at least 3
G.start(); startRun(G);
const achBefore = countAchievements(G);
// First Possession
try { possessType(G, 'brute'); } catch (e) { /* ignore if layout fails */ }
// Deep Diver: floor 7
try { G.setFloor(7); startRun(G); } catch (e) {}
// Essence Hoarder: bump essence to 30 if settable
if (G.essence != null) { G.essence = 30; tick(G,1); }
tick(G, 5);
const achAfter = countAchievements(G);
assert(achAfter - achBefore >= 3 || achAfter >= 3, 'at least 3 achievements trigger (before=' + achBefore + ', after=' + achAfter + ')');
// audio methods invoked
calls.audioMethods.length = 0;
G.start(); startRun(G);
try { possessType(G, 'brute'); input(G,' '); tick(G,2); } catch (e) {}
// some games init audio lazily; force a known sound path
if (typeof G.playSound === 'function') { try { G.playSound('hit'); } catch (e) {} }
if (calls.audioMethods.length === 0) { try { possessType(G, 'skitterer'); input(G,' '); tick(G,3); } catch (e) {} }
assert(calls.audioMethods.length > 0, 'audio context methods are called (sound system exercised)');
// 200-tick stress test: move, possess, attack, descend 3 floors, no throw
G.start(); startRun(G);
let stressErr = null;
try {
for (let f=1; f<=3; f++) {
if (G.floor !== f) { try { G.setFloor(f); } catch (e) {} }
// possess something if possible
const sp = findAdjacentFloor(G, G.player.x, G.player.y);
if (sp && G.state === 'playing') { G.spawn('brute', sp.x, sp.y); input(G,' '); tick(G,3); }
// attack + move around
for (let i=0;i<30;i++) {
input(G, ['ArrowUp','ArrowRight','ArrowDown','ArrowLeft',' '][i%5]);
tick(G,1);
}
// descend if an exit is reachable
const e = findExit(G);
if (e) { if (G.state==='possessed'){input(G,'x');tick(G,2);} walkTo(G, e.x, e.y, 120); tick(G,2); }
}
for (let i=0;i<60;i++) tick(G,1);
} catch (e) { stressErr = e; }
assert(!stressErr, '200-tick stress test throws no error (' + ((stressErr && stressErr.message)||'') + ')');
console.log('PHASE 5 PASSED (' + passed + ' checks)');
}
function countAchievements(G){
const a = G.achievements;
if (!a) return 0;
if (typeof a.size === 'number') return a.size;
if (Array.isArray(a)) return a.length;
return Object.keys(a).length;
}
/* ---- run ---------------------------------------------------------------- */
const phases = { 1: phase1, 2: phase2, 3: phase3, 4: phase4, 5: phase5 };
const fn = phases[PHASE];
if (!fn) fail('unknown phase ' + PHASE + ' (use 1..5)');
try { fn(); } catch (e) { fail('uncaught exception in phase ' + PHASE + ': ' + ((e && e.stack) || e)); }
process.exit(0);