Files

113 lines
5.7 KiB
JavaScript

// Shared browser checks for the Three.js tic-tac-toe game (offline test driver, not shipped): 6 checks, real mouse clicks.
// node check_ttt.mjs /path/to/index.html (needs `playwright` + its chromium installed in the test directory only)
import { chromium } from 'playwright';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { resolve, dirname, basename, extname, join } from 'node:path';
const file = resolve(process.argv[2] ?? 'index.html');
// ES module imports are blocked on file:// (CORS), so the game's directory is served over local http, as any real deployment would.
const types = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png' };
const root = dirname(file);
const server = createServer(async (req, res) => {
try {
const path = decodeURIComponent(new URL(req.url, 'http://x').pathname);
const target = path === '/' ? file : join(root, path);
if (!target.startsWith(root)) { res.writeHead(403).end(); return; }
const body = await readFile(target);
res.writeHead(200, { 'content-type': types[extname(target)] ?? 'application/octet-stream' }).end(body);
} catch { res.writeHead(404).end(); }
});
await new Promise((ok) => server.listen(0, '127.0.0.1', ok));
const url = `http://127.0.0.1:${server.address().port}/${basename(file)}`;
const results = [];
const check = (name, ok, detail = '') => {
results.push({ name, ok: !!ok, detail });
console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${ok ? '' : ' :: ' + detail}`);
};
const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
const page = await browser.newPage({ viewport: { width: 900, height: 900 } });
const errors = [];
page.on('pageerror', (e) => errors.push(String(e)));
page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto(url);
await page.waitForTimeout(1500);
check('1 loads without page error', errors.length === 0, errors.join(' | ').slice(0, 300));
const box = await page.evaluate(() => {
const c = document.querySelector('canvas');
if (!c) return null;
const r = c.getBoundingClientRect();
return { x: r.x, y: r.y, w: r.width, h: r.height };
});
check('2 visible WebGL canvas', box && box.w > 100 && box.h > 100, JSON.stringify(box));
const status = async () => (await page.evaluate(() => document.getElementById('status')?.textContent ?? '')).trim();
const restart = async () => { const b = await page.$('#restart'); if (b) await b.click(); await page.waitForTimeout(200); };
// The board layout is the game's own (camera, perspective, size): find the nine cells by probing. Click a dense grid over the
// canvas; a point that changes the status text placed a mark (then restart). The accepted points form nine clusters.
const initial = await status();
const accepted = [];
const N = 28;
for (let gy = 0; gy < N; gy++) {
for (let gx = 0; gx < N; gx++) {
const x = box.x + (gx + 0.5) * box.w / N, y = box.y + (gy + 0.5) * box.h / N;
await page.mouse.click(x, y);
await page.waitForTimeout(40);
if ((await status()) !== initial) { accepted.push([x, y]); await restart(); }
}
}
let pts = [];
if (accepted.length >= 9) {
// Rows are thirds of the accepted y-range, columns thirds of that row's x-range; each cell is the accepted point nearest to the third's centre.
const ys = accepted.map((p) => p[1]);
const y0 = Math.min(...ys), y1 = Math.max(...ys);
for (let r = 0; r < 3; r++) {
const lo = y0 + (r * (y1 - y0 + 1)) / 3, hi = y0 + ((r + 1) * (y1 - y0 + 1)) / 3;
const band = accepted.filter((p) => p[1] >= lo && p[1] < hi);
if (!band.length) continue;
const x0 = Math.min(...band.map((p) => p[0])), x1 = Math.max(...band.map((p) => p[0]));
const cy = band.reduce((a, p) => a + p[1], 0) / band.length;
for (let c = 0; c < 3; c++) {
const cx = x0 + ((c + 0.5) * (x1 - x0 + 1)) / 3;
pts.push(band.reduce((best, p) => (Math.hypot(p[0] - cx, p[1] - cy) < Math.hypot(best[0] - cx, best[1] - cy) ? p : best), band[0]));
}
}
}
console.log(`probe: ${accepted.length} accepted clicks, ${pts.length} cell centres`);
if (pts.length !== 9) {
check('3 row win via real clicks', false, 'could not find nine clickable cells');
check('4 moves blocked after the win', false, 'no cells');
check('5 restart to empty board (X to move)', false, 'no cells');
check('6 draw via real clicks', false, 'no cells');
await browser.close(); server.close();
console.log('SUMMARY ' + results.filter((r) => r.ok).length + '/6');
process.exit(1);
}
const click = async (i) => { await page.mouse.click(pts[i][0], pts[i][1]); await page.waitForTimeout(Number(process.env.CLICK_WAIT_MS ?? 250)); };
// 3: row win via real clicks: X takes 0,1,2; O takes 3,4
for (const i of [0, 3, 1, 4, 2]) await click(i);
const s3 = await status();
check('3 row win via real clicks', /X/i.test(s3) && /win/i.test(s3), s3);
// 4: moves blocked after the win
const before = await status();
await click(5); await click(6);
const after = await status();
check('4 moves blocked after the win', before === after && /win/i.test(after), `${before} -> ${after}`);
// 5: restart to an empty board
await restart();
const s5 = await status();
check('5 restart to empty board (X to move)', /X/i.test(s5) && !/win|draw/i.test(s5), s5);
// 6: draw via real clicks: X O X / X O O / O X X
for (const i of [0, 1, 2, 4, 3, 5, 7, 6, 8]) { await click(i); if (process.env.TRACE) console.log(" click", i, "->", await status()); }
const s6 = await status();
check('6 draw via real clicks', /draw/i.test(s6), s6);
await browser.close();
server.close();
const passed = results.filter((r) => r.ok).length;
console.log(`SUMMARY ${passed}/6`);
process.exit(passed === 6 ? 0 : 1);