fix: limit trainer jumps and exit positions

This commit is contained in:
nyan404 committed 2026-11-22 16:33:30 +03:00
1 parent 27b3e0aaae
commit cc6bcb23c8
12 files changed
+174 -79

No files matched your search

+92 -25
View File
@@ -7,14 +7,31 @@ const {chromium} = require('playwright');
const origin = process.env.BELKI_TEST_URL || 'http://127.0.0.1:8876';
assert(['127.0.0.1','localhost','[::1]'].includes(new URL(origin).hostname));
const shotDir = process.env.BELKI_SCREENSHOT_DIR;
const allowedExits = [19,29,39,49,55,56,57,58,59];
function seeded(seed = 19) { return () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; }; }
const cellIds = locator => locator.evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.id)));
async function checkTransitions(page, expectedExit) {
const sceneExit = await cellIds(page.locator('#scene-grid .exit button'));
assert.equal(sceneExit.length,1);
const [exit] = sceneExit;
assert(allowedExits.includes(exit),`unexpected exit cell: ${exit}`);
if (expectedExit !== undefined) assert.equal(exit,expectedExit);
for (const grid of ['scene-grid','map-grid']) {
assert.deepEqual(await cellIds(page.locator(`#${grid} .entrance button`)),[0]);
assert.deepEqual(await cellIds(page.locator(`#${grid} .exit button`)),[exit]);
assert.equal(await page.locator(`#${grid} .transition.available`).count(),0);
}
return exit;
}
async function run() {
const {generateField, DEFAULTS, coordinate, neighbors} = await import(pathToFileURL(path.resolve(__dirname,'../../web/lu-trainer/engine.js')));
const field = generateField(DEFAULTS,seeded());
const [first, second, note] = field.base;
const hintCell = field.base.find(id => field.values[id] > 0);
assert.notEqual(hintCell, undefined);
const first = 1, second = 2, note = 30;
const hintIndex = field.base.findIndex(id => field.values[id] > 0);
assert(hintIndex > 0,'hint fixture needs a quiet approach cell to revisit from');
const hintRoute = field.base.slice(0,hintIndex + 1);
const hintCell = hintRoute.at(-1), beforeHint = hintRoute.at(-2);
const hintText = `Подсказка: ${coordinate(neighbors(hintCell).find(id => field.hazards.has(id)))}`;
const browser = await chromium.launch({headless:true, ...(process.env.CHROMIUM_PATH ? {executablePath:process.env.CHROMIUM_PATH} : {})});
const captures = [];
@@ -40,21 +57,33 @@ async function run() {
const map = id => page.locator(`#map-grid button[data-id="${id}"]`);
const noOverflow = async () => assert(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth),`overflow at ${width}`);
const select = async id => { await scene(id).click(); if (width === 390) await page.locator('#jump').click(); };
const assertAvailable = async ids => {
for (const grid of ['scene-grid','map-grid']) {
assert.deepEqual(await cellIds(page.locator(`#${grid} .available button`)),ids,`${grid} jump targets`);
}
};
await noOverflow();
assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: вход, персонаж здесь$/);
for (const grid of ['scene-grid','map-grid']) {
assert.equal(await page.locator(`#${grid} .entrance button`).getAttribute('data-id'),'0');
assert.equal(await page.locator(`#${grid} .exit button`).getAttribute('data-id'),String(field.exit));
}
await checkTransitions(page,field.exit);
assert(await page.locator('#jump').isDisabled());
assert(await page.locator('#mark').isDisabled());
assert.match(await page.locator('#transition-coordinates').textContent(), /Вход: x1 y1/);
assert((await page.locator('#transition-coordinates').textContent()).includes(`Выход: ${coordinate(field.exit)}`));
assert.equal(await page.locator('#scene-grid .hazard').count(),0);
assert.equal(await page.locator('#scene-grid .opened').count(),0);
await assertAvailable([1,10,11]);
// Modal help must not modify the field, and Escape must restore focus.
await page.locator('#help-open').click();
assert(await page.locator('#help-dialog').isVisible());
await page.keyboard.press('Escape');
assert(await page.locator('#help-open').evaluate(n=>n===document.activeElement));
// Even a safe upper-row cell is out of reach two columns from the entrance.
await select(second);
assert(await page.locator('#jump').isEnabled());
assert.match(await page.locator('#status').textContent(),/соседнюю клетку/);
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[0]);
assert.equal(await page.locator('#history li').count(),0);
assert.equal(await page.locator('#scene-grid .opened').count(),0);
if (width === 390) {
await scene(first).tap();
assert.equal(await page.locator('#scene-grid .opened').count(),0,'touch overview must only select');
@@ -66,6 +95,7 @@ async function run() {
assert.equal(await page.locator('#history li').count(),1);
assert.match(await scene(first).getAttribute('aria-label'),/персонаж здесь/);
assert.match(await page.locator('#messages').textContent(),/Опасностей рядом/);
await assertAvailable([2,10,11,12]);
// Native button keyboard actions and spatial focus; focus is not character position.
await scene(first).focus(); await page.keyboard.press('ArrowRight');
assert(await scene(second).evaluate(n=>n===document.activeElement));
@@ -73,8 +103,20 @@ async function run() {
await page.keyboard.press('Enter');
assert.equal(await page.locator('#scene-grid .opened').count(),2);
assert.equal(await page.locator('#history li').count(),2);
await assertAvailable([1,3,11,12,13]);
await page.keyboard.press(' ');
assert.equal(await page.locator('#history li').count(),3,'one keyboard action, one history item');
assert.equal(await page.locator('#history li').count(),2,'cannot jump to the current cell');
// Cell 10 still touches opened cell 1, but not the current position (cell 2).
await select(10);
assert.match(await page.locator('#status').textContent(),/соседнюю клетку/);
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[second]);
assert.equal(await page.locator('#history li').count(),2);
await scene(second).focus(); await page.keyboard.press('ArrowLeft');
await page.keyboard.press(' ');
assert.equal(await page.locator('#history li').count(),3,'one keyboard revisit, one history item');
assert.match(await page.locator('#history li').last().textContent(),/Повторный прыжок/);
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[first]);
assert.equal(await page.locator('#scene-grid .opened').count(),2);
await page.keyboard.press('End');
assert(await scene(9).evaluate(n=>n===document.activeElement));
await page.keyboard.press('Home'); assert(await scene(0).evaluate(n=>n===document.activeElement));
@@ -83,8 +125,9 @@ async function run() {
await map(note).click();
assert.equal(await page.locator('#scene-grid .opened').count(),2);
await page.locator('#map-mark').click();
assert.equal(await page.locator('#map-grid .marked').count(),1);
assert.equal(await page.locator('#scene-grid .marked').count(),1);
assert.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[note]);
assert.deepEqual(await cellIds(page.locator('#scene-grid .marked button')),[note]);
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[first]);
await page.locator('#project-marks').uncheck();
assert.equal(await page.locator('#scene-grid .marked').count(),0);
assert.equal(await page.locator('#map-grid .marked').count(),1);
@@ -94,7 +137,7 @@ async function run() {
await page.locator('#clear-marks').click(); await page.keyboard.press('Escape');
assert.equal(await page.locator('#map-grid .marked').count(),1);
await page.locator('#clear-marks').click(); await page.locator('#confirm-action').click();
assert.equal(await page.locator('#map-grid .marked').count(),0);
await page.locator('#map-grid .marked').waitFor({state:'detached'});
assert.equal(await page.locator('#map-grid .opened').count(),2);
assert.equal(await page.locator('#history li').count(),5);
if (width === 390) {
@@ -125,11 +168,34 @@ async function run() {
assert.equal(await page.locator('#history li').count(),0);
assert.equal(await page.locator('#timer').textContent(),'00:00');
assert.match(await scene(0).getAttribute('aria-label'), /вход, персонаж здесь/);
assert.equal(await page.locator('#scene-grid .exit button').getAttribute('data-id'), await page.locator('#map-grid .exit button').getAttribute('data-id'));
await checkTransitions(page);
await assertAvailable([1,10,11]);
assert.deepEqual(errors,[]);
console.log(`PASS ${width}x${height}: render, keyboard/touch, synchronized map, notes, dialogs, settings, console`);
console.log(`PASS ${width}x${height}: render, adjacent jumps, keyboard/touch, synchronized map, notes, dialogs, settings, console`);
} finally { await context.close(); }
}
// Sample all exit buckets without coupling this test to their internal order.
const exits = new Set();
const boundary = await browser.newContext({viewport:{width:1366,height:768}});
try {
for (let i = 0; i < allowedExits.length; i++) {
const page = await boundary.newPage();
try {
await page.addInitScript(roll => { Math.random = () => roll; },(i + .5) / allowedExits.length);
await page.goto(`${origin}/trainer`);
await page.locator('#scene-grid button').last().waitFor();
const exit = await checkTransitions(page);
exits.add(exit);
await page.locator('#map-grid .exit button').click();
assert(await page.locator('#jump').isDisabled());
assert(await page.locator('#map-mark').isDisabled());
assert.equal(await page.locator('#scene-grid .opened').count(),0);
assert.equal(await page.locator('#history li').count(),0);
} finally { await page.close(); }
}
assert.deepEqual([...exits].sort((a,b)=>a-b),allowedExits);
console.log('PASS all permitted exit cells, synchronized transitions, exit cannot be jumped to or marked');
} finally { await boundary.close(); }
// Deterministic result/clock/hint lifetime checks at desktop size.
const context = await browser.newContext({viewport:{width:1366,height:768}});
try {
@@ -138,17 +204,17 @@ async function run() {
await page.goto(`${origin}/trainer`);
await page.locator('#scene-grid button').last().waitFor();
const cell = id=>page.locator(`#scene-grid button[data-id="${id}"]`);
// Open safe reachable cells until a known adjacent hazard can be reached.
let hazard;
for (let guard=0;guard<60;guard++) {
const ids = await page.locator('#scene-grid .available:not(.opened):not(.transition) button').evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.id)));
hazard = ids.find(id=>field.hazards.has(id));
if (hazard !== undefined) break;
const next = ids.find(id=>!field.hazards.has(id)); assert.notEqual(next,undefined); await cell(next).click();
// The seeded route includes a diagonal jump from the entrance.
const hazard = 31;
for (const id of [11,20]) {
assert(!field.hazards.has(id),`loss fixture: approach cell ${id} must be safe`);
await cell(id).click();
assert.match(await cell(id).getAttribute('aria-label'),/персонаж здесь/);
}
assert.notEqual(hazard,undefined); await cell(hazard).click();
assert(field.hazards.has(hazard),'loss fixture: final cell must be hazardous');
await cell(hazard).click();
assert(await page.locator('#result').isVisible());
assert.match(await page.locator('#result').textContent(),/Падение/);
assert((await page.locator('#result').textContent()).includes(`Падение на ${coordinate(hazard)}`));
assert.equal(await page.locator('#scene-grid .hazard').count(),field.hazards.size);
const count = await page.locator('#history li').count();
await cell(1).click(); assert.equal(await page.locator('#history li').count(),count);
@@ -172,17 +238,18 @@ async function run() {
await page.setViewportSize({width:1366,height:768});
await page.reload(); await page.locator('#scene-grid button').last().waitFor();
await page.evaluate(()=>Math.random=()=>0);
await cell(hintCell).click();
for (const id of hintRoute) await cell(id).click();
assert.equal(await page.locator('#scene-grid .hint').count(),1);
assert.equal(await page.locator('#map-grid .hint').count(),1);
assert((await page.locator('#messages').textContent()).includes(hintText));
await page.waitForTimeout(1100); await cell(hintCell).click();
const revisitHint = async () => { await cell(beforeHint).click(); await cell(hintCell).click(); };
await page.waitForTimeout(1100); await revisitHint();
await page.waitForTimeout(1100);
assert.equal(await page.locator('#scene-grid .hint').count(),1,'repeat hint renews the full display duration');
await page.waitForTimeout(1000);
assert.equal(await page.locator('#scene-grid .hint').count(),0);
assert((await page.locator('#messages').textContent()).includes(hintText));
await cell(hintCell).click();
await revisitHint();
assert.equal(await page.locator('#scene-grid .hint').count(),1);
await page.locator('#new-game').click(); await page.locator('#confirm-action').click();
await page.waitForTimeout(2100);
+45 -34
View File
@@ -9,28 +9,17 @@ const options = {height: 1, lu: 5, growth: 12, season: 0};
function fixture(settings = options, seed = 19) {
return {field: generateField(settings, seeded(seed)), game: new Training(settings, seeded(seed))};
}
function openReachableSafe(game, field) {
let progress = true;
while (progress && !['won', 'lost'].includes(game.view().status)) {
progress = false;
for (const cell of game.view().cells) {
if (cell.available && !cell.opened && !cell.transition && !field.hazards.has(cell.id)) {
game.jump(cell.id); progress = true;
}
}
}
}
test('entrance is always x1 y1 and every other cell can host the exit', () => {
test('entrance is always x1 y1 and exits vary only on the allowed edges', () => {
assert.equal(START, 0);
assert.equal(coordinate(START), 'x1 y1');
assert.equal(coordinate(59), 'x10 y6');
const exits = new Set();
for (let id = 1; id < 60; id++) {
const random = () => (id - .5) / 59;
const allowed = [19,29,39,49,55,56,57,58,59];
for (let i = 0; i < allowed.length; i++) {
const random = () => (i + .5) / allowed.length;
const field = generateField(options, random);
assert.equal(field.start, 0);
assert.equal(field.exit, id);
assert(allowed.includes(field.exit));
exits.add(field.exit);
assert(!field.hazards.has(field.start));
assert(!field.hazards.has(field.exit));
@@ -47,7 +36,7 @@ test('entrance is always x1 y1 and every other cell can host the exit', () => {
assert.equal(game.jump(field.exit).code, 'transition');
assert.equal(game.mark(field.exit).code, 'transition');
}
assert.equal(exits.size, 59);
assert.deepEqual([...exits].sort((a,b)=>a-b), allowed);
});
test('generation covers every settings combination with safe transitions, base and connecting route', () => {
@@ -59,8 +48,10 @@ test('generation covers every settings combination with safe transitions, base a
assert.equal(field.base.length, height === 1 ? 5 : 3);
assert.equal(field.hazards.size, Math.min(Math.max(5, growth + season + 2 * (height - 1)), 60 - field.reserved.size));
const reached = new Set([START]);
for (const id of reached) for (const next of neighbors(id)) if (!field.hazards.has(next)) reached.add(next);
assert(reached.has(field.exit));
for (const id of reached) for (const next of neighbors(id)) {
if (next !== field.exit && !field.hazards.has(next)) reached.add(next);
}
assert(neighbors(field.exit).some(id => reached.has(id)));
for (const id of field.base) assert(reached.has(id));
for (let id = 0; id < 60; id++) assert.equal(field.values[id], neighbors(id).filter(n => field.hazards.has(n)).length);
}
@@ -70,16 +61,27 @@ test('edge neighborhoods do not wrap rows', () => {
assert.equal(neighbors(9).length, 3); assert.equal(neighbors(25).length, 8);
assert.deepEqual(neighbors(59).sort((a,b)=>a-b), [48,49,58]);
});
test('only base or neighbors of any opened cell are available; transitions never count', () => {
test('only the current position’s neighbors are available, even for safe or opened cells', () => {
const {game} = fixture();
assert.equal(game.jump(START).code, 'transition');
assert.equal(game.jump(game.view().exit).code, 'transition');
assert.equal(game.jump(25).code, 'unreachable');
assert.equal(game.jump(2).code, 'unreachable'); // safe upper-row cell, two columns away
assert.deepEqual(game.view().cells.filter(c => c.available).map(c => c.id), [1,10,11]);
assert.equal(game.mark(START).code, 'transition');
assert.equal(game.jump(1).code, 'opened');
game.jump(4); // last position differs: adjacency still belongs to any open cell
assert.equal(game.jump(1).code, 'unreachable');
assert(game.view().cells[10].available);
assert.equal(game.view().position, 4);
assert.equal(game.jump(2).code, 'opened');
assert(!game.view().cells[10].available); // still next to opened cell 1
assert.equal(game.jump(10).code, 'unreachable');
assert.equal(game.jump(3).code, 'opened');
assert.equal(game.jump(1).code, 'unreachable'); // previously opened
assert.equal(game.view().position, 3);
assert.equal(game.jump(2).code, 'revisited');
const diagonal = fixture();
assert(!diagonal.field.hazards.has(11));
assert.equal(diagonal.game.jump(11).code, 'opened');
});
test('notes hide no facts, block jumps, clear independently and reject invalid IDs', () => {
const {game} = fixture();
@@ -112,7 +114,17 @@ test('all and only hazards marked wins; terminal actions cannot change state', (
});
test('opening all safe cells wins without entering either transition', () => {
const {game,field} = fixture();
openReachableSafe(game, field);
function explore(position) {
for (const id of neighbors(position)) {
if (game.view().status === 'won') return;
const cell = game.view().cells[id];
if (cell.opened || cell.transition || field.hazards.has(id)) continue;
assert.equal(game.jump(id).code, 'opened');
explore(id);
if (game.view().status !== 'won' && position !== START) assert.equal(game.jump(position).code, 'revisited');
}
}
explore(START);
assert.equal(game.view().status, 'won');
assert.equal(game.view().opened, 58 - field.hazards.size);
});
@@ -130,20 +142,19 @@ test('hazard ends attempt, reveals wrong notes and preserves last safe position'
});
test('LU hint probability, repeated safe visits and hidden information boundary', () => {
assert.deepEqual(Array.from({length:10}, (_,lu)=>hintChance(lu)), [0,0,0,0,.1,.2,.3,.3,.3,.3]);
const {game,field} = fixture();
openReachableSafe(game, field);
// Separate active game: choose an available safe base cell with adjacent hazards.
const active = fixture();
const id = active.field.base.find(n => active.field.values[n] > 0);
assert.notEqual(id, undefined);
active.game.jump(id, () => 0);
const revisit = active.game.jump(id, () => 0);
const active = fixture(), noHints = fixture({...options, lu:0});
const route = [1,2,3,4,5,4,5];
for (const id of route.slice(0,-1)) {
active.game.jump(id, () => 1);
noHints.game.jump(id, () => 0);
}
const revisit = active.game.jump(5, () => 0);
assert.equal(revisit.code, 'revisited');
assert(active.field.hazards.has(revisit.hint));
assert.equal(active.game.view().cells[revisit.hint].value, null);
assert.equal(active.game.view().opened, 1);
assert.equal(active.game.view().history.length, 2);
assert.equal(new Training({...options,lu:0}, seeded()).jump(id, () => 0).hint, null);
assert.equal(active.game.view().opened, 5);
assert.equal(active.game.view().history.length, route.length);
assert.equal(noHints.game.jump(5, () => 0).hint, null);
});
test('invalid settings are rejected rather than corrupting generation', () => {
for (const bad of [{height:0},{lu:10},{growth:99},{season:7}]) assert.throws(()=>new Training({...options,...bad}), RangeError);