293 lines
18 KiB
JavaScript
293 lines
18 KiB
JavaScript
#!/usr/bin/env node
|
|
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const vm = require('vm');
|
|
|
|
const phase = Number(process.argv[2] || 5);
|
|
const checks = [];
|
|
const ok = (condition, message) => {
|
|
if (!condition) throw new Error(message);
|
|
checks.push(message);
|
|
};
|
|
const value = (object, names, fallback) => {
|
|
for (const name of names) if (object && object[name] != null) return object[name];
|
|
return fallback;
|
|
};
|
|
const tileName = tile => String((tile && (tile.type ?? tile.kind ?? tile.tile)) ?? tile).toLowerCase();
|
|
const isWall = tile => /wall|#/.test(tileName(tile)) || tile === 1;
|
|
const isFloor = tile => !isWall(tile) && !/void|unknown/.test(tileName(tile));
|
|
const keyFor = (dx, dy) => dx < 0 ? 'ArrowLeft' : dx > 0 ? 'ArrowRight' : dy < 0 ? 'ArrowUp' : 'ArrowDown';
|
|
const gridRows = game => Array.isArray(game.grid?.[0]) ? game.grid : [];
|
|
const setPlayerPosition = (game, x, y) => {
|
|
game.player.x = x; game.player.y = y;
|
|
if ('tx' in game.player) game.player.tx = x;
|
|
if ('ty' in game.player) game.player.ty = y;
|
|
if ('renderX' in game.player) game.player.renderX = x;
|
|
if ('renderY' in game.player) game.player.renderY = y;
|
|
};
|
|
const position = entity => [Number(value(entity, ['x', 'col'], 0)), Number(value(entity, ['y', 'row'], 0))];
|
|
|
|
function mocks() {
|
|
const storage = new Map();
|
|
let storageWrites = 0;
|
|
let audioCalls = 0;
|
|
const noop = () => {};
|
|
const gradient = { addColorStop: noop };
|
|
const context2d = new Proxy({ canvas: null, measureText: text => ({ width: String(text).length * 8 }), createLinearGradient: () => gradient, createRadialGradient: () => gradient, createPattern: () => ({}), getImageData: () => ({ data: new Uint8ClampedArray(4) }) }, { get: (target, key) => key in target ? target[key] : noop, set: (target, key, val) => (target[key] = val, true) });
|
|
const listeners = {};
|
|
const element = tag => ({
|
|
tagName: String(tag).toUpperCase(), id: '', width: tag === 'canvas' ? 800 : 0, height: tag === 'canvas' ? 640 : 0,
|
|
style: {}, classList: { add: noop, remove: noop, toggle: noop, contains: () => false }, children: [],
|
|
appendChild(child) { this.children.push(child); return child; }, remove: noop, focus: noop,
|
|
addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, removeEventListener: noop,
|
|
getContext: () => context2d, getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 640 }),
|
|
setAttribute(name, val) { this[name] = val; }, getAttribute(name) { return this[name] ?? null; },
|
|
querySelector: () => null, querySelectorAll: () => []
|
|
});
|
|
const canvas = element('canvas');
|
|
canvas.id = 'game'; context2d.canvas = canvas;
|
|
const body = element('body'); body.appendChild(canvas);
|
|
const document = {
|
|
body, readyState: 'loading', hidden: false,
|
|
createElement: element,
|
|
getElementById: id => id === 'game' || id === 'canvas' ? canvas : null,
|
|
querySelector: selector => selector === 'canvas' || selector === '#game' || selector === '#canvas' ? canvas : null,
|
|
querySelectorAll: selector => selector === 'canvas' ? [canvas] : [],
|
|
addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, removeEventListener: noop,
|
|
dispatchEvent(event) { for (const fn of listeners[event.type] || []) fn(event); },
|
|
};
|
|
class AudioParam { setValueAtTime() { audioCalls++; } linearRampToValueAtTime() { audioCalls++; } exponentialRampToValueAtTime() { audioCalls++; } cancelScheduledValues() {} }
|
|
class AudioNode { constructor() { this.frequency = new AudioParam(); this.gain = new AudioParam(); this.type = 'sine'; } connect() { audioCalls++; return this; } disconnect() {} start() { audioCalls++; } stop() { audioCalls++; } }
|
|
class AudioContext { constructor() { audioCalls++; this.currentTime = 0; this.destination = new AudioNode(); this.state = 'running'; } createOscillator() { audioCalls++; return new AudioNode(); } createGain() { audioCalls++; return new AudioNode(); } createBiquadFilter() { return new AudioNode(); } resume() { audioCalls++; return Promise.resolve(); } close() { return Promise.resolve(); } }
|
|
const localStorage = { getItem: key => storage.has(key) ? storage.get(key) : null, setItem: (key, val) => { storageWrites++; storage.set(key, String(val)); }, removeItem: key => storage.delete(key), clear: () => storage.clear(), key: i => [...storage.keys()][i] ?? null, get length() { return storage.size; } };
|
|
let now = 1000;
|
|
const window = {
|
|
document, localStorage, AudioContext, webkitAudioContext: AudioContext, innerWidth: 800, innerHeight: 640, devicePixelRatio: 1,
|
|
performance: { now: () => (now += 16) }, navigator: { userAgent: 'verify.js' }, location: { reload: noop },
|
|
addEventListener(type, fn) { (listeners[type] ||= []).push(fn); }, removeEventListener: noop,
|
|
dispatchEvent(event) { for (const fn of listeners[event.type] || []) fn(event); },
|
|
requestAnimationFrame: fn => (window.__raf = fn, 1), cancelAnimationFrame: noop,
|
|
setTimeout: () => 1, clearTimeout: noop, setInterval: () => 1, clearInterval: noop,
|
|
confirm: () => false, alert: noop,
|
|
};
|
|
window.window = window; window.self = window; window.globalThis = window;
|
|
const sandbox = {
|
|
window, self: window, document, localStorage, AudioContext, webkitAudioContext: AudioContext,
|
|
requestAnimationFrame: window.requestAnimationFrame, cancelAnimationFrame: noop,
|
|
setTimeout: window.setTimeout, clearTimeout: noop, setInterval: window.setInterval, clearInterval: noop,
|
|
performance: window.performance, navigator: window.navigator, location: window.location,
|
|
console, Math, Date, JSON, Array, Object, String, Number, Boolean, Map, Set, WeakMap, Promise,
|
|
Uint8ClampedArray, Event: class Event { constructor(type, init = {}) { this.type = type; Object.assign(this, init); } },
|
|
KeyboardEvent: class KeyboardEvent { constructor(type, init = {}) { this.type = type; Object.assign(this, init); } },
|
|
};
|
|
sandbox.globalThis = sandbox;
|
|
return { sandbox, window, storage, metrics: { get storageWrites() { return storageWrites; }, get audioCalls() { return audioCalls; } } };
|
|
}
|
|
|
|
function boot() {
|
|
const file = path.join(__dirname, 'index.html');
|
|
ok(fs.existsSync(file), 'index.html exists');
|
|
const html = fs.readFileSync(file, 'utf8');
|
|
ok(/<canvas\b/i.test(html), 'index.html contains a canvas');
|
|
ok(/<script\b/i.test(html), 'index.html contains inline JavaScript');
|
|
ok(!/<script\b[^>]*\bsrc\s*=/i.test(html), 'no external script src attributes');
|
|
ok(!/<(?:link|img|audio|video)\b[^>]*(?:href|src)\s*=\s*["']https?:/i.test(html), 'no external asset dependencies');
|
|
ok(!/<script\b[^>]*\btype\s*=\s*["']module["']/i.test(html), 'no ES modules');
|
|
ok(!/(^|[;{}]\s*)import\s+(?:[\w*{]|["'])/m.test(html), 'no import statements');
|
|
const scripts = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/gi)].map(match => match[1]);
|
|
const env = mocks();
|
|
vm.createContext(env.sandbox);
|
|
scripts.forEach((script, i) => vm.runInContext(script, env.sandbox, { filename: `index.html:inline-${i + 1}`, timeout: 3000 }));
|
|
const game = env.window.GAME || env.sandbox.GAME;
|
|
ok(game && typeof game === 'object', 'window.GAME is exposed');
|
|
ok(typeof game.start === 'function', 'GAME.start() is exposed');
|
|
ok(typeof game.input === 'function', 'GAME.input(key) is exposed');
|
|
ok(typeof game.tick === 'function', 'GAME.tick(n) is exposed');
|
|
game.start();
|
|
if (game.state === 'title') game.input('Enter');
|
|
return { ...env, game, html };
|
|
}
|
|
|
|
function adjacentFloor(game, origin = game.player) {
|
|
const rows = gridRows(game); const [x, y] = position(origin);
|
|
for (const [dx, dy] of [[1,0],[-1,0],[0,1],[0,-1]]) if (rows[y + dy] && isFloor(rows[y + dy][x + dx])) return { x: x + dx, y: y + dy, dx, dy };
|
|
for (let yy = 1; yy < rows.length - 1; yy++) for (let xx = 1; xx < rows[yy].length - 1; xx++) {
|
|
if (!isFloor(rows[yy][xx])) continue;
|
|
for (const [dx, dy] of [[1,0],[-1,0],[0,1],[0,-1]]) if (isFloor(rows[yy + dy]?.[xx + dx])) { setPlayerPosition(game, xx, yy); return { x: xx + dx, y: yy + dy, dx, dy }; }
|
|
}
|
|
throw new Error('no adjacent floor tiles available');
|
|
}
|
|
|
|
function phase1(env) {
|
|
const game = env.game;
|
|
const validStates = ['title','playing','ghost','possessed','shop','paused','won','lost','gameover','victory'];
|
|
ok(validStates.includes(String(game.state).toLowerCase()), 'GAME.state is valid');
|
|
ok(game.player && typeof game.player === 'object', 'GAME.player is exposed');
|
|
const rows = gridRows(game);
|
|
ok(rows.length > 0 && rows[0].length > 0, 'grid is a two-dimensional array');
|
|
const flat = rows.flat();
|
|
ok(flat.some(isWall), 'grid contains walls');
|
|
ok(flat.some(isFloor), 'grid contains floor tiles');
|
|
game.state = 'ghost'; if ('mode' in game.player) game.player.mode = 'ghost';
|
|
const step = adjacentFloor(game); const before = position(game.player);
|
|
game.input(keyFor(step.dx, step.dy));
|
|
const after = position(game.player);
|
|
ok(after[0] !== before[0] || after[1] !== before[1], 'Arrow/WASD input moves the ghost');
|
|
let wallCase;
|
|
for (let y = 1; y < rows.length - 1 && !wallCase; y++) for (let x = 1; x < rows[y].length - 1; x++) if (isFloor(rows[y][x])) {
|
|
for (const [dx, dy] of [[1,0],[-1,0],[0,1],[0,-1]]) if (isWall(rows[y + dy]?.[x + dx])) { wallCase = { x, y, dx, dy }; break; }
|
|
}
|
|
ok(wallCase, 'grid has a floor tile adjacent to a wall');
|
|
setPlayerPosition(game, wallCase.x, wallCase.y); game.input(keyFor(wallCase.dx, wallCase.dy));
|
|
ok(position(game.player)[0] === wallCase.x && position(game.player)[1] === wallCase.y, 'ghost cannot move through walls without upgrade');
|
|
}
|
|
|
|
function clearEnemies(game) {
|
|
ok(Array.isArray(game.enemies), 'GAME.enemies is exposed');
|
|
game.enemies.length = 0;
|
|
if (Array.isArray(game.projectiles)) game.projectiles.length = 0;
|
|
}
|
|
function spawn(game, type, x, y) {
|
|
ok(typeof game.spawn === 'function', 'GAME.spawn(type,x,y) is exposed for testing');
|
|
const before = game.enemies.length;
|
|
const result = game.spawn(type, x, y);
|
|
const enemy = result || game.enemies[game.enemies.length - 1];
|
|
ok(enemy && game.enemies.length > before, `${type} can be spawned`);
|
|
return enemy;
|
|
}
|
|
function ghostSetup(game) {
|
|
game.state = 'ghost'; clearEnemies(game);
|
|
game.player.host = null; game.player.body = null; game.player.type = 'ghost'; game.player.hp = 1;
|
|
game.player.ghostTimer = 8; game.player.timer = 8;
|
|
return adjacentFloor(game);
|
|
}
|
|
function possess(game, type) {
|
|
const spot = ghostSetup(game);
|
|
const enemy = spawn(game, type, spot.x, spot.y);
|
|
game.input('Space');
|
|
if (game.state !== 'possessed') game.input('Space');
|
|
ok(game.state === 'possessed', `${type} is possessable with Space`);
|
|
return { enemy, body: game.player.host || game.player.body || game.player };
|
|
}
|
|
|
|
function phase2(env) {
|
|
const game = env.game;
|
|
const expected = { Brute: [8,3], Skitterer: [2,1], Sentinel: [4,0] };
|
|
for (const [type, [hp, damage]] of Object.entries(expected)) {
|
|
const { body } = possess(game, type);
|
|
ok(Number(value(body, ['maxHp','maxHP','hp'])) === hp, `${type} has ${hp} HP`);
|
|
ok(Number(value(body, ['damage','attack','dmg'], 0)) === damage, `${type} has expected damage ${damage}`);
|
|
ok(value(body, ['speed','moveEvery','moveDelay']) != null, `${type} exposes movement speed`);
|
|
if (type === 'Sentinel') {
|
|
const before = game.projectiles?.length || 0; game.input('Space');
|
|
ok((game.projectiles?.length || 0) > before || /shoot|projectile|ranged/i.test(String(value(body, ['special','ability','attackType'], ''))), 'Sentinel has a projectile attack and no melee');
|
|
}
|
|
}
|
|
const { body } = possess(game, 'Brute');
|
|
body.hp = 0; game.player.hp = 0; game.tick(1);
|
|
ok(game.state === 'ghost', 'dead host ejects the player as a ghost');
|
|
ok(Number(value(game.player, ['ghostTimer','timer'], 0)) > 0, 'ejection starts a positive ghost timer');
|
|
const spot = adjacentFloor(game); const target = spawn(game, 'Skitterer', spot.x, spot.y); const essence = Number(game.essence || 0);
|
|
ok(typeof game.damageEnemy === 'function', 'GAME.damageEnemy(enemy,amount) is exposed for deterministic testing');
|
|
game.damageEnemy(target, 999);
|
|
ok(Number(game.essence || 0) > essence, 'enemy death drops and awards essence');
|
|
ok(typeof game.findPath === 'function', 'GAME.findPath() exposes enemy pathfinding');
|
|
const enemy = spawn(game, 'Brute', spot.x, spot.y); const old = position(enemy); game.state = 'ghost'; game.tick(2); const moved = position(enemy);
|
|
ok(moved[0] !== old[0] || moved[1] !== old[1] || Math.abs(old[0]-position(game.player)[0]) + Math.abs(old[1]-position(game.player)[1]) <= 1, 'enemy pathfinding advances toward the ghost');
|
|
}
|
|
|
|
const TYPES = ['Brute','Skitterer','Sentinel','Shielder','Bomber','Healer','Phaser','Turret','Charger','Siren','Mimic','Leech'];
|
|
function phase3(env) {
|
|
const game = env.game; clearEnemies(game);
|
|
const signatures = new Set();
|
|
let tile = adjacentFloor(game);
|
|
for (const type of TYPES) {
|
|
const enemy = spawn(game, type, tile.x, tile.y);
|
|
const signature = [value(enemy,['maxHp','maxHP','hp']), value(enemy,['damage','attack','dmg'],0), value(enemy,['speed','moveEvery','moveDelay'],1)].join(':');
|
|
ok(!signatures.has(signature), `${type} has a distinct HP/damage/speed kit`); signatures.add(signature);
|
|
game.enemies.splice(game.enemies.indexOf(enemy), 1);
|
|
const { body } = possess(game, type);
|
|
game.input('Space'); game.tick(1);
|
|
ok(value(body, ['special','ability','attackType','type'], type) != null, `${type} special executes without error`);
|
|
}
|
|
const originalGrid = game.grid;
|
|
const testGrid = [
|
|
['wall','wall','wall','wall','wall'],
|
|
['wall','floor','wall','floor','wall'],
|
|
['wall','floor','wall','floor','wall'],
|
|
['wall','floor','floor','floor','wall'],
|
|
['wall','wall','wall','wall','wall'],
|
|
];
|
|
game.grid = testGrid;
|
|
const route = game.findPath(1,1,3,1);
|
|
game.grid = originalGrid;
|
|
ok(Array.isArray(route) && route.length >= 6, 'pathfinder routes around blocking walls');
|
|
ok(!route.some(step => position(step)[0] === 2 && position(step)[1] < 3), 'pathfinder never routes through walls');
|
|
}
|
|
|
|
function layout(game) { return gridRows(game).map(row => row.map(tile => isWall(tile) ? '#' : tileName(tile).includes('exit') || tileName(tile).includes('stairs') ? 'E' : '.').join('')).join('\n'); }
|
|
function phase4(env) {
|
|
const game = env.game;
|
|
ok(typeof game.generateFloor === 'function', 'GAME.generateFloor(floor) is exposed');
|
|
const layouts = new Set();
|
|
for (let i = 0; i < 3; i++) {
|
|
game.generateFloor(1);
|
|
const text = layout(game); layouts.add(text);
|
|
ok(text.includes('E') || gridRows(game).flat().some(tile => /exit|stair/.test(tileName(tile))), 'generated floor contains exit stairs');
|
|
}
|
|
ok(layouts.size === 3, 'three generated dungeons have different layouts');
|
|
ok(typeof game.completeFloor === 'function', 'GAME.completeFloor() is exposed for floor transitions');
|
|
game.floor = 1; game.state = 'ghost'; game.completeFloor();
|
|
ok(game.state === 'shop', 'shop appears between floors');
|
|
ok(Array.isArray(game.shopChoices) && game.shopChoices.length === 3, 'shop presents three choices');
|
|
ok(typeof game.buyUpgrade === 'function', 'GAME.buyUpgrade(index) is exposed');
|
|
game.essence = 999; const before = JSON.stringify(game.upgrades);
|
|
game.buyUpgrade(0);
|
|
ok(JSON.stringify(game.upgrades) !== before, 'purchasing a shop choice changes upgrades');
|
|
ok(typeof game.save === 'function' && typeof game.load === 'function', 'GAME.save/load are exposed');
|
|
game.floor = 4; game.essence = 37;
|
|
if (Array.isArray(game.upgrades)) game.upgrades.push('verify_roundtrip'); else game.upgrades.verify_roundtrip = true;
|
|
const upgrades = JSON.stringify(game.upgrades); game.save();
|
|
ok(env.metrics.storageWrites > 0 && env.storage.has('bodysnatcher_save'), 'save writes bodysnatcher_save to localStorage');
|
|
game.floor = 1; game.essence = 0; game.upgrades = Array.isArray(game.upgrades) ? [] : {};
|
|
game.load();
|
|
ok(Number(game.floor) === 4 && Number(game.essence) === 37 && JSON.stringify(game.upgrades) === upgrades, 'save/load round-trip preserves floor, essence, and upgrades');
|
|
}
|
|
|
|
function phase5(env) {
|
|
const game = env.game;
|
|
ok(typeof game.newRun === 'function', 'GAME.newRun() is exposed');
|
|
game.newRun(); game.floor = 10; game.state = 'ghost'; game.completeFloor();
|
|
ok(game.state === 'won' || game.state === 'victory', 'completing floor 10 reaches the win state');
|
|
game.newRun(); game.state = 'ghost'; game.player.host = null; game.player.body = null; game.player.ghostTimer = 0; game.player.timer = 0; game.tick(1);
|
|
ok(game.state === 'lost' || game.state === 'gameover', 'expired ghost timer reaches the lose state');
|
|
const achievements = game.achievements;
|
|
ok(achievements && Object.keys(achievements).length >= 8, 'all eight achievements are defined');
|
|
ok(typeof game.unlockAchievement === 'function', 'GAME.unlockAchievement(name) is exposed');
|
|
for (const name of Object.keys(achievements).slice(0, 3)) game.unlockAchievement(name);
|
|
const unlocked = Object.values(game.achievements).filter(item => item === true || item?.unlocked).length;
|
|
ok(unlocked >= 3, 'at least three achievements can unlock');
|
|
if (typeof game.sound === 'function') game.sound('hit'); else { game.newRun(); game.input('Space'); }
|
|
ok(env.metrics.audioCalls > 0, 'Web Audio API is initialized and used');
|
|
game.newRun();
|
|
const keys = ['ArrowRight','ArrowDown','ArrowLeft','ArrowUp','Space','q','e'];
|
|
for (let i = 0; i < 200; i++) { game.input(keys[i % keys.length]); game.tick(1); }
|
|
for (let i = 0; i < 3; i++) { if (game.state === 'shop') game.input('Enter'); if (!['won','lost','gameover'].includes(game.state)) game.completeFloor(); }
|
|
ok(true, '200-tick movement/combat/transition stress test completes without errors');
|
|
}
|
|
|
|
try {
|
|
ok(Number.isInteger(phase) && phase >= 1 && phase <= 5, 'phase argument is 1 through 5');
|
|
const env = boot();
|
|
const phases = [phase1, phase2, phase3, phase4, phase5];
|
|
for (let i = 0; i < phase; i++) phases[i](env);
|
|
console.log(`PASS phase ${phase}: ${checks.length} checks`);
|
|
for (const check of checks) console.log(` ✓ ${check}`);
|
|
} catch (error) {
|
|
console.error(`FAIL phase ${phase}: ${error.message}`);
|
|
if (process.env.VERBOSE) console.error(error.stack);
|
|
process.exitCode = 1;
|
|
}
|