Files
cwshed-clone/tests/browser/lu-trainer.cjs
T

673 lines
41 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Browser plugin not available: use bundled Playwright against an isolated loopback server.
const assert = require('node:assert/strict');
const path = require('node:path');
const {pathToFileURL} = require('node:url');
const {mkdir} = require('node:fs/promises');
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)));
const levelButtons = page => page.locator('#map-levels button[data-level]');
const levelButton = (page,level) => page.locator(`#map-levels button[data-level="${level}"]`);
const valueText = async (cell,selector) => (await cell.locator(selector).allTextContents()).join('').trim();
async function assertRatingControls(page,{disabled = false, active = null} = {}) {
const buttons = levelButtons(page);
assert.deepEqual(await buttons.evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.level))),[0,1,2,3,4,5,6,7]);
for (const button of await buttons.all()) {
assert(await button.isVisible(),'the rating menu stays under the map');
assert.equal(await button.isDisabled(),disabled);
assert.equal(await button.getAttribute('aria-pressed'),String(Number(await button.getAttribute('data-level')) === active));
}
assert.equal(await page.locator('#map-clear-level').isDisabled(),disabled || active === null);
}
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 assertEntranceLevel(page, value, current = true) {
for (const grid of ['scene-grid','map-grid']) {
const entrance = page.locator(`#${grid} .entrance button[data-id="0"]`);
assert.equal(await valueText(entrance,'.cell-value'),value === null ? '↥' : `↥ ${value}`);
assert.equal(await entrance.getAttribute('aria-label'),`x1 y1: вход${value === null ? '' : `, опасностей рядом: ${value}`}${current ? ', персонаж здесь' : ''}`);
assert.equal(await page.locator(`#${grid} .entrance.opened`).count(),0);
}
assert.equal(await valueText(page.locator('#scene-grid .entrance button'),'.cell-coord'),'x1 y1');
}
async function finishDialog(page, dialogId, openerId, action) {
await page.locator(`#${dialogId}`).evaluate(dialog=>{
dialog.closeSeen = false;
dialog.addEventListener('close',()=>{ dialog.closeSeen = true; },{once:true});
});
await action();
// The native dialog can become hidden before its close handler restores focus.
await page.waitForFunction(id=>document.getElementById(id).closeSeen,dialogId);
assert(await page.locator(`#${openerId}`).evaluate(n=>n===document.activeElement));
}
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 = 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 = [];
try {
if (shotDir) await mkdir(shotDir,{recursive:true});
for (const [width,height,touch = false] of [[1920,1080],[1366,768],[768,1024],[390,844,true],[844,390,true],[1024,768,true]]) {
const mobile = width <= 700 || width === 844, compact = mobile || touch;
const context = await browser.newContext({viewport:{width,height}, reducedMotion:'reduce', locale:'ru-RU', hasTouch:touch, isMobile:mobile});
try {
await context.addInitScript(() => {
let seed = 19;
Math.random = () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; };
});
const page = await context.newPage(), errors = [];
page.on('pageerror',error => errors.push(error.message));
page.on('console',message => { if (message.type() === 'error') errors.push(message.text()); });
await page.goto(`${origin}/trainer${width === 768 ? '/' : ''}`);
await page.locator('#scene-grid button').last().waitFor();
assert.equal(await page.title(),'Тренажёр ЛУ — Лесные уступы');
assert.equal(await page.locator('#scene-grid button').count(),60);
assert.equal(await page.locator('#map-grid button').count(),60);
assert(await page.getByRole('heading',{name:'Тренажёр ЛУ',exact:true}).isVisible());
const scene = id => page.locator(`#scene-grid button[data-id="${id}"]`);
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 jump = page.locator('#jump'), mark = page.locator('#mark');
const selection = page.locator('#selection'), status = page.locator('#status');
const history = page.locator('#history li');
const assertPosition = async id => assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[id]);
const assertSelection = async (id, reason = '') => {
assert.equal(await selection.textContent(),`Клетка ${coordinate(id)}${reason ? ` (${reason})` : ''}`);
};
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: вход, персонаж здесь$/);
await checkTransitions(page,field.exit);
assert.equal(await page.locator('input[name="mode"], input[type="radio"], [role="radio"]').count(),0);
assert.equal(await page.locator('#touch-actions').isVisible(),compact);
assert.equal(await jump.isVisible(),compact);
assert.equal(await mark.isVisible(),compact);
if (compact) {
assert(await jump.isDisabled());
assert(await mark.isDisabled());
for (const control of [jump,mark]) {
const box = await control.boundingBox();
assert(box.height >= 44 && box.width >= 44,'touch controls meet the minimum target size');
}
} else {
assert.equal(await page.getByRole('button',{name:'Прыгнуть',exact:true}).count(),0);
const noteButtons = page.getByRole('button',{name:'Отметить опасной',exact:true});
assert.equal(await noteButtons.count(),1,'only the map keeps its note button on desktop');
assert.equal(await noteButtons.getAttribute('id'),'map-mark');
}
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.
if (compact) {
const beforeSelection = await status.textContent();
for (const [id,reason] of [[field.exit,'выход'],[0,'вы здесь']]) {
await scene(id).tap();
await assertSelection(id,reason);
assert(await jump.isDisabled(),reason);
assert(await mark.isDisabled(),reason);
}
await scene(second).tap();
await assertSelection(second,'вне досягаемости');
assert(await jump.isDisabled());
assert(await mark.isEnabled(),'distant cells can still be marked');
assert.equal(await status.textContent(),beforeSelection);
} else {
await scene(second).click();
assert.equal(await status.textContent(),'Выберите соседнюю клетку для прыжка.');
}
await assertPosition(0);
assert.equal(await history.count(),0);
assert.equal(await page.locator('#scene-grid .opened').count(),0);
await page.locator('#simple-mode').check(); // Exercise the existing diagnostics in simplified mode.
if (compact) {
await scene(first).click();
await scene(first).tap();
await assertSelection(first);
assert(await jump.isEnabled());
await assertPosition(0);
assert.equal(await history.count(),0,'compact overview must only select');
await jump.tap();
await assertSelection(first,'вы здесь');
assert(await jump.isDisabled());
} else await scene(first).click();
assert.equal(await page.locator('#scene-grid .opened').count(),1);
assert.equal(await page.locator('#map-grid .opened').count(),1);
assert.equal(await history.count(),1);
assert.match(await scene(first).getAttribute('aria-label'),/персонаж здесь/);
const proximity = `Опасностей рядом: ${field.values[first]}.`;
assert.equal(await status.textContent(),proximity);
assert.equal(await page.locator('#messages li').last().textContent(),`${coordinate(first)} · Звуков нет. ${proximity}`);
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));
assert.match(await scene(first).getAttribute('aria-label'),/персонаж здесь/);
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]);
// Cell 10 still touches opened cell 1, but not the current position (cell 2).
const beforeDistant = await history.allTextContents();
if (compact) {
await scene(10).tap();
await assertSelection(10,'вне досягаемости');
assert(await jump.isDisabled());
} else {
await scene(10).press('Enter');
assert.equal(await status.textContent(),'Выберите соседнюю клетку для прыжка.');
}
await assertPosition(second);
assert.deepEqual(await history.allTextContents(),beforeDistant);
await scene(second).press(' ');
assert.equal(await history.count(),2,'cannot jump to the current cell');
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));
// Click/tap an eligible neighbor on the map: selection and rating must never jump.
if (mobile) {
const historyState = await page.evaluate(()=>({url:location.href,length:window.history.length}));
await page.evaluate(()=>window.scrollTo(0,0));
const grid = page.locator('#map-grid');
assert(await grid.isVisible(),'the phone map must be in the page before activating its shortcut');
assert(await page.locator('#map-home').evaluate(n=>n.getBoundingClientRect().top >= document.querySelector('.location').getBoundingClientRect().bottom));
await page.mouse.move(width - 4,height / 2);
await page.mouse.wheel(0,(await grid.boundingBox()).y - height / 3);
await page.waitForFunction(()=>{
const {top} = document.querySelector('#map-grid').getBoundingClientRect();
return scrollY > 0 && top >= 0 && top < innerHeight;
});
await page.locator('#map-open').press('Enter');
const heading = page.getByRole('heading',{name:'Минное поле',exact:true});
assert(await heading.evaluate(n=>n===document.activeElement && n.getBoundingClientRect().top >= 0 && n.getBoundingClientRect().bottom <= innerHeight));
assert(await page.locator('#scene-grid').isVisible(),'the scene stays in the document');
assert(await page.locator('#panel-dialog').isHidden(),'the shortcut only scrolls the page');
assert.deepEqual(await page.evaluate(()=>({url:location.href,length:window.history.length})),historyState);
await page.keyboard.press('Tab');
assert(await grid.evaluate(n=>n.contains(document.activeElement)));
}
const ratingCell = 11;
const mapSelection = page.locator('#map-selection');
const mapMark = page.locator('#map-mark');
const project = page.locator('#project-marks');
const chooseOnMap = async cell => touch ? cell.tap() : cell.click();
for (const id of [0,field.exit]) {
await chooseOnMap(map(id));
await assertRatingControls(page,{disabled:true});
await map(id).press('4');
assert.equal(await valueText(map(id),'.cell-rating'),'','cannot rate a transition');
}
await chooseOnMap(map(ratingCell));
assert((await mapSelection.textContent()).includes(coordinate(ratingCell)));
await assertRatingControls(page);
await assertPosition(first);
assert.equal(await page.locator('#scene-grid .opened').count(),2);
assert.equal(await history.count(),3,'map selection has not changed jump history');
const assertRating = async level => {
assert.equal(await valueText(map(ratingCell),'.cell-rating'),String(level));
assert.equal(await valueText(scene(ratingCell),'.cell-rating'),String(level));
assert.doesNotMatch(await valueText(map(ratingCell),'.cell-value'),/\d/,'an estimate is not the field value');
assert.match(await mapSelection.textContent(),new RegExp(`оценк[^\\d]*${level}\\b`,'i'));
await assertRatingControls(page,{active:level});
};
if (touch) {
await levelButton(page,1).tap();
await assertRating(1);
await levelButton(page,7).tap();
} else {
await map(ratingCell).press('1');
await assertRating(1);
await map(ratingCell).press('7');
await assertRating(7);
for (const outside of ['8','9']) await map(ratingCell).press(outside);
}
await assertRating(7);
assert.deepEqual(await cellIds(page.locator('#map-grid .rated button')),[ratingCell]);
assert.deepEqual(await cellIds(page.locator('#scene-grid .rated button')),[ratingCell]);
assert.equal(await page.locator('#mark-count').textContent(),'0');
assert.equal(await page.locator('#map-grid .marked').count(),0);
await assertAvailable([2,10,11,12]);
await assertPosition(first);
await project.uncheck();
assert.equal(await valueText(scene(ratingCell),'.cell-rating'),'');
assert.equal(await page.locator('#scene-grid .rated').count(),0);
assert.equal(await valueText(map(ratingCell),'.cell-rating'),'7');
await project.check();
await assertRating(7);
if (shotDir && (width === 1366 || mobile)) {
const file = `${shotDir}/lu-ratings-${width}.png`;
await page.screenshot({path:file});
captures.push(file);
}
// Old flags and ratings coexist; clearing either one must leave the other intact.
await chooseOnMap(mapMark);
assert.equal(await page.locator('#mark-count').textContent(),'1');
assert.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[ratingCell]);
await assertRating(7);
if (touch) await page.locator('#map-clear-level').tap();
else await map(ratingCell).press('Delete');
assert.equal(await valueText(map(ratingCell),'.cell-rating'),'');
assert.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[ratingCell]);
await assertRatingControls(page);
if (touch) await levelButton(page,0).tap();
else await map(ratingCell).press('0');
await assertRating(0);
await chooseOnMap(mapMark);
await assertRating(0);
assert.equal(await page.locator('#mark-count').textContent(),'0');
if (!touch) {
await levelButton(page,4).click();
await assertRating(4);
await map(ratingCell).press('0');
await assertRating(0);
}
if (touch) await page.locator('#map-clear-level').tap();
else await map(ratingCell).press('Backspace');
assert.equal(await page.locator('#map-grid .rated, #scene-grid .rated').count(),0);
await assertRatingControls(page);
await assertPosition(first);
await map(note).click();
const beforeFlag = await history.count();
await mapMark.click();
assert.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[note]);
assert.deepEqual(await cellIds(page.locator('#scene-grid .marked button')),[note]);
assert.equal(await valueText(map(note),'.cell-rating'),'','an ordinary flag has no rating');
await assertPosition(first);
await project.uncheck();
assert.equal(await page.locator('#scene-grid .marked').count(),0);
assert.equal(await page.locator('#map-grid .marked').count(),1);
assert.equal(await history.count(),beforeFlag + 1);
await project.check();
// Clearing first cancels, then confirms; facts and history remain.
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();
await page.locator('#map-grid .marked').waitFor({state:'detached'});
assert.equal(await page.locator('#map-grid .opened').count(),2);
assert.equal(await history.count(),beforeFlag + 2);
if (mobile) {
await page.locator('#history-open').click();
assert(await page.locator('#panel-dialog #history').isVisible());
await page.keyboard.press('Escape');
await page.locator('#history-home #history').waitFor({state:'attached'});
assert(await page.locator('#history-open').evaluate(n=>n===document.activeElement));
} else {
await page.locator('#map-toggle').click(); assert(await page.locator('#map-body').isHidden());
await page.locator('#map-expand').click(); assert(await page.locator('#panel-dialog #map-grid').isVisible());
await page.keyboard.press('Escape');
await page.locator('#map-home #map-body[hidden]').waitFor({state:'attached'});
assert(await page.locator('#map-expand').evaluate(n=>n===document.activeElement));
if (width === 768) {
await page.setViewportSize({width:690,height});
await page.locator('#map-grid').waitFor({state:'visible'});
await page.setViewportSize({width,height});
await page.locator('#map-body').waitFor({state:'hidden'});
}
await page.locator('#map-toggle').click();
}
if (shotDir) {
const file = `${shotDir}/lu-${width}.png`;
// Full-page capture temporarily resizes emulation and can reset the wide coarse-pointer mode.
await page.screenshot({path:file,fullPage:!touch || width <= 700});
captures.push(file);
}
// Restart confirmations preserve/cancel the existing state; settings are staged until submit.
const escape = () => page.keyboard.press('Escape');
await page.locator('#new-game').click();
await finishDialog(page,'confirm-dialog','new-game',escape);
assert.equal(await page.locator('#scene-grid .opened').count(),2);
await page.locator('#settings-open').click(); await page.locator('#setting-height').selectOption('2');
await finishDialog(page,'settings-dialog','settings-open',escape);
assert.match(await page.locator('#height-value').textContent(),/^1/);
await page.locator('#settings-open').click();
assert.equal(await page.locator('#setting-height').inputValue(),'1');
await page.locator('#setting-height').selectOption('2');
await finishDialog(page,'settings-dialog','settings-open',()=>page.getByRole('button',{name:'Начать новую игру',exact:true}).click());
assert.match(await page.locator('#height-value').textContent(),/^2/);
assert.equal(await page.locator('#scene-grid .opened').count(),0);
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'), /^x1 y1: вход(?:, опасностей рядом: [0-2])?, персонаж здесь$/);
await checkTransitions(page);
await assertAvailable([1,10,11]);
// Mark and unmark with compact buttons or Shift+Enter without moving the character.
const toggleMark = async () => {
if (compact) await mark.tap();
else await scene(first).press('Shift+Enter');
};
if (compact) await scene(first).tap();
await toggleMark();
for (const grid of ['scene-grid','map-grid']) {
assert.deepEqual(await cellIds(page.locator(`#${grid} .marked button`)),[first]);
}
assert.equal(await history.count(),1,'one mark, no extra jump');
assert.match(await history.last().textContent(),/Поставлена отметка/);
if (compact) {
await assertSelection(first,'есть отметка');
assert(await jump.isDisabled(),'a marked neighbor cannot be jumped to');
assert.equal(await mark.textContent(),'Снять отметку');
}
await toggleMark();
assert.equal(await page.locator('#scene-grid .marked, #map-grid .marked').count(),0);
assert.equal(await history.count(),2,'one unmark, no extra jump');
assert.match(await history.last().textContent(),/Снята отметка/);
await assertPosition(0);
if (compact) assert(await jump.isEnabled());
assert.deepEqual(errors,[]);
console.log(`PASS ${width}x${height} (${compact ? 'compact' : 'desktop'}): render, adjacent jumps, keyboard/touch controls, map ratings and flags, projection, 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('#map-selection').textContent()).includes(`${coordinate(exit)} · выход`));
await page.locator('#scene-grid .exit button').click();
assert.match(await page.locator('#status').textContent(),/Это переход/);
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(); }
// Seed one entrance at each legal level, including a real zero.
const entrances = await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true});
try {
for (const [entranceSeed, value] of [[1,0],[2,1],[6,2]]) {
assert.equal(generateField(DEFAULTS,seeded(entranceSeed)).values[0],value);
const page = await entrances.newPage();
try {
await page.addInitScript(seed => {
Math.random = () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; };
window.entranceCues = 0;
window.AudioContext = class extends AudioContext {
createBuffer(...args) { window.entranceCues++; return super.createBuffer(...args); }
};
},entranceSeed);
await page.goto(`${origin}/trainer`);
await page.locator('#scene-grid .entrance button').waitFor();
const replay = page.locator('#replay-sound'), simple = page.locator('#simple-mode');
await assertEntranceLevel(page,null);
assert.equal(await page.evaluate(()=>window.entranceCues),0,'no entrance audio plays automatically');
assert.equal(await replay.isDisabled(),value === 0);
if (value > 0) {
await replay.tap();
await page.waitForFunction(()=>window.entranceCues === 1);
}
await simple.check();
await assertEntranceLevel(page,value);
if (shotDir && value === 2) {
const file = `${shotDir}/lu-entrance-390.png`;
await page.screenshot({path:file});
captures.push(file);
}
assert(await replay.isDisabled());
await simple.uncheck();
await assertEntranceLevel(page,null);
assert.equal(await page.evaluate(()=>window.entranceCues),value > 0 ? 1 : 0,'mode changes do not play a cue');
assert.equal(await page.locator('#history li').count(),0,'replaying an entrance cue is not a jump');
} finally { await page.close(); }
}
console.log('PASS entrance 0–2, mode-dependent arrow/level and ARIA, manual replay only');
} finally { await entrances.close(); }
// The same opened cell can display both the player's rating and the model's actual value.
const audio = await browser.newContext({viewport:{width:1366,height:768}});
try {
const page = await audio.newPage();
await page.addInitScript(() => {
let seed = 19;
Math.random = () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; };
});
await page.goto(`${origin}/trainer`);
const scene = id => page.locator(`#scene-grid button[data-id="${id}"]`);
const map = id => page.locator(`#map-grid button[data-id="${id}"]`);
const simple = page.locator('#simple-mode');
const status = page.locator('#status');
const informative = 20, real = field.values[informative];
assert(real > 0 && real !== 7 && real !== 6 && field.values[11] === 0,'sound fixture must contrast zero, positive and guessed values');
await scene(0).waitFor();
assert.equal(await simple.isChecked(),false,'sound mode is the default');
await page.evaluate(()=>Math.random=()=>0); // A positive jump could draw a hint in simplified mode.
await scene(11).click();
assert.equal(await status.textContent(),'Звуков нет.');
const replay = page.locator('#replay-sound');
assert(await replay.isDisabled(),'there is no signal to replay at level zero');
assert.equal(await valueText(map(11),'.cell-value'),'·');
await map(informative).press('7');
assert.equal(await valueText(map(informative),'.cell-rating'),'7');
await scene(informative).click();
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[informative],'ratings cannot block a jump');
assert.equal(await status.textContent(),'Прислушайтесь к звуку.');
assert.equal(await page.locator('#scene-grid .opened').count(),2);
const journal = page.locator('#messages');
const history = page.locator('#history');
const noFactInLogs = async () => {
for (const log of [history,journal]) {
assert.doesNotMatch(await log.textContent(),/(?:рядом:?\s*\d|подсказка:)/i);
}
assert.equal(await page.locator('#scene-grid .hint, #map-grid .hint').count(),0);
};
const assertCellNumbers = async (fact,rating) => {
for (const cell of [scene(informative),map(informative)]) {
const displayedFact = await valueText(cell,'.cell-value');
if (fact === null) assert.doesNotMatch(displayedFact,/\d/);
else assert.equal(displayedFact,fact);
assert.equal(await valueText(cell,'.cell-rating'),rating);
}
};
await noFactInLogs();
await assertCellNumbers(null,'7');
assert.doesNotMatch(await scene(informative).getAttribute('aria-label'),/рядом:?\s*\d/);
const beforeReplay = await history.locator('li').count();
await replay.click();
assert.equal(await history.locator('li').count(),beforeReplay,'replaying sound does not jump');
await noFactInLogs();
const beforeModeSwitch = await history.locator('li').count();
await simple.check();
await assertCellNumbers(String(real),'7');
assert.equal(await valueText(map(11),'.cell-value'),'0','simplified mode shows a real zero');
const project = page.locator('#project-marks');
await project.uncheck();
assert.equal(await valueText(scene(informative),'.cell-value'),String(real),'projection does not hide the model value');
assert.equal(await valueText(scene(informative),'.cell-rating'),'');
assert.equal(await valueText(map(informative),'.cell-rating'),'7');
await project.check();
await map(informative).click();
await assertRatingControls(page,{active:7});
assert(await page.locator('#map-mark').isDisabled(),'opened cells can be rated but not flagged');
assert.match(await history.textContent(),new RegExp(`рядом:?\\s*${real}\\b`));
assert.match(await journal.textContent(),new RegExp(`рядом:?\\s*${real}\\b`));
await simple.uncheck();
await assertCellNumbers(null,'7');
await noFactInLogs();
assert.equal(await history.locator('li').count(),beforeModeSwitch,'switching modes does not append a game action');
await map(informative).press('6');
await assertCellNumbers(null,'6');
await assertRatingControls(page,{active:6});
await map(informative).press('Backspace');
await assertCellNumbers(null,'');
await assertRatingControls(page);
await simple.check();
await assertCellNumbers(String(real),'');
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[informative]);
assert.equal(await page.locator('#map-grid .opened').count(),2);
console.log('PASS default sound mode, zero/positive jumps and replay, fact/log disclosure, independent ratings on opened cells, no restart');
} finally { await audio.close(); }
// Deterministic result/clock/hint lifetime checks at desktop size.
const context = await browser.newContext({viewport:{width:1366,height:768}});
try {
await context.addInitScript(() => { let seed=19; Math.random=()=>{seed=(Math.imul(seed,1664525)+1013904223)>>>0;return seed/2**32;}; });
const page = await context.newPage();
await page.goto(`${origin}/trainer`);
await page.locator('#scene-grid button').last().waitFor();
const cell = id=>page.locator(`#scene-grid button[data-id="${id}"]`);
// 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(field.hazards.has(hazard),'loss fixture: final cell must be hazardous');
await cell(hazard).click();
assert(await page.locator('#result').isVisible());
assert((await page.locator('#result').textContent()).includes(`Падение на ${coordinate(hazard)}`));
await assertEntranceLevel(page,field.values[0],false);
assert(await page.locator('#replay-sound').isDisabled());
assert.equal(await page.locator('#scene-grid .hazard').count(),field.hazards.size);
const count = await page.locator('#history li').count();
await cell(11).click(); // Previously opened, adjacent to the current cell: blocked only by the result lock.
await cell(30).click({button:'right'});
const postResult = page.locator('#map-grid button[data-id="30"]');
await postResult.click();
await assertRatingControls(page,{disabled:true});
await postResult.press('7');
assert.equal(await valueText(postResult,'.cell-rating'),'','keyboard ratings also respect the result lock');
assert.equal(await page.locator('#history li').count(),count);
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[20]);
const frozen = await page.locator('#timer').textContent();
await page.waitForTimeout(1100); assert.equal(await page.locator('#timer').textContent(),frozen);
await cell(2).click(); assert.equal(await page.locator('#timer').textContent(),frozen,'result inspection must not advance the stopped clock');
// The narrow, fine-pointer layout exposes the controls without lifting the result lock.
await page.setViewportSize({width:683,height:384});
const jump = page.locator('#jump'), mark = page.locator('#mark');
await jump.waitFor({state:'visible'});
assert(await mark.isVisible());
await cell(30).click();
assert(await jump.isDisabled());
assert(await mark.isDisabled());
// Restart must cancel old hints, facts and the clock.
await page.locator('#new-game').click(); await page.locator('#confirm-action').click();
await page.waitForTimeout(2100);
assert.equal(await page.locator('#timer').textContent(),'00:00');
assert.equal(await page.locator('#scene-grid .hint').count(),0);
// Equivalent layout viewport at 200% browser zoom; then explicit CSS magnification.
assert(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth));
await page.evaluate(()=>document.documentElement.style.zoom='2');
assert(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth));
assert(await page.locator('#new-game').isVisible());
console.log('PASS terminal state, frozen clock, restart timer cleanup, 200% layout/magnification');
await page.evaluate(()=>document.documentElement.style.zoom='1');
await page.setViewportSize({width:1366,height:768});
await jump.waitFor({state:'hidden'});
await page.reload(); await page.locator('#scene-grid button').last().waitFor();
await page.locator('#simple-mode').check();
await page.evaluate(()=>Math.random=()=>0);
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));
assert.equal(await page.locator('#status').textContent(),`Опасностей рядом: ${field.values[hintCell]}. ${hintText} (опасная клетка).`);
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 revisitHint();
assert.equal(await page.locator('#scene-grid .hint').count(),1);
await page.locator('#simple-mode').uncheck();
assert.equal(await page.locator('#scene-grid .hint, #map-grid .hint').count(),0);
assert.doesNotMatch(await page.locator('#messages').textContent(),/Подсказка:/);
await page.locator('#simple-mode').check();
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);
assert.equal(await page.locator('#scene-grid .hint').count(),0);
assert.equal(await page.locator('#history li').count(),0);
assert.equal(await page.locator('#timer').textContent(),'00:00');
// Ratings neither satisfy nor obstruct the exact-flag victory condition.
await page.reload(); await page.locator('#scene-grid button').last().waitFor();
for (const id of field.hazards) await page.locator(`#map-grid button[data-id="${id}"]`).press('7');
assert.equal(await page.locator('#mark-count').textContent(),'0');
assert(await page.locator('#result').isHidden(),'rating every hazard does not win without flags');
const ratedSafe = page.locator(`#map-grid button[data-id="${first}"]`);
await ratedSafe.press('1');
assert.equal(await valueText(ratedSafe,'.cell-rating'),'1');
for (const id of field.hazards) await cell(id).click({button:'right'});
assert.match(await page.locator('#result').textContent(),/Карта готова/);
assert(await page.locator('#clear-marks').isDisabled());
await page.locator(`#map-grid button[data-id="${second}"]`).click();
await assertRatingControls(page,{disabled:true});
const wonHistory = await page.locator('#history li').count();
await cell(first).click({button:'right'}); // A safe, unopened cell would normally accept a note.
await cell(first).press('Enter');
assert.equal(await page.locator('#history li').count(),wonHistory);
console.log('PASS hint duration/log persistence, restart cancels active hint, exact-note victory and terminal locks');
} finally {await context.close();}
// Image failure is intentional; the forest and cat have independent text/grid fallbacks.
const broken = await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true});
try {
const page = await broken.newPage();
await page.route('**/lu-trainer/assets/*',route=>route.abort());
await page.goto(`${origin}/trainer`);
await page.locator('#scene-grid button').last().waitFor();
assert(await page.locator('.forest').isHidden());
assert(await page.locator('#character > span').isVisible());
await page.locator('#scene-grid button[data-id="1"]').tap(); await page.locator('#jump').tap();
assert.equal(await page.locator('#scene-grid .opened').count(),1);
console.log('PASS failed-image fallback retains training controls and character marker');
} finally { await broken.close(); }
console.log(JSON.stringify({screenshots:captures}));
} finally {await browser.close();}
}
run().catch(error=>{console.error(error); process.exitCode=1;});