From ba074df4ec3087db5b3ce31a13c6e2bf6ad5a6b1 Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Sun, 22 Nov 2026 18:06:12 +0300 Subject: [PATCH] Allow returning to the safe trainer start --- AGENTS.md | 2 +- LU_TRAINER_PROJECT.md | 4 +- README.md | 8 ++-- docs/staging/specs/2026-11-17-lu-trainer.md | 4 +- tests/browser/lu-trainer.cjs | 52 +++++++++++++++++---- tests/lu-trainer/engine.test.mjs | 37 +++++++++------ web/lu-trainer.html | 14 +++--- web/lu-trainer/engine.js | 10 ++-- web/lu-trainer/style.css | 2 +- web/lu-trainer/ui.js | 17 ++++--- 10 files changed, 102 insertions(+), 48 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 20df59e..be8cccc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ - 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 and the entrance. `audio.js` generates cues locally and starts playback only via an action or replay. -- Keep the phone map below the scene on the same scrollable page. The entrance is safe and has 0–2 neighboring hazards; the caps for x1 y2 and x1 y3 are 3 and 4. Apply those limits to generated hazards, not displayed values. The entrance number is visible in simplified mode and after the attempt, without counting the entrance as opened. +- Keep the phone map below the scene on the same scrollable page. The safe start x1 y1 is not a transition; it can be revisited from an adjacent cell but does not count as opened or accept marks/ratings. Only the exit remains an impassable transition. The start has 0–2 neighboring hazards, x1 y2 at most 3 and x1 y3 at most 4. Apply those limits to generated hazards, not displayed values. The start number is visible in simplified mode and after the attempt. - 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 ff7f4b8..d944271 100644 --- a/LU_TRAINER_PROJECT.md +++ b/LU_TRAINER_PROJECT.md @@ -6,7 +6,9 @@ ## Уточнение владельца о переходах — 2026-11-17 -**Актуальные правила (2026-11-22):** прыгать можно только из текущей клетки в одну из восьми соседних, без скачков через безопасные или проверенные клетки. Выход случайный, но только в `x10 y2–y6` или `y6 x6–x10`. Вход `x1 y1` безопасен, рядом с ним от 0 до 2 опасностей. У `x1 y2` максимум 3 соседние опасности, у `x1 y3` максимум 4. Условия победы, отметки и назначение переходов как ориентиров не меняются. Описание ниже относится к прежней версии. +**Уточнение о старте:** `x1 y1` не переход между этажами, а безопасная клетка, где появляется кот. На неё можно вернуться с соседней клетки, но она не входит в число клеток для победы. Владелец описал спуск как переход в сторону нижнего левого края, подъём как переход вправо. Смена этажей в тренажёре пока не реализована. + +**Актуальные правила (2026-11-22):** прыгать можно только из текущей клетки в одну из восьми соседних, без скачков через безопасные или проверенные клетки. Выход случайный, но только в `x10 y2–y6` или `y6 x6–x10`. Стартовая клетка `x1 y1` безопасна, рядом с ней от 0 до 2 опасностей. У `x1 y2` максимум 3 соседние опасности, у `x1 y3` максимум 4. Описание ниже относится к прежней версии. Владелец уточнил: «вход всегда на клетке x1 y1, выход может быть в разных местах». Это заменяет координаты переходов из исходного тренажёра в текущей реализации. `x1 y1` отображается в верхней левой клетке; X растёт вправо, Y — вниз. Генератор выбирает выход для каждой новой попытки из остальных 59 клеток — это способ реализации вариативности, а не подтверждённое распределение выходов в CatWar. Пять/три начальные безопасные клетки сохранены отдельно от переходов. Состояние попытки хранит координаты входа/выхода; локация, карта, справка и сообщения используют их совместно. Наблюдения об исходнике ниже остаются историческими. diff --git a/README.md b/README.md index eb72565..1b93587 100644 --- a/README.md +++ b/README.md @@ -47,15 +47,15 @@ python3 -m app.belki.vk_bot На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Стрелки и Home / End перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Показывать заметки на поле» меняет только их видимость на локации. Очистка отметок и новая игра имеют разные подтверждения. -По умолчанию после прыжка звучат синтезированные шорохи: при уровне 0 — тишина, при 1–7 — столько же шорохов. Уровень равен числу соседних опасностей с учётом диагоналей, но 7 означает «семь и больше». «Повторить звук» воспроизводит сигнал текущей клетки. «Упрощённый режим» показывает уровни на входе и проверенных клетках вместо звука и включает подсказки ЛУ. +По умолчанию после прыжка звучат синтезированные шорохи: при уровне 0 — тишина, при 1–7 — столько же шорохов. Уровень равен числу соседних опасностей с учётом диагоналей, но 7 означает «семь и больше». «Повторить звук» воспроизводит сигнал текущей клетки. «Упрощённый режим» показывает уровни на стартовой и проверенных клетках вместо звука и включает подсказки ЛУ. На телефоне прокрутите страницу вниз до «Минного поля». На карте клик или касание выбирает клетку для ручной оценки. Уровень ставится клавишей или кнопкой 0–7; Delete, Backspace или «Убрать оценку» снимает его. 0 — явная оценка, не пустая клетка. Оценка не двигает персонажа, не блокирует прыжок и не влияет на условие победы; отдельные флажки работают как раньше. -Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Вход безопасен, рядом с ним от 0 до 2 опасностей. У `x1 y2` не больше 3 соседних опасностей, у `x1 y3` не больше 4. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от входа: перескакивать через них нельзя. +Кот начинает в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Стартовая клетка безопасна, рядом с ней от 0 до 2 опасностей. У `x1 y2` не больше 3 соседних опасностей, у `x1 y3` не больше 4. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. На старт можно вернуться с соседней клетки. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от старта: перескакивать через них нельзя. -Выход выбирается заново для каждой попытки: `x10 y2–y6` или `y6 x6–x10`. Координаты переходов показаны на локации и на карте. В этой версии тренажёра выход обозначает место перехода, но не переключает высоту. +Выход выбирается заново для каждой попытки: `x10 y2–y6` или `y6 x6–x10`. Старт и выход показаны на локации и на карте. В этой версии тренажёра выход служит ориентиром: прыгать на него и менять через него высоту нельзя. -Победа — все безопасные клетки, кроме переходов, либо все опасности без лишних отметок. Падение завершает попытку. Настройки высоты, ЛУ, сезона и роста применяются явным началом новой игры. Это модель описанного исходного тренажёра, а не подтверждённые правила CatWar. Оригинальные изображения и промпты перечислены в `web/lu-trainer/assets/README.md`; код и изображения исходного тренажёра не переносились. +Чтобы победить, откройте все безопасные клетки, кроме старта и выхода, или отметьте все опасности без лишних отметок. Падение завершает попытку. Настройки высоты, ЛУ, сезона и роста применяются явным началом новой игры. Это модель описанного исходного тренажёра, а не подтверждённые правила CatWar. Оригинальные изображения и промпты перечислены в `web/lu-trainer/assets/README.md`; код и изображения исходного тренажёра не переносились. Страница раздаётся и `app.main`, и Nginx gateway. Для изолированных проверок используйте временные SQLite-пути по инструкции в `AGENTS.md`, затем: diff --git a/docs/staging/specs/2026-11-17-lu-trainer.md b/docs/staging/specs/2026-11-17-lu-trainer.md index ed5f964..588a404 100644 --- a/docs/staging/specs/2026-11-17-lu-trainer.md +++ b/docs/staging/specs/2026-11-17-lu-trainer.md @@ -5,7 +5,7 @@ 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, hazard flags, user ratings, last successful position, ready/playing/won/lost status and action log. During play a public snapshot omits hidden hazards and exposes values only for the entrance and opened cells. UI owns selection, display mode 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: 6x10, safe start x1 y1 (top-left, index 0), exit selected per attempt from x10 y2–y6 or y6 x6–x10. Neither start nor exit counts toward victory or accepts marks/ratings. The start can be revisited, the exit cannot. The first 5/3 top-row cells to the right of the start 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 start, base and exit. Preserve documented hazard formula and 0/10/20/30% hint probabilities. Win by opening every other safe cell or marking all and only hazards; loss ends actions. Repeat safe visits produce feedback and may hint. The character tracks the last successful jump. 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 the entrance and opened cells and enables existing LU hints without restarting. @@ -18,3 +18,5 @@ Review: spec-compliance/consistency review closed the hint and terminal-action g Owner corrections: entrance fixed x1 y1 and exit variable (2026-11-17); limit exits to the specified edges and jumps to immediate neighbors (2026-11-22). Uniform random placement among permitted sites is an implementation choice, not a verified game distribution. Coordinates are one-based X right/Y down. Tests cover every allowed exit position, safe-route connectivity and matching transition labels on both grids after regeneration. Additional owner correction (2026-11-22): x1 y1 is safe and has at most 2 neighboring hazards, x1 y2 at most 3, and x1 y3 at most 4. The entrance value is available as a fact without opening the entrance; keep it hidden in sound mode until the attempt ends. + +Start-cell correction: x1 y1 is a safe spawn, not a floor transition. Jumping back from an adjacent cell is a revisit. Floor switching remains out of scope. diff --git a/tests/browser/lu-trainer.cjs b/tests/browser/lu-trainer.cjs index 7f82566..eb073db 100644 --- a/tests/browser/lu-trainer.cjs +++ b/tests/browser/lu-trainer.cjs @@ -32,6 +32,7 @@ async function checkTransitions(page, expectedExit) { for (const grid of ['scene-grid','map-grid']) { assert.deepEqual(await cellIds(page.locator(`#${grid} .entrance button`)),[0]); assert.deepEqual(await cellIds(page.locator(`#${grid} .exit button`)),[exit]); + assert.deepEqual(await cellIds(page.locator(`#${grid} .transition button`)),[exit]); assert.equal(await page.locator(`#${grid} .transition.available`).count(),0); } return exit; @@ -41,7 +42,7 @@ async function assertEntranceLevel(page, value, current = true) { for (const grid of ['scene-grid','map-grid']) { const entrance = page.locator(`#${grid} .entrance button[data-id="0"]`); assert.equal(await valueText(entrance,'.cell-value'),value === null ? '↥' : `↥ ${value}`); - assert.equal(await entrance.getAttribute('aria-label'),`x1 y1: вход${value === null ? '' : `, опасностей рядом: ${value}`}${current ? ', персонаж здесь' : ''}`); + assert.equal(await entrance.getAttribute('aria-label'),`x1 y1: стартовая клетка${value === null ? '' : `, опасностей рядом: ${value}`}${current ? ', персонаж здесь' : ''}`); assert.equal(await page.locator(`#${grid} .entrance.opened`).count(),0); } assert.equal(await valueText(page.locator('#scene-grid .entrance button'),'.cell-coord'),'x1 y1'); @@ -104,7 +105,7 @@ async function run() { } }; await noOverflow(); - assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: вход, персонаж здесь$/); + assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: стартовая клетка, персонаж здесь$/); await checkTransitions(page,field.exit); assert.equal(await page.locator('input[name="mode"], input[type="radio"], [role="radio"]').count(),0); assert.equal(await page.locator('#touch-actions').isVisible(),compact); @@ -123,7 +124,7 @@ async function run() { 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.match(await page.locator('#transition-coordinates').textContent(), /Старт: x1 y1/); assert((await page.locator('#transition-coordinates').textContent()).includes(`Выход: ${coordinate(field.exit)}`)); assert.equal(await page.locator('#scene-grid .hazard').count(),0); assert.equal(await page.locator('#scene-grid .opened').count(),0); @@ -173,7 +174,7 @@ async function run() { 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]); + await assertAvailable([0,2,10,11,12]); // Native button keyboard actions and spatial focus; focus is not character position. await scene(first).focus(); await page.keyboard.press('ArrowRight'); assert(await scene(second).evaluate(n=>n===document.activeElement)); @@ -234,9 +235,10 @@ async function run() { const chooseOnMap = async cell => touch ? cell.tap() : cell.click(); for (const id of [0,field.exit]) { await chooseOnMap(map(id)); + assert(await mapMark.isDisabled()); await assertRatingControls(page,{disabled:true}); await map(id).press('4'); - assert.equal(await valueText(map(id),'.cell-rating'),'','cannot rate a transition'); + assert.equal(await valueText(map(id),'.cell-rating'),'','cannot rate the entrance or exit'); } await chooseOnMap(map(ratingCell)); assert((await mapSelection.textContent()).includes(coordinate(ratingCell))); @@ -268,7 +270,7 @@ async function run() { 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 assertAvailable([0,2,10,11,12]); await assertPosition(first); await project.uncheck(); assert.equal(await valueText(scene(ratingCell),'.cell-rating'),''); @@ -371,7 +373,7 @@ async function run() { assert.equal(await page.locator('#scene-grid .opened').count(),0); assert.equal(await page.locator('#history li').count(),0); assert.equal(await page.locator('#timer').textContent(),'00:00'); - assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: вход(?:, опасностей рядом: [0-2])?, персонаж здесь$/); + assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: стартовая клетка(?:, опасностей рядом: [0-2])?, персонаж здесь$/); await checkTransitions(page); await assertAvailable([1,10,11]); // Mark and unmark with compact buttons or Shift+Enter without moving the character. @@ -397,8 +399,42 @@ async function run() { assert.match(await history.last().textContent(),/Снята отметка/); await assertPosition(0); if (compact) assert(await jump.isEnabled()); + // The entrance is safe to revisit, but is not an opened cell. + await page.locator('#simple-mode').check(); + const entranceValue = await valueText(scene(0),'.cell-value'); + assert.match(entranceValue,/^↥ [0-2]$/); + if (compact) await jump.tap(); + else await scene(first).click(); + await assertPosition(first); + await assertAvailable([0,2,10,11,12]); + assert.equal(await valueText(scene(0),'.cell-value'),entranceValue); + assert.match(await scene(0).getAttribute('aria-label'), /стартовая клетка, опасностей рядом: [0-2], можно прыгнуть$/); + if (compact) { + await scene(0).tap(); + await assertSelection(0,'старт'); + assert(await jump.isEnabled()); + assert(await mark.isDisabled()); + } + const progress = await page.locator('#progress').textContent(); + if (compact) await jump.tap(); + else await scene(0).click(); + await assertPosition(0); + if (compact) { + await assertSelection(0,'вы здесь'); + assert(await jump.isDisabled()); + } + assert.equal(await page.locator('#progress').textContent(),progress); + assert.match(await history.last().textContent(),/^x1 y1 · Повторный прыжок/); + assert.match(await status.textContent(),new RegExp(`^Опасностей рядом: ${entranceValue.at(-1)}\\.`)); + await assertEntranceLevel(page,Number(entranceValue.at(-1))); + await assertAvailable([1,10,11]); + if (shotDir && (width === 1366 || width === 390)) { + const file = `${shotDir}/lu-return-${width}.png`; + await page.locator('.location').screenshot({path:file}); + captures.push(file); + } assert.deepEqual(errors,[]); - console.log(`PASS ${width}x${height} (${compact ? 'compact' : 'desktop'}): render, adjacent jumps, keyboard/touch controls, map ratings and flags, projection, dialogs, settings, console`); + console.log(`PASS ${width}x${height} (${compact ? 'compact' : 'desktop'}): render, adjacent jumps and safe entrance return, 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. diff --git a/tests/lu-trainer/engine.test.mjs b/tests/lu-trainer/engine.test.mjs index a853b47..db13696 100644 --- a/tests/lu-trainer/engine.test.mjs +++ b/tests/lu-trainer/engine.test.mjs @@ -22,7 +22,7 @@ test('sound cue is silent at zero and has one distinct pulse per level', () => { function fixture(settings = options, seed = 19) { return {field: generateField(settings, seeded(seed)), game: new Training(settings, seeded(seed))}; } -test('entrance is always x1 y1 and exits vary only on the allowed edges', () => { +test('the start is always x1 y1 and exits vary only on the allowed edges', () => { assert.equal(START, 0); assert.equal(coordinate(START), 'x1 y1'); assert.equal(coordinate(59), 'x10 y6'); @@ -45,7 +45,7 @@ test('entrance is always x1 y1 and exits vary only on the allowed edges', () => assert.equal(view.exit, field.exit); assert.equal(view.cells.filter(cell => cell.entrance).length, 1); assert.equal(view.cells.filter(cell => cell.exit).length, 1); - assert.equal(view.cells.filter(cell => cell.transition).length, 2); + assert.deepEqual(view.cells.filter(cell => cell.transition).map(cell => cell.id), [field.exit]); assert.equal(game.jump(field.exit).code, 'transition'); assert.equal(game.mark(field.exit).code, 'transition'); } @@ -75,7 +75,7 @@ test('entrance-area limits apply to actual hazards without making either lower c assert.deepEqual(edgeHazards, new Set([COLS, 2 * COLS])); }); -test('the ready snapshot reveals the entrance number but does not open the transition', () => { +test('the safe start can be revisited from a neighbor without counting as opened', () => { const dense = {...options, height: 5, growth: 25, season: 5}; for (const seed of [0, 2, 5]) { const {field, game} = fixture(dense, seed); @@ -86,12 +86,21 @@ test('the ready snapshot reveals the entrance number but does not open the trans assert.equal(start.available, false); assert.equal(view.opened, 0); assert(view.cells.every(cell => cell.entrance || cell.value === null)); - assert.equal(game.jump(START).code, 'transition'); - assert.equal(game.mark(START).code, 'transition'); - assert.equal(game.rate(START, 1).code, 'transition'); + assert.equal(game.jump(START).code, 'unreachable'); + assert.equal(game.mark(START).code, 'opened'); + assert.equal(game.rate(START, 1).code, 'opened'); assert.equal(game.jump(1).code, 'opened'); - assert.equal(game.view().cells[START].value, start.value); - assert.equal(game.view().opened, 1); + assert.equal(game.view().cells[START].available, true); + assert.deepEqual(game.jump(START, () => 1), {code:'revisited', id:START, value:start.value, hint:null}); + const returned = game.view(); + assert.equal(returned.position, START); + assert.equal(returned.cells[START].opened, false); + assert.equal(returned.opened, 1); + assert.equal(returned.safe, view.safe); + assert.equal(returned.status, 'playing'); + assert.equal(game.jump(1).code, 'revisited'); + assert.equal(game.jump(2).code, 'opened'); + assert.equal(game.jump(START).code, 'unreachable'); } }); @@ -119,12 +128,12 @@ test('edge neighborhoods do not wrap rows', () => { }); test('only the current position’s neighbors are available, even for safe or opened cells', () => { const {game} = fixture(); - assert.equal(game.jump(START).code, 'transition'); + assert.equal(game.jump(START).code, 'unreachable'); assert.equal(game.jump(game.view().exit).code, 'transition'); assert.equal(game.jump(25).code, 'unreachable'); assert.equal(game.jump(2).code, 'unreachable'); // safe upper-row cell, two columns away assert.deepEqual(game.view().cells.filter(c => c.available).map(c => c.id), [1,10,11]); - assert.equal(game.mark(START).code, 'transition'); + assert.equal(game.mark(START).code, 'opened'); assert.equal(game.jump(1).code, 'opened'); assert.equal(game.jump(1).code, 'unreachable'); assert(game.view().cells[10].available); @@ -174,7 +183,7 @@ test('manual levels are independent of facts, hazard flags and movement', () => 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(START, 3).code, 'opened'); assert.equal(game.rate(view.exit, 3).code, 'transition'); assert.equal(game.clearMarks().code, 'cleared'); assert.equal(game.view().cells[1].rating, null); @@ -197,13 +206,13 @@ test('all and only hazards marked wins; terminal actions cannot change state', ( assert.equal(game.clearMarks().code, 'finished'); assert.deepEqual(game.view(), ended); }); -test('opening all safe cells wins without entering either transition', () => { +test('opening all playable safe cells wins without counting the start or exit', () => { const {game,field} = fixture(); function explore(position) { for (const id of neighbors(position)) { if (game.view().status === 'won') return; const cell = game.view().cells[id]; - if (cell.opened || cell.transition || field.hazards.has(id)) continue; + if (cell.opened || cell.entrance || cell.transition || field.hazards.has(id)) continue; assert.equal(game.jump(id).code, 'opened'); explore(id); if (game.view().status !== 'won' && position !== START) assert.equal(game.jump(position).code, 'revisited'); @@ -217,7 +226,7 @@ test('hazard ends attempt, reveals wrong notes and preserves last safe position' const {game,field} = fixture(); game.mark(4); game.jump(1); while (game.view().status !== 'lost') { - const cell = game.view().cells.find(c => c.available && !c.opened && !c.transition && !c.marked); + const cell = game.view().cells.find(c => c.available && !c.opened && !c.entrance && !c.transition && !c.marked); assert(cell); game.jump(cell.id); } const end = game.view(); diff --git a/web/lu-trainer.html b/web/lu-trainer.html index 3c12b5d..b222dd3 100644 --- a/web/lu-trainer.html +++ b/web/lu-trainer.html @@ -43,7 +43,7 @@ -

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

+

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

Нажмите на соседнюю клетку, чтобы прыгнуть. Правая кнопка мыши или Shift+Enter ставят или снимают флажок.

@@ -57,7 +57,7 @@

-

↥ Вход / выход · Проверено ⚑ Флажок опасности 0–7 Ваша оценка × Опасность после игры ≠ Ошибочная отметка

+

↥ Старт ↗ Выход · Проверено ⚑ Флажок опасности 0–7 Ваша оценка × Опасность после игры ≠ Ошибочная отметка

@@ -70,7 +70,7 @@

Флажки: 0 / 12 · Оценки: 0

Выберите клетку и нажмите кнопку или клавишу от 0 до 7. Поставьте 0, если считаете, что рядом нет опасностей.

-

Клетка x1 y1 · вход

+

Клетка x1 y1 · стартовая клетка

Ваша оценка @@ -107,13 +107,13 @@

Как освоиться на уступах

Это отдельный тренажёр, сделанный по мотивам работы tek1laa. Правила в CatWar могут отличаться.

diff --git a/web/lu-trainer/engine.js b/web/lu-trainer/engine.js index c6ac2c0..c7f5380 100644 --- a/web/lu-trainer/engine.js +++ b/web/lu-trainer/engine.js @@ -85,7 +85,7 @@ export class Training { } #valid(id) { return Number.isInteger(id) && id >= 0 && id < ROWS * COLS; } #finished() { return this.#status === 'won' || this.#status === 'lost'; } - #transition(id) { return id === START || id === this.#field.exit; } + #transition(id) { return id === this.#field.exit; } #available(id) { return !this.#transition(id) && distance(this.#position, id) === 1; } #guard(id) { if (this.#finished()) return {code: 'finished'}; @@ -108,8 +108,9 @@ export class Training { this.#history.push({type: 'fall', id}); return {code: 'fall', id, hint: null}; } - const code = this.#opened.has(id) ? 'revisited' : 'opened'; - this.#opened.add(id); this.#position = id; + const code = id === START || this.#opened.has(id) ? 'revisited' : 'opened'; + if (id !== START) this.#opened.add(id); + this.#position = id; const value = this.#field.values[id]; this.#history.push({type: code, id, value}); this.#win(); @@ -121,7 +122,7 @@ export class Training { mark(id) { const rejected = this.#guard(id); if (rejected) return rejected; - if (this.#opened.has(id)) return {code: 'opened'}; + if (id === START || this.#opened.has(id)) return {code: 'opened'}; const marked = !this.#marks.has(id); if (marked) this.#marks.add(id); else this.#marks.delete(id); this.#history.push({type: marked ? 'marked' : 'unmarked', id}); @@ -131,6 +132,7 @@ export class Training { rate(id, rating) { const rejected = this.#guard(id); if (rejected) return rejected; + if (id === START) return {code: 'opened'}; if (rating !== null && (!Number.isInteger(rating) || rating < 0 || rating > 7)) return {code: 'invalid-level'}; if ((this.#ratings.get(id) ?? null) === rating) return {code: 'unchanged'}; if (rating === null) this.#ratings.delete(id); else this.#ratings.set(id, rating); diff --git a/web/lu-trainer/style.css b/web/lu-trainer/style.css index 084d3d7..c3c17c4 100644 --- a/web/lu-trainer/style.css +++ b/web/lu-trainer/style.css @@ -67,7 +67,7 @@ dd { margin: 0; text-align: right; font-weight: bold; } .cell-grid .current button { box-shadow: inset 0 0 0 2px var(--light); } .scene-grid .hint button { background: var(--danger); color: var(--light); } .cell-grid button:focus-visible { outline: 3px solid var(--focus); outline-offset: -4px; box-shadow: inset 0 0 0 5px var(--ink); z-index: 3; position: relative; } -.cell-grid .transition button { background: #222b28cc; color: var(--light); } +.cell-grid :is(.entrance, .transition) button { background: #222b28cc; color: var(--light); } .cell-grid .wrong button { background: var(--paper); color: var(--danger); } .cell-coord { position: absolute; left: 4px; top: 2px; font-size: 10px; font-weight: normal; color: var(--light); background: #17120dbb; padding: 0 2px; line-height: 1.4; } .cell-value { font-size: clamp(14px, 1.5vw, 24px); } diff --git a/web/lu-trainer/ui.js b/web/lu-trainer/ui.js index 07eae5a..1df1210 100644 --- a/web/lu-trainer/ui.js +++ b/web/lu-trainer/ui.js @@ -43,8 +43,9 @@ function describe(cell, view, showNotes = true, isMap = false) { if (cell.hazard) return `опасная клетка${rating}`; if (cell.entrance || cell.opened || ended(view)) { const fact = simple() || ended(view) ? `, ${levelText(cell.value).slice(0, -1).toLowerCase()}` : ''; - if (cell.entrance) return `вход${fact}`; - return `${cell.opened ? 'проверено' : 'безопасная клетка'}${fact}${rating}${!isMap && cell.available ? ', можно прыгнуть' : ''}`; + const jump = !isMap && cell.available ? ', можно прыгнуть' : ''; + if (cell.entrance) return `стартовая клетка${fact}${jump}`; + return `${cell.opened ? 'проверено' : 'безопасная клетка'}${fact}${rating}${jump}`; } if (cell.marked && showNotes) return `ваш флажок опасности${rating}`; if (hints.has(cell.id)) return `подсказка: опасность${rating}`; @@ -189,7 +190,7 @@ function render() { $('lu-value').textContent = `${view.options.lu} ЛУ`; $('height-value').textContent = `${view.options.height} из 5`; $('scene-height').textContent = `Высота ${view.options.height}`; - $('transition-coordinates').textContent = `Вход: ${coordinate(view.start)} · Выход: ${coordinate(view.exit)}`; + $('transition-coordinates').textContent = `Старт: ${coordinate(view.start)} · Выход: ${coordinate(view.exit)}`; $('season-value').textContent = {'-3':'Лето',0:'Демисезон',5:'Зима'}[view.options.season]; $('growth-value').textContent = {12:'45–75%',15:'76–85%',18:'81–88%',22:'89–95%',25:'96–100%'}[view.options.growth]; $('hint-chance').textContent = simple() ? `${Math.round(hintChance(view.options.lu) * 100)}%` : 'Выкл.'; @@ -202,15 +203,17 @@ function render() { $('scene-instructions').textContent = compact.matches ? 'Выберите клетку, затем нажмите нужную кнопку под полем.' : 'Нажмите на соседнюю клетку, чтобы прыгнуть. Правая кнопка мыши или Shift+Enter ставят или снимают флажок.'; const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной'; const selectionState = finished ? 'попытка завершена' : cell.id === view.position ? 'вы здесь' : - cell.transition ? (cell.entrance ? 'вход' : 'выход') : cell.marked ? 'есть отметка' : + cell.entrance ? (cell.available ? 'старт' : 'старт, вне досягаемости') : + cell.transition ? 'выход' : cell.marked ? 'есть отметка' : !cell.available ? 'вне досягаемости' : ''; $('touch-actions').hidden = !compact.matches; $('selection').textContent = `Клетка ${coordinate(selected)}${selectionState ? ` (${selectionState})` : ''}`; $('map-selection').textContent = `Клетка ${coordinate(selected)} · ${describe(cell, view, true, true)}`; $('mark').textContent = note; $('map-mark').textContent = note; $('jump').disabled = finished || !cell.available || cell.marked; - for (const id of ['mark','map-mark']) $(id).disabled = finished || cell.opened || cell.transition; - $('map-levels').disabled = finished || cell.transition; + const notesLocked = finished || cell.entrance || cell.transition; + for (const id of ['mark','map-mark']) $(id).disabled = notesLocked || cell.opened; + $('map-levels').disabled = notesLocked; for (const button of $('map-levels').querySelectorAll('[data-level]')) button.setAttribute('aria-pressed', String(Number(button.dataset.level) === cell.rating)); $('map-clear-level').disabled = cell.rating === null; $('clear-marks').disabled = finished || (view.marks === 0 && view.ratings === 0); @@ -321,7 +324,7 @@ $('new-game').addEventListener('click', event => confirmAction('Начать з $('clear-marks').addEventListener('click', event => confirmAction('Очистить отметки?', 'Исчезнут только ваши флажки и оценки. Проверенные клетки и история останутся, а игру можно будет продолжить.', 'Очистить отметки', () => { game.clearMarks(); $('status').textContent = 'Флажки и оценки убраны. Можно продолжать.'; render(); }, event.currentTarget)); $('simple-mode').addEventListener('change', () => { stopSound(); clearHints(); - $('status').textContent = simple() ? 'В упрощённом режиме уровни видны на входе и на проверенных клетках.' : 'В звуковом режиме оцените клетку по шорохам.'; + $('status').textContent = simple() ? 'В упрощённом режиме уровни видны на стартовой и проверенных клетках.' : 'В звуковом режиме оцените клетку по шорохам.'; $('messages').replaceChildren(); messages.forEach(renderMessage); $('history').replaceChildren(); renderedHistory = 0; render();