(Body Snatcher) Pass 3 Addendum

This commit is contained in:
AlexKucera committed 2026-08-13 07:30:24 +02:00
1 parent c61d73bdfc
commit 7fcbfcd476
2 files changed
+2969

No files matched your search

File diff suppressed because it is too large. Load diff
+316
View File
@@ -0,0 +1,316 @@
#!/usr/bin/env node
'use strict';
/*
verify.js — headless test harness for Body Snatcher (single index.html).
Uses only Node builtins: fs, vm, path.
Usage: node verify.js <phase> (phase 1..5). Exit 0 = pass, 1 = fail.
*/
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const PHASE = parseInt(process.argv[2] || '1', 10);
const HTML = path.join(__dirname, 'index.html');
const SAVE_KEY = 'bodysnatcher_save';
const ENEMIES = ['Brute','Skitterer','Sentinel','Shielder','Bomber','Healer','Phaser','Turret','Charger','Siren','Mimic','Leech'];
const VALID_STATES = ['title','playing','possessed','shop','paused','won','lost'];
function fail(msg){ const e = new Error(msg || 'assertion failed'); e._assert = true; throw e; }
function assert(c, m){ if (!c) fail(m || 'assertion failed'); }
// ---------------------------------------------------------------- read source
if (!fs.existsSync(HTML)) { console.error(`FAIL: index.html not found`); process.exit(1); }
const SRC = fs.readFileSync(HTML, 'utf8');
const scriptRe = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
let mm, SCRIPT = '', externalSrc = false;
while ((mm = scriptRe.exec(SRC))) {
if (/\bsrc\s*=/.test(mm[1] || '')) externalSrc = true;
SCRIPT += '\n' + (mm[2] || '');
}
if (!SCRIPT.trim()) { /* maybe the game is all inline anyway; keep going */ }
// ----------------------------------------------------------------- mocks
function noop(){ return undefined; }
const grad = { addColorStop: noop, addColorStop: noop };
const texts = [];
function makeCtx(canvas){
const base = {
canvas,
fillStyle:'#000', strokeStyle:'#000', shadowColor:'#000', font:'10px sans-serif',
textAlign:'left', textBaseline:'alphabetic', globalAlpha:1, lineWidth:1, lineCap:'butt',
lineJoin:'miter', miterLimit:10, shadowBlur:0, shadowOffsetX:0, shadowOffsetY:0,
globalCompositeOperation:'source-over', imageSmoothingEnabled:true, lineDashOffset:0,
save:noop, restore:noop, scale:noop, rotate:noop, translate:noop, transform:noop,
setTransform:noop, resetTransform:noop,
beginPath:noop, closePath:noop, moveTo:noop, lineTo:noop, bezierCurveTo:noop,
quadraticCurveTo:noop, arc:noop, arcTo:noop, rect:noop, ellipse:noop, fill:noop,
stroke:noop, clip:noop, isPointInPath:()=>false,
clearRect:noop, fillRect:noop, strokeRect:noop, drawImage:noop,
fillText:(t)=>{ texts.push(String(t)); }, strokeText:(t)=>{ texts.push(String(t)); },
measureText:(s)=>({ width: ((String(s)||'').length*7)+2 }),
getImageData:(x,y,w,h)=>({ data: new Uint8ClampedArray(Math.max(1,(w||1))*(h||1)*4) }),
putImageData:noop, createImageData:(w,h)=>({ data: new Uint8ClampedArray((w||1)*(h||1)*4) }),
createLinearGradient:()=>({addColorStop:noop}), createRadialGradient:()=>({addColorStop:noop}),
createPattern:()=>({}), setLineDash:noop, getLineDash:()=>[], drawFocusIfNeeded:noop,
};
return new Proxy(base, {
get(t,p){ return (p in t) ? t[p] : noop; },
set(t,p,v){ t[p]=v; return true; },
});
}
function makeCanvas(id){
const canvas = { id, width:800, height:640, clientWidth:800, clientHeight:640,
style:{}, tabindex:0, addEventListener:noop, removeEventListener:noop, focus:noop, blur:noop,
getBoundingClientRect:()=>({left:0,top:0,right:800,bottom:640,width:800,height:640,x:0,y:0}) };
const ctx = makeCtx(canvas);
canvas.getContext = (type)=> (/2d/i.test(String(type)) ? ctx : {});
return canvas;
}
const els = {};
['game','canvas','screen','board','c','main','stage','view','bg','overlay','hud'].forEach(id=>{ els[id] = makeCanvas(id); });
function genericEl(){
return { style:{}, addEventListener:noop, removeEventListener:noop, appendChild:noop,
removeChild:noop, setAttribute:noop, getAttribute:()=>null, getContext:()=>({}),
innerHTML:'', textContent:'', firstChild:null, lastChild:null, childNodes:[], children:[],
parentElement:null, focus:noop, click:noop, blur:noop,
classList:{add:noop,remove:noop,toggle:noop,contains:()=>false}, dataset:{}, append:noop,
prepend:noop, insertBefore:noop, replaceChild:noop };
}
const keyHandlers = [];
const loadHandlers = [];
const documentMock = {
getElementById:(id)=> (els[id] !== undefined ? els[id] : null),
createElement:(tag)=> (String(tag).toLowerCase()==='canvas' ? makeCanvas() : genericEl()),
createElementNS:(_n,tag)=> documentMock.createElement(tag),
createTextNode:(t)=>({ textContent:String(t), nodeType:3 }),
addEventListener:(ev,cb)=>{ if (/key/i.test(ev)) keyHandlers.push(cb); if (/load|domcontent/i.test(ev)) loadHandlers.push(cb); },
removeEventListener:noop,
body: Object.assign(genericEl(), { addEventListener:noop }),
documentElement: Object.assign(genericEl(), { clientWidth:800, clientHeight:640, addEventListener:noop }),
head: genericEl(),
readyState:'complete', querySelector:()=>null, querySelectorAll:()=>[],
getElementsByTagName:()=>[], getElementsByClassName:()=>[],
createEvent:()=>({ initEvent:noop, initCustomEvent:noop }),
title:'', hidden:false, visibilityState:'visible', hasFocus:()=>true,
};
const store = {};
const setItemCalls = [];
const localStorageMock = {
getItem:(k)=> Object.prototype.hasOwnProperty.call(store,k) ? store[k] : null,
setItem:(k,v)=>{ store[k]=String(v); setItemCalls.push(String(k)); },
removeItem:(k)=>{ delete store[k]; },
clear:()=>{ Object.keys(store).forEach(k=>delete store[k]); },
key:(i)=> Object.keys(store)[i] || null,
get length(){ return Object.keys(store).length; },
};
const audioMethods = {};
let audioCreated = 0;
function makeAudioNode(){ return {
connect:()=>({}), disconnect:noop, start:noop, stop:noop, frequency:{value:440,setValueAtTime:noop,linearRampToValueAtTime:noop,exponentialRampToValueAtTime:noop},
gain:{value:1,setValueAtTime:noop,linearRampToValueAtTime:noop,exponentialRampToValueAtTime:noop},
detune:{value:0,setValueAtTime:noop}, type:'', playbackRate:{value:1,setValueAtTime:noop},
Q:{value:1,setValueAtTime:noop}, buffer:null, loop:false, destination:{}
}; }
class MockAudioContext {
constructor(){ audioCreated++; this.currentTime=0; this.state='running'; this.sampleRate=44100;
this.destination={ connect:()=>({}) }; this.listener={}; }
createOscillator(){ audioMethods.createOscillator=1; return makeAudioNode(); }
createGain(){ audioMethods.createGain=1; return makeAudioNode(); }
createBufferSource(){ audioMethods.createBufferSource=1; return makeAudioNode(); }
createDynamicsCompressor(){ return makeAudioNode(); }
createAnalyser(){ return makeAudioNode(); }
createBiquadFilter(){ return makeAudioNode(); }
createDelay(){ return makeAudioNode(); }
createBuffer(){ return { getChannelData:()=>new Float32Array(1024) }; }
decodeAudioData(){ return Promise.resolve({}); }
resume(){ audioMethods.resume=1; return Promise.resolve(); }
suspend(){ return Promise.resolve(); }
close(){ return Promise.resolve(); }
}
let perfNow = 0;
const sb = {};
sb.setTimeout = (fn)=>{ const id=Math.random(); return id; }; // no-op (deterministic loop via tick)
sb.clearTimeout = noop; sb.setInterval = ()=>1; sb.clearInterval = noop;
sb.queueMicrotask = (fn)=>{ Promise.resolve().then(fn); };
sb.requestAnimationFrame = ()=>1; sb.cancelAnimationFrame = noop;
sb.requestIdleCallback = ()=>1; sb.cancelIdleCallback = noop;
sb.performance = { now:()=>(perfNow+=16), timeOrigin:0, mark:noop, measure:noop };
sb.Date = Date;
sb.localStorage = localStorageMock;
sb.AudioContext = MockAudioContext; sb.webkitAudioContext = MockAudioContext;
sb.document = documentMock;
sb.console = { log:noop, debug:noop, info:noop, trace:noop,
warn:(...a)=>process.stderr.write('[game.warn] '+a.map(String).join(' ')+'\n'),
error:(...a)=>process.stderr.write('[game.err] '+a.map(String).join(' ')+'\n') };
sb.navigator = { userAgent:'node.js', platform:process.platform, language:'en' };
sb.location = { href:'file:///', reload:noop };
sb.screen = { width:800, height:640 };
sb.matchMedia = ()=>({ matches:false, addListener:noop, removeListener:noop, addEventListener:noop, removeEventListener:noop });
sb.innerWidth = 800; sb.innerHeight = 640; sb.devicePixelRatio = 1;
['Math','JSON','Object','Array','String','Number','Boolean','RegExp','Map','Set','WeakMap','WeakSet','Symbol','Error','TypeError','RangeError','SyntaxError','Promise','Reflect','Proxy','Uint8Array','Uint8ClampedArray','Int8Array','Int16Array','Uint16Array','Int32Array','Uint32Array','Float32Array','Float64Array','ArrayBuffer','DataView','Number','parseInt','parseFloat','isNaN','isFinite','encodeURIComponent','decodeURIComponent','encodeURI','decodeURI'].forEach(k=>{ if (global[k]!==undefined) sb[k]=global[k]; });
sb.btoa = (s)=> Buffer.from(s,'binary').toString('base64');
sb.atob = (s)=> Buffer.from(s,'base64').toString('binary');
sb.window = sb; sb.self = sb; sb.globalThis = sb;
// ----------------------------------------------------------------- run script
vm.createContext(sb);
try {
vm.runInContext(SCRIPT, sb, { filename:'index.html-inline', timeout:8000 });
} catch (e) {
console.error('FAIL: index.html inline script threw on load:\n' + (e && e.stack || e));
process.exit(1);
}
for (const h of loadHandlers) { try { h({type:'load'}); } catch(_){} }
const G = sb.GAME;
if (!G) { console.error('FAIL: window.GAME is not defined after load'); process.exit(1); }
// ----------------------------------------------------------------- helpers
const H = {};
H.inBounds = (x,y)=>{ const g=G.grid; return !!(g && y>=0 && y<g.length && x>=0 && x<g[y].length); };
H.tileType = (x,y)=>{ if(!H.inBounds(x,y)) return -1; const t=G.grid[y][x]; return (t && typeof t==='object') ? (t.type!==undefined?t.type:0) : t; };
H.isWall = (x,y)=>{ if(H.tileType(x,y)===1) return true; const t=G.grid && G.grid[y] && G.grid[y][x]; return !!(t && typeof t==='object' && t.solid); };
H.setTile = (x,y,type,solid)=>{ if(!H.inBounds(x,y)) return; const cur=G.grid[y][x]; const sol = solid!==undefined?solid:(type===1);
if (cur && typeof cur==='object') { cur.type=type; cur.solid=sol; } else { G.grid[y][x]=type; } };
H.floor = (x,y)=> H.setTile(x,y,0,false);
H.wall = (x,y)=> H.setTile(x,y,1,true);
H.clearRow = (y,x1,x2)=>{ for(let x=x1;x<=x2;x++) if(H.inBounds(x,y)) H.floor(x,y); };
H.clearCol = (x,y1,y2)=>{ for(let y=y1;y<=y2;y++) if(H.inBounds(x,y)) H.floor(x,y); };
H.manhattan = (a,b)=> Math.abs(a.x-b.x)+Math.abs(a.y-b.y);
H.cheby = (a,b)=> Math.max(Math.abs(a.x-b.x),Math.abs(a.y-b.y));
H.ppos = ()=> ({ x:G.player.x, y:G.player.y });
H.start = ()=>{ if (typeof G.start==='function') G.start(); };
H.newRun = ()=>{ if (typeof G.newRun==='function') { G.newRun(); } else { if(typeof G.start==='function')G.start(); G.input('Enter'); } };
H.findExit = ()=>{ if (G._exit && G._exit.x!==undefined) return {x:G._exit.x,y:G._exit.y};
const g=G.grid; for(let y=0;y<g.length;y++) for(let x=0;x<g[y].length;x++) if(H.tileType(x,y)===3) return {x,y}; return null; };
H.findFreeNear = (x,y,r)=>{ for(let rad=0;rad<=(r||6);rad++) for(let dy=-rad;dy<=rad;dy++) for(let dx=-rad;dx<=rad;dx++){ const nx=x+dx,ny=y+dy; if(H.inBounds(nx,ny)&&!H.isWall(nx,ny)) return {x:nx,y:ny}; } return null; };
H.spawnAt = (type,x,y)=>{ if(H.inBounds(x,y)) H.floor(x,y); return G.spawn(type,x,y); };
H.maxHp = (e)=> e && (e.maxHp!==undefined?e.maxHp:e.hp);
H.statVal = (e,keys)=>{ for(const k of keys) if(e && e[k]!==undefined) return e[k]; return undefined; };
H.countAch = ()=>{ const a=G.achievements; if(!a) return 0;
if(Array.isArray(a)) return a.filter(x=>x && (x.unlocked||x.done||x.unlockedAt)).length;
return Object.values(a).filter(v=> v===true || (v && v.unlocked)).length; };
H.descend = ()=>{ // step the player onto the exit tile; returns resulting state
const ex = H.findExit(); if(!ex) return null;
// place player on a floor neighbour of the exit
const neigh=[[-1,0],[1,0],[0,-1],[0,1]].find(([dx,dy])=>H.inBounds(ex.x+dx,ex.y+dy));
if(!neigh) return G.state;
const sx=ex.x+neigh[0], sy=ex.y+neigh[1]; H.floor(sx,sy);
G.player.x=sx; G.player.y=sy;
// move onto exit
if(ex.x>sx) G.input('ArrowRight'); else if(ex.x<sx) G.input('ArrowLeft');
else if(ex.y>sy) G.input('ArrowDown'); else G.input('ArrowUp');
return G.state;
};
H.projectilesAt = ()=> (Array.isArray(G.projectiles)?G.projectiles.length:(G.projectiles?Object.keys(G.projectiles).length:0));
H.tankHost = ()=>{ const h=G.player&&G.player.host; if(h){ h.hp=999; if(h.maxHp!==undefined)h.maxHp=999; } };
// ----------------------------------------------------------------- phase defs
function p1(){
const checks = [];
checks.push(['index.html has <canvas> and <script>', ()=>{ assert(/<canvas/i.test(SRC), 'no <canvas>'); assert(/<script/i.test(SRC), 'no <script>'); }]);
checks.push(['no external src= or import', ()=>{ assert(!externalSrc, 'external <script src=> found'); assert(!/^\s*import\s/m.test(SCRIPT) && !/\bimport\s*["']/m.test(SCRIPT), 'ES import found'); }]);
checks.push(['GAME.start() runs, valid state', ()=>{ H.start(); assert(VALID_STATES.includes(G.state), 'invalid state: '+G.state); }]);
checks.push(['grid has wall and floor tiles', ()=>{ const g=G.grid; assert(g && g.length, 'no grid'); let w=0,f=0; for(let y=0;y<g.length;y++) for(let x=0;x<g[y].length;x++){ const t=H.tileType(x,y); if(t===1)w++; else if(t===0)f++; } assert(w>0,'no walls'); assert(f>0,'no floor'); }]);
checks.push(['ghost moves on input, blocked by wall', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y);
// choose an in-bounds horizontal direction
let dir='ArrowRight', nx=p.x+1; if(!H.inBounds(p.x+1,p.y)){ dir='ArrowLeft'; nx=p.x-1; }
H.wall(nx,p.y); G.input(dir); assert(G.player.x===p.x, 'ghost moved into wall');
H.floor(nx,p.y); G.input(dir); assert(G.player.x===nx, 'ghost did not move onto floor');
}]);
checks.push(['title screen explains controls (WASD/arrows/SPACE/Q-E/ENTER/ESC)', ()=>{ assert(/WASD/i.test(SRC), 'WASD missing'); assert(/arrow/i.test(SRC), 'arrows missing'); assert(/space/i.test(SRC), 'SPACE missing'); assert(/enter/i.test(SRC), 'ENTER missing'); assert(/esc|escape|pause/i.test(SRC), 'ESC/pause missing'); assert(/facing|rotate|\bQ\b.*\bE\b|\bQ\/E\b|Q\/E/i.test(SRC), 'Q/E facing missing'); }]);
checks.push(['enemy legend (bestiary) reachable, lists enemies', ()=>{ assert(/legend|bestiary/i.test(SRC), 'no legend/bestiary panel'); let names=0; for(const n of ENEMIES) if(new RegExp(n,'i').test(SRC)) names++; assert(names>=6, 'only '+names+' enemy names in source'); H.start(); assert(typeof G.input==='function'); let ok=true; try { G.input('l'); } catch(e){ ok=false; } assert(ok, "input('l') threw"); }]);
checks.push(['starting ghost timer >= 15s', ()=>{ H.newRun(); assert(G.player && (G.player.timer||0)>=15, 'timer='+(G.player&&G.player.timer)); }]);
return checks;
}
function p2(){
const checks = [];
checks.push(['SPACE on adjacent enemy -> possessed', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); const e=H.spawnAt('Brute', p.x+1, p.y); assert(e, 'spawn failed'); G.input('Space'); assert(G.state==='possessed', 'state='+G.state); assert(!!G.player.host, 'no host'); }]);
checks.push(['X abandons host: ghost returns, host survives, lockout', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); assert(G.state==='possessed'); const hostId = G.player.host && (G.player.host.id||G.player.host._id); const before = (G.enemies||[]).length; G.input('x'); assert(G.state!=='possessed', 'still possessed after X'); assert(!G.player.host, 'host still set'); assert(G.player.ghost===true, 'not ghost'); assert((G.player.timer||0)>0, 'timer<=0 after abandon'); assert((G.enemies||[]).length>=before, 'host disappeared from enemies'); // lockout: immediate re-possess must fail
G.input('Space'); assert(G.state!=='possessed', 're-possessed immediately (no lockout)'); }]);
checks.push(['Brute/Skitterer/Sentinel stats', ()=>{ for(const [t,hp,dmg] of [['Brute',8,3],['Skitterer',2,1],['Sentinel',4,null]]){ const p=H.ppos?H.ppos():{x:5,y:5}; H.newRun(); const pp=H.ppos(); H.floor(pp.x,pp.y); const e=H.spawnAt(t, pp.x+1, pp.y); assert(e, t+' spawn failed'); assert(H.maxHp(e)===hp, t+' maxHp='+H.maxHp(e)+' want '+hp); if(dmg!==null) assert(H.statVal(e,['damage','dmg','attack','atk'])===dmg, t+' damage mismatch'); } }]);
checks.push(['Sentinel fires a burst then OVERHEATS (no-fire window)', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const brute=H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); assert(G.state==='possessed','need possessed host'); const hp=H.ppos(); H.tankHost(); const sx=Math.max(1,hp.x-5); H.clearRow(hp.y,sx,hp.x); const sen=H.spawnAt('Sentinel', sx, hp.y); assert(sen,'sentinel spawn'); let ohMax=0,fired=false; for(let i=0;i<22;i++){ const b=H.projectilesAt(); const bl0=sen.burstLeft; G.tick(1); if(H.projectilesAt()>b||sen.burstLeft<bl0) fired=true; ohMax=Math.max(ohMax, sen.overheatLeft||0); } assert(fired,'sentinel never fired (setup/aggro issue)'); assert(ohMax>=3,'sentinel never entered a 3-turn overheat (ohMax='+ohMax+')'); }]);
checks.push(['enemies pathfind toward the ghost', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const ex=Math.max(1,p.x-5); H.clearRow(p.y,ex,p.x); const e=H.spawnAt('Brute', ex, p.y); assert(e); const d0=H.manhattan({x:ex,y:p.y},p); let moved=false; for(let i=0;i<14;i++){ G.tick(1); } const df=H.manhattan({x:e.x,y:e.y},p); assert(df<d0, 'enemy did not approach (d0='+d0+', df='+df+')'); }]);
checks.push(['killing host ejects ghost with timer>0', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Skitterer', p.x+1, p.y); G.input('Space'); assert(G.state==='possessed'); const host=G.player.host; assert(host,'no host'); host.hp=0; G.tick(1); assert(G.player.ghost===true,'not ghost after host death'); assert(!G.player.host,'host still set'); assert((G.player.timer||0)>0,'timer<=0'); }]);
checks.push(['essence increases on kill', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); assert(G.state==='possessed'); const target=H.spawnAt('Skitterer', p.x+2, p.y); H.floor(p.x+2,p.y); const e0=G.essence||0; let got=false; for(let i=0;i<8;i++){ G.input('Space'); if((G.essence||0)>e0){got=true;break;} G.input('e'); G.input('q'); } assert(got,'essence did not increase after kill (e0='+e0+', e='+G.essence+')'); }]);
checks.push(['no friendly fire: Sentinel projectiles never hit another enemy', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const brute=H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); const hp=H.ppos(); H.tankHost(); const sx=Math.max(1,hp.x-5); H.clearRow(hp.y,sx,hp.x); const mid=Math.round((sx+hp.x)/2); H.floor(mid,hp.y); const meat=H.spawnAt('Skitterer', mid, hp.y); assert(meat); const sen=H.spawnAt('Sentinel', sx, hp.y); assert(sen); const meatHp0=H.maxHp(meat); let fired=0; for(let i=0;i<16;i++){ const b=H.projectilesAt(); G.tick(1); if(H.projectilesAt()-b>0) fired++; } assert(fired>=2,'sentinel did not fire (fired='+fired+')'); assert((meat.hp||0)===meatHp0 || H.maxHp(meat)===meatHp0, 'friendly fire: meat enemy lost HP ('+meatHp0+'->'+(meat.hp)+')'); }]);
return checks;
}
function p3(){
const checks = [];
checks.push(['all 12 enemy types instantiate', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); for(const t of ENEMIES){ const spot=H.findFreeNear(p.x,p.y,8); const e=G.spawn(t, spot.x, spot.y); assert(e, t+' spawn returned falsy'); assert(e && (e.type===t || (e.type||'').toLowerCase()===t.toLowerCase() || e.kind===t), t+' wrong type'); } }]);
checks.push(['distinct hp+damage+speed tuples', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); const seen=new Set(); let i=0; for(const t of ENEMIES){ const spot=H.findFreeNear(p.x,p.y,10); const e=G.spawn(t, spot.x, spot.y); const hp=H.maxHp(e), dmg=H.statVal(e,['damage','dmg','attack','atk'])??'?'; const sp=H.statVal(e,['speed','moveInterval','moveEvery','moveCd'])??'?'; const key=t+'|'+hp+'|'+dmg+'|'+sp; seen.add(key); i++; } // at least 10 of 12 distinct combinations
assert(seen.size>=10, 'only '+seen.size+' distinct stat tuples'); }]);
checks.push(['each special ability triggers without error', ()=>{ for(const t of ENEMIES){ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const e=H.spawnAt(t, p.x+1, p.y); G.input('Space'); // possess (some types may need LOS/adjacency; best effort)
let threw=false; try { if(G.state==='possessed'){ G.input('e'); G.input('Space'); G.input('q'); G.input('Space'); } } catch(err){ threw=true; } assert(!threw, t+' ability threw'); } }]);
checks.push(['pathfinder navigates around walls (not through)', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y);
// clear a room (remove procgen interference), then a wall column with a DOOR on the player's row so LOS stays clear and the Brute aggros; it must reach the player via the door without clipping walls
for(let yy=p.y-6;yy<=p.y+6;yy++) for(let xx=p.x-9;xx<=p.x+4;xx++) if(H.inBounds(xx,yy)) H.floor(xx,yy);
const wx=p.x-3; for(let yy=p.y-3;yy<=p.y+3;yy++) if(yy!==p.y) H.wall(wx,yy); H.floor(wx,p.y);
const ex=p.x-5; H.floor(ex,p.y); const e=H.spawnAt('Brute', ex, p.y); assert(e,'brute spawn'); const d0=H.manhattan({x:ex,y:p.y},p);
for(let i=0;i<44;i++) G.tick(1); const df=H.manhattan({x:e.x,y:e.y},p); assert(df<=2,'did not navigate to player through the door (d0='+d0+',df='+df+')'); }]);
checks.push(['Bomber AoE damages player only, never other enemies', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const b=H.spawnAt('Bomber', p.x+1, p.y); const meat=H.spawnAt('Skitterer', p.x+2, p.y); H.floor(p.x+2,p.y); const m0=meat.hp; let exploded=false; for(let i=0;i<14;i++){ const ben=(G.enemies||[]).find(x=>x===b||x.type==='Bomber'); G.tick(1); if(!ben || (b.hp!==undefined && b.hp<=0) || !(G.enemies||[]).includes(b)){ exploded=true; break; } } assert(exploded,'bomber never exploded'); assert((meat.hp||0)>=m0 || !((G.enemies||[]).includes(meat) && meat.hp<m0), 'friendly fire: meat lost HP ('+m0+'->'+(meat.hp)+')'); }]);
checks.push(['Charger charge hits player only, never other enemies', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const cx=Math.max(1,p.x-5); const meat=H.spawnAt('Skitterer', p.x-3, p.y); H.floor(p.x-3,p.y); const ch=H.spawnAt('Charger', cx, p.y); assert(ch); const m0=meat.hp; for(let i=0;i<16;i++) G.tick(1); assert((meat.hp||0)===m0 || !(G.enemies||[]).includes(meat), 'friendly fire: charger damaged meat ('+m0+'->'+(meat.hp)+')'); }]);
checks.push(['Turret shots hit player only, never other enemies', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const brute=H.spawnAt('Brute', p.x+1,p.y); G.input('Space'); const hp=H.ppos(); H.tankHost(); const cx=Math.max(1,hp.x-5); H.clearRow(hp.y,cx,hp.x); const meat=H.spawnAt('Skitterer', hp.x-3, hp.y); H.floor(hp.x-3,hp.y); const tur=H.spawnAt('Turret', cx, hp.y); assert(tur); const m0=meat.hp; let fired=0; for(let i=0;i<14;i++){ const b=H.projectilesAt(); G.tick(1); if(H.projectilesAt()-b>0) fired++; } assert(fired>=2,'turret did not fire'); assert((meat.hp||0)===m0,'friendly fire: turret shot meat ('+m0+'->'+(meat.hp)+')'); }]);
checks.push(['Turret OVERHEATS after burst', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.clearRow(p.y,0,24); const brute=H.spawnAt('Brute', p.x+1,p.y); G.input('Space'); const hp=H.ppos(); H.tankHost(); const cx=Math.max(1,hp.x-5); H.clearRow(hp.y,cx,hp.x); const tur=H.spawnAt('Turret', cx, hp.y); assert(tur); let ohMax=0,fired=false; for(let i=0;i<22;i++){ const b=H.projectilesAt(); const bl0=tur.burstLeft; G.tick(1); if(H.projectilesAt()>b||tur.burstLeft<bl0) fired=true; ohMax=Math.max(ohMax, tur.overheatLeft||0); } assert(fired,'turret never fired (setup/aggro issue)'); assert(ohMax>=3,'turret never entered a 3-turn overheat (ohMax='+ohMax+')'); }]);
return checks;
}
function p4(){
const checks = [];
checks.push(['procedural dungeons differ across runs', ()=>{ const snaps=[]; for(let r=0;r<3;r++){ H.newRun(); const g=G.grid; let s=''; for(let y=0;y<g.length;y++){ let row=''; for(let x=0;x<g[y].length;x++) row += H.isWall(x,y)?'1':'0'; s+=row+'\n'; } snaps.push(s); } const uniq=new Set(snaps); assert(uniq.size>=2,'all 3 layouts identical'); }]);
checks.push(['exit tile exists on the floor', ()=>{ H.newRun(); const ex=H.findExit(); assert(ex,'no exit tile / G._exit'); }]);
checks.push(['shop appears on floor transition', ()=>{ H.newRun(); const st=H.descend(); assert(st==='shop','state='+st+' after descending (expected shop)'); }]);
checks.push(['buying an upgrade changes GAME.upgrades', ()=>{ H.newRun(); if(typeof G.openShop!=='function') fail('no openShop'); G.openShop(); assert(G.state==='shop','openShop state='+G.state); const choices=G.choices||G.shopChoices||G.upgradeChoices; assert(choices && choices.length>=3,'choices<3 ('+(choices?choices.length:0)+')'); const before=JSON.stringify(G.upgrades||{}); let bought=false; for(let idx=0;idx<(choices?choices.length:3);idx++){ const ess=G.essence; try { G.buy(idx); } catch(e){ continue; } if(JSON.stringify(G.upgrades||{})!==before){ bought=true; break; } } assert(bought,'no buy() changed upgrades'); }]);
checks.push(['save() writes to localStorage', ()=>{ setItemCalls.length=0; store[SAVE_KEY] && delete store[SAVE_KEY]; assert(typeof G.save==='function'); G.save(); assert(setItemCalls.indexOf(SAVE_KEY)>=0,'save() did not call setItem("'+SAVE_KEY+'")'); }]);
checks.push(['save/load round-trip persists floor+essence+upgrades', ()=>{ H.newRun(); // establish some state
const st=H.descend(); if(st==='shop'){ try{G.buy(0);}catch(_){} try{G.input('Enter');}catch(_){} } if(typeof G.setFloor==='function'){ try{G.setFloor(3);}catch(_){} } G.essence=42; const upBefore=JSON.stringify(G.upgrades||{}); const fl=(G.floor||1); const ess=(G.essence||0); G.save(); assert(store[SAVE_KEY],'no save data written'); if(typeof G.load!=='function') fail('no load()'); H.newRun(); G.load(); assert((G.floor||1)===fl,'floor not restored ('+G.floor+' vs '+fl+')'); assert((G.essence||0)===ess,'essence not restored ('+G.essence+' vs '+ess+')'); assert(JSON.stringify(G.upgrades||{})===upBefore,'upgrades not restored'); }]);
return checks;
}
function p5(){
const checks = [];
checks.push(['can reach WON (floor 10 exit)', ()=>{ if(typeof G.setFloor!=='function') fail('no setFloor'); G.setFloor(10); assert(G.floor===10 || G.floor===9,'setFloor(10) -> floor='+G.floor); const st=H.descend(); assert(G.state==='won','state='+st+' (expected won)'); }]);
checks.push(['can reach LOST (ghost timer expires)', ()=>{ H.newRun(); assert(G.player.ghost===true); G.player.timer=1; for(let i=0;i<5;i++){ G.tick(1); if(G.state==='lost') break; } assert(G.state==='lost','state='+G.state); }]);
checks.push(['at least 3 achievements trigger', ()=>{ // fresh: first possession, deep diver, essence hoarder
H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); // First Possession
try{ if(typeof G.setFloor==='function') G.setFloor(7); }catch(_){} // Deep Diver
G.essence=29; // one more -> 30 for hoarder
const tg=H.findFreeNear(p.x,p.y,6); if(tg && G.state!=='possessed'){ H.spawnAt('Brute',p.x+1,p.y); G.input('Space'); } const target=H.findFreeNear(G.player.x,G.player.y,4); if(target){ H.spawnAt('Skitterer', target.x, target.y); for(let i=0;i<8;i++){ G.input('Space'); if((G.essence||0)>=30) break; G.input('e'); } } try{ G.tick(1); }catch(_){} const n=H.countAch(); assert(n>=3,'only '+n+' achievements unlocked'); }]);
checks.push(['audio system initialised and used', ()=>{ H.newRun(); const p=H.ppos(); H.floor(p.x,p.y); H.spawnAt('Brute', p.x+1, p.y); G.input('Space'); G.input('x'); assert(audioCreated>0,'AudioContext never constructed'); assert(audioMethods.createOscillator||audioMethods.createGain||audioMethods.createBufferSource||audioMethods.resume,'no audio methods called'); }]);
checks.push(['no errors during 200-tick stress (move/possess/attack/descend)', ()=>{ H.newRun(); const keys=['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Space','x','q','e']; let err=null; try { for(let i=0;i<200;i++){ const k=keys[i%keys.length]; G.input(k); if(i%50===49){ // descend a floor where possible
try{ H.descend(); if(G.state==='shop'){ G.input('Enter'); } }catch(_){} } G.tick(1); if(G.state==='lost'||G.state==='won'){ H.newRun(); } } } catch(e){ err=e; } assert(!err,'threw during stress: '+(err&&err.message)); }]);
return checks;
}
const PHASES = { 1:p1, 2:p2, 3:p3, 4:p4, 5:p5 };
const fn = PHASES[PHASE];
if (!fn) { console.error('FAIL: unknown phase '+PHASE+' (use 1..5)'); process.exit(1); }
// ----------------------------------------------------------------- run checks
let checks;
try { checks = fn(); }
catch (e) { console.error('FAIL: phase '+PHASE+' setup threw: '+(e&&e.stack||e)); process.exit(1); }
let pass=0, failCount=0;
const failures=[];
for (const [name, c] of checks){
try { c(); pass++; console.log(' ✓ '+name); }
catch (e){ failCount++; failures.push(name+' :: '+(e&&e.message||e)); console.log(' ✗ '+name+' → '+(e&&e.message||e)); }
}
console.log('');
if (failCount===0){ console.log(`Phase ${PHASE}: PASS (${pass}/${pass})`); process.exit(0); }
console.log(`Phase ${PHASE}: FAIL (${pass} passed, ${failCount} failed)`);
for (const f of failures) console.log(' - '+f);
process.exit(1);