diff --git a/AGENTS.md b/AGENTS.md index 0091257..3ea79bf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,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. +- Trainer map ratings 0–7 are independent of verified values and hazard flags; `null` means no rating, `0` means no danger around the cell. Sound mode hides numeric facts and LU hints during play; simplified mode reveals the level of opened cells. `audio.js` generates cues locally and starts playback only via an action or replay. - 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 9d019cb..7e3a10b 100644 --- a/LU_TRAINER_PROJECT.md +++ b/LU_TRAINER_PROJECT.md @@ -113,7 +113,7 @@ 2. Выбирает параметры и начинает попытку. Изменение параметров во время попытки применяется только через явное начало новой игры с предупреждением о сбросе. 3. Нажимает допустимую клетку: она открывается, персонаж показывается на последней успешно выбранной клетке, история и сообщения обновляются, известное значение появляется на карте. 4. Отмечает подозрительную клетку через карту, правым кликом или Shift+Enter на локации, либо кнопкой под полем на сенсорном экране. Отметка не открывает клетку и блокирует прыжок на неё. -5. Повторное посещение проверенной клетки воспроизводит текстовую обратную связь и предусмотренную моделью проверку подсказки. +5. Повторное посещение проверенной клетки даёт звуковой сигнал. В упрощённом режиме вместо звука виден числовой уровень и доступна предусмотренная моделью подсказка ЛУ. 6. После падения либо выполнения условия победы действия попытки прекращаются, показываются результат и раскрытие поля. Доступны осмотр результата и новая игра. **Текущая механика тренажёра:** восемь соседей отсчитываются от позиции персонажа, а не от любой проверенной клетки, как было в первой версии. Формулы, шансы подсказок и условия победы сохранены. @@ -138,6 +138,7 @@ | `web/lu-trainer/style.css` | Изолированные стили и токены | | `web/lu-trainer/engine.js` | Генерация и правила без DOM, управляемая случайность для проверок | | `web/lu-trainer/ui.js` | События пользователя, обе сетки, история, фокус и подсказки | +| `web/lu-trainer/audio.js` | Синтез и воспроизведение от 1 до 7 коротких шорохов, без аудиозаписей CatWar | | `web/lu-trainer/assets/` | Проверенные изображения с указанием происхождения | | `app/main.py`, `nginx.conf` | Маршруты страницы и ассетов после выбора способа раздачи | diff --git a/README.md b/README.md index 4530996..982f486 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,10 @@ python3 -m app.belki.vk_bot На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Стрелки и Home / End перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Перенос на игровое поле» меняет только видимость отметок на локации. Очистка отметок и новая игра имеют разные подтверждения. +По умолчанию после прыжка звучат синтезированные шорохи: при уровне 0 — тишина, при 1–7 — столько же шорохов. Уровень равен числу соседних опасностей с учётом диагоналей, но 7 означает «семь и больше». «Повторить звук» воспроизводит сигнал текущей клетки. «Упрощённый режим» показывает уровни на проверенных клетках вместо звука и включает подсказки ЛУ. + +На «Минном поле» клик или касание выбирает клетку для ручной оценки. Уровень ставится клавишей или кнопкой 0–7; Delete, Backspace или «Убрать оценку» снимает его. 0 — явная оценка, не пустая клетка. Оценка не двигает персонажа, не блокирует прыжок и не влияет на условие победы; отдельные флажки работают как раньше. + Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от входа: перескакивать через них нельзя. Выход выбирается заново для каждой попытки: `x10 y2–y6` или `y6 x6–x10`. Координаты переходов показаны на локации и на карте. В этой версии тренажёра выход обозначает место перехода, но не переключает высоту. diff --git a/docs/staging/specs/2026-11-17-lu-trainer.md b/docs/staging/specs/2026-11-17-lu-trainer.md index 30e2b0f..4f21be6 100644 --- a/docs/staging/specs/2026-11-17-lu-trainer.md +++ b/docs/staging/specs/2026-11-17-lu-trainer.md @@ -4,13 +4,14 @@ Authorization: the owner requested implementation of root `LU_TRAINER_PROJECT.md 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/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. +state: engine owns 60 cells, per-attempt start/exit identities, hazards, opened set, hazard flags, user ratings, last successful position, ready/playing/won/lost status and action log. A public snapshot omits hidden hazards/values. UI owns selection, display mode, map visibility and note 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. +invariant: map keys/buttons 0–7 assign a user rating; Delete/Backspace or the remove button clears it. Rating 0 differs from no rating; ratings on opened cells are allowed, do not affect flags or movement, and render separately from facts. Sound mode plays a synthesized cue of min(7, neighbor count) rustles (zero is silent) and hides numeric facts and LU hints during play. Simplified mode shows that level on opened cells and enables existing LU hints without restarting. 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. +deferred: verification of real CatWar rules, multiple saved maps, server accounts, deployment. Generated original art provenance and prompts live in assets/README.md. Review: spec-compliance/consistency review closed the hint and terminal-action gaps. Hints intentionally return a temporary hazard ID in action results only (not hidden snapshot values), last 2000 ms and retain their coordinate in the readable message log. Only unmarked neighboring hazards are candidates. At completion marking/clearing are disabled; selection remains available for inspection. Defaults: height 1, LU 5, growth 12, season 0; growth accepts 12/15/18/22/25 and season -3/0/5. diff --git a/structure_and_data.md b/structure_and_data.md index fcee3e9..1864bf8 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -1,5 +1,10 @@ # Structure and Data +## Trainer sound and manual ratings — 2026-11-22 + +- `audio.js` synthesizes counted rustles using Web Audio; no media downloads or runtime dependencies. The sound and simplified views share one `min(7, neighbors)` level. Switching modes preserves the field and ratings and updates prior messages without showing verified numbers in sound mode during play. +- `Training.rate()` stores separate ratings 0–7, including on opened cells. Ratings render as badges and do not affect moves or victory. One map serves mouse, keyboard, and touch controls. + ## 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. diff --git a/tests/browser/lu-trainer.cjs b/tests/browser/lu-trainer.cjs index 9e7edf2..6fd0a92 100644 --- a/tests/browser/lu-trainer.cjs +++ b/tests/browser/lu-trainer.cjs @@ -10,6 +10,19 @@ 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); @@ -120,6 +133,7 @@ async function run() { 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(); @@ -170,26 +184,110 @@ async function run() { 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. + // Click/tap an eligible neighbor on the map: selection and rating must never jump. if (mobile) await page.locator('#map-open').click(); - await map(note).click(); + 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); - await page.locator('#map-mark').click(); + 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.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[first]); - await page.locator('#project-marks').uncheck(); + 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 page.locator('#history li').count(),4); - await page.locator('#project-marks').check(); + 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 page.locator('#history li').count(),5); + assert.equal(await history.count(),beforeFlag + 2); if (mobile) { await page.keyboard.press('Escape'); assert(await page.locator('#map-open').evaluate(n=>n===document.activeElement)); @@ -249,7 +347,7 @@ async function run() { 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, synchronized map, notes, dialogs, settings, console`); + 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. @@ -276,6 +374,89 @@ async function run() { 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(); } + // 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 { @@ -299,6 +480,11 @@ async function run() { 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(); @@ -327,6 +513,7 @@ async function run() { 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); @@ -342,16 +529,30 @@ async function run() { 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'); - // Marking is available anywhere; only the exact hazard set wins. + // 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'); diff --git a/tests/lu-trainer/engine.test.mjs b/tests/lu-trainer/engine.test.mjs index 8bf30b9..f741f5f 100644 --- a/tests/lu-trainer/engine.test.mjs +++ b/tests/lu-trainer/engine.test.mjs @@ -1,11 +1,24 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { Training, generateField, neighbors, hintChance, START, coordinate } from '../../web/lu-trainer/engine.js'; +import { rustleSamples } from '../../web/lu-trainer/audio.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}; +test('sound cue is silent at zero and has one distinct pulse per level', () => { + const sampleRate = 48000, step = 11040, audible = 4560; + assert.equal(rustleSamples(0, sampleRate).length, 0); + for (let level = 1; level <= 7; level++) { + const samples = rustleSamples(level, sampleRate); + assert.equal(samples.length, level * step); + for (let start = 0; start < samples.length; start += step) { + assert(samples.slice(start, start + audible).some(value => Math.abs(value) > .01)); + assert(samples.slice(start + audible, start + step).every(value => value === 0)); + } + } +}); function fixture(settings = options, seed = 19) { return {field: generateField(settings, seeded(seed)), game: new Training(settings, seeded(seed))}; } @@ -98,9 +111,37 @@ test('notes hide no facts, block jumps, clear independently and reject invalid I 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('manual levels are independent of facts, hazard flags and movement', () => { + const {game} = fixture(); + assert.equal(game.rate(1, 7).code, 'rated'); + assert.equal(game.rate(1, 1).code, 'rated'); + assert.equal(game.rate(1, 1).code, 'unchanged'); + assert.equal(game.rate(1, 0).code, 'rated'); + for (const level of [8, -1, 1.5, '1', undefined]) assert.equal(game.rate(1, level).code, 'invalid-level'); + const view = game.view(); + assert.equal(view.marks, 0); + assert.equal(view.position, START); + assert.equal(view.cells[1].rating, 0); + assert.equal(view.cells[1].value, null); + assert.equal(game.mark(1).code, 'marked'); + assert.equal(game.rate(1, null).code, 'unrated'); + assert.equal(game.rate(1, null).code, 'unchanged'); + assert.equal(game.view().cells[1].rating, null); + assert.equal(game.jump(1).code, 'marked'); + assert.equal(game.mark(1).code, 'unmarked'); + assert.equal(game.jump(1).code, 'opened'); + assert.equal(game.rate(1, 3).code, 'rated'); + assert.equal(game.rate(START, 3).code, 'transition'); + assert.equal(game.rate(view.exit, 3).code, 'transition'); + assert.equal(game.clearMarks().code, 'cleared'); + assert.equal(game.view().cells[1].rating, null); + assert(game.view().cells[1].opened); +}); test('all and only hazards marked wins; terminal actions cannot change state', () => { const {game,field} = fixture(); game.mark(1); + for (const id of field.hazards) game.rate(id, 7); + assert.notEqual(game.view().status, 'won'); for (const id of field.hazards) game.mark(id); assert.notEqual(game.view().status, 'won'); game.mark(1); @@ -109,6 +150,7 @@ test('all and only hazards marked wins; terminal actions cannot change state', ( 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.rate(1, 3).code, 'finished'); assert.equal(game.clearMarks().code, 'finished'); assert.deepEqual(game.view(), ended); }); diff --git a/tests/test_lu_trainer.py b/tests/test_lu_trainer.py index 5e42b3e..a666433 100644 --- a/tests/test_lu_trainer.py +++ b/tests/test_lu_trainer.py @@ -38,7 +38,7 @@ class TrainerRoutesTests(unittest.TestCase): 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')]: + for asset, media_type in [('engine.js', 'javascript'), ('ui.js', 'javascript'), ('audio.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) diff --git a/web/lu-trainer.html b/web/lu-trainer.html index d2781ac..740a34c 100644 --- a/web/lu-trainer.html +++ b/web/lu-trainer.html @@ -39,6 +39,10 @@
Вход: x1 y1 · Выход выбирается для новой попытки
Клик по соседней клетке — прыжок. Правый клик — поставить или снять отметку.
↥ Вход / выход · Проверено ⚑ Ваша отметка × Опасность в результате ≠ Ошибочная отметка
+↥ Вход / выход · Проверено ⚑ Флажок опасности Ваша оценка × Опасность в результате ≠ Ошибочная отметка
Карта заметок · 0 отметок / 12 опасностей
+Флажки: 0 / 12 · Оценки: 0
Клетка карты только выбирается. Заметка не подтверждает опасность.
+Выберите клетку и поставьте оценку 0–7 кнопкой или клавишей. Ноль — рядом нет опасностей.
Выбрана x1 y1 · вход
+ + @@ -96,14 +109,12 @@