UXInteract / task_049 /tests /validate_ui_behavior.js
DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
13.8 kB
// Tiered, deterministic correctness verifier for the Flappy Bird task.
// Drives window.__game and asserts exact state transitions WITHOUT real time:
// physics advances only through step(dtMs) calls. Prints PASS/FAIL per tier and
// a final `SCORE=<fraction>` used by test.sh as the (partial) reward.
const path = require('path');
const { pathToFileURL } = require('url');
const { chromium } = require('playwright');
function assert(cond, msg){ if (!cond) throw new Error(msg); }
function eq(a, b){ return require("node:util").isDeepStrictEqual(a,b); }
(async () => {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 480, height: 760 } });
const errs = [];
page.on('pageerror', e => errs.push(e.message));
await page.goto(pathToFileURL(path.join(process.cwd(), 'index.html')).href, { waitUntil: 'domcontentloaded' });
await page.waitForTimeout(300);
const hasApi = await page.evaluate(() => !!(window.__game
&& typeof window.__game.init === 'function'
&& typeof window.__game.getState === 'function'
&& typeof window.__game.flap === 'function'
&& typeof window.__game.step === 'function'));
// Helper: run an in-page function with one argument, return its result.
const run = (fn, arg) => page.evaluate(fn, arg);
const tiers = [
['T1 API present + canvas + getState has bird & a pipe + status ready', async () => {
assert(hasApi, 'window.__game with init/getState/flap/step is required');
assert(errs.length === 0, 'no page errors allowed: ' + errs.join(' | '));
const canvasOk = await run(() => {
const c = document.querySelector('canvas[data-testid="canvas"]') || document.querySelector('canvas');
return !!c && c.width >= 100 && c.height >= 100;
});
assert(canvasOk, 'a >=100x100 canvas must render');
const st = await run(() => window.__game.init({ seed: 1 }));
assert(st && st.bird && typeof st.bird.y === 'number' && typeof st.bird.vy === 'number', 'getState must expose bird {y,vy}');
assert(Array.isArray(st.pipes) && st.pipes.length >= 1, 'getState must expose at least one upcoming pipe');
const p = st.pipes[0];
assert(typeof p.x === 'number' && typeof p.gapY === 'number' && typeof p.gapH === 'number' && typeof p.passed === 'boolean',
'pipe must have {x, gapY, gapH, passed}');
assert(st.status === 'ready', 'fresh game status must be "ready", got ' + st.status);
// Canvas-paint anti-fake: a real renderer paints the sky, pipes, ground and
// bird, so the canvas pixels must contain several distinct colors. An engine
// that updates state but never draws leaves a blank/uniform canvas.
const distinctColors = await run(() => {
window.__game.init({seed:1,gravity:0.2,flapImpulse:4,width:500,height:600,birdY:300,pipes:[]});
window.__game.flap(); // start play so pipes/bird animate
for (let i = 0; i < 5; i++) window.__game.step(16);
const c = document.querySelector('canvas[data-testid="canvas"]') || document.querySelector('canvas');
const ctx = c.getContext('2d');
const data = ctx.getImageData(0, 0, c.width, c.height).data;
const seen = new Set();
for (let i = 0; i < data.length; i += 4){
seen.add(data[i] + ',' + data[i+1] + ',' + data[i+2]);
if (seen.size >= 8) break;
}
return seen.size;
});
assert(distinctColors >= 2, 'canvas must paint multiple visible colors, got ' + distinctColors);
// restore the fresh "ready" state for any later assumptions
await run(() => window.__game.init({ seed: 1 }));
}],
['T2 gravity makes bird fall + full determinism across re-init', async () => {
// gravity/flapImpulse are INJECTABLE params (the instruction only requires
// "sensible defaults"), so we must NOT reverse-engineer the reference's
// default constant. Instead drive gravity via the documented injection API
// (as T4/T5 already do) with a KNOWN value and start already 'playing' with
// no flap, so the only vertical force is the injected gravity. Then assert
// the bird falls under THAT injected gravity.
const GRAVITY = 0.5; // value we INJECT, not an assumed default
const a = await run((G) => {
window.__game.init({ seed: 1, status: 'playing', width: 500, height: 600, birdX: 80, birdR: 12, pipeWidth: 52, pipeSpeed: 0, gravity: G, birdY: 60, birdVy: 0, pipes: [] });
const ys = [], vys = [];
for (let i = 0; i < 30; i++){
const s = window.__game.step(16);
ys.push(s.bird.y); vys.push(s.bird.vy);
}
return { ys, vys, final: window.__game.getState().bird };
}, GRAVITY);
const EPS = 1e-9;
// vy must be NON-DECREASING each step (a terminal-velocity clamp that holds
// vy constant is acceptable).
for (let i = 1; i < a.vys.length; i++){
assert(a.vys[i] >= a.vys[i-1] - EPS, 'vy must be non-decreasing under gravity at step ' + i + ' (' + a.vys[i-1] + ' -> ' + a.vys[i] + ')');
}
// With no flap, the bird must net-fall: both vy and y increase over the run.
// We also allow (but do not require) the precise semi-implicit-Euler net
// increase under the INJECTED gravity, accepting either as evidence of fall.
const netVy = a.vys[a.vys.length - 1] - a.vys[0];
const minNet = GRAVITY * (a.vys.length - 1);
assert(netVy > EPS || netVy >= minNet - EPS,
'vy must increase (bird accelerates downward) under injected gravity, net=' + netVy);
for (let i = 1; i < a.ys.length; i++){
assert(a.ys[i] >= a.ys[i-1] - EPS, 'with no flap, bird.y must move downward (increase) at step ' + i);
}
assert(a.ys[a.ys.length - 1] > a.ys[0], 'bird should net fall downward over the run');
// Determinism: identical init + identical step sequence -> identical state.
const b = await run((G) => {
window.__game.init({ seed: 1, status: 'playing', width: 500, height: 600, birdX: 80, birdR: 12, pipeWidth: 52, pipeSpeed: 0, gravity: G, birdY: 60, birdVy: 0, pipes: [] });
for (let i = 0; i < 30; i++) window.__game.step(16);
return window.__game.getState().bird;
}, GRAVITY);
assert(eq(a.final, b), 'determinism failed: same seed + same steps must give identical bird, got '
+ JSON.stringify(a.final) + ' vs ' + JSON.stringify(b));
}],
['T3 flap pushes the bird up (vy negative; ends higher than baseline)', async () => {
const r = await run((K) => {
// Baseline: start play with a flap, then step K times.
window.__game.init({seed:1,gravity:0.2,flapImpulse:4,width:500,height:600,birdY:300,pipes:[]});
window.__game.flap();
for (let i = 0; i < K; i++) window.__game.step(16);
const baselineY = window.__game.getState().bird.y;
// Flapped run: same start, but flap AGAIN partway through to push up.
window.__game.init({seed:1,gravity:0.2,flapImpulse:4,width:500,height:600,birdY:300,pipes:[]});
window.__game.flap();
const flapState = window.__game.getState(); // vy right after flap
const half = Math.floor(K / 2);
for (let i = 0; i < half; i++) window.__game.step(16);
window.__game.flap(); // extra upward impulse
const vyAfterMidFlap = window.__game.getState().bird.vy;
for (let i = half; i < K; i++) window.__game.step(16);
const flappedY = window.__game.getState().bird.y;
return { baselineY, flappedY, vyAfterFirstFlap: flapState.bird.vy, vyAfterMidFlap };
}, 20);
assert(r.vyAfterFirstFlap < 0, 'immediately after flap() vy must be negative (upward), got ' + r.vyAfterFirstFlap);
assert(r.vyAfterMidFlap < 0, 'after a mid-run flap vy must be negative (upward), got ' + r.vyAfterMidFlap);
assert(r.flappedY < r.baselineY, 'flapping must push the bird UP (smaller y) vs baseline: flapped '
+ r.flappedY + ' should be < baseline ' + r.baselineY);
}],
['T4 score increments exactly once per pipe across a multi-step pass', async () => {
const r = await run(() => {
// Single explicit pipe placed just to the right of the bird, with a wide
// gap aligned to the bird so the pass is safe. autoPipes off so no new
// pipes interfere. Bird kept aligned in the gap.
window.__game.init({
seed: 1,
status: 'playing', birdX:80,birdR:12,pipeWidth:52,width:500,height:400, // start in play without a flap (vy stays 0)
gravity: 0, // remove vertical drift so the bird stays in the gap
pipeSpeed: 4,
birdY: 200,
birdVy: 0,
pipes: [{ x: 80, gapY: 140, gapH: 140, passed: false }]
});
const scores = [];
for (let i = 0; i < 40; i++){
const s = window.__game.step(16);
scores.push(s.score);
if (s.status === 'over') break;
}
const afterPass = window.__game.getState();
// step further (no other pipe) -> score must not change.
for (let i = 0; i < 10; i++) window.__game.step(16);
const later = window.__game.getState();
return { scores, afterPassScore: afterPass.score, afterPassStatus: afterPass.status,
laterScore: later.score, laterStatus: later.status };
});
// Score should reach exactly 1 and never exceed 1 (one pipe, counted once).
const maxScore = Math.max.apply(null, r.scores);
assert(maxScore === 1, 'score must reach exactly 1 after passing one pipe, got max ' + maxScore + ' (statuses: ' + r.afterPassStatus + ')');
assert(r.afterPassScore === 1, 'score after the pass must be exactly 1, got ' + r.afterPassScore);
// The increment must be a single +1 step (never +2 in one frame, never re-counted).
let increments = 0;
for (let i = 1; i < r.scores.length; i++){
const d = r.scores[i] - r.scores[i-1];
assert(d === 0 || d === 1, 'score must change by at most 1 per step, saw delta ' + d);
if (d === 1) increments++;
}
assert(increments === 1, 'exactly one scoring event expected, saw ' + increments);
assert(r.laterScore === 1, 'stepping further without a new pipe must keep score at 1, got ' + r.laterScore);
}],
['T5 collision: gap is safe; crash ends game; over halts step/flap', async () => {
// (a) Bird aligned inside a pipe gap; step past the pipe -> stays playing.
const safe = await run(() => {
window.__game.init({
seed:1,status:'playing',gravity:0,pipeSpeed:4,birdX:80,birdR:12,pipeWidth:52,width:500,height:400,
birdY: 200, birdVy: 0, // aligned inside the gap, no drift
pipes: [{ x: 120, gapY: 150, gapH: 120, passed: false }]
});
const states = [];
for (let i = 0; i < 60; i++){
const s = window.__game.step(16);
states.push(s.status);
if (s.status === 'over') break;
}
return { final: window.__game.getState().status, everOver: states.includes('over') };
});
assert(!safe.everOver && safe.final === 'playing',
'passing through the gap must NOT end the game, got final ' + safe.final + ' everOver=' + safe.everOver);
// (b) Force a collision: bird outside the gap (below it) hits the pipe column.
const crash = await run(() => {
window.__game.init({
seed:1,status:'playing',gravity:0,pipeSpeed:4,birdX:80,birdR:12,pipeWidth:52,width:500,height:400,
birdY: 360, birdVy: 0, // well below the gap
pipes: [{ x: 80, gapY: 120, gapH: 100, passed: false }]
});
let st = 'playing';
for (let i = 0; i < 40; i++){
const s = window.__game.step(16);
st = s.status;
if (st === 'over') break;
}
return st;
});
assert(crash === 'over', 'hitting a pipe column outside the gap must set status "over", got ' + crash);
// (c) Ground collision and post-over freeze.
const frozen = await run(() => {
window.__game.init({ seed: 1, status: 'playing', gravity:1,width:500,height:400,birdX:80,birdR:12,pipeWidth:52,birdY:380, pipes: [] });
for (let i = 0; i < 60; i++){
const s = window.__game.step(16);
if (s.status === 'over') break;
}
const over = window.__game.getState();
// After over, step()/flap() must not change bird or score.
window.__game.step(16); window.__game.step(16);
window.__game.flap();
const after = window.__game.getState();
return { overStatus: over.status, sameBird: over.bird.y===after.bird.y && over.bird.vy===after.bird.vy,
sameScore: over.score === after.score, sameStatus: after.status };
});
assert(frozen.overStatus === 'over', 'falling to the ground must end the game, got ' + frozen.overStatus);
assert(frozen.sameStatus === 'over', 'status must stay "over" after further calls, got ' + frozen.sameStatus);
assert(frozen.sameBird, 'step()/flap() after "over" must not move the bird');
assert(frozen.sameScore, 'step()/flap() after "over" must not change score');
}],
];
let passed = 0;
for (const [name, fn] of tiers){
try { await fn(); passed++; console.log('PASS ' + name); }
catch (e){ console.log('FAIL ' + name + ': ' + (e && e.message || e)); }
}
console.log('TIERS ' + passed + '/' + tiers.length);
console.log('SCORE=' + (passed / tiers.length).toFixed(3));
await browser.close();
})().catch(e => { console.log('FATAL ' + (e && e.stack || e)); console.log('SCORE=0'); });