diff --git a/AGENTS.md b/AGENTS.md index 6b2b54e..0091257 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,6 +36,7 @@ ## Notes - LU trainer is implemented at `/trainer` and `/trainer/` through both Python and Nginx. `web/lu-trainer/engine.js` is DOM-free; UI consumes public snapshots without hidden hazards/values. Keep notes separate from facts, map selection separate from jumping, jumps limited to the eight neighbors of the current position, and transition cells outside victory counts. Entrance is fixed at x1 y1 (top-left); choose each field's exit from x10 y2–y6 or y6 x6–x10. UI/map must use snapshot transition identities, never a global exit constant. Coordinates are one-based X right/Y down. Preserve documented training formulas; do not claim they are verified CatWar rules. Original art provenance is in `web/lu-trainer/assets/README.md`. +- Trainer controls: click/Enter/Space jumps; right-click or Shift+Enter on the scene toggles a mark. Compact and coarse-pointer layouts use selection plus buttons under the field, without a separate action-mode switch. Keep the field status brief and the detailed jump message in the journal. - LU checks (prefer remote test-zone MCP when exposed): Node 24 `node --test tests/lu-trainer/engine.test.mjs`; isolated Python `python -m unittest tests.test_lu_trainer tests.test_calculator_web -q`; `node --check web/lu-trainer/ui.js`; `node tests/browser/lu-trainer.cjs` with the same bundled Playwright, loopback server and temporary stores as the calculator suite. No npm install or runtime dependency is needed. Browser coverage includes 1920/1366/768/390 widths, mouse/touch/keyboard, map projection, clear/restart confirmation, result locks, hints/timers, 200% layout and failed images. Inspect screenshots outside Git. Nginx aliases must serve the same HTML and correct asset MIME types; do not deploy to validate a client-only change. - `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint (3-second timeout, 64 KiB bound, 5-minute process cache, 1-minute failure cache). `/api/weather/ulli` exposes only decoration settings; shared CSS/JS live at `/api/weather/effect.css` and `/api/weather/effect.js` so the existing gateway `/api/` route handles them. Keep weather independent of reports/storage, skip trend/remark/vicinity groups, reject observations older than 2 hours, and retain leaves on failure. Do not disable TLS verification. - VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule. diff --git a/LU_TRAINER_PROJECT.md b/LU_TRAINER_PROJECT.md index 964328a..9d019cb 100644 --- a/LU_TRAINER_PROJECT.md +++ b/LU_TRAINER_PROJECT.md @@ -112,7 +112,7 @@ 1. Пользователь открывает тренажёр, видит игровую локацию, краткую подсказку управления и кнопку настроек. Полная инструкция открывается по желанию. 2. Выбирает параметры и начинает попытку. Изменение параметров во время попытки применяется только через явное начало новой игры с предупреждением о сбросе. 3. Нажимает допустимую клетку: она открывается, персонаж показывается на последней успешно выбранной клетке, история и сообщения обновляются, известное значение появляется на карте. -4. Отмечает подозрительную клетку через карту или режим «Опасная» на локации. Отметка не открывает клетку. Попытка прыгнуть на неё предлагает сначала снять отметку. +4. Отмечает подозрительную клетку через карту, правым кликом или Shift+Enter на локации, либо кнопкой под полем на сенсорном экране. Отметка не открывает клетку и блокирует прыжок на неё. 5. Повторное посещение проверенной клетки воспроизводит текстовую обратную связь и предусмотренную моделью проверку подсказки. 6. После падения либо выполнения условия победы действия попытки прекращаются, показываются результат и раскрытие поля. Доступны осмотр результата и новая игра. @@ -124,7 +124,7 @@ - На широком экране локация и обе боковые колонки видны вместе. На планшете второстепенные панели сворачиваются, но локация и действия остаются основными. - На телефоне порядок: краткое состояние → локация → действия → сообщения. История и карта открываются отдельными панелями; закрытие возвращает фокус к кнопке открытия. Тренировка при этом не сбрасывается. -- Все действия доступны мышью, касанием и клавиатурой. Клавиатура: стрелки перемещают фокус по сетке, Enter/Space выполняет выбранное действие; фокус не равен положению персонажа. Режим действия имеет текстовое и программное обозначение. +- Все действия доступны мышью, касанием и клавиатурой. Стрелки перемещают фокус, Enter/пробел на локации выполняет прыжок, Shift+Enter ставит или снимает отметку. Фокус не равен положению персонажа. На сенсорном экране касание выбирает клетку, а действия находятся под полем; на компьютере эти кнопки не дублируют управление мышью. - Десять клеток шириной 44 px не помещаются на телефон 390 px. Поэтому компактный обзор локации служит выбору клетки, а отдельные кнопки не меньше 44×44 px подтверждают прыжок/отметку; выбранная клетка и её координаты хорошо видны. Не считать уменьшенную сетку полноценной заменой удобных сенсорных действий. - Масштабирование браузером разрешено; горизонтального скролла всей страницы нет. Уведомления о ходе доступны скринридеру, таймер не озвучивается каждую секунду. Подсказка не должна зависеть только от hover или краткой вспышки. diff --git a/README.md b/README.md index 58e0121..4530996 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ python3 -m app.belki.vk_bot Самостоятельная клиентская тренировка без регистрации, БД и новых runtime-зависимостей. Она не подключается к CatWar и не начисляет ЛУ. Поле, история и заметки существуют до перезагрузки страницы. -На компьютере клик по локации выполняет выбранный «Прыжок» или «Опасная»; правая кнопка ставит/снимает заметку. На телефоне касание сначала выбирает клетку, затем действие подтверждается отдельной крупной кнопкой. На обеих сетках доступны стрелки, Home / End, Enter и пробел. «Минное поле» выбирает клетку для заметки и автоматически показывает результаты прыжков. «Перенос на игровое поле» меняет только видимость заметок на локации. Очистка заметок и новая игра имеют разные подтверждения. +На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Стрелки и Home / End перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Перенос на игровое поле» меняет только видимость отметок на локации. Очистка отметок и новая игра имеют разные подтверждения. Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от входа: перескакивать через них нельзя. diff --git a/docs/staging/specs/2026-11-17-lu-trainer.md b/docs/staging/specs/2026-11-17-lu-trainer.md index 339f8b3..30e2b0f 100644 --- a/docs/staging/specs/2026-11-17-lu-trainer.md +++ b/docs/staging/specs/2026-11-17-lu-trainer.md @@ -3,10 +3,11 @@ Authorization: the owner requested implementation of root `LU_TRAINER_PROJECT.md` on 2026-11-17. That existing design is the approved specification; this file records implementation choices within its scope. contract: standalone `/trainer` and `/trainer/`, shared HTML/CSS/ES-module assets served by Python and Nginx. No new runtime dependency or storage. Gateway serves the page with `try_files`; assets use the existing static serving. -convention: native buttons/radios/dialogs, CSS tokens, Verdana/Georgia, Russian copy, DOM-independent ES-module engine, no upstream code or asset copying. -state: engine owns 60 cells, per-attempt start/exit identities, hazards, opened set, marks set, last successful position, ready/playing/won/lost status and action log. A public snapshot omits hidden hazards/values. UI owns selection, action mode, map visibility and mark projection. +convention: native buttons/dialogs, CSS tokens, Verdana/Georgia, Russian copy, DOM-independent ES-module engine, no upstream code or asset copying. +state: engine owns 60 cells, per-attempt start/exit identities, hazards, opened set, marks set, last successful position, ready/playing/won/lost status and action log. A public snapshot omits hidden hazards/values. UI owns selection, map visibility and mark projection. invariant: 6x10, entrance x1 y1 (top-left, index 0), exit selected per attempt from x10 y2–y6 or y6 x6–x10; transition cells do not count toward victory and cannot be opened/marked. The first 5/3 top-row cells to the right of the entrance are safe, but there is no special jump permission for them. A jump must target one of the current position’s eight neighbors, even for previously opened cells. Eight-neighbor counts; safe path connects entrance, base and exit. Preserve documented hazard formula and 0/10/20/30% hint probabilities. Win by all non-transition safe cells or all and only hazards marked; loss ends actions. Repeat safe visits produce feedback and may hint. The character tracks the last successful non-transition visit. invariant: one click produces one action; map selection never jumps; marks are separate from facts. Projection only changes scene rendering. Confirm clear marks and restart, including settings restart. Ending/restarting cancels hint and timer callbacks. At completion reveal the whole board, including incorrect notes. +invariant: scene mouse click jumps, right click and Shift+Enter toggle a mark, and Enter/Space jump. Compact/coarse-pointer mode selects a cell with a tap and shows explicit action buttons below the grid; unavailable jumps are disabled with a reason in the selection text. Full jump messages belong in the journal, not the action row. contract: desktop direct cell action; compact/coarse-pointer overview selects only and uses >=44px confirm controls. Arrow/Home/End navigation and Enter/Space work. Screen-reader live status excludes timer ticks. Map/history mobile panels restore focus. Native dialogs support Escape/cancel. Failed images leave cells and character fallback usable. test: deterministic Node tests for generator safety/reachability/counts, all settings combinations, adjacency, transition exclusion, notes, win/loss, hints and public snapshots. HTTP test for aliases and asset MIME/containment. Browser checks at 1920x1080,1366x768,768x1024,390x844; two grids, logs, marks, confirmations, focus, keyboard/touch, reduced motion, 200% layout and image failures. Review real screenshots. Nginx syntax/serving check in isolated container if Docker available; no deployment. deferred: verification of real CatWar rules, multiple saved maps, audio, server accounts, deployment. Generated original art provenance and prompts live in assets/README.md. diff --git a/structure_and_data.md b/structure_and_data.md index 9318987..fcee3e9 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -1,5 +1,9 @@ # Structure and Data +## Trainer controls — 2026-11-22 + +- `/trainer` no longer has a separate action panel or mode toggle. The scene handles mouse and keyboard actions directly; narrow and coarse-pointer layouts use selection and explicit buttons below the grid. The inline status is short, and detailed jumps and hints remain in the message journal. + ## Trainer movement and exit edges — 2026-11-22 - Jumps and the grids’ availability indicators use the eight neighbors of the current character position, including from the entrance. An opened cell can be revisited only from an adjacent cell; selecting or marking a cell on the map does not move the character. diff --git a/tests/browser/lu-trainer.cjs b/tests/browser/lu-trainer.cjs index 5606980..9e7edf2 100644 --- a/tests/browser/lu-trainer.cjs +++ b/tests/browser/lu-trainer.cjs @@ -37,8 +37,9 @@ async function run() { 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} : {})}); + for (const [width,height,touch = false] of [[1920,1080],[1366,768],[768,1024],[390,844,true],[1024,768,true]]) { + const mobile = width <= 700, 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; @@ -56,7 +57,13 @@ async function run() { 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(); }; + 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`); @@ -65,8 +72,23 @@ async function run() { await noOverflow(); assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: вход, персонаж здесь$/); await checkTransitions(page,field.exit); - assert(await page.locator('#jump').isDisabled()); - assert(await page.locator('#mark').isDisabled()); + 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); @@ -78,23 +100,44 @@ async function run() { 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); + 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); - if (width === 390) { + if (compact) { + await scene(first).click(); await scene(first).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(first); + 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 page.locator('#history li').count(),1); + assert.equal(await history.count(),1); assert.match(await scene(first).getAttribute('aria-label'),/персонаж здесь/); - assert.match(await page.locator('#messages').textContent(),/Опасностей рядом/); + 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'); @@ -104,13 +147,20 @@ async function run() { 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(),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); + 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'); @@ -121,7 +171,7 @@ async function run() { 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(); + if (mobile) await page.locator('#map-open').click(); await map(note).click(); assert.equal(await page.locator('#scene-grid .opened').count(),2); await page.locator('#map-mark').click(); @@ -140,7 +190,7 @@ async function run() { 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) { + if (mobile) { await page.keyboard.press('Escape'); assert(await page.locator('#map-open').evaluate(n=>n===document.activeElement)); await page.locator('#history-open').click(); @@ -153,7 +203,12 @@ async function run() { 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); } + 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 || mobile}); + 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); @@ -170,8 +225,31 @@ async function run() { assert.match(await scene(0).getAttribute('aria-label'), /вход, персонаж здесь/); 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}: render, adjacent jumps, keyboard/touch, synchronized map, notes, dialogs, settings, console`); + console.log(`PASS ${width}x${height} (${compact ? 'compact' : 'desktop'}): render, adjacent jumps, keyboard/touch controls, synchronized map, notes, dialogs, settings, console`); } finally { await context.close(); } } // Sample all exit buckets without coupling this test to their internal order. @@ -187,7 +265,9 @@ async function run() { 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-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); @@ -217,18 +297,27 @@ async function run() { 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); - assert(await page.locator('#jump').isDisabled()); assert(await page.locator('#mark').isDisabled()); + await cell(11).click(); // Previously opened, adjacent to the current cell: blocked only by the result lock. + await cell(30).click({button:'right'}); + 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. - 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)); @@ -236,12 +325,14 @@ async function run() { 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.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); @@ -262,7 +353,8 @@ async function run() { 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'}); + 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'); diff --git a/web/lu-trainer.html b/web/lu-trainer.html index 7f431d6..d2781ac 100644 --- a/web/lu-trainer.html +++ b/web/lu-trainer.html @@ -40,21 +40,21 @@

Лесные уступы

Высота 1

Вход: x1 y1 · Выход выбирается для новой попытки

-

Прыгайте только в соседние клетки, в том числе по диагонали.

+

Клик по соседней клетке — прыжок. Правый клик — поставить или снять отметку.

+
+ +

+

↥ Вход / выход · Проверено ⚑ Ваша отметка × Опасность в результате ≠ Ошибочная отметка

-
-
-

Действия

-
Действие на локации
-

Выбрана клетка x1 y1 · вход

-
-

Начните с клетки рядом со входом. Стрелки перемещают фокус, Enter или пробел выполняет действие.

@@ -97,8 +97,8 @@
  • Вход всегда находится в x1 y1 — верхней левой клетке. X растёт вправо, Y — вниз. Выход выбирается случайно: на правом краю (x10, начиная с y2) или на нижнем (y6, начиная с x6). Стрелки отмечают переходы; в тренажёре по ним не прыгают.
  • Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. Безопасные клетки верхнего ряда начинаются сразу справа от входа: 5 на первой высоте и 3 на остальных. Идите по ним по одной.
  • Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.
  • -
  • На компьютере клик выполняет выбранное действие, правая кнопка ставит заметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной».
  • -
  • На обеих сетках стрелки перемещают фокус; Home / End — начало / конец строки. Enter и пробел выполняют действие. На карте они только выбирают клетку.
  • +
  • На компьютере клик по клетке — прыжок, правый клик ставит или снимает отметку. На телефоне сначала коснитесь клетки, затем нажмите «Прыгнуть» или «Отметить опасной» под полем.
  • +
  • Стрелки перемещают фокус; Home / End — начало / конец строки. На локации Enter и пробел выполняют прыжок, Shift+Enter ставит или снимает отметку. На карте Enter и пробел только выбирают клетку.
  • Отмеченная клетка закрыта для прыжка, пока вы не снимете отметку. Карта не показывает скрытые опасности. При ЛУ от 4 возможна подсказка «!»: координата останется в сообщениях.
  • Победа: открыть все безопасные клетки, кроме переходов, или отметить все опасности без лишних отметок. Достижение выхода не завершает игру. Опасный прыжок заканчивается падением.
  • diff --git a/web/lu-trainer/style.css b/web/lu-trainer/style.css index db82fa9..314b8cb 100644 --- a/web/lu-trainer/style.css +++ b/web/lu-trainer/style.css @@ -75,14 +75,12 @@ dd { margin: 0; text-align: right; font-weight: bold; } .character-sprite:has(img:not([hidden])) > span { visibility: hidden; } .legend { display: flex; gap: 4px 12px; flex-wrap: wrap; padding: 12px 16px; font-size: var(--small); } .result { margin: 0 12px 12px; padding: 12px; background: var(--paper); border: 2px solid var(--border); font-weight: bold; } -.mode { border: 0; padding: 0; margin: 0 0 12px; display: flex; flex-wrap: wrap; gap: 8px; } -.mode legend { font-size: var(--small); margin-bottom: 8px; } -.mode label { cursor: pointer; padding: 8px 12px; border: 1px solid var(--border); border-radius: 4px; min-height: 44px; display: flex; gap: 8px; align-items: center; background: var(--inner); } -.mode label:has(:checked) { background: var(--map); color: var(--light); } input { accent-color: var(--map); } -.mode input { accent-color: var(--active); } +.cell-controls:has(#touch-actions:not([hidden])), .cell-controls:has(#status:not(:empty)) { padding: 8px 16px 0; } +#selection { font-size: var(--small); } .action-buttons { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; } -#status { margin-top: 12px; font-size: var(--small); min-height: 3em; } +#status { font-size: var(--small); } +#touch-actions:not([hidden]) + #status:not(:empty) { margin-top: 8px; } .mobile-tools { display: none; } .journal { list-style-position: inside; margin: 0; padding: 0; max-height: 280px; overflow: auto; font-size: var(--small); scrollbar-color: var(--border) var(--inner); } .journal li { padding: 8px 0; border-bottom: 1px solid var(--border); overflow-wrap: anywhere; } @@ -137,10 +135,9 @@ select { min-height: 44px; padding: 8px; width: 100%; } .character .stats { display: flex; flex-wrap: wrap; gap: 4px 16px; } .character .stats > div { border: 0; padding: 2px 0; } .location { order: 1; } - .actions { order: 2; } .history-panel { display: none; } .right-column { order: 3; width: 100%; display: grid; grid-template-columns: 1fr 1fr; align-items: start; } - .mobile-tools { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; } + .mobile-tools { display: flex; flex-wrap: wrap; gap: 8px; padding: 0 12px 12px; } .mobile-tools button { flex: 1; } .brand { display: block; } .topbar { align-items: start; } @@ -163,20 +160,17 @@ select { min-height: 44px; padding: 8px; width: 100%; } .character .stats > div { border: 0; padding: 2px 0; } .character .stats:first-of-type > div:last-child, .character .stats:last-of-type > div:nth-child(n+3) { display: none; } .location { order: 1; padding: 0; } - .actions { order: 2; } .messages-panel { order: 3; } .map-panel, .history-panel { display: none; } - .mobile-tools { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; } - .mobile-tools button { flex: 1; } .cell-coord { font-size: 8px; left: 1px; top: 1px; padding: 0 1px; } .cell-value { font-size: 14px; } .scene-grid .opened .cell-coord { display: none; } - .action-buttons button { flex: 1; } + .action-buttons button { flex: 1 1 125px; } .legend { padding: 8px 12px; } .settings-fields { grid-template-columns: 1fr; } dialog { padding: 16px; } footer { padding: 16px 12px; } } -@media (pointer: coarse) { .action-buttons button, .mobile-tools button, #map-mark, .mode label { min-height: 48px; } } +@media (pointer: coarse) { .action-buttons button, .mobile-tools button, #map-mark { min-height: 48px; } } @media (prefers-reduced-motion: reduce) { button { transition: none; } } @media (forced-colors: active) { .cell-grid .selected button, .cell-grid .current button { outline: 2px solid Highlight; outline-offset: -3px; } } diff --git a/web/lu-trainer/ui.js b/web/lu-trainer/ui.js index 11e2a22..03f5e45 100644 --- a/web/lu-trainer/ui.js +++ b/web/lu-trainer/ui.js @@ -4,7 +4,7 @@ const $ = id => document.getElementById(id); const compact = matchMedia('(max-width: 700px), (pointer: coarse)'); const mobile = matchMedia('(max-width: 700px)'); const sounds = ['Звуков нет', 'Едва различимый шорох', 'Тихий шорох', 'Приглушённый шорох', 'Громкий шорох']; -let game, selected = START, mode = 'jump', hints = new Set(), hintTimers = new Map(); +let game, selected = START, hints = new Set(), hintTimers = new Map(); let clock = null, startedAt = null, renderedHistory = 0, pendingConfirmation = null, panelReturn = null; let panelOrigin = null, panelBody = null; const grids = []; @@ -35,6 +35,12 @@ function cellValue(cell, view, showMarks) { if (hints.has(cell.id)) return '!'; return ''; } +function selectCell(id) { + if (id === selected) return; + selected = id; + $('status').textContent = ''; + render(); +} function makeGrid(id, isMap) { const root = $(id), cells = [], buttons = []; for (let r = 0; r < ROWS; r++) { @@ -53,20 +59,32 @@ function makeGrid(id, isMap) { } root.addEventListener('click', event => { const button = event.target.closest('button[data-id]'); if (!button) return; - selected = Number(button.dataset.id); render(); - if (!isMap && (!compact.matches || event.detail === 0)) act(mode); + selectCell(Number(button.dataset.id)); + if (!isMap && (!compact.matches || event.detail === 0)) act('jump'); }); root.addEventListener('contextmenu', event => { const button = event.target.closest('button[data-id]'); if (!button) return; - event.preventDefault(); selected = Number(button.dataset.id); act('mark'); + event.preventDefault(); + selectCell(Number(button.dataset.id)); + if (event.pointerType !== 'touch') act('mark'); }); root.addEventListener('focusin', event => { if (!event.target.matches('button[data-id]')) return; - selected = Number(event.target.dataset.id); render(); + selectCell(Number(event.target.dataset.id)); }); root.addEventListener('keydown', event => { - if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || !buttons.includes(event.target)) return; + if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || !buttons.includes(event.target)) return; const from = event.target, index = Number(from.dataset.id); + if (event.shiftKey) { + if (!isMap && event.key === 'Enter') { + event.preventDefault(); + if (!event.repeat) { + selectCell(index); + act('mark'); + } + } + return; + } let next; if (event.key === 'Home') next = buttons[Math.floor(index / COLS) * COLS]; else if (event.key === 'End') next = buttons[Math.floor(index / COLS) * COLS + COLS - 1]; @@ -104,7 +122,7 @@ function start(options = DEFAULTS) { stopTimers(); game = new Training(options); selected = START; startedAt = null; renderedHistory = 0; $('history').replaceChildren(); $('messages').replaceChildren(); addItem($('messages'), 'Лес затих. Звуки появятся после прыжка.'); - $('status').textContent = 'Начните с клетки рядом со входом. Стрелки перемещают фокус, Enter или пробел выполняет действие.'; + $('status').textContent = ''; updateClock(); render(); } function render() { @@ -132,15 +150,18 @@ function render() { $('progress').textContent = `${view.opened} / ${view.safe}`; $('mark-count').textContent = view.marks; $('hazard-count').textContent = view.hazards; $('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status]; - $('scene-instructions').textContent = compact.matches ? 'Выберите соседнюю клетку и нажмите «Прыгнуть». Отметку можно поставить где угодно на уступе.' : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Прыгать можно только в соседние клетки, в том числе по диагонали.`; + $('scene-instructions').textContent = compact.matches ? 'Коснитесь клетки, затем выберите действие под полем.' : 'Клик по соседней клетке — прыжок. Правый клик или Shift+Enter — поставить или снять отметку.'; const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной'; - $('selection').textContent = `Выбрана клетка ${coordinate(selected)} · ${describe(cell, view)}`; + const selectionState = finished ? 'попытка завершена' : cell.id === view.position ? 'вы здесь' : + cell.transition ? (cell.entrance ? 'вход' : 'выход') : cell.marked ? 'есть отметка' : + !cell.available ? 'вне досягаемости' : ''; + $('touch-actions').hidden = !compact.matches; + $('selection').textContent = `Клетка ${coordinate(selected)}${selectionState ? ` — ${selectionState}` : ''}`; $('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view)}`; $('mark').textContent = note; $('map-mark').textContent = note; - $('jump').disabled = finished || cell.transition; + $('jump').disabled = finished || !cell.available || cell.marked; for (const id of ['mark','map-mark']) $(id).disabled = finished || cell.opened || cell.transition; $('clear-marks').disabled = finished || view.marks === 0; - document.querySelectorAll('input[name=mode]').forEach(input => { input.disabled = finished; }); $('history-empty').hidden = view.history.length > 0; for (const entry of view.history.slice(renderedHistory)) { const text = entry.type === 'cleared' ? 'Все заметки очищены; открытые клетки сохранены.' : `${coordinate(entry.id)} · ${{opened:'Прыжок',revisited:'Повторный прыжок',fall:'Падение',marked:'Поставлена отметка',unmarked:'Снята отметка'}[entry.type]}${entry.value !== undefined ? ` · рядом ${entry.value}` : ''}`; @@ -155,25 +176,26 @@ function act(action) { const view = game.view(); let text; if (action === 'jump' && ['opened','revisited'].includes(result.code)) { - text = `${coordinate(selected)} · ${sound(result.value)}. Опасностей рядом: ${result.value}.`; - addItem($('messages'), text); + text = `Опасностей рядом: ${result.value}.`; + addItem($('messages'), `${coordinate(selected)} · ${sound(result.value)}. ${text}`); if (startedAt === null) { startedAt = Date.now(); clock = setInterval(updateClock,1000); } if (result.hint !== null) { clearTimeout(hintTimers.get(result.hint)); hints.add(result.hint); const hintText = `Подсказка: ${coordinate(result.hint)} — опасная клетка. Значок «!» виден 2 секунды; координата остаётся здесь.`; - addItem($('messages'), hintText); text += ` ${hintText}`; + addItem($('messages'), hintText); text += ` Подсказка: ${coordinate(result.hint)} — опасная клетка.`; const attempt = game; const timer = setTimeout(() => { hintTimers.delete(result.hint); if (game === attempt) { hints.delete(result.hint); render(); } },2000); hintTimers.set(result.hint, timer); } } else if (result.code === 'fall') { - text = `Падение на ${coordinate(selected)}. Попытка завершена.`; addItem($('messages'), text); + addItem($('messages'), `Падение на ${coordinate(selected)}. Попытка завершена.`); + text = 'Падение. Попытка завершена.'; } else { - text = {finished:'Попытка завершена. Изучите поле или начните новую игру.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Прыгнуть можно только в соседнюю клетку. Выберите клетку рядом с персонажем.',marked: action === 'jump' ? 'Сначала снимите отметку опасности с этой клетки.' : `${coordinate(selected)}: поставлена ваша отметка опасности.`,unmarked:`${coordinate(selected)}: отметка снята.`,opened:'Проверенную клетку нельзя отметить опасной.'}[result.code]; + text = {finished:'Попытка завершена.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Выберите соседнюю клетку для прыжка.',marked: action === 'jump' ? 'Сначала снимите отметку с этой клетки.' : 'Отметка поставлена.',unmarked:'Отметка снята.',opened:'Проверенную клетку нельзя отметить опасной.'}[result.code]; } if (ended(view)) { if (clock !== null) updateClock(); stopTimers(); } - if (view.status === 'won') text += ' Карта готова! Победа. Всё поле раскрыто.'; + if (view.status === 'won') text += ' Карта готова!'; $('status').textContent = text; render(); } function showDialog(dialog, opener) { @@ -228,7 +250,6 @@ $('settings-form').addEventListener('submit', event => { $('new-game').addEventListener('click', event => confirmAction('Начать заново?', 'Текущее поле, заметки и история будут сброшены. Условия тренировки сохранятся.', 'Начать новую игру', () => start(game.view().options), event.currentTarget)); $('clear-marks').addEventListener('click', event => confirmAction('Очистить отметки?', 'Удалятся только ваши заметки. Проверенные клетки, история и текущая попытка сохранятся.', 'Очистить отметки', () => { game.clearMarks(); $('status').textContent = 'Отметки очищены. Попытка продолжается.'; render(); }, event.currentTarget)); $('project-marks').addEventListener('change', render); -for (const input of document.querySelectorAll('input[name=mode]')) input.addEventListener('change', () => { mode = input.value; render(); }); $('jump').addEventListener('click', () => act('jump')); $('mark').addEventListener('click', () => act('mark')); $('map-mark').addEventListener('click', () => act('mark'));