feat: implement game-like LU trainer and companion map

This commit is contained in:
nyan404 committed 2026-11-17 16:24:02 +03:00
1 parent 87d5a6720f
commit 74c8504d52
21 files changed
+1160 -14

No files matched your search

+206
View File
@@ -0,0 +1,206 @@
// 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;
function seeded(seed = 19) { return () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; }; }
async function run() {
const {generateField, DEFAULTS} = await import(pathToFileURL(path.resolve(__dirname,'../../web/lu-trainer/engine.js')));
const field = generateField(DEFAULTS,seeded());
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] of [[1920,1080],[1366,768],[768,1024],[390,844]]) {
const context = await browser.newContext({viewport:{width,height}, reducedMotion:'reduce', locale:'ru-RU', ...(width === 390 ? {hasTouch:true,isMobile:true} : {})});
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}/lu-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 select = async id => { await scene(id).click(); if (width === 390) await page.locator('#jump').click(); };
await noOverflow();
assert.equal(await page.locator('#scene-grid .hazard').count(),0);
assert.equal(await page.locator('#scene-grid .opened').count(),0);
// 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));
if (width === 390) {
await scene(0).tap();
assert.equal(await page.locator('#scene-grid .opened').count(),0,'touch overview must only select');
const box = await page.locator('#jump').boundingBox(); assert(box.height >= 44 && box.width >= 44);
await page.locator('#jump').tap();
} else await select(0);
assert.equal(await page.locator('#scene-grid .opened').count(),1);
assert.equal(await page.locator('#map-grid .opened').count(),1);
assert.equal(await page.locator('#history li').count(),1);
assert.match(await scene(0).getAttribute('aria-label'),/персонаж здесь/);
assert.match(await page.locator('#messages').textContent(),/Опасностей рядом/);
// Native button keyboard actions and spatial focus; focus is not character position.
await scene(0).focus(); await page.keyboard.press('ArrowRight');
assert(await scene(1).evaluate(n=>n===document.activeElement));
assert.match(await scene(0).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 page.keyboard.press(' ');
assert.equal(await page.locator('#history li').count(),3,'one keyboard action, one history item');
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));
// Notes select on the map without jumping. One DOM map is moved into the modal on phone.
if (width === 390) await page.locator('#map-open').click();
await map(2).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);
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);
assert.equal(await page.locator('#history li').count(),4);
await page.locator('#project-marks').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();
assert.equal(await page.locator('#map-grid .marked').count(),0);
assert.equal(await page.locator('#map-grid .opened').count(),2);
assert.equal(await page.locator('#history li').count(),5);
if (width === 390) {
await page.keyboard.press('Escape');
assert(await page.locator('#map-open').evaluate(n=>n===document.activeElement));
await page.locator('#history-open').click();
assert(await page.locator('#panel-dialog #history').isVisible());
await page.keyboard.press('Escape');
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'); assert(await page.locator('#map-body').isHidden());
await page.locator('#map-toggle').click();
}
if (shotDir) { const file = `${shotDir}/lu-${width}.png`; await page.screenshot({path:file,fullPage:true}); captures.push(file); }
// Restart confirmations preserve/cancel the existing state; settings are staged until submit.
await page.locator('#new-game').click(); await page.keyboard.press('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 page.keyboard.press('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 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.deepEqual(errors,[]);
console.log(`PASS ${width}x${height}: render, keyboard/touch, synchronized map, notes, dialogs, settings, console`);
} finally { await context.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}/lu-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();
}
assert.notEqual(hazard,undefined); await cell(hazard).click();
assert(await page.locator('#result').isVisible());
assert.match(await page.locator('#result').textContent(),/Падение/);
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);
assert(await page.locator('#jump').isDisabled()); assert(await page.locator('#mark').isDisabled());
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');
// 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.
await page.setViewportSize({width:683,height:384});
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 page.reload(); await page.locator('#scene-grid button').last().waitFor();
await page.evaluate(()=>Math.random=()=>0);
await cell(2).click();
assert.equal(await page.locator('#scene-grid .hint').count(),1);
assert.equal(await page.locator('#map-grid .hint').count(),1);
assert.match(await page.locator('#messages').textContent(),/Подсказка: Б4/);
await page.waitForTimeout(1100); await cell(2).click();
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.match(await page.locator('#messages').textContent(),/Подсказка: Б4/);
await cell(2).click();
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');
// Marking is available anywhere; only the exact hazard set wins.
await page.reload(); await page.locator('#scene-grid button').last().waitFor();
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());
const wonHistory = await page.locator('#history li').count();
await cell(0).click({button:'right'});
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}/lu-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="0"]').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;});
+121
View File
@@ -0,0 +1,121 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Training, generateField, neighbors, hintChance, START, EXIT } from '../../web/lu-trainer/engine.js';
function seeded(seed = 19) {
return () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed / 2 ** 32; };
}
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('generation covers every settings combination with safe transitions, base and connecting route', () => {
for (let height = 1; height <= 5; height++) for (const growth of [12,15,18,22,25]) for (const season of [-3,0,5]) {
const field = generateField({...options, height, growth, season}, seeded(height * growth + season));
assert.equal(field.values.length, 60);
assert(!field.hazards.has(START) && !field.hazards.has(EXIT));
for (const id of field.base) assert(!field.hazards.has(id));
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(EXIT));
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);
}
});
test('edge neighborhoods do not wrap rows', () => {
assert.deepEqual(neighbors(0).sort((a,b)=>a-b), [1,10,11]);
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', () => {
const {game} = fixture();
assert.equal(game.jump(START).code, 'transition');
assert.equal(game.jump(EXIT).code, 'transition');
assert.equal(game.jump(25).code, 'unreachable');
assert.equal(game.mark(START).code, 'transition');
assert.equal(game.jump(0).code, 'opened');
game.jump(4); // last position differs: adjacency still belongs to any open cell
assert(game.view().cells[10].available);
assert.equal(game.view().position, 4);
});
test('notes hide no facts, block jumps, clear independently and reject invalid IDs', () => {
const {game} = fixture();
game.jump(0); game.mark(1);
const before = game.view();
assert.equal(game.jump(1).code, 'marked');
assert.equal(before.cells[1].value, null);
assert(!Object.hasOwn(before.cells[1], 'hazard'));
assert.equal(game.mark(0).code, 'opened');
game.clearMarks();
assert(game.view().cells[0].opened);
assert.equal(game.view().marks, 0);
assert.equal(game.view().position, before.position);
assert(game.view().history.length > before.history.length);
for (const id of [-1,60,1.5,'1',null]) assert.equal(game.jump(id).code, 'invalid');
});
test('all and only hazards marked wins; terminal actions cannot change state', () => {
const {game,field} = fixture();
game.mark(0);
for (const id of field.hazards) game.mark(id);
assert.notEqual(game.view().status, 'won');
game.mark(0);
assert.equal(game.view().status, 'won');
const ended = game.view();
for (const cell of ended.cells) assert.equal(typeof cell.hazard, 'boolean');
assert.equal(game.jump(0).code, 'finished');
assert.equal(game.mark(1).code, 'finished');
assert.equal(game.clearMarks().code, 'finished');
assert.deepEqual(game.view(), ended);
});
test('opening all safe cells wins without entering either transition', () => {
const {game,field} = fixture();
openReachableSafe(game, field);
assert.equal(game.view().status, 'won');
assert.equal(game.view().opened, 58 - field.hazards.size);
});
test('hazard ends attempt, reveals wrong notes and preserves last safe position', () => {
const {game,field} = fixture();
game.mark(4); game.jump(0);
while (game.view().status !== 'lost') {
const cell = game.view().cells.find(c => c.available && !c.opened && !c.transition && !c.marked);
assert(cell); game.jump(cell.id);
}
const end = game.view();
assert(end.cells[4].wrong);
assert(field.hazards.has(end.hit));
assert(!field.hazards.has(end.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);
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);
});
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);
});
+49
View File
@@ -0,0 +1,49 @@
"""Standalone LU trainer routing must work without any game/session store."""
import http.client
import threading
import unittest
from app.main import BelkiHTTPServer, Handler
class TrainerRoutesTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = BelkiHTTPServer(('127.0.0.1', 0), Handler)
cls.worker = threading.Thread(target=cls.server.serve_forever, daemon=True)
cls.worker.start()
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.server.server_close()
cls.worker.join()
def get(self, path):
connection = http.client.HTTPConnection('127.0.0.1', self.server.server_port, timeout=5)
try:
connection.request('GET', path)
response = connection.getresponse()
return response.status, response.getheader('Content-Type'), response.read()
finally:
connection.close()
def test_page_aliases_return_the_same_trainer(self):
pages = [self.get(path) for path in ['/lu-trainer', '/lu-trainer/', '/lu-trainer.html']]
for status, content_type, content in pages:
self.assertEqual(status, 200)
self.assertEqual(content_type, 'text/html')
self.assertIn('Тренажёр ЛУ'.encode(), content)
self.assertEqual(pages[0][2], pages[1][2])
def test_assets_have_browser_compatible_mime_types(self):
for asset, media_type in [('engine.js', 'javascript'), ('ui.js', 'javascript'), ('style.css', 'text/css'), ('assets/forest.webp', 'image/webp'), ('assets/cat.png', 'image/png')]:
with self.subTest(asset=asset):
status, content_type, content = self.get('/lu-trainer/' + asset)
self.assertEqual(status, 200)
self.assertIn(media_type, content_type)
self.assertGreater(len(content), 0)
def test_missing_and_escaping_assets_are_not_served(self):
for path in ['/lu-trainer/missing.js', '/lu-trainer/%2e%2e/%2e%2e/project-info.txt']:
self.assertEqual(self.get(path)[0], 404)