632 lines
27 KiB
JavaScript
632 lines
27 KiB
JavaScript
#!/usr/bin/env node
|
|
'use strict';
|
|
/*
|
|
* Body Snatcher — automated verification harness.
|
|
* Node.js builtins only (fs, vm, path). No npm packages.
|
|
*
|
|
* node verify.js <phase>
|
|
*
|
|
* Loads index.html, evals its <script> in a sandbox with DOM/Audio/localStorage
|
|
* mocks, drives window.GAME, and asserts per-phase behavior. Exit 0 = pass.
|
|
*
|
|
* ============================================================================
|
|
* DEBUG API CONTRACT — the game MUST expose all of this on window.GAME:
|
|
* start() initialize to the TITLE screen (do NOT auto-start play)
|
|
* input(key) handle one key token; MUST accept:
|
|
* ArrowUp/Down/Left/Right, w a s d, ' ' and 'Space',
|
|
* q e, Enter, Escape
|
|
* tick(n=1) advance the loop n times; DETERMINISTIC; must advance
|
|
* enemy AI AND decrement the ghost timer
|
|
* spawn(type, tx, ty) create an enemy of `type` at tile coords; returns it
|
|
* setFloor(n) DEBUG jump: generate floor n, place player (ghost) at
|
|
* spawn, state 'playing'
|
|
* newRun() start fresh floor-1 run with a NEW procgen layout
|
|
* save() / load() localStorage persistence (key 'bodysnatcher_save')
|
|
* openShop() DEBUG: enter shop state with 3 choices
|
|
* buy(index) purchase shop choice at index
|
|
* Properties: state, player, enemies, grid, floor, essence, upgrades,
|
|
* achievements, projectiles, log
|
|
* player = {x,y,ghost,timer,host,facing}
|
|
* enemy = {type,hp,maxHp,damage,speed,x,y,...}
|
|
* grid[y][x] tile = number (0 floor,1 wall,2 door,3 exit,4 shop,5 chest)
|
|
* OR object {type:'floor'|'wall'|'door'|'exit'|'stairs'|
|
|
* 'shop'|'chest', solid:bool}
|
|
* state ∈ {'title','playing','possessed','shop','paused','won','lost'}
|
|
* The 12 enemy types: brute, skitterer, sentinel, shielder, bomber, healer,
|
|
* phaser, turret, charger, siren, mimic, leech
|
|
* ============================================================================
|
|
*/
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const vm = require('vm');
|
|
|
|
const INDEX = path.join(__dirname, 'index.html');
|
|
const SAVE_KEY = 'bodysnatcher_save';
|
|
const ENEMY_TYPES = ['brute','skitterer','sentinel','shielder','bomber',
|
|
'healer','phaser','turret','charger','siren','mimic','leech'];
|
|
const VALID_STATES = new Set(['title','playing','possessed','shop','paused','won','lost']);
|
|
const phase = parseInt(process.argv[2] || '1', 10);
|
|
|
|
const failures = [];
|
|
function check(name, fn) {
|
|
try { fn(); console.log(' PASS ' + name); }
|
|
catch (e) { const m = (e && e.message) || String(e); failures.push(name + ' :: ' + m); console.log(' FAIL ' + name + ' :: ' + m); }
|
|
}
|
|
function assert(c, m) { if (!c) throw new Error(m || 'assertion failed'); }
|
|
|
|
// ----------------------------- tile helpers --------------------------------
|
|
function isWall(tile) {
|
|
if (tile == null) return false;
|
|
if (typeof tile === 'number') return tile === 1;
|
|
const t = tile.type;
|
|
return t === 'wall' || tile.solid === true || tile.blocked === true;
|
|
}
|
|
function isExit(tile) {
|
|
if (tile == null) return false;
|
|
if (typeof tile === 'number') return tile === 3;
|
|
const t = tile.type;
|
|
return t === 'exit' || t === 'stairs';
|
|
}
|
|
function isFloor(tile) {
|
|
if (tile == null) return false;
|
|
if (typeof tile === 'number') return tile === 0;
|
|
const t = tile.type;
|
|
return t === 'floor' || t === undefined && !tile.solid;
|
|
}
|
|
function floorTileOf(G) {
|
|
const g = G.grid;
|
|
for (let y = 0; y < g.length; y++)
|
|
for (let x = 0; x < g[y].length; x++)
|
|
if (isFloor(g[y][x])) return JSON.parse(JSON.stringify(g[y][x]));
|
|
return { type: 'floor' };
|
|
}
|
|
function setTile(G, x, y, val) { if (G.grid[y] && x >= 0 && x < G.grid[y].length) G.grid[y][x] = val; }
|
|
function clearArea(G, cx, cy, r) {
|
|
const f = floorTileOf(G);
|
|
for (let y = cy - r; y <= cy + r; y++)
|
|
for (let x = cx - r; x <= cx + r; x++)
|
|
setTile(G, x, y, JSON.parse(JSON.stringify(f)));
|
|
}
|
|
function findExit(G) {
|
|
const g = G.grid;
|
|
for (let y = 0; y < g.length; y++)
|
|
for (let x = 0; x < g[y].length; x++)
|
|
if (isExit(g[y][x])) return { x, y };
|
|
return null;
|
|
}
|
|
function manhattan(ax, ay, bx, by) { return Math.abs(ax - bx) + Math.abs(ay - by); }
|
|
function ghostAt(G) { return G.player && G.player.ghost === true && !G.player.host; }
|
|
|
|
// ----------------------------- browser mock --------------------------------
|
|
function makeCtxMock() {
|
|
const measure = { width: 0 };
|
|
const grad = new Proxy({}, { get: (t, p) => (p in t ? t[p] : (() => grad)) });
|
|
return new Proxy({}, {
|
|
get(t, p) {
|
|
if (p === 'measureText') return () => measure;
|
|
if (p === 'getImageData') return () => ({ data: new Uint8ClampedArray(4) });
|
|
if (p === 'createLinearGradient' || p === 'createRadialGradient' || p === 'createPattern')
|
|
return () => grad;
|
|
if (p === 'canvas') return null;
|
|
if (p in t) return t[p];
|
|
if (typeof p === 'string') return () => {};
|
|
return undefined;
|
|
},
|
|
set(t, p, v) { t[p] = v; return true; },
|
|
});
|
|
}
|
|
|
|
function loadGame() {
|
|
const html = fs.readFileSync(INDEX, 'utf8');
|
|
// collect inline <script> blocks (skip any with src=)
|
|
const blocks = [];
|
|
const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
|
|
let m;
|
|
while ((m = re.exec(html)) !== null) {
|
|
if (/src\s*=/.test(m[1])) continue;
|
|
if (m[2].trim()) blocks.push(m[2]);
|
|
}
|
|
const code = blocks.join('\n;\n');
|
|
|
|
const CTX = makeCtxMock();
|
|
const store = new Map();
|
|
let setItemCalls = [];
|
|
const localStorage = {
|
|
getItem: (k) => (store.has(k) ? store.get(k) : null),
|
|
setItem: (k, v) => { store.set(k, String(v)); setItemCalls.push(k); },
|
|
removeItem: (k) => { store.delete(k); },
|
|
clear: () => store.clear(),
|
|
key: (i) => Array.from(store.keys())[i] || null,
|
|
get length() { return store.size; },
|
|
};
|
|
|
|
function makeEl(tag) {
|
|
return {
|
|
tagName: (tag || 'div').toUpperCase(), style: {}, children: [], _ls: {},
|
|
width: 0, height: 0, value: '', textContent: '', innerHTML: '',
|
|
getContext: () => CTX,
|
|
addEventListener: () => {}, removeEventListener: () => {},
|
|
appendChild: (c) => c, removeChild: (c) => c, insertBefore: (c) => c,
|
|
setAttribute: () => {}, getAttribute: () => null, hasAttribute: () => false,
|
|
getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 600, right: 800, bottom: 600 }),
|
|
focus: () => {}, blur: () => {}, click: () => {}, dispatchEvent: () => true,
|
|
querySelector: () => null, querySelectorAll: () => [], cloneNode: () => makeEl(tag),
|
|
};
|
|
}
|
|
const canvasEl = makeEl('canvas');
|
|
|
|
let audioCalls = 0;
|
|
function audioNode() {
|
|
return new Proxy({ connect: () => audioNode(), disconnect: () => {},
|
|
start: () => { audioCalls++; }, stop: () => { audioCalls++; },
|
|
frequency: mockParam(), gain: mockParam(), type: '', playbackRate: mockParam(),
|
|
loop: false, buffer: null, destination: { connect: () => audioNode() } },
|
|
{ get: (t, p) => (p in t ? t[p] : (() => audioNode())), set: (t, p, v) => { t[p] = v; return true; } });
|
|
}
|
|
function mockParam() { return { value: 0, setValueAtTime: () => {}, linearRampToValueAtTime: () => {},
|
|
exponentialRampToValueAtTime: () => {}, cancelScheduledValues: () => {} }; }
|
|
function AudioContextMock() {
|
|
audioCalls++;
|
|
return new Proxy({
|
|
destination: {}, currentTime: 0, sampleRate: 44100, state: 'running', baseLatency: 0,
|
|
listener: {}, resume: () => Promise.resolve(), close: () => Promise.resolve(),
|
|
createOscillator: () => { audioCalls++; return audioNode(); },
|
|
createGain: () => { audioCalls++; return audioNode(); },
|
|
createBuffer: () => ({}), createBufferSource: () => audioNode(),
|
|
decodeAudioData: () => Promise.resolve({}), getChannelData: () => new Float32Array(0),
|
|
}, { get: (t, p) => (p in t ? t[p] : (() => audioNode())), set: (t, p, v) => { t[p] = v; return true; } });
|
|
}
|
|
|
|
const sandbox = {};
|
|
sandbox.window = sandbox;
|
|
sandbox.self = sandbox;
|
|
sandbox.globalThis = sandbox;
|
|
sandbox.console = { log: () => {}, warn: () => {}, error: () => {}, info: () => {}, debug: () => {} };
|
|
sandbox.setTimeout = () => 0; sandbox.setInterval = () => 0;
|
|
sandbox.clearTimeout = () => {}; sandbox.clearInterval = () => {};
|
|
sandbox.requestAnimationFrame = () => 1; sandbox.cancelAnimationFrame = () => {};
|
|
sandbox.queueMicrotask = (fn) => Promise.resolve().then(fn);
|
|
sandbox.localStorage = localStorage;
|
|
sandbox.navigator = { userAgent: 'node-verify', vibrate: () => {} };
|
|
sandbox.location = { href: 'file:///index.html', reload: () => {}, hostname: '' };
|
|
sandbox.performance = { now: () => Date.now(), timing: {} };
|
|
sandbox.Image = function () { return makeEl('img'); };
|
|
sandbox.AudioContext = AudioContextMock;
|
|
sandbox.webkitAudioContext = AudioContextMock;
|
|
sandbox.atob = (s) => Buffer.from(s, 'base64').toString('binary');
|
|
sandbox.btoa = (s) => Buffer.from(s, 'binary').toString('base64');
|
|
sandbox.structuredClone = (o) => JSON.parse(JSON.stringify(o));
|
|
sandbox.URL = URL;
|
|
sandbox.TextEncoder = TextEncoder; sandbox.TextDecoder = TextDecoder;
|
|
sandbox.crypto = { getRandomValues: (a) => { for (let i = 0; i < a.length; i++) a[i] = (Math.random() * 256) | 0; return a; } };
|
|
sandbox.alert = () => {}; sandbox.confirm = () => true; sandbox.prompt = () => '';
|
|
sandbox.addEventListener = () => {}; sandbox.removeEventListener = () => {};
|
|
sandbox.dispatchEvent = () => true;
|
|
sandbox.innerHeight = 600; sandbox.innerWidth = 800; sandbox.devicePixelRatio = 1;
|
|
sandbox.document = {
|
|
getElementById: () => canvasEl,
|
|
createElement: (t) => makeEl(t),
|
|
createElementNS: (ns, t) => makeEl(t),
|
|
createTextNode: (t) => ({ nodeValue: t }),
|
|
body: makeEl('body'), head: makeEl('head'), documentElement: makeEl('html'),
|
|
addEventListener: () => {}, removeEventListener: () => {},
|
|
querySelector: () => null, querySelectorAll: () => [],
|
|
getElementsByTagName: () => [], getElementsByClassName: () => [],
|
|
readyState: 'complete', hidden: false,
|
|
};
|
|
|
|
vm.createContext(sandbox);
|
|
try {
|
|
vm.runInContext(code, sandbox, { filename: 'index.html.inline', timeout: 5000 });
|
|
} catch (e) {
|
|
throw new Error('script load threw: ' + (e && e.stack || e));
|
|
}
|
|
const GAME = sandbox.window.GAME;
|
|
if (!GAME) throw new Error('window.GAME is not defined');
|
|
return { GAME, sandbox, localStorage, getAudioCalls: () => audioCalls, getSetItemCalls: () => setItemCalls };
|
|
}
|
|
|
|
// ----------------------------- drivers -------------------------------------
|
|
function beginPlay(G) {
|
|
if (G.state !== 'title') { try { G.start(); } catch (e) {} }
|
|
if (G.state === 'title') { G.input('Enter'); G.tick(1); }
|
|
if (G.state === 'title') { G.input(' '); G.tick(1); }
|
|
if (G.state !== 'playing' && G.state !== 'possessed') {
|
|
// fall back: explicit start into play
|
|
if (typeof G.setFloor === 'function') { G.setFloor(G.floor || 1); }
|
|
}
|
|
return G.state;
|
|
}
|
|
function forceGhost(G) {
|
|
if (G.player && G.player.host) { G.player.host.hp = 0; G.tick(1); }
|
|
if (G.player) { G.player.ghost = true; G.player.host = null; }
|
|
}
|
|
function possessType(G, type) {
|
|
// place player as ghost on open ground, spawn target adjacent, face it, possess
|
|
forceGhost(G);
|
|
const px = G.player.x, py = G.player.y;
|
|
clearArea(G, px, py, 4);
|
|
const e = G.spawn(type, px + 1, py);
|
|
G.player.facing = 'right';
|
|
G.input('Space'); G.tick(2);
|
|
return G.state === 'possessed' ? e : null;
|
|
}
|
|
|
|
// ============================================================================
|
|
// PHASE 1 — engine exists and runs
|
|
// ============================================================================
|
|
function phase1() {
|
|
check('index.html exists with canvas+script', () => {
|
|
const html = fs.readFileSync(INDEX, 'utf8');
|
|
assert(/<canvas/i.test(html), 'no <canvas>');
|
|
assert(/<script\b[^>]*>[\s\S]*?<\/script>/i.test(html), 'no inline <script>');
|
|
});
|
|
check('no external src= / import / require', () => {
|
|
const html = fs.readFileSync(INDEX, 'utf8');
|
|
assert(!/<script\b[^>]*\bsrc\s*=/i.test(html), 'found <script src=>');
|
|
const blocks = [];
|
|
let m; const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
|
|
while ((m = re.exec(html)) !== null) if (!/src\s*=/.test(m[1]) && m[2].trim()) blocks.push(m[2]);
|
|
const js = blocks.join('\n');
|
|
assert(!/^\s*import\s/m.test(js), 'found ES import');
|
|
assert(!/from\s+['"]https?:\/\//m.test(js), 'found http import');
|
|
assert(!/\brequire\s*\(/.test(js), 'found require()');
|
|
});
|
|
let L;
|
|
check('GAME loads + start() runs without throwing', () => {
|
|
L = loadGame();
|
|
assert(typeof L.GAME.start === 'function', 'GAME.start not a function');
|
|
L.GAME.start();
|
|
assert(VALID_STATES.has(L.GAME.state), 'invalid state: ' + L.GAME.state);
|
|
});
|
|
check('starts on title (no auto-start)', () => {
|
|
const F = loadGame();
|
|
assert(VALID_STATES.has(F.GAME.state), 'pre-start state invalid: ' + F.GAME.state);
|
|
// on load, before start, must be title-ish (not mid-play)
|
|
F.GAME.start();
|
|
assert(F.GAME.state === 'title', 'start() should land on title, got ' + F.GAME.state);
|
|
});
|
|
check('grid exists with wall + floor tiles', () => {
|
|
const G = L.GAME;
|
|
assert(Array.isArray(G.grid) && G.grid.length > 0, 'grid missing');
|
|
let walls = 0, floors = 0;
|
|
for (let y = 0; y < G.grid.length; y++)
|
|
for (let x = 0; x < G.grid[y].length; x++) {
|
|
if (isWall(G.grid[y][x])) walls++;
|
|
else if (isFloor(G.grid[y][x])) floors++;
|
|
}
|
|
assert(walls > 0 && floors > 0, 'need both walls(' + walls + ') and floors(' + floors + ')');
|
|
});
|
|
check('title screen explains controls (WASD, SPACE, Q/E, ENTER, ESC)', () => {
|
|
const html = fs.readFileSync(INDEX, 'utf8').toLowerCase();
|
|
assert(/wasd/.test(html), 'no WASD mention');
|
|
assert(/space/.test(html), 'no SPACE mention');
|
|
assert(/enter/.test(html), 'no ENTER mention');
|
|
assert(/esc/.test(html) || /pause/.test(html), 'no ESC/PAUSE mention');
|
|
assert(/\bq\b/.test(html) && /\be\b/.test(html), 'no Q/E mention');
|
|
});
|
|
check('ghost moves on ArrowRight', () => {
|
|
const G = L.GAME; G.start();
|
|
beginPlay(G);
|
|
clearArea(G, G.player.x, G.player.y, 3);
|
|
const before = G.player.x;
|
|
G.input('ArrowRight'); G.tick(1);
|
|
assert(G.player.x === before + 1, 'ghost did not move right (' + before + '->' + G.player.x + ')');
|
|
});
|
|
check('ghost cannot move into walls', () => {
|
|
const G = L.GAME; G.start(); beginPlay(G);
|
|
clearArea(G, G.player.x, G.player.y, 2);
|
|
setTile(G, G.player.x + 1, G.player.y, { type: 'wall', solid: true });
|
|
const before = G.player.x;
|
|
G.input('ArrowRight'); G.tick(1);
|
|
assert(G.player.x === before, 'ghost moved into a wall');
|
|
});
|
|
check('starting ghost timer >= 15 seconds', () => {
|
|
const G = L.GAME; G.start(); beginPlay(G);
|
|
const t = G.player.timer;
|
|
assert(typeof t === 'number' && t >= 15, 'ghost timer ' + t + ' < 15');
|
|
});
|
|
}
|
|
|
|
// ============================================================================
|
|
// PHASE 2 — possession + first 3 enemies
|
|
// ============================================================================
|
|
function phase2() {
|
|
let L;
|
|
check('load + begin play', () => { L = loadGame(); L.GAME.start(); beginPlay(L.GAME); assert(['playing','possessed'].includes(L.GAME.state), 'state ' + L.GAME.state); });
|
|
|
|
check('possess adjacent enemy -> state possessed', () => {
|
|
const G = L.GAME; forceGhost(G);
|
|
clearArea(G, G.player.x, G.player.y, 4);
|
|
G.spawn('brute', G.player.x + 1, G.player.y);
|
|
G.player.facing = 'right';
|
|
G.input('Space'); G.tick(2);
|
|
assert(G.state === 'possessed', 'not possessed after Space, state=' + G.state);
|
|
assert(G.player.host, 'player.host missing after possession');
|
|
});
|
|
|
|
check('Brute: HP 8, damage 3, slow movement', () => {
|
|
const G = L.GAME; forceGhost(G);
|
|
clearArea(G, G.player.x, G.player.y, 4);
|
|
const e = G.spawn('brute', G.player.x + 2, G.player.y);
|
|
const hp = e.maxHp || e.hp, dmg = e.damage, spd = e.speed ?? e.moveEvery ?? e.moveDelay;
|
|
assert(hp === 8, 'brute hp ' + hp);
|
|
assert(dmg === 3, 'brute damage ' + dmg);
|
|
assert(spd >= 2, 'brute should be slow (move delay>=2), got ' + spd);
|
|
});
|
|
|
|
check('Skitterer: HP 2, damage 1, fast movement', () => {
|
|
const G = L.GAME; forceGhost(G);
|
|
clearArea(G, G.player.x, G.player.y, 4);
|
|
const e = G.spawn('skitterer', G.player.x + 2, G.player.y);
|
|
const hp = e.maxHp || e.hp, dmg = e.damage, spd = e.speed ?? e.moveEvery ?? e.moveDelay;
|
|
assert(hp === 2, 'skitterer hp ' + hp);
|
|
assert(dmg === 1, 'skitterer damage ' + dmg);
|
|
assert(spd <= 1, 'skitterer should be fast (delay<=1), got ' + spd);
|
|
});
|
|
|
|
check('Sentinel: HP 4, ranged projectiles, no melee', () => {
|
|
const G = L.GAME; forceGhost(G);
|
|
clearArea(G, G.player.x, G.player.y, 6);
|
|
const e = G.spawn('sentinel', G.player.x + 5, G.player.y);
|
|
const hp = e.maxHp || e.hp;
|
|
assert(hp === 4, 'sentinel hp ' + hp);
|
|
let sawProj = false;
|
|
const before = (G.projectiles || []).length;
|
|
for (let i = 0; i < 8; i++) { G.tick(1); if ((G.projectiles || []).length > before) { sawProj = true; break; } }
|
|
assert(sawProj || e.ranged === true || e.melee === false, 'sentinel never fired / not flagged ranged');
|
|
});
|
|
|
|
check('enemies pathfind toward the ghost', () => {
|
|
const G = L.GAME; forceGhost(G);
|
|
clearArea(G, G.player.x, G.player.y, 7);
|
|
const e = G.spawn('brute', G.player.x + 6, G.player.y);
|
|
const d0 = manhattan(e.x, e.y, G.player.x, G.player.y);
|
|
let movedCloser = false;
|
|
for (let i = 0; i < 12; i++) {
|
|
G.tick(1);
|
|
const d = manhattan(e.x, e.y, G.player.x, G.player.y);
|
|
if (d < d0) { movedCloser = true; break; }
|
|
}
|
|
assert(movedCloser, 'brute never moved closer over 12 ticks');
|
|
});
|
|
|
|
check('killing host ejects ghost with timer > 0', () => {
|
|
const G = L.GAME;
|
|
possessType(G, 'brute');
|
|
assert(G.state === 'possessed', 'need a host first');
|
|
G.player.host.hp = 0; G.tick(2);
|
|
assert(G.player.ghost === true || ghostAt(G), 'not ejected as ghost');
|
|
assert(G.player.timer > 0, 'timer not > 0 after ejection: ' + G.player.timer);
|
|
});
|
|
|
|
check('essence increases on kill', () => {
|
|
const G = L.GAME;
|
|
possessType(G, 'brute');
|
|
assert(G.state === 'possessed', 'need host');
|
|
clearArea(G, G.player.x, G.player.y, 4);
|
|
const target = G.spawn('skitterer', G.player.x + 1, G.player.y);
|
|
G.player.facing = 'right';
|
|
const before = G.essence;
|
|
for (let i = 0; i < 4 && target.hp > 0; i++) { G.input('Space'); G.tick(1); }
|
|
assert(G.essence > before, 'essence did not increase (' + before + '->' + G.essence + ')');
|
|
});
|
|
}
|
|
|
|
// ============================================================================
|
|
// PHASE 3 — all 12 enemy types
|
|
// ============================================================================
|
|
function phase3() {
|
|
let L;
|
|
check('load + begin play', () => { L = loadGame(); L.GAME.start(); beginPlay(L.GAME); });
|
|
|
|
for (const type of ENEMY_TYPES) {
|
|
check('spawn ' + type + ' without error', () => {
|
|
const G = L.GAME; forceGhost(G);
|
|
clearArea(G, G.player.x, G.player.y, 5);
|
|
const e = G.spawn(type, G.player.x + 2, G.player.y);
|
|
assert(e && (e.type === type || String(e.type).toLowerCase() === type), type + ' spawn type mismatch: ' + e.type);
|
|
G.tick(2);
|
|
});
|
|
}
|
|
|
|
check('12 enemies have distinct (hp,damage,speed) tuples', () => {
|
|
const G = L.GAME; forceGhost(G);
|
|
clearArea(G, G.player.x, G.player.y, 6);
|
|
const tuples = new Set();
|
|
for (const type of ENEMY_TYPES) {
|
|
const e = G.spawn(type, G.player.x + 2, G.player.y + (ENEMY_TYPES.indexOf(type) % 5));
|
|
const hp = e.maxHp || e.hp, dmg = e.damage ?? 0, spd = e.speed ?? e.moveEvery ?? e.moveDelay ?? 0;
|
|
tuples.add(hp + '|' + dmg + '|' + spd);
|
|
}
|
|
assert(tuples.size === ENEMY_TYPES.length, 'only ' + tuples.size + ' distinct stat tuples among 12 enemies');
|
|
});
|
|
|
|
check('each ability triggers without error when possessed', () => {
|
|
const G = L.GAME;
|
|
for (const type of ENEMY_TYPES) {
|
|
const e = possessType(G, type);
|
|
if (!e) throw new Error('could not possess ' + type);
|
|
// fire the host special/attack a few times
|
|
for (let i = 0; i < 4; i++) { G.input('Space'); G.input('q'); G.input('e'); G.tick(1); }
|
|
assert(VALID_STATES.has(G.state), type + ' ability left invalid state ' + G.state);
|
|
forceGhost(G);
|
|
}
|
|
});
|
|
|
|
check('pathfinder navigates AROUND walls (never into them)', () => {
|
|
const G = L.GAME; forceGhost(G);
|
|
clearArea(G, G.player.x, G.player.y, 8);
|
|
// build a vertical wall between enemy and player with a gap
|
|
const wx = G.player.x + 4;
|
|
for (let y = G.player.y - 4; y <= G.player.y + 4; y++)
|
|
if (y !== G.player.y + 3) setTile(G, wx, y, { type: 'wall', solid: true });
|
|
const e = G.spawn('brute', G.player.x + 7, G.player.y);
|
|
let violated = false, reached = false;
|
|
for (let i = 0; i < 30; i++) {
|
|
G.tick(1);
|
|
if (isWall(G.grid[e.y] && G.grid[e.y][e.x])) violated = true;
|
|
if (manhattan(e.x, e.y, G.player.x, G.player.y) <= 1) { reached = true; break; }
|
|
}
|
|
assert(!violated, 'enemy entered a wall tile');
|
|
assert(reached, 'enemy never reached player around the wall');
|
|
});
|
|
}
|
|
|
|
// ============================================================================
|
|
// PHASE 4 — procgen + shop + save/load
|
|
// ============================================================================
|
|
function hashWalls(G) {
|
|
let s = '';
|
|
for (let y = 0; y < G.grid.length; y++)
|
|
for (let x = 0; x < G.grid[y].length; x++) s += isWall(G.grid[y][x]) ? '#' : '.';
|
|
return s;
|
|
}
|
|
function phase4() {
|
|
let L;
|
|
check('load + begin play', () => { L = loadGame(); L.GAME.start(); beginPlay(L.GAME); });
|
|
|
|
check('3 generated dungeons have different layouts', () => {
|
|
const G = L.GAME;
|
|
const hashes = new Set();
|
|
for (let i = 0; i < 3; i++) { G.newRun(); hashes.add(hashWalls(G)); }
|
|
assert(hashes.size >= 2, 'all 3 layouts identical (not random)');
|
|
});
|
|
|
|
check('exit tile exists on each floor', () => {
|
|
const G = L.GAME;
|
|
for (let f = 1; f <= 3; f++) { G.setFloor(f); assert(findExit(G), 'no exit on floor ' + f); }
|
|
});
|
|
|
|
check('shop opens with 3 choices', () => {
|
|
const G = L.GAME; G.openShop();
|
|
assert(G.state === 'shop', 'not in shop state: ' + G.state);
|
|
const choices = G.shop && G.shop.choices ? G.shop.choices : G.choices;
|
|
assert(Array.isArray(choices) && choices.length >= 3, 'shop needs >=3 choices, got ' + (choices && choices.length));
|
|
});
|
|
|
|
check('purchasing an upgrade changes GAME.upgrades', () => {
|
|
const G = L.GAME; G.openShop();
|
|
const before = JSON.stringify(G.upgrades || {});
|
|
let bought = false;
|
|
for (let i = 0; i < 3; i++) {
|
|
try { G.buy(i); bought = true; break; } catch (e) {}
|
|
}
|
|
assert(bought, 'could not buy any upgrade');
|
|
const after = JSON.stringify(G.upgrades || {});
|
|
assert(before !== after, 'upgrades unchanged after buy');
|
|
});
|
|
|
|
check('save() writes localStorage[bodysnatcher_save]', () => {
|
|
const G = L.GAME; G.start(); beginPlay(G);
|
|
G.essence = 42; G.floor = 3;
|
|
G.save();
|
|
assert(L.getSetItemCalls().indexOf(SAVE_KEY) >= 0, 'save() never called setItem(' + SAVE_KEY + ')');
|
|
assert(L.localStorage.getItem(SAVE_KEY), 'no save payload present');
|
|
});
|
|
|
|
check('save/load round-trip persists floor + essence + upgrades', () => {
|
|
const G = L.GAME; G.start(); beginPlay(G);
|
|
G.essence = 17; G.floor = 5;
|
|
G.openShop(); G.buy(0);
|
|
const upBefore = JSON.stringify(G.upgrades || {});
|
|
const floorBefore = G.floor, essBefore = G.essence;
|
|
G.save();
|
|
// mutate, then load
|
|
G.essence = 0; G.floor = 1; G.upgrades = {};
|
|
G.load();
|
|
assert(G.floor === floorBefore, 'floor not restored: ' + G.floor + ' vs ' + floorBefore);
|
|
assert(G.essence === essBefore, 'essence not restored: ' + G.essence + ' vs ' + essBefore);
|
|
assert(JSON.stringify(G.upgrades || {}) === upBefore, 'upgrades not restored');
|
|
});
|
|
}
|
|
|
|
// ============================================================================
|
|
// PHASE 5 — polish + completeness
|
|
// ============================================================================
|
|
function unlockedCount(G) {
|
|
const a = G.achievements || {};
|
|
let n = 0;
|
|
for (const k in a) { const v = a[k]; if (v === true || (v && v.unlocked === true)) n++; }
|
|
return n;
|
|
}
|
|
function phase5() {
|
|
let L;
|
|
check('load + begin play', () => { L = loadGame(); L.GAME.start(); beginPlay(L.GAME); });
|
|
|
|
check('can reach WON state (floor 10 exit)', () => {
|
|
const G = L.GAME; G.setFloor(10);
|
|
const ex = findExit(G);
|
|
assert(ex, 'no exit on floor 10');
|
|
clearArea(G, ex.x, ex.y, 2);
|
|
// stand adjacent then step onto the exit
|
|
G.player.x = ex.x - 1; G.player.y = ex.y; G.player.facing = 'right'; forceGhost(G);
|
|
G.input('ArrowRight'); G.tick(3);
|
|
if (G.state !== 'won') { // some games trigger on tick once standing on it
|
|
G.player.x = ex.x; G.player.y = ex.y; G.tick(3);
|
|
}
|
|
assert(G.state === 'won', 'did not reach won (state=' + G.state + ')');
|
|
});
|
|
|
|
check('can reach LOST state (ghost timer hits 0)', () => {
|
|
const G = L.GAME; G.start(); beginPlay(G); forceGhost(G);
|
|
G.player.timer = 0;
|
|
for (let i = 0; i < 6 && G.state !== 'lost'; i++) G.tick(1);
|
|
assert(G.state === 'lost', 'did not reach lost (state=' + G.state + ')');
|
|
});
|
|
|
|
check('at least 3 achievements can trigger', () => {
|
|
const G = L.GAME; G.start(); beginPlay(G);
|
|
possessType(G, 'brute'); // First Possession
|
|
for (const t of ['skitterer','sentinel','shielder','healer']) possessType(G, t); // Body Hopper
|
|
G.setFloor(7); G.tick(1); // Deep Diver
|
|
const n = unlockedCount(G);
|
|
assert(n >= 3, 'only ' + n + ' achievements unlocked');
|
|
});
|
|
|
|
check('audio system is exercised (AudioContext methods called)', () => {
|
|
const G = L.GAME; G.start(); beginPlay(G);
|
|
possessType(G, 'brute');
|
|
clearArea(G, G.player.x, G.player.y, 4);
|
|
G.spawn('skitterer', G.player.x + 1, G.player.y);
|
|
G.player.facing = 'right';
|
|
G.input('Space'); G.tick(2);
|
|
assert(L.getAudioCalls() > 0, 'no AudioContext methods were called');
|
|
});
|
|
|
|
check('200-tick stress test (move/possess/attack/descend) throws nothing', () => {
|
|
const G = L.GAME; G.start(); beginPlay(G);
|
|
const keys = ['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','Space','q','e','Enter'];
|
|
let lastErr = null;
|
|
try {
|
|
for (let i = 0; i < 200; i++) {
|
|
G.input(keys[i % keys.length]);
|
|
G.tick(1);
|
|
if (i === 60) { try { G.setFloor(2); } catch (e) {} }
|
|
if (i === 140) { try { G.setFloor(3); } catch (e) {} }
|
|
if (G.state === 'lost' || G.state === 'won') break;
|
|
}
|
|
} catch (e) { lastErr = e; }
|
|
assert(!lastErr, 'stress test threw: ' + (lastErr && lastErr.message));
|
|
});
|
|
}
|
|
|
|
// ----------------------------- run -----------------------------------------
|
|
const runners = { 1: phase1, 2: phase2, 3: phase3, 4: phase4, 5: phase5 };
|
|
if (!fs.existsSync(INDEX)) {
|
|
console.log('index.html not found');
|
|
process.exit(1);
|
|
}
|
|
const fn = runners[phase];
|
|
if (!fn) { console.log('unknown phase: ' + phase); process.exit(1); }
|
|
console.log('=== Phase ' + phase + ' ===');
|
|
fn();
|
|
console.log('=== Phase ' + phase + ' ' + (failures.length === 0 ? 'PASSED' : 'FAILED (' + failures.length + ')') + ' ===');
|
|
if (failures.length) {
|
|
console.log('\nFailures:');
|
|
failures.forEach((f) => console.log(' - ' + f));
|
|
process.exit(1);
|
|
}
|
|
process.exit(0);
|