Fix trainer mobile map and entrance hazard limits
This commit is contained in:
1 parent
eb04ce3e48
commit
ba25b64190
10 files changed
+208
-39
No files matched your search
@@ -37,7 +37,8 @@
|
|||||||
## Notes
|
## 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`.
|
- 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 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.
|
- 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.
|
||||||
- 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.
|
- 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.
|
- `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.
|
- 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.
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
## Уточнение владельца о переходах — 2026-11-17
|
## Уточнение владельца о переходах — 2026-11-17
|
||||||
|
|
||||||
**Актуальные правила (2026-11-22):** прыгать можно только из текущей клетки в одну из восьми соседних, без скачков через безопасные или проверенные клетки. Выход по-прежнему случайный, но только в `x10 y2–y6` или `y6 x6–x10`. Вход, условия победы, отметки и назначение переходов как ориентиров не меняются. Описание ниже относится к прежней версии.
|
**Актуальные правила (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. Пять/три начальные безопасные клетки сохранены отдельно от переходов. Состояние попытки хранит координаты входа/выхода; локация, карта, справка и сообщения используют их совместно. Наблюдения об исходнике ниже остаются историческими.
|
Владелец уточнил: «вход всегда на клетке x1 y1, выход может быть в разных местах». Это заменяет координаты переходов из исходного тренажёра в текущей реализации. `x1 y1` отображается в верхней левой клетке; X растёт вправо, Y — вниз. Генератор выбирает выход для каждой новой попытки из остальных 59 клеток — это способ реализации вариативности, а не подтверждённое распределение выходов в CatWar. Пять/три начальные безопасные клетки сохранены отдельно от переходов. Состояние попытки хранит координаты входа/выхода; локация, карта, справка и сообщения используют их совместно. Наблюдения об исходнике ниже остаются историческими.
|
||||||
|
|
||||||
@@ -123,7 +123,7 @@
|
|||||||
## Узкие экраны и доступность
|
## Узкие экраны и доступность
|
||||||
|
|
||||||
- На широком экране локация и обе боковые колонки видны вместе. На планшете второстепенные панели сворачиваются, но локация и действия остаются основными.
|
- На широком экране локация и обе боковые колонки видны вместе. На планшете второстепенные панели сворачиваются, но локация и действия остаются основными.
|
||||||
- На телефоне порядок: краткое состояние → локация → действия → сообщения. История и карта открываются отдельными панелями; закрытие возвращает фокус к кнопке открытия. Тренировка при этом не сбрасывается.
|
- На телефоне «Минное поле» находится ниже локации на той же странице и доступно обычной прокруткой. История открывается отдельной панелью; закрытие возвращает фокус к кнопке открытия. Тренировка при этом не сбрасывается.
|
||||||
- Все действия доступны мышью, касанием и клавиатурой. Стрелки перемещают фокус, Enter/пробел на локации выполняет прыжок, Shift+Enter ставит или снимает отметку. Фокус не равен положению персонажа. На сенсорном экране касание выбирает клетку, а действия находятся под полем; на компьютере эти кнопки не дублируют управление мышью.
|
- Все действия доступны мышью, касанием и клавиатурой. Стрелки перемещают фокус, Enter/пробел на локации выполняет прыжок, Shift+Enter ставит или снимает отметку. Фокус не равен положению персонажа. На сенсорном экране касание выбирает клетку, а действия находятся под полем; на компьютере эти кнопки не дублируют управление мышью.
|
||||||
- Десять клеток шириной 44 px не помещаются на телефон 390 px. Поэтому компактный обзор локации служит выбору клетки, а отдельные кнопки не меньше 44×44 px подтверждают прыжок/отметку; выбранная клетка и её координаты хорошо видны. Не считать уменьшенную сетку полноценной заменой удобных сенсорных действий.
|
- Десять клеток шириной 44 px не помещаются на телефон 390 px. Поэтому компактный обзор локации служит выбору клетки, а отдельные кнопки не меньше 44×44 px подтверждают прыжок/отметку; выбранная клетка и её координаты хорошо видны. Не считать уменьшенную сетку полноценной заменой удобных сенсорных действий.
|
||||||
- Масштабирование браузером разрешено; горизонтального скролла всей страницы нет. Уведомления о ходе доступны скринридеру, таймер не озвучивается каждую секунду. Подсказка не должна зависеть только от hover или краткой вспышки.
|
- Масштабирование браузером разрешено; горизонтального скролла всей страницы нет. Уведомления о ходе доступны скринридеру, таймер не озвучивается каждую секунду. Подсказка не должна зависеть только от hover или краткой вспышки.
|
||||||
|
|||||||
@@ -45,13 +45,13 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
Самостоятельная клиентская тренировка без регистрации, БД и новых runtime-зависимостей. Она не подключается к CatWar и не начисляет ЛУ. Поле, история и заметки существуют до перезагрузки страницы.
|
Самостоятельная клиентская тренировка без регистрации, БД и новых runtime-зависимостей. Она не подключается к CatWar и не начисляет ЛУ. Поле, история и заметки существуют до перезагрузки страницы.
|
||||||
|
|
||||||
На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Стрелки и Home / End перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Перенос на игровое поле» меняет только видимость отметок на локации. Очистка отметок и новая игра имеют разные подтверждения.
|
На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Стрелки и Home / End перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Показывать заметки на поле» меняет только их видимость на локации. Очистка отметок и новая игра имеют разные подтверждения.
|
||||||
|
|
||||||
По умолчанию после прыжка звучат синтезированные шорохи: при уровне 0 — тишина, при 1–7 — столько же шорохов. Уровень равен числу соседних опасностей с учётом диагоналей, но 7 означает «семь и больше». «Повторить звук» воспроизводит сигнал текущей клетки. «Упрощённый режим» показывает уровни на проверенных клетках вместо звука и включает подсказки ЛУ.
|
По умолчанию после прыжка звучат синтезированные шорохи: при уровне 0 — тишина, при 1–7 — столько же шорохов. Уровень равен числу соседних опасностей с учётом диагоналей, но 7 означает «семь и больше». «Повторить звук» воспроизводит сигнал текущей клетки. «Упрощённый режим» показывает уровни на входе и проверенных клетках вместо звука и включает подсказки ЛУ.
|
||||||
|
|
||||||
На «Минном поле» клик или касание выбирает клетку для ручной оценки. Уровень ставится клавишей или кнопкой 0–7; Delete, Backspace или «Убрать оценку» снимает его. 0 — явная оценка, не пустая клетка. Оценка не двигает персонажа, не блокирует прыжок и не влияет на условие победы; отдельные флажки работают как раньше.
|
На телефоне прокрутите страницу вниз до «Минного поля». На карте клик или касание выбирает клетку для ручной оценки. Уровень ставится клавишей или кнопкой 0–7; Delete, Backspace или «Убрать оценку» снимает его. 0 — явная оценка, не пустая клетка. Оценка не двигает персонажа, не блокирует прыжок и не влияет на условие победы; отдельные флажки работают как раньше.
|
||||||
|
|
||||||
Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от входа: перескакивать через них нельзя.
|
Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Вход безопасен, рядом с ним от 0 до 2 опасностей. У `x1 y2` не больше 3 соседних опасностей, у `x1 y3` не больше 4. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от входа: перескакивать через них нельзя.
|
||||||
|
|
||||||
Выход выбирается заново для каждой попытки: `x10 y2–y6` или `y6 x6–x10`. Координаты переходов показаны на локации и на карте. В этой версии тренажёра выход обозначает место перехода, но не переключает высоту.
|
Выход выбирается заново для каждой попытки: `x10 y2–y6` или `y6 x6–x10`. Координаты переходов показаны на локации и на карте. В этой версии тренажёра выход обозначает место перехода, но не переключает высоту.
|
||||||
|
|
||||||
|
|||||||
@@ -4,15 +4,17 @@ 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.
|
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.
|
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. A public snapshot omits hidden hazards/values. UI owns selection, display mode, map visibility and note 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. 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, 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: 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: 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.
|
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.
|
||||||
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.
|
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. The phone map stays below the scene on the same scrollable page; the separate history panel restores focus on close. 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.
|
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, 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.
|
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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
+104
-11
@@ -37,6 +37,27 @@ async function checkTransitions(page, expectedExit) {
|
|||||||
return exit;
|
return exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function assertEntranceLevel(page, value, current = true) {
|
||||||
|
for (const grid of ['scene-grid','map-grid']) {
|
||||||
|
const entrance = page.locator(`#${grid} .entrance button[data-id="0"]`);
|
||||||
|
assert.equal(await valueText(entrance,'.cell-value'),value === null ? '↥' : `↥ ${value}`);
|
||||||
|
assert.equal(await entrance.getAttribute('aria-label'),`x1 y1: вход${value === null ? '' : `, опасностей рядом: ${value}`}${current ? ', персонаж здесь' : ''}`);
|
||||||
|
assert.equal(await page.locator(`#${grid} .entrance.opened`).count(),0);
|
||||||
|
}
|
||||||
|
assert.equal(await valueText(page.locator('#scene-grid .entrance button'),'.cell-coord'),'x1 y1');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function finishDialog(page, dialogId, openerId, action) {
|
||||||
|
await page.locator(`#${dialogId}`).evaluate(dialog=>{
|
||||||
|
dialog.closeSeen = false;
|
||||||
|
dialog.addEventListener('close',()=>{ dialog.closeSeen = true; },{once:true});
|
||||||
|
});
|
||||||
|
await action();
|
||||||
|
// The native dialog can become hidden before its close handler restores focus.
|
||||||
|
await page.waitForFunction(id=>document.getElementById(id).closeSeen,dialogId);
|
||||||
|
assert(await page.locator(`#${openerId}`).evaluate(n=>n===document.activeElement));
|
||||||
|
}
|
||||||
|
|
||||||
async function run() {
|
async function run() {
|
||||||
const {generateField, DEFAULTS, coordinate, neighbors} = await import(pathToFileURL(path.resolve(__dirname,'../../web/lu-trainer/engine.js')));
|
const {generateField, DEFAULTS, coordinate, neighbors} = await import(pathToFileURL(path.resolve(__dirname,'../../web/lu-trainer/engine.js')));
|
||||||
const field = generateField(DEFAULTS,seeded());
|
const field = generateField(DEFAULTS,seeded());
|
||||||
@@ -50,8 +71,8 @@ async function run() {
|
|||||||
const captures = [];
|
const captures = [];
|
||||||
try {
|
try {
|
||||||
if (shotDir) await mkdir(shotDir,{recursive:true});
|
if (shotDir) await mkdir(shotDir,{recursive:true});
|
||||||
for (const [width,height,touch = false] of [[1920,1080],[1366,768],[768,1024],[390,844,true],[1024,768,true]]) {
|
for (const [width,height,touch = false] of [[1920,1080],[1366,768],[768,1024],[390,844,true],[844,390,true],[1024,768,true]]) {
|
||||||
const mobile = width <= 700, compact = mobile || touch;
|
const mobile = width <= 700 || width === 844, compact = mobile || touch;
|
||||||
const context = await browser.newContext({viewport:{width,height}, reducedMotion:'reduce', locale:'ru-RU', hasTouch:touch, isMobile:mobile});
|
const context = await browser.newContext({viewport:{width,height}, reducedMotion:'reduce', locale:'ru-RU', hasTouch:touch, isMobile:mobile});
|
||||||
try {
|
try {
|
||||||
await context.addInitScript(() => {
|
await context.addInitScript(() => {
|
||||||
@@ -185,7 +206,27 @@ async function run() {
|
|||||||
assert(await scene(9).evaluate(n=>n===document.activeElement));
|
assert(await scene(9).evaluate(n=>n===document.activeElement));
|
||||||
await page.keyboard.press('Home'); assert(await scene(0).evaluate(n=>n===document.activeElement));
|
await page.keyboard.press('Home'); assert(await scene(0).evaluate(n=>n===document.activeElement));
|
||||||
// Click/tap an eligible neighbor on the map: selection and rating must never jump.
|
// Click/tap an eligible neighbor on the map: selection and rating must never jump.
|
||||||
if (mobile) await page.locator('#map-open').click();
|
if (mobile) {
|
||||||
|
const historyState = await page.evaluate(()=>({url:location.href,length:window.history.length}));
|
||||||
|
await page.evaluate(()=>window.scrollTo(0,0));
|
||||||
|
const grid = page.locator('#map-grid');
|
||||||
|
assert(await grid.isVisible(),'the phone map must be in the page before activating its shortcut');
|
||||||
|
assert(await page.locator('#map-home').evaluate(n=>n.getBoundingClientRect().top >= document.querySelector('.location').getBoundingClientRect().bottom));
|
||||||
|
await page.mouse.move(width - 4,height / 2);
|
||||||
|
await page.mouse.wheel(0,(await grid.boundingBox()).y - height / 3);
|
||||||
|
await page.waitForFunction(()=>{
|
||||||
|
const {top} = document.querySelector('#map-grid').getBoundingClientRect();
|
||||||
|
return scrollY > 0 && top >= 0 && top < innerHeight;
|
||||||
|
});
|
||||||
|
await page.locator('#map-open').press('Enter');
|
||||||
|
const heading = page.getByRole('heading',{name:'Минное поле',exact:true});
|
||||||
|
assert(await heading.evaluate(n=>n===document.activeElement && n.getBoundingClientRect().top >= 0 && n.getBoundingClientRect().bottom <= innerHeight));
|
||||||
|
assert(await page.locator('#scene-grid').isVisible(),'the scene stays in the document');
|
||||||
|
assert(await page.locator('#panel-dialog').isHidden(),'the shortcut only scrolls the page');
|
||||||
|
assert.deepEqual(await page.evaluate(()=>({url:location.href,length:window.history.length})),historyState);
|
||||||
|
await page.keyboard.press('Tab');
|
||||||
|
assert(await grid.evaluate(n=>n.contains(document.activeElement)));
|
||||||
|
}
|
||||||
const ratingCell = 11;
|
const ratingCell = 11;
|
||||||
const mapSelection = page.locator('#map-selection');
|
const mapSelection = page.locator('#map-selection');
|
||||||
const mapMark = page.locator('#map-mark');
|
const mapMark = page.locator('#map-mark');
|
||||||
@@ -289,38 +330,48 @@ async function run() {
|
|||||||
assert.equal(await page.locator('#map-grid .opened').count(),2);
|
assert.equal(await page.locator('#map-grid .opened').count(),2);
|
||||||
assert.equal(await history.count(),beforeFlag + 2);
|
assert.equal(await history.count(),beforeFlag + 2);
|
||||||
if (mobile) {
|
if (mobile) {
|
||||||
await page.keyboard.press('Escape');
|
|
||||||
assert(await page.locator('#map-open').evaluate(n=>n===document.activeElement));
|
|
||||||
await page.locator('#history-open').click();
|
await page.locator('#history-open').click();
|
||||||
assert(await page.locator('#panel-dialog #history').isVisible());
|
assert(await page.locator('#panel-dialog #history').isVisible());
|
||||||
await page.keyboard.press('Escape');
|
await page.keyboard.press('Escape');
|
||||||
|
await page.locator('#history-home #history').waitFor({state:'attached'});
|
||||||
assert(await page.locator('#history-open').evaluate(n=>n===document.activeElement));
|
assert(await page.locator('#history-open').evaluate(n=>n===document.activeElement));
|
||||||
} else {
|
} else {
|
||||||
await page.locator('#map-toggle').click(); assert(await page.locator('#map-body').isHidden());
|
await page.locator('#map-toggle').click(); assert(await page.locator('#map-body').isHidden());
|
||||||
await page.locator('#map-expand').click(); assert(await page.locator('#panel-dialog #map-grid').isVisible());
|
await page.locator('#map-expand').click(); assert(await page.locator('#panel-dialog #map-grid').isVisible());
|
||||||
await page.keyboard.press('Escape'); assert(await page.locator('#map-body').isHidden());
|
await page.keyboard.press('Escape');
|
||||||
|
await page.locator('#map-home #map-body[hidden]').waitFor({state:'attached'});
|
||||||
|
assert(await page.locator('#map-expand').evaluate(n=>n===document.activeElement));
|
||||||
|
if (width === 768) {
|
||||||
|
await page.setViewportSize({width:690,height});
|
||||||
|
await page.locator('#map-grid').waitFor({state:'visible'});
|
||||||
|
await page.setViewportSize({width,height});
|
||||||
|
await page.locator('#map-body').waitFor({state:'hidden'});
|
||||||
|
}
|
||||||
await page.locator('#map-toggle').click();
|
await page.locator('#map-toggle').click();
|
||||||
}
|
}
|
||||||
if (shotDir) {
|
if (shotDir) {
|
||||||
const file = `${shotDir}/lu-${width}.png`;
|
const file = `${shotDir}/lu-${width}.png`;
|
||||||
// Full-page capture temporarily resizes emulation and can reset the wide coarse-pointer mode.
|
// Full-page capture temporarily resizes emulation and can reset the wide coarse-pointer mode.
|
||||||
await page.screenshot({path:file,fullPage:!touch || mobile});
|
await page.screenshot({path:file,fullPage:!touch || width <= 700});
|
||||||
captures.push(file);
|
captures.push(file);
|
||||||
}
|
}
|
||||||
// Restart confirmations preserve/cancel the existing state; settings are staged until submit.
|
// Restart confirmations preserve/cancel the existing state; settings are staged until submit.
|
||||||
await page.locator('#new-game').click(); await page.keyboard.press('Escape');
|
const escape = () => page.keyboard.press('Escape');
|
||||||
|
await page.locator('#new-game').click();
|
||||||
|
await finishDialog(page,'confirm-dialog','new-game',escape);
|
||||||
assert.equal(await page.locator('#scene-grid .opened').count(),2);
|
assert.equal(await page.locator('#scene-grid .opened').count(),2);
|
||||||
await page.locator('#settings-open').click(); await page.locator('#setting-height').selectOption('2');
|
await page.locator('#settings-open').click(); await page.locator('#setting-height').selectOption('2');
|
||||||
await page.keyboard.press('Escape'); assert.match(await page.locator('#height-value').textContent(),/^1/);
|
await finishDialog(page,'settings-dialog','settings-open',escape);
|
||||||
|
assert.match(await page.locator('#height-value').textContent(),/^1/);
|
||||||
await page.locator('#settings-open').click();
|
await page.locator('#settings-open').click();
|
||||||
assert.equal(await page.locator('#setting-height').inputValue(),'1');
|
assert.equal(await page.locator('#setting-height').inputValue(),'1');
|
||||||
await page.locator('#setting-height').selectOption('2');
|
await page.locator('#setting-height').selectOption('2');
|
||||||
await page.getByRole('button',{name:'Начать новую игру',exact:true}).click();
|
await finishDialog(page,'settings-dialog','settings-open',()=>page.getByRole('button',{name:'Начать новую игру',exact:true}).click());
|
||||||
assert.match(await page.locator('#height-value').textContent(),/^2/);
|
assert.match(await page.locator('#height-value').textContent(),/^2/);
|
||||||
assert.equal(await page.locator('#scene-grid .opened').count(),0);
|
assert.equal(await page.locator('#scene-grid .opened').count(),0);
|
||||||
assert.equal(await page.locator('#history li').count(),0);
|
assert.equal(await page.locator('#history li').count(),0);
|
||||||
assert.equal(await page.locator('#timer').textContent(),'00:00');
|
assert.equal(await page.locator('#timer').textContent(),'00:00');
|
||||||
assert.match(await scene(0).getAttribute('aria-label'), /вход, персонаж здесь/);
|
assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: вход(?:, опасностей рядом: [0-2])?, персонаж здесь$/);
|
||||||
await checkTransitions(page);
|
await checkTransitions(page);
|
||||||
await assertAvailable([1,10,11]);
|
await assertAvailable([1,10,11]);
|
||||||
// Mark and unmark with compact buttons or Shift+Enter without moving the character.
|
// Mark and unmark with compact buttons or Shift+Enter without moving the character.
|
||||||
@@ -374,6 +425,46 @@ async function run() {
|
|||||||
assert.deepEqual([...exits].sort((a,b)=>a-b),allowedExits);
|
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');
|
console.log('PASS all permitted exit cells, synchronized transitions, exit cannot be jumped to or marked');
|
||||||
} finally { await boundary.close(); }
|
} finally { await boundary.close(); }
|
||||||
|
// Seed one entrance at each legal level, including a real zero.
|
||||||
|
const entrances = await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true});
|
||||||
|
try {
|
||||||
|
for (const [entranceSeed, value] of [[1,0],[2,1],[6,2]]) {
|
||||||
|
assert.equal(generateField(DEFAULTS,seeded(entranceSeed)).values[0],value);
|
||||||
|
const page = await entrances.newPage();
|
||||||
|
try {
|
||||||
|
await page.addInitScript(seed => {
|
||||||
|
Math.random = () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; };
|
||||||
|
window.entranceCues = 0;
|
||||||
|
window.AudioContext = class extends AudioContext {
|
||||||
|
createBuffer(...args) { window.entranceCues++; return super.createBuffer(...args); }
|
||||||
|
};
|
||||||
|
},entranceSeed);
|
||||||
|
await page.goto(`${origin}/trainer`);
|
||||||
|
await page.locator('#scene-grid .entrance button').waitFor();
|
||||||
|
const replay = page.locator('#replay-sound'), simple = page.locator('#simple-mode');
|
||||||
|
await assertEntranceLevel(page,null);
|
||||||
|
assert.equal(await page.evaluate(()=>window.entranceCues),0,'no entrance audio plays automatically');
|
||||||
|
assert.equal(await replay.isDisabled(),value === 0);
|
||||||
|
if (value > 0) {
|
||||||
|
await replay.tap();
|
||||||
|
await page.waitForFunction(()=>window.entranceCues === 1);
|
||||||
|
}
|
||||||
|
await simple.check();
|
||||||
|
await assertEntranceLevel(page,value);
|
||||||
|
if (shotDir && value === 2) {
|
||||||
|
const file = `${shotDir}/lu-entrance-390.png`;
|
||||||
|
await page.screenshot({path:file});
|
||||||
|
captures.push(file);
|
||||||
|
}
|
||||||
|
assert(await replay.isDisabled());
|
||||||
|
await simple.uncheck();
|
||||||
|
await assertEntranceLevel(page,null);
|
||||||
|
assert.equal(await page.evaluate(()=>window.entranceCues),value > 0 ? 1 : 0,'mode changes do not play a cue');
|
||||||
|
assert.equal(await page.locator('#history li').count(),0,'replaying an entrance cue is not a jump');
|
||||||
|
} finally { await page.close(); }
|
||||||
|
}
|
||||||
|
console.log('PASS entrance 0–2, mode-dependent arrow/level and ARIA, manual replay only');
|
||||||
|
} finally { await entrances.close(); }
|
||||||
// The same opened cell can display both the player's rating and the model's actual value.
|
// 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}});
|
const audio = await browser.newContext({viewport:{width:1366,height:768}});
|
||||||
try {
|
try {
|
||||||
@@ -476,6 +567,8 @@ async function run() {
|
|||||||
await cell(hazard).click();
|
await cell(hazard).click();
|
||||||
assert(await page.locator('#result').isVisible());
|
assert(await page.locator('#result').isVisible());
|
||||||
assert((await page.locator('#result').textContent()).includes(`Падение на ${coordinate(hazard)}`));
|
assert((await page.locator('#result').textContent()).includes(`Падение на ${coordinate(hazard)}`));
|
||||||
|
await assertEntranceLevel(page,field.values[0],false);
|
||||||
|
assert(await page.locator('#replay-sound').isDisabled());
|
||||||
assert.equal(await page.locator('#scene-grid .hazard').count(),field.hazards.size);
|
assert.equal(await page.locator('#scene-grid .hazard').count(),field.hazards.size);
|
||||||
const count = await page.locator('#history li').count();
|
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(11).click(); // Previously opened, adjacent to the current cell: blocked only by the result lock.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { Training, generateField, neighbors, hintChance, START, coordinate } from '../../web/lu-trainer/engine.js';
|
import { Training, generateField, neighbors, hintChance, START, COLS, coordinate } from '../../web/lu-trainer/engine.js';
|
||||||
import { rustleSamples } from '../../web/lu-trainer/audio.js';
|
import { rustleSamples } from '../../web/lu-trainer/audio.js';
|
||||||
|
|
||||||
function seeded(seed = 19) {
|
function seeded(seed = 19) {
|
||||||
@@ -52,6 +52,49 @@ test('entrance is always x1 y1 and exits vary only on the allowed edges', () =>
|
|||||||
assert.deepEqual([...exits].sort((a,b)=>a-b), allowed);
|
assert.deepEqual([...exits].sort((a,b)=>a-b), allowed);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('entrance-area limits apply to actual hazards without making either lower cell safe', () => {
|
||||||
|
const dense = {...options, height: 5, growth: 25, season: 5};
|
||||||
|
const limits = [[START, 2], [COLS, 3], [2 * COLS, 4]];
|
||||||
|
const levels = limits.map(() => new Set());
|
||||||
|
const edgeHazards = new Set();
|
||||||
|
for (let seed = 0; seed < 100; seed++) {
|
||||||
|
const field = generateField(dense, seeded(seed));
|
||||||
|
assert.equal(field.hazards.size, 38, `seed ${seed}`);
|
||||||
|
assert(!field.hazards.has(START));
|
||||||
|
limits.forEach(([id, max], i) => {
|
||||||
|
const actual = neighbors(id).filter(neighbor => field.hazards.has(neighbor)).length;
|
||||||
|
assert(actual <= max, `seed ${seed}: ${coordinate(id)} has ${actual} hazards, expected at most ${max}`);
|
||||||
|
assert.equal(field.values[id], actual);
|
||||||
|
levels[i].add(actual);
|
||||||
|
if (field.hazards.has(id)) edgeHazards.add(id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
assert.deepEqual(levels[0], new Set([0, 1, 2]));
|
||||||
|
assert(levels[1].has(3));
|
||||||
|
assert(levels[2].has(4));
|
||||||
|
assert.deepEqual(edgeHazards, new Set([COLS, 2 * COLS]));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the ready snapshot reveals the entrance number but does not open the transition', () => {
|
||||||
|
const dense = {...options, height: 5, growth: 25, season: 5};
|
||||||
|
for (const seed of [0, 2, 5]) {
|
||||||
|
const {field, game} = fixture(dense, seed);
|
||||||
|
const view = game.view();
|
||||||
|
const start = view.cells[view.start];
|
||||||
|
assert.equal(start.value, field.values[START]);
|
||||||
|
assert.equal(start.opened, false);
|
||||||
|
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(1).code, 'opened');
|
||||||
|
assert.equal(game.view().cells[START].value, start.value);
|
||||||
|
assert.equal(game.view().opened, 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('generation covers every settings combination with safe transitions, base and connecting route', () => {
|
test('generation covers every settings combination with safe transitions, base and connecting route', () => {
|
||||||
for (let height = 1; height <= 5; height++) for (const growth of [12,15,18,22,25]) for (const season of [-3,0,5]) {
|
for (let height = 1; height <= 5; height++) for (const growth of [12,15,18,22,25]) for (const season of [-3,0,5]) {
|
||||||
const field = generateField({...options, height, growth, season}, seeded(height * growth + season));
|
const field = generateField({...options, height, growth, season}, seeded(height * growth + season));
|
||||||
|
|||||||
+4
-4
@@ -59,13 +59,13 @@
|
|||||||
</div>
|
</div>
|
||||||
<p class="legend">↥ Вход / выход <span>· Проверено</span> <span>⚑ Флажок опасности</span> <span><span class="rating-key">0–7</span> Ваша оценка</span> <span>× Опасность после игры</span> <span>≠ Ошибочная отметка</span></p>
|
<p class="legend">↥ Вход / выход <span>· Проверено</span> <span>⚑ Флажок опасности</span> <span><span class="rating-key">0–7</span> Ваша оценка</span> <span>× Опасность после игры</span> <span>≠ Ошибочная отметка</span></p>
|
||||||
<p id="result" class="result" hidden></p>
|
<p id="result" class="result" hidden></p>
|
||||||
<div class="mobile-tools"><button id="map-open" type="button">Минное поле</button><button id="history-open" type="button">История</button></div>
|
<div class="mobile-tools"><button id="map-open" type="button" aria-controls="map-body">Минное поле</button><button id="history-open" type="button">История</button></div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
<div class="right-column">
|
<div class="right-column">
|
||||||
<section class="panel messages-panel"><h2>Сообщения</h2><p id="sound-guide" class="fineprint">После прыжка прислушайтесь к шорохам и запишите свою оценку на карте.</p><ol id="messages" class="journal messages"><li class="initial-message">Лес затих. Прислушайтесь после прыжка.</li></ol></section>
|
<section class="panel messages-panel"><h2>Сообщения</h2><p id="sound-guide" class="fineprint">После прыжка прислушайтесь к шорохам и запишите свою оценку на карте.</p><ol id="messages" class="journal messages"><li class="initial-message">Лес затих. Прислушайтесь после прыжка.</li></ol></section>
|
||||||
<section class="panel map-panel" id="map-home">
|
<section class="panel map-panel" id="map-home">
|
||||||
<div class="panel-heading"><h2><button id="map-toggle" type="button" aria-expanded="true" aria-controls="map-body">Минное поле <span aria-hidden="true">−</span></button></h2><button id="map-expand" type="button">Развернуть</button></div>
|
<div class="panel-heading"><h2 id="map-title" tabindex="-1"><span class="phone-map-title">Минное поле</span><button id="map-toggle" type="button" aria-expanded="true" aria-controls="map-body">Минное поле <span aria-hidden="true">−</span></button></h2><button id="map-expand" type="button">Развернуть</button></div>
|
||||||
<div id="map-body">
|
<div id="map-body">
|
||||||
<p class="fineprint">Флажки: <span id="mark-count">0</span> / <span id="hazard-count">12</span> · Оценки: <span id="rating-count">0</span></p>
|
<p class="fineprint">Флажки: <span id="mark-count">0</span> / <span id="hazard-count">12</span> · Оценки: <span id="rating-count">0</span></p>
|
||||||
<div class="map-scroll"><div id="map-grid" class="cell-grid map-grid" role="grid" aria-label="Минное поле" aria-rowcount="6" aria-colcount="10" aria-describedby="map-instructions"></div></div>
|
<div class="map-scroll"><div id="map-grid" class="cell-grid map-grid" role="grid" aria-label="Минное поле" aria-rowcount="6" aria-colcount="10" aria-describedby="map-instructions"></div></div>
|
||||||
@@ -109,10 +109,10 @@
|
|||||||
<ul class="help-list">
|
<ul class="help-list">
|
||||||
<li>Вход всегда в верхней левой клетке (x1 y1). X растёт вправо, Y растёт вниз. Для каждой попытки тренажёр случайно выбирает выход: на правом краю (x10, с y2 по y6) или на нижнем (y6, с x6 по x10). Вход и выход отмечены стрелками. Прыгать на эти клетки нельзя.</li>
|
<li>Вход всегда в верхней левой клетке (x1 y1). X растёт вправо, Y растёт вниз. Для каждой попытки тренажёр случайно выбирает выход: на правом краю (x10, с y2 по y6) или на нижнем (y6, с x6 по x10). Вход и выход отмечены стрелками. Прыгать на эти клетки нельзя.</li>
|
||||||
<li>Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. В верхнем ряду сразу справа от входа есть безопасные клетки: 5 на первой высоте и 3 на остальных. Прыгайте по ним по одной клетке за раз.</li>
|
<li>Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. В верхнем ряду сразу справа от входа есть безопасные клетки: 5 на первой высоте и 3 на остальных. Прыгайте по ним по одной клетке за раз.</li>
|
||||||
<li>После прыжка прислушайтесь: тишина означает уровень 0, а число коротких шорохов подсказывает уровень от 1 до 7. Эти звуки создаёт тренажёр. В упрощённом режиме вместо звука вы увидите число опасностей вокруг проверенной клетки. Соседи по диагонали тоже считаются. 7 означает семь или больше.</li>
|
<li>После прыжка прислушайтесь: тишина означает уровень 0, а число коротких шорохов подсказывает уровень от 1 до 7. На входе звук можно включить кнопкой «Повторить звук», если рядом есть опасности. В упрощённом режиме число опасностей видно на входе и на проверенных клетках. Соседи по диагонали тоже считаются. 7 означает семь или больше.</li>
|
||||||
<li>Если под полем есть кнопки, сначала выберите клетку, затем нажмите «Прыгнуть», «Отметить опасной» или «Снять отметку». Если кнопок нет, нажмите на соседнюю клетку, чтобы прыгнуть. Правая кнопка мыши ставит или снимает флажок.</li>
|
<li>Если под полем есть кнопки, сначала выберите клетку, затем нажмите «Прыгнуть», «Отметить опасной» или «Снять отметку». Если кнопок нет, нажмите на соседнюю клетку, чтобы прыгнуть. Правая кнопка мыши ставит или снимает флажок.</li>
|
||||||
<li>Выбирайте клетки стрелками. Нажмите Home, чтобы перейти в начало строки, или End, чтобы перейти в конец. На игровом поле Enter и пробел позволяют прыгнуть, а Shift+Enter ставит или снимает флажок. На карте Enter и пробел только выбирают клетку.</li>
|
<li>Выбирайте клетки стрелками. Нажмите Home, чтобы перейти в начало строки, или End, чтобы перейти в конец. На игровом поле Enter и пробел позволяют прыгнуть, а Shift+Enter ставит или снимает флажок. На карте Enter и пробел только выбирают клетку.</li>
|
||||||
<li>На «Минном поле» выберите клетку и поставьте свою оценку кнопкой или клавишей 0–7. Чтобы убрать оценку, нажмите Delete или Backspace. Оценка не мешает прыгать и не влияет на победу. Чтобы прыгнуть на клетку с флажком, сначала снимите флажок. В упрощённом режиме при 4 ЛУ и выше может появиться подсказка «!».</li>
|
<li>На телефоне прокрутите страницу вниз до «Минного поля». На карте выберите клетку и поставьте свою оценку кнопкой или клавишей 0–7. Чтобы убрать оценку, нажмите Delete или Backspace. Оценка не мешает прыгать и не влияет на победу. Чтобы прыгнуть на клетку с флажком, сначала снимите флажок. В упрощённом режиме при 4 ЛУ и выше может появиться подсказка «!».</li>
|
||||||
<li>Чтобы победить, откройте все безопасные клетки, кроме переходов, или отметьте флажками все опасности без ошибок. Выход сам по себе не завершает игру. Прыжок на опасную клетку заканчивается падением.</li>
|
<li>Чтобы победить, откройте все безопасные клетки, кроме переходов, или отметьте флажками все опасности без ошибок. Выход сам по себе не завершает игру. Прыжок на опасную клетку заканчивается падением.</li>
|
||||||
</ul>
|
</ul>
|
||||||
<div class="dialog-actions"><button type="button" data-close autofocus>Вернуться к тренировке</button></div>
|
<div class="dialog-actions"><button type="button" data-close autofocus>Вернуться к тренировке</button></div>
|
||||||
|
|||||||
@@ -52,7 +52,19 @@ export function generateField(input = DEFAULTS, random = Math.random) {
|
|||||||
[candidates[i], candidates[j]] = [candidates[j], candidates[i]];
|
[candidates[i], candidates[j]] = [candidates[j], candidates[i]];
|
||||||
}
|
}
|
||||||
const count = Math.min(Math.max(5, options.growth + options.season + 2 * (options.height - 1)), candidates.length);
|
const count = Math.min(Math.max(5, options.growth + options.season + 2 * (options.height - 1)), candidates.length);
|
||||||
const hazards = new Set(candidates.slice(0, count));
|
// The safe entrance and x2 y1 already cap x1 y1 at 2 and x1 y2 at 3.
|
||||||
|
// Cap x1 y3 at 4 during placement, skipping only a fifth hazard in its neighborhood.
|
||||||
|
const leftThirdNeighbors = neighbors(2 * COLS);
|
||||||
|
const hazards = new Set();
|
||||||
|
let leftThirdHazards = 0;
|
||||||
|
for (const id of candidates) {
|
||||||
|
if (hazards.size === count) break;
|
||||||
|
if (leftThirdNeighbors.includes(id)) {
|
||||||
|
if (leftThirdHazards === 4) continue;
|
||||||
|
leftThirdHazards++;
|
||||||
|
}
|
||||||
|
hazards.add(id);
|
||||||
|
}
|
||||||
const values = Array.from({length: ROWS * COLS}, (_,id)=>neighbors(id).filter(n => hazards.has(n)).length);
|
const values = Array.from({length: ROWS * COLS}, (_,id)=>neighbors(id).filter(n => hazards.has(n)).length);
|
||||||
return { start: START, exit, base, reserved, hazards, values };
|
return { start: START, exit, base, reserved, hazards, values };
|
||||||
}
|
}
|
||||||
@@ -143,7 +155,7 @@ export class Training {
|
|||||||
id, entrance: id === START, exit: id === this.#field.exit, transition: this.#transition(id), base: this.#field.base.includes(id),
|
id, entrance: id === START, exit: id === this.#field.exit, transition: this.#transition(id), base: this.#field.base.includes(id),
|
||||||
opened: this.#opened.has(id), marked: this.#marks.has(id), rating: this.#ratings.get(id) ?? null,
|
opened: this.#opened.has(id), marked: this.#marks.has(id), rating: this.#ratings.get(id) ?? null,
|
||||||
available: !ended && this.#available(id),
|
available: !ended && this.#available(id),
|
||||||
value: this.#opened.has(id) || ended ? this.#field.values[id] : null,
|
value: id === START || this.#opened.has(id) || ended ? this.#field.values[id] : null,
|
||||||
...(ended ? {hazard: this.#field.hazards.has(id), wrong: this.#marks.has(id) && !this.#field.hazards.has(id)} : {}),
|
...(ended ? {hazard: this.#field.hazards.has(id), wrong: this.#marks.has(id) && !this.#field.hazards.has(id)} : {}),
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -71,6 +71,8 @@ dd { margin: 0; text-align: right; font-weight: bold; }
|
|||||||
.cell-grid .wrong button { background: var(--paper); color: var(--danger); }
|
.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-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); }
|
.cell-value { font-size: clamp(14px, 1.5vw, 24px); }
|
||||||
|
.entrance .cell-value { font-size: clamp(.8125rem, 1.2vw, 1rem); line-height: 1.25; white-space: nowrap; }
|
||||||
|
.scene-grid .entrance .cell-value { position: absolute; right: 2px; bottom: 2px; z-index: 1; padding: 0 2px; border-radius: 2px; background: var(--map); }
|
||||||
.cell-rating, .rating-key { background: var(--active); color: var(--ink); padding: 0 3px; border-radius: 2px; font-weight: bold; }
|
.cell-rating, .rating-key { background: var(--active); color: var(--ink); padding: 0 3px; border-radius: 2px; font-weight: bold; }
|
||||||
.cell-rating { position: absolute; bottom: 1px; right: 1px; font-size: .6875rem; line-height: 1.15; text-shadow: none; }
|
.cell-rating { position: absolute; bottom: 1px; right: 1px; font-size: .6875rem; line-height: 1.15; text-shadow: none; }
|
||||||
.character-sprite { position: absolute; width: 10%; height: 16.6667%; left: 0; top: 83.3333%; pointer-events: none; display: flex; align-items: center; justify-content: center; }
|
.character-sprite { position: absolute; width: 10%; height: 16.6667%; left: 0; top: 83.3333%; pointer-events: none; display: flex; align-items: center; justify-content: center; }
|
||||||
@@ -93,6 +95,7 @@ input { accent-color: var(--map); }
|
|||||||
.map-panel .fineprint, #panel-dialog:has(#map-body) .fineprint { color: var(--paper); }
|
.map-panel .fineprint, #panel-dialog:has(#map-body) .fineprint { color: var(--paper); }
|
||||||
.panel-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 12px; }
|
.panel-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 12px; }
|
||||||
.panel-heading h2 { min-width: 0; }
|
.panel-heading h2 { min-width: 0; }
|
||||||
|
.phone-map-title { display: none; }
|
||||||
#map-toggle { color: inherit; background: none; border: 0; padding: 0 4px; text-align: left; font: inherit; }
|
#map-toggle { color: inherit; background: none; border: 0; padding: 0 4px; text-align: left; font: inherit; }
|
||||||
#map-expand { padding: 4px 8px; font-size: var(--small); }
|
#map-expand { padding: 4px 8px; font-size: var(--small); }
|
||||||
.map-grid { display: grid; gap: 2px; margin: 12px 0; }
|
.map-grid { display: grid; gap: 2px; margin: 12px 0; }
|
||||||
@@ -169,8 +172,7 @@ select { min-height: 44px; padding: 8px; width: 100%; }
|
|||||||
.character .stats > div { border: 0; padding: 2px 0; }
|
.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; }
|
.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; }
|
.location { order: 1; padding: 0; }
|
||||||
.messages-panel { order: 3; }
|
.messages-panel, .map-panel { order: 3; }
|
||||||
.map-panel, .history-panel { display: none; }
|
|
||||||
.cell-coord { font-size: 8px; left: 1px; top: 1px; padding: 0 1px; }
|
.cell-coord { font-size: 8px; left: 1px; top: 1px; padding: 0 1px; }
|
||||||
.cell-value { font-size: 14px; }
|
.cell-value { font-size: 14px; }
|
||||||
.scene-grid .opened .cell-coord { display: none; }
|
.scene-grid .opened .cell-coord { display: none; }
|
||||||
@@ -180,6 +182,11 @@ select { min-height: 44px; padding: 8px; width: 100%; }
|
|||||||
dialog { padding: 16px; }
|
dialog { padding: 16px; }
|
||||||
footer { padding: 16px 12px; }
|
footer { padding: 16px 12px; }
|
||||||
}
|
}
|
||||||
|
@media (max-width: 700px), (max-width: 1100px) and (max-height: 500px) and (pointer: coarse) {
|
||||||
|
#map-title { scroll-margin-block-start: 12px; }
|
||||||
|
.phone-map-title { display: inline; }
|
||||||
|
#map-toggle, #map-expand { display: none; }
|
||||||
|
}
|
||||||
@media (pointer: coarse) { .action-buttons button, .mobile-tools button, #map-mark, #map-levels button, .listen-controls button, .listen-controls .check { min-height: 48px; } }
|
@media (pointer: coarse) { .action-buttons button, .mobile-tools button, #map-mark, #map-levels button, .listen-controls button, .listen-controls .check { min-height: 48px; } }
|
||||||
@media (prefers-reduced-motion: reduce) { button { transition: none; } }
|
@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; } }
|
@media (forced-colors: active) { .cell-grid .selected button, .cell-grid .current button { outline: 2px solid Highlight; outline-offset: -3px; } }
|
||||||
+20
-9
@@ -3,7 +3,7 @@ import {playSound, stopSound} from './audio.js';
|
|||||||
|
|
||||||
const $ = id => document.getElementById(id);
|
const $ = id => document.getElementById(id);
|
||||||
const compact = matchMedia('(max-width: 700px), (pointer: coarse)');
|
const compact = matchMedia('(max-width: 700px), (pointer: coarse)');
|
||||||
const mobile = matchMedia('(max-width: 700px)');
|
const phoneMap = matchMedia('(max-width: 700px), (max-width: 1100px) and (max-height: 500px) and (pointer: coarse)');
|
||||||
const sounds = ['Звуков нет', 'Едва различимый шорох', 'Тихий шорох', 'Приглушённый шорох', 'Громкий шорох'];
|
const sounds = ['Звуков нет', 'Едва различимый шорох', 'Тихий шорох', 'Приглушённый шорох', 'Громкий шорох'];
|
||||||
let game, selected = START, hints = new Set(), hintTimers = new Map();
|
let game, selected = START, hints = new Set(), hintTimers = new Map();
|
||||||
let messages = [];
|
let messages = [];
|
||||||
@@ -37,13 +37,13 @@ function recordMessage(message) {
|
|||||||
renderMessage(message);
|
renderMessage(message);
|
||||||
}
|
}
|
||||||
function describe(cell, view, showNotes = true, isMap = false) {
|
function describe(cell, view, showNotes = true, isMap = false) {
|
||||||
if (cell.entrance) return 'вход';
|
|
||||||
if (cell.exit) return 'выход';
|
if (cell.exit) return 'выход';
|
||||||
const rating = showNotes && cell.rating !== null ? `, ваша оценка ${cell.rating}` : '';
|
const rating = showNotes && cell.rating !== null ? `, ваша оценка ${cell.rating}` : '';
|
||||||
if (cell.wrong) return `ошибочная отметка, безопасно${rating}`;
|
if (cell.wrong) return `ошибочная отметка, безопасно${rating}`;
|
||||||
if (cell.hazard) return `опасная клетка${rating}`;
|
if (cell.hazard) return `опасная клетка${rating}`;
|
||||||
if (cell.opened || ended(view)) {
|
if (cell.entrance || cell.opened || ended(view)) {
|
||||||
const fact = simple() || ended(view) ? `, ${levelText(cell.value).slice(0, -1).toLowerCase()}` : '';
|
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 ? ', можно прыгнуть' : ''}`;
|
return `${cell.opened ? 'проверено' : 'безопасная клетка'}${fact}${rating}${!isMap && cell.available ? ', можно прыгнуть' : ''}`;
|
||||||
}
|
}
|
||||||
if (cell.marked && showNotes) return `ваш флажок опасности${rating}`;
|
if (cell.marked && showNotes) return `ваш флажок опасности${rating}`;
|
||||||
@@ -51,7 +51,8 @@ function describe(cell, view, showNotes = true, isMap = false) {
|
|||||||
return `клетка не проверена${rating}${isMap ? '' : cell.available ? ', рядом с персонажем' : ', не рядом с персонажем'}`;
|
return `клетка не проверена${rating}${isMap ? '' : cell.available ? ', рядом с персонажем' : ', не рядом с персонажем'}`;
|
||||||
}
|
}
|
||||||
function cellValue(cell, view, showMarks) {
|
function cellValue(cell, view, showMarks) {
|
||||||
if (cell.transition) return cell.entrance ? '↥' : '↗';
|
if (cell.entrance) return simple() || ended(view) ? `↥ ${cell.value}` : '↥';
|
||||||
|
if (cell.exit) return '↗';
|
||||||
if (cell.wrong) return '≠';
|
if (cell.wrong) return '≠';
|
||||||
if (cell.hazard) return '×';
|
if (cell.hazard) return '×';
|
||||||
if (cell.marked && showMarks) return '⚑';
|
if (cell.marked && showMarks) return '⚑';
|
||||||
@@ -283,20 +284,27 @@ function openPanel(kind, opener) {
|
|||||||
$('panel-dialog-title').textContent = kind === 'map' ? 'Минное поле' : 'История действий';
|
$('panel-dialog-title').textContent = kind === 'map' ? 'Минное поле' : 'История действий';
|
||||||
$('panel-dialog-content').append(panelBody); showDialog($('panel-dialog'), opener);
|
$('panel-dialog-content').append(panelBody); showDialog($('panel-dialog'), opener);
|
||||||
}
|
}
|
||||||
|
function syncMapVisibility() {
|
||||||
|
$('map-body').hidden = !phoneMap.matches && $('map-toggle').getAttribute('aria-expanded') === 'false';
|
||||||
|
}
|
||||||
$('panel-dialog').addEventListener('close', () => {
|
$('panel-dialog').addEventListener('close', () => {
|
||||||
if (panelBody) {
|
if (panelBody) {
|
||||||
panelOrigin.append(panelBody);
|
panelOrigin.append(panelBody);
|
||||||
if (panelBody.id === 'map-body') panelBody.hidden = $('map-toggle').getAttribute('aria-expanded') === 'false';
|
if (panelBody.id === 'map-body') syncMapVisibility();
|
||||||
panelBody = null; panelOrigin = null;
|
panelBody = null; panelOrigin = null;
|
||||||
}
|
}
|
||||||
panelReturn?.focus(); panelReturn = null;
|
panelReturn?.focus(); panelReturn = null;
|
||||||
});
|
});
|
||||||
$('map-open').addEventListener('click', event => openPanel('map',event.currentTarget));
|
$('map-open').addEventListener('click', event => {
|
||||||
|
if (!phoneMap.matches) { openPanel('map',event.currentTarget); return; }
|
||||||
|
$('map-title').focus({preventScroll:true});
|
||||||
|
$('map-title').scrollIntoView({block:'start'});
|
||||||
|
});
|
||||||
$('map-expand').addEventListener('click', event => openPanel('map',event.currentTarget));
|
$('map-expand').addEventListener('click', event => openPanel('map',event.currentTarget));
|
||||||
$('history-open').addEventListener('click', event => openPanel('history',event.currentTarget));
|
$('history-open').addEventListener('click', event => openPanel('history',event.currentTarget));
|
||||||
$('map-toggle').addEventListener('click', () => {
|
$('map-toggle').addEventListener('click', () => {
|
||||||
const open = $('map-toggle').getAttribute('aria-expanded') !== 'true';
|
const open = $('map-toggle').getAttribute('aria-expanded') !== 'true';
|
||||||
$('map-toggle').setAttribute('aria-expanded',String(open)); $('map-body').hidden = !open;
|
$('map-toggle').setAttribute('aria-expanded',String(open)); syncMapVisibility();
|
||||||
$('map-toggle').querySelector('span').textContent = open ? '−' : '+';
|
$('map-toggle').querySelector('span').textContent = open ? '−' : '+';
|
||||||
});
|
});
|
||||||
$('help-open').addEventListener('click', event => showDialog($('help-dialog'),event.currentTarget));
|
$('help-open').addEventListener('click', event => showDialog($('help-dialog'),event.currentTarget));
|
||||||
@@ -313,7 +321,7 @@ $('new-game').addEventListener('click', event => confirmAction('Начать з
|
|||||||
$('clear-marks').addEventListener('click', event => confirmAction('Очистить отметки?', 'Исчезнут только ваши флажки и оценки. Проверенные клетки и история останутся, а игру можно будет продолжить.', 'Очистить отметки', () => { game.clearMarks(); $('status').textContent = 'Флажки и оценки убраны. Можно продолжать.'; render(); }, event.currentTarget));
|
$('clear-marks').addEventListener('click', event => confirmAction('Очистить отметки?', 'Исчезнут только ваши флажки и оценки. Проверенные клетки и история останутся, а игру можно будет продолжить.', 'Очистить отметки', () => { game.clearMarks(); $('status').textContent = 'Флажки и оценки убраны. Можно продолжать.'; render(); }, event.currentTarget));
|
||||||
$('simple-mode').addEventListener('change', () => {
|
$('simple-mode').addEventListener('change', () => {
|
||||||
stopSound(); clearHints();
|
stopSound(); clearHints();
|
||||||
$('status').textContent = simple() ? 'В упрощённом режиме уровни видны на проверенных клетках.' : 'В звуковом режиме оцените клетку по шорохам.';
|
$('status').textContent = simple() ? 'В упрощённом режиме уровни видны на входе и на проверенных клетках.' : 'В звуковом режиме оцените клетку по шорохам.';
|
||||||
$('messages').replaceChildren(); messages.forEach(renderMessage);
|
$('messages').replaceChildren(); messages.forEach(renderMessage);
|
||||||
$('history').replaceChildren(); renderedHistory = 0;
|
$('history').replaceChildren(); renderedHistory = 0;
|
||||||
render();
|
render();
|
||||||
@@ -333,7 +341,10 @@ $('jump').addEventListener('click', () => act('jump'));
|
|||||||
$('mark').addEventListener('click', () => act('mark'));
|
$('mark').addEventListener('click', () => act('mark'));
|
||||||
$('map-mark').addEventListener('click', () => act('mark'));
|
$('map-mark').addEventListener('click', () => act('mark'));
|
||||||
compact.addEventListener('change', render);
|
compact.addEventListener('change', render);
|
||||||
mobile.addEventListener('change', () => { if ($('panel-dialog').open) $('panel-dialog').close(); });
|
phoneMap.addEventListener('change', () => {
|
||||||
|
if ($('panel-dialog').open) $('panel-dialog').close();
|
||||||
|
syncMapVisibility();
|
||||||
|
});
|
||||||
for (const img of document.images) {
|
for (const img of document.images) {
|
||||||
img.addEventListener('error', () => { img.hidden = true; });
|
img.addEventListener('error', () => { img.hidden = true; });
|
||||||
if (img.complete && !img.naturalWidth) img.hidden = true;
|
if (img.complete && !img.naturalWidth) img.hidden = true;
|
||||||
|
|||||||
Reference in new issue
Block a user