feat: add trainer sound mode and manual danger ratings

This commit is contained in:
nyan404 committed 2026-11-22 16:58:47 +03:00
1 parent 9be0bb48c8
commit ad8e2d1438
13 files changed
+466 -58

No files matched your search

+1
View File
@@ -37,6 +37,7 @@
## 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.
- 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.
+2 -1
View File
@@ -113,7 +113,7 @@
2. Выбирает параметры и начинает попытку. Изменение параметров во время попытки применяется только через явное начало новой игры с предупреждением о сбросе. 2. Выбирает параметры и начинает попытку. Изменение параметров во время попытки применяется только через явное начало новой игры с предупреждением о сбросе.
3. Нажимает допустимую клетку: она открывается, персонаж показывается на последней успешно выбранной клетке, история и сообщения обновляются, известное значение появляется на карте. 3. Нажимает допустимую клетку: она открывается, персонаж показывается на последней успешно выбранной клетке, история и сообщения обновляются, известное значение появляется на карте.
4. Отмечает подозрительную клетку через карту, правым кликом или Shift+Enter на локации, либо кнопкой под полем на сенсорном экране. Отметка не открывает клетку и блокирует прыжок на неё. 4. Отмечает подозрительную клетку через карту, правым кликом или Shift+Enter на локации, либо кнопкой под полем на сенсорном экране. Отметка не открывает клетку и блокирует прыжок на неё.
5. Повторное посещение проверенной клетки воспроизводит текстовую обратную связь и предусмотренную моделью проверку подсказки. 5. Повторное посещение проверенной клетки даёт звуковой сигнал. В упрощённом режиме вместо звука виден числовой уровень и доступна предусмотренная моделью подсказка ЛУ.
6. После падения либо выполнения условия победы действия попытки прекращаются, показываются результат и раскрытие поля. Доступны осмотр результата и новая игра. 6. После падения либо выполнения условия победы действия попытки прекращаются, показываются результат и раскрытие поля. Доступны осмотр результата и новая игра.
**Текущая механика тренажёра:** восемь соседей отсчитываются от позиции персонажа, а не от любой проверенной клетки, как было в первой версии. Формулы, шансы подсказок и условия победы сохранены. **Текущая механика тренажёра:** восемь соседей отсчитываются от позиции персонажа, а не от любой проверенной клетки, как было в первой версии. Формулы, шансы подсказок и условия победы сохранены.
@@ -138,6 +138,7 @@
| `web/lu-trainer/style.css` | Изолированные стили и токены | | `web/lu-trainer/style.css` | Изолированные стили и токены |
| `web/lu-trainer/engine.js` | Генерация и правила без DOM, управляемая случайность для проверок | | `web/lu-trainer/engine.js` | Генерация и правила без DOM, управляемая случайность для проверок |
| `web/lu-trainer/ui.js` | События пользователя, обе сетки, история, фокус и подсказки | | `web/lu-trainer/ui.js` | События пользователя, обе сетки, история, фокус и подсказки |
| `web/lu-trainer/audio.js` | Синтез и воспроизведение от 1 до 7 коротких шорохов, без аудиозаписей CatWar |
| `web/lu-trainer/assets/` | Проверенные изображения с указанием происхождения | | `web/lu-trainer/assets/` | Проверенные изображения с указанием происхождения |
| `app/main.py`, `nginx.conf` | Маршруты страницы и ассетов после выбора способа раздачи | | `app/main.py`, `nginx.conf` | Маршруты страницы и ассетов после выбора способа раздачи |
+4
View File
@@ -47,6 +47,10 @@ python3 -m app.belki.vk_bot
На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Стрелки и Home / End перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Перенос на игровое поле» меняет только видимость отметок на локации. Очистка отметок и новая игра имеют разные подтверждения. На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Стрелки и Home / End перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Перенос на игровое поле» меняет только видимость отметок на локации. Очистка отметок и новая игра имеют разные подтверждения.
По умолчанию после прыжка звучат синтезированные шорохи: при уровне 0 — тишина, при 1–7 — столько же шорохов. Уровень равен числу соседних опасностей с учётом диагоналей, но 7 означает «семь и больше». «Повторить звук» воспроизводит сигнал текущей клетки. «Упрощённый режим» показывает уровни на проверенных клетках вместо звука и включает подсказки ЛУ.
На «Минном поле» клик или касание выбирает клетку для ручной оценки. Уровень ставится клавишей или кнопкой 0–7; Delete, Backspace или «Убрать оценку» снимает его. 0 — явная оценка, не пустая клетка. Оценка не двигает персонажа, не блокирует прыжок и не влияет на условие победы; отдельные флажки работают как раньше.
Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от входа: перескакивать через них нельзя. Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от входа: перескакивать через них нельзя.
Выход выбирается заново для каждой попытки: `x10 y2–y6` или `y6 x6–x10`. Координаты переходов показаны на локации и на карте. В этой версии тренажёра выход обозначает место перехода, но не переключает высоту. Выход выбирается заново для каждой попытки: `x10 y2–y6` или `y6 x6–x10`. Координаты переходов показаны на локации и на карте. В этой версии тренажёра выход обозначает место перехода, но не переключает высоту.
+3 -2
View File
@@ -4,13 +4,14 @@ Authorization: the owner requested implementation of root `LU_TRAINER_PROJECT.md
contract: standalone `/trainer` and `/trainer/`, shared HTML/CSS/ES-module assets served by Python and Nginx. No new runtime dependency or storage. Gateway serves the page with `try_files`; assets use the existing static serving. 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, marks set, last successful position, ready/playing/won/lost status and action log. A public snapshot omits hidden hazards/values. UI owns selection, map visibility and mark projection. state: engine owns 60 cells, per-attempt start/exit identities, hazards, opened set, hazard flags, user ratings, last successful position, ready/playing/won/lost status and action log. A public snapshot omits hidden hazards/values. UI owns selection, display mode, map visibility and note projection.
invariant: 6x10, entrance x1 y1 (top-left, index 0), exit selected per attempt from x10 y2–y6 or y6 x6–x10; transition cells do not count toward victory and cannot be opened/marked. The first 5/3 top-row cells to the right of the entrance are safe, but there is no special jump permission for them. A jump must target one of the current position’s eight neighbors, even for previously opened cells. Eight-neighbor counts; safe path connects entrance, base and exit. Preserve documented hazard formula and 0/10/20/30% hint probabilities. Win by all non-transition safe cells or all and only hazards marked; loss ends actions. Repeat safe visits produce feedback and may hint. The character tracks the last successful non-transition visit. invariant: 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.
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. Map/history mobile panels restore focus. Native dialogs support Escape/cancel. Failed images leave cells and character fallback usable.
test: deterministic Node tests for generator safety/reachability/counts, all settings combinations, adjacency, transition exclusion, notes, win/loss, hints and public snapshots. HTTP test for aliases and asset MIME/containment. Browser checks at 1920x1080,1366x768,768x1024,390x844; two grids, logs, marks, confirmations, focus, keyboard/touch, reduced motion, 200% layout and image failures. Review real screenshots. Nginx syntax/serving check in isolated container if Docker available; no deployment. test: deterministic Node tests for generator safety/reachability/counts, all settings combinations, adjacency, transition exclusion, notes, win/loss, hints and public snapshots. HTTP test for aliases and asset MIME/containment. Browser checks at 1920x1080,1366x768,768x1024,390x844; two grids, logs, marks, confirmations, focus, keyboard/touch, reduced motion, 200% layout and image failures. Review real screenshots. Nginx syntax/serving check in isolated container if Docker available; no deployment.
deferred: verification of real CatWar rules, multiple saved maps, audio, server accounts, deployment. Generated original art provenance and prompts live in assets/README.md. deferred: verification of real CatWar rules, multiple saved maps, server accounts, deployment. Generated original art provenance and prompts live in assets/README.md.
Review: spec-compliance/consistency review closed the hint and terminal-action gaps. Hints intentionally return a temporary hazard ID in action results only (not hidden snapshot values), last 2000 ms and retain their coordinate in the readable message log. Only unmarked neighboring hazards are candidates. At completion marking/clearing are disabled; selection remains available for inspection. Defaults: height 1, LU 5, growth 12, season 0; growth accepts 12/15/18/22/25 and season -3/0/5. 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.
+5
View File
@@ -1,5 +1,10 @@
# Structure and Data # Structure and Data
## Trainer sound and manual ratings — 2026-11-22
- `audio.js` synthesizes counted rustles using Web Audio; no media downloads or runtime dependencies. The sound and simplified views share one `min(7, neighbors)` level. Switching modes preserves the field and ratings and updates prior messages without showing verified numbers in sound mode during play.
- `Training.rate()` stores separate ratings 0–7, including on opened cells. Ratings render as badges and do not affect moves or victory. One map serves mouse, keyboard, and touch controls.
## Trainer controls — 2026-11-22 ## Trainer controls — 2026-11-22
- `/trainer` no longer has a separate action panel or mode toggle. The scene handles mouse and keyboard actions directly; narrow and coarse-pointer layouts use selection and explicit buttons below the grid. The inline status is short, and detailed jumps and hints remain in the message journal. - `/trainer` no longer has a separate action panel or mode toggle. The scene handles mouse and keyboard actions directly; narrow and coarse-pointer layouts use selection and explicit buttons below the grid. The inline status is short, and detailed jumps and hints remain in the message journal.
+211 -10
View File
@@ -10,6 +10,19 @@ const shotDir = process.env.BELKI_SCREENSHOT_DIR;
const allowedExits = [19,29,39,49,55,56,57,58,59]; const allowedExits = [19,29,39,49,55,56,57,58,59];
function seeded(seed = 19) { return () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; }; } function seeded(seed = 19) { return () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; }; }
const cellIds = locator => locator.evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.id))); const cellIds = locator => locator.evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.id)));
const levelButtons = page => page.locator('#map-levels button[data-level]');
const levelButton = (page,level) => page.locator(`#map-levels button[data-level="${level}"]`);
const valueText = async (cell,selector) => (await cell.locator(selector).allTextContents()).join('').trim();
async function assertRatingControls(page,{disabled = false, active = null} = {}) {
const buttons = levelButtons(page);
assert.deepEqual(await buttons.evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.level))),[0,1,2,3,4,5,6,7]);
for (const button of await buttons.all()) {
assert(await button.isVisible(),'the rating menu stays under the map');
assert.equal(await button.isDisabled(),disabled);
assert.equal(await button.getAttribute('aria-pressed'),String(Number(await button.getAttribute('data-level')) === active));
}
assert.equal(await page.locator('#map-clear-level').isDisabled(),disabled || active === null);
}
async function checkTransitions(page, expectedExit) { async function checkTransitions(page, expectedExit) {
const sceneExit = await cellIds(page.locator('#scene-grid .exit button')); const sceneExit = await cellIds(page.locator('#scene-grid .exit button'));
assert.equal(sceneExit.length,1); assert.equal(sceneExit.length,1);
@@ -120,6 +133,7 @@ async function run() {
await assertPosition(0); await assertPosition(0);
assert.equal(await history.count(),0); assert.equal(await history.count(),0);
assert.equal(await page.locator('#scene-grid .opened').count(),0); assert.equal(await page.locator('#scene-grid .opened').count(),0);
await page.locator('#simple-mode').check(); // Exercise the existing diagnostics in simplified mode.
if (compact) { if (compact) {
await scene(first).click(); await scene(first).click();
await scene(first).tap(); await scene(first).tap();
@@ -170,26 +184,110 @@ async function run() {
await page.keyboard.press('End'); await page.keyboard.press('End');
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));
// Notes select on the map without jumping. One DOM map is moved into the modal on phone. // Click/tap an eligible neighbor on the map: selection and rating must never jump.
if (mobile) await page.locator('#map-open').click(); if (mobile) await page.locator('#map-open').click();
await map(note).click(); const ratingCell = 11;
const mapSelection = page.locator('#map-selection');
const mapMark = page.locator('#map-mark');
const project = page.locator('#project-marks');
const chooseOnMap = async cell => touch ? cell.tap() : cell.click();
for (const id of [0,field.exit]) {
await chooseOnMap(map(id));
await assertRatingControls(page,{disabled:true});
await map(id).press('4');
assert.equal(await valueText(map(id),'.cell-rating'),'','cannot rate a transition');
}
await chooseOnMap(map(ratingCell));
assert((await mapSelection.textContent()).includes(coordinate(ratingCell)));
await assertRatingControls(page);
await assertPosition(first);
assert.equal(await page.locator('#scene-grid .opened').count(),2); assert.equal(await page.locator('#scene-grid .opened').count(),2);
await page.locator('#map-mark').click(); assert.equal(await history.count(),3,'map selection has not changed jump history');
const assertRating = async level => {
assert.equal(await valueText(map(ratingCell),'.cell-rating'),String(level));
assert.equal(await valueText(scene(ratingCell),'.cell-rating'),String(level));
assert.doesNotMatch(await valueText(map(ratingCell),'.cell-value'),/\d/,'an estimate is not the field value');
assert.match(await mapSelection.textContent(),new RegExp(`оценк[^\\d]*${level}\\b`,'i'));
await assertRatingControls(page,{active:level});
};
if (touch) {
await levelButton(page,1).tap();
await assertRating(1);
await levelButton(page,7).tap();
} else {
await map(ratingCell).press('1');
await assertRating(1);
await map(ratingCell).press('7');
await assertRating(7);
for (const outside of ['8','9']) await map(ratingCell).press(outside);
}
await assertRating(7);
assert.deepEqual(await cellIds(page.locator('#map-grid .rated button')),[ratingCell]);
assert.deepEqual(await cellIds(page.locator('#scene-grid .rated button')),[ratingCell]);
assert.equal(await page.locator('#mark-count').textContent(),'0');
assert.equal(await page.locator('#map-grid .marked').count(),0);
await assertAvailable([2,10,11,12]);
await assertPosition(first);
await project.uncheck();
assert.equal(await valueText(scene(ratingCell),'.cell-rating'),'');
assert.equal(await page.locator('#scene-grid .rated').count(),0);
assert.equal(await valueText(map(ratingCell),'.cell-rating'),'7');
await project.check();
await assertRating(7);
if (shotDir && (width === 1366 || mobile)) {
const file = `${shotDir}/lu-ratings-${width}.png`;
await page.screenshot({path:file});
captures.push(file);
}
// Old flags and ratings coexist; clearing either one must leave the other intact.
await chooseOnMap(mapMark);
assert.equal(await page.locator('#mark-count').textContent(),'1');
assert.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[ratingCell]);
await assertRating(7);
if (touch) await page.locator('#map-clear-level').tap();
else await map(ratingCell).press('Delete');
assert.equal(await valueText(map(ratingCell),'.cell-rating'),'');
assert.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[ratingCell]);
await assertRatingControls(page);
if (touch) await levelButton(page,0).tap();
else await map(ratingCell).press('0');
await assertRating(0);
await chooseOnMap(mapMark);
await assertRating(0);
assert.equal(await page.locator('#mark-count').textContent(),'0');
if (!touch) {
await levelButton(page,4).click();
await assertRating(4);
await map(ratingCell).press('0');
await assertRating(0);
}
if (touch) await page.locator('#map-clear-level').tap();
else await map(ratingCell).press('Backspace');
assert.equal(await page.locator('#map-grid .rated, #scene-grid .rated').count(),0);
await assertRatingControls(page);
await assertPosition(first);
await map(note).click();
const beforeFlag = await history.count();
await mapMark.click();
assert.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[note]); assert.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[note]);
assert.deepEqual(await cellIds(page.locator('#scene-grid .marked button')),[note]); assert.deepEqual(await cellIds(page.locator('#scene-grid .marked button')),[note]);
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[first]); assert.equal(await valueText(map(note),'.cell-rating'),'','an ordinary flag has no rating');
await page.locator('#project-marks').uncheck(); await assertPosition(first);
await project.uncheck();
assert.equal(await page.locator('#scene-grid .marked').count(),0); assert.equal(await page.locator('#scene-grid .marked').count(),0);
assert.equal(await page.locator('#map-grid .marked').count(),1); assert.equal(await page.locator('#map-grid .marked').count(),1);
assert.equal(await page.locator('#history li').count(),4); assert.equal(await history.count(),beforeFlag + 1);
await page.locator('#project-marks').check(); await project.check();
// Clearing first cancels, then confirms; facts and history remain. // Clearing first cancels, then confirms; facts and history remain.
await page.locator('#clear-marks').click(); await page.keyboard.press('Escape'); await page.locator('#clear-marks').click(); await page.keyboard.press('Escape');
assert.equal(await page.locator('#map-grid .marked').count(),1); assert.equal(await page.locator('#map-grid .marked').count(),1);
await page.locator('#clear-marks').click(); await page.locator('#confirm-action').click(); await page.locator('#clear-marks').click(); await page.locator('#confirm-action').click();
await page.locator('#map-grid .marked').waitFor({state:'detached'}); await page.locator('#map-grid .marked').waitFor({state:'detached'});
assert.equal(await page.locator('#map-grid .opened').count(),2); assert.equal(await page.locator('#map-grid .opened').count(),2);
assert.equal(await page.locator('#history li').count(),5); assert.equal(await history.count(),beforeFlag + 2);
if (mobile) { if (mobile) {
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
assert(await page.locator('#map-open').evaluate(n=>n===document.activeElement)); assert(await page.locator('#map-open').evaluate(n=>n===document.activeElement));
@@ -249,7 +347,7 @@ async function run() {
await assertPosition(0); await assertPosition(0);
if (compact) assert(await jump.isEnabled()); if (compact) assert(await jump.isEnabled());
assert.deepEqual(errors,[]); assert.deepEqual(errors,[]);
console.log(`PASS ${width}x${height} (${compact ? 'compact' : 'desktop'}): render, adjacent jumps, keyboard/touch controls, synchronized map, notes, dialogs, settings, console`); console.log(`PASS ${width}x${height} (${compact ? 'compact' : 'desktop'}): render, adjacent jumps, keyboard/touch controls, map ratings and flags, projection, dialogs, settings, console`);
} finally { await context.close(); } } finally { await context.close(); }
} }
// Sample all exit buckets without coupling this test to their internal order. // Sample all exit buckets without coupling this test to their internal order.
@@ -276,6 +374,89 @@ async function run() {
assert.deepEqual([...exits].sort((a,b)=>a-b),allowedExits); 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(); }
// The same opened cell can display both the player's rating and the model's actual value.
const audio = await browser.newContext({viewport:{width:1366,height:768}});
try {
const page = await audio.newPage();
await page.addInitScript(() => {
let seed = 19;
Math.random = () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; };
});
await page.goto(`${origin}/trainer`);
const scene = id => page.locator(`#scene-grid button[data-id="${id}"]`);
const map = id => page.locator(`#map-grid button[data-id="${id}"]`);
const simple = page.locator('#simple-mode');
const status = page.locator('#status');
const informative = 20, real = field.values[informative];
assert(real > 0 && real !== 7 && real !== 6 && field.values[11] === 0,'sound fixture must contrast zero, positive and guessed values');
await scene(0).waitFor();
assert.equal(await simple.isChecked(),false,'sound mode is the default');
await page.evaluate(()=>Math.random=()=>0); // A positive jump could draw a hint in simplified mode.
await scene(11).click();
assert.equal(await status.textContent(),'Звуков нет.');
const replay = page.locator('#replay-sound');
assert(await replay.isDisabled(),'there is no signal to replay at level zero');
assert.equal(await valueText(map(11),'.cell-value'),'·');
await map(informative).press('7');
assert.equal(await valueText(map(informative),'.cell-rating'),'7');
await scene(informative).click();
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[informative],'ratings cannot block a jump');
assert.equal(await status.textContent(),'Прислушайтесь к звуку.');
assert.equal(await page.locator('#scene-grid .opened').count(),2);
const journal = page.locator('#messages');
const history = page.locator('#history');
const noFactInLogs = async () => {
for (const log of [history,journal]) {
assert.doesNotMatch(await log.textContent(),/(?:рядом:?\s*\d|подсказка:)/i);
}
assert.equal(await page.locator('#scene-grid .hint, #map-grid .hint').count(),0);
};
const assertCellNumbers = async (fact,rating) => {
for (const cell of [scene(informative),map(informative)]) {
const displayedFact = await valueText(cell,'.cell-value');
if (fact === null) assert.doesNotMatch(displayedFact,/\d/);
else assert.equal(displayedFact,fact);
assert.equal(await valueText(cell,'.cell-rating'),rating);
}
};
await noFactInLogs();
await assertCellNumbers(null,'7');
assert.doesNotMatch(await scene(informative).getAttribute('aria-label'),/рядом:?\s*\d/);
const beforeReplay = await history.locator('li').count();
await replay.click();
assert.equal(await history.locator('li').count(),beforeReplay,'replaying sound does not jump');
await noFactInLogs();
const beforeModeSwitch = await history.locator('li').count();
await simple.check();
await assertCellNumbers(String(real),'7');
assert.equal(await valueText(map(11),'.cell-value'),'0','simplified mode shows a real zero');
const project = page.locator('#project-marks');
await project.uncheck();
assert.equal(await valueText(scene(informative),'.cell-value'),String(real),'projection does not hide the model value');
assert.equal(await valueText(scene(informative),'.cell-rating'),'');
assert.equal(await valueText(map(informative),'.cell-rating'),'7');
await project.check();
await map(informative).click();
await assertRatingControls(page,{active:7});
assert(await page.locator('#map-mark').isDisabled(),'opened cells can be rated but not flagged');
assert.match(await history.textContent(),new RegExp(`рядом:?\\s*${real}\\b`));
assert.match(await journal.textContent(),new RegExp(`рядом:?\\s*${real}\\b`));
await simple.uncheck();
await assertCellNumbers(null,'7');
await noFactInLogs();
assert.equal(await history.locator('li').count(),beforeModeSwitch,'switching modes does not append a game action');
await map(informative).press('6');
await assertCellNumbers(null,'6');
await assertRatingControls(page,{active:6});
await map(informative).press('Backspace');
await assertCellNumbers(null,'');
await assertRatingControls(page);
await simple.check();
await assertCellNumbers(String(real),'');
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[informative]);
assert.equal(await page.locator('#map-grid .opened').count(),2);
console.log('PASS default sound mode, zero/positive jumps and replay, fact/log disclosure, independent ratings on opened cells, no restart');
} finally { await audio.close(); }
// Deterministic result/clock/hint lifetime checks at desktop size. // Deterministic result/clock/hint lifetime checks at desktop size.
const context = await browser.newContext({viewport:{width:1366,height:768}}); const context = await browser.newContext({viewport:{width:1366,height:768}});
try { try {
@@ -299,6 +480,11 @@ async function run() {
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.
await cell(30).click({button:'right'}); await cell(30).click({button:'right'});
const postResult = page.locator('#map-grid button[data-id="30"]');
await postResult.click();
await assertRatingControls(page,{disabled:true});
await postResult.press('7');
assert.equal(await valueText(postResult,'.cell-rating'),'','keyboard ratings also respect the result lock');
assert.equal(await page.locator('#history li').count(),count); assert.equal(await page.locator('#history li').count(),count);
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[20]); assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[20]);
const frozen = await page.locator('#timer').textContent(); const frozen = await page.locator('#timer').textContent();
@@ -327,6 +513,7 @@ async function run() {
await page.setViewportSize({width:1366,height:768}); await page.setViewportSize({width:1366,height:768});
await jump.waitFor({state:'hidden'}); await jump.waitFor({state:'hidden'});
await page.reload(); await page.locator('#scene-grid button').last().waitFor(); await page.reload(); await page.locator('#scene-grid button').last().waitFor();
await page.locator('#simple-mode').check();
await page.evaluate(()=>Math.random=()=>0); await page.evaluate(()=>Math.random=()=>0);
for (const id of hintRoute) await cell(id).click(); for (const id of hintRoute) await cell(id).click();
assert.equal(await page.locator('#scene-grid .hint').count(),1); assert.equal(await page.locator('#scene-grid .hint').count(),1);
@@ -342,16 +529,30 @@ async function run() {
assert((await page.locator('#messages').textContent()).includes(hintText)); assert((await page.locator('#messages').textContent()).includes(hintText));
await revisitHint(); await revisitHint();
assert.equal(await page.locator('#scene-grid .hint').count(),1); assert.equal(await page.locator('#scene-grid .hint').count(),1);
await page.locator('#simple-mode').uncheck();
assert.equal(await page.locator('#scene-grid .hint, #map-grid .hint').count(),0);
assert.doesNotMatch(await page.locator('#messages').textContent(),/Подсказка:/);
await page.locator('#simple-mode').check();
await revisitHint();
assert.equal(await page.locator('#scene-grid .hint').count(),1);
await page.locator('#new-game').click(); await page.locator('#confirm-action').click(); await page.locator('#new-game').click(); await page.locator('#confirm-action').click();
await page.waitForTimeout(2100); await page.waitForTimeout(2100);
assert.equal(await page.locator('#scene-grid .hint').count(),0); assert.equal(await page.locator('#scene-grid .hint').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');
// Marking is available anywhere; only the exact hazard set wins. // Ratings neither satisfy nor obstruct the exact-flag victory condition.
await page.reload(); await page.locator('#scene-grid button').last().waitFor(); await page.reload(); await page.locator('#scene-grid button').last().waitFor();
for (const id of field.hazards) await page.locator(`#map-grid button[data-id="${id}"]`).press('7');
assert.equal(await page.locator('#mark-count').textContent(),'0');
assert(await page.locator('#result').isHidden(),'rating every hazard does not win without flags');
const ratedSafe = page.locator(`#map-grid button[data-id="${first}"]`);
await ratedSafe.press('1');
assert.equal(await valueText(ratedSafe,'.cell-rating'),'1');
for (const id of field.hazards) await cell(id).click({button:'right'}); for (const id of field.hazards) await cell(id).click({button:'right'});
assert.match(await page.locator('#result').textContent(),/Карта готова/); assert.match(await page.locator('#result').textContent(),/Карта готова/);
assert(await page.locator('#clear-marks').isDisabled()); assert(await page.locator('#clear-marks').isDisabled());
await page.locator(`#map-grid button[data-id="${second}"]`).click();
await assertRatingControls(page,{disabled:true});
const wonHistory = await page.locator('#history li').count(); const wonHistory = await page.locator('#history li').count();
await cell(first).click({button:'right'}); // A safe, unopened cell would normally accept a note. await cell(first).click({button:'right'}); // A safe, unopened cell would normally accept a note.
await cell(first).press('Enter'); await cell(first).press('Enter');
+42
View File
@@ -1,11 +1,24 @@
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, coordinate } from '../../web/lu-trainer/engine.js';
import { rustleSamples } from '../../web/lu-trainer/audio.js';
function seeded(seed = 19) { function seeded(seed = 19) {
return () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed / 2 ** 32; }; return () => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return seed / 2 ** 32; };
} }
const options = {height: 1, lu: 5, growth: 12, season: 0}; const options = {height: 1, lu: 5, growth: 12, season: 0};
test('sound cue is silent at zero and has one distinct pulse per level', () => {
const sampleRate = 48000, step = 11040, audible = 4560;
assert.equal(rustleSamples(0, sampleRate).length, 0);
for (let level = 1; level <= 7; level++) {
const samples = rustleSamples(level, sampleRate);
assert.equal(samples.length, level * step);
for (let start = 0; start < samples.length; start += step) {
assert(samples.slice(start, start + audible).some(value => Math.abs(value) > .01));
assert(samples.slice(start + audible, start + step).every(value => value === 0));
}
}
});
function fixture(settings = options, seed = 19) { function fixture(settings = options, seed = 19) {
return {field: generateField(settings, seeded(seed)), game: new Training(settings, seeded(seed))}; return {field: generateField(settings, seeded(seed)), game: new Training(settings, seeded(seed))};
} }
@@ -98,9 +111,37 @@ test('notes hide no facts, block jumps, clear independently and reject invalid I
assert(game.view().history.length > before.history.length); assert(game.view().history.length > before.history.length);
for (const id of [-1,60,1.5,'1',null]) assert.equal(game.jump(id).code, 'invalid'); for (const id of [-1,60,1.5,'1',null]) assert.equal(game.jump(id).code, 'invalid');
}); });
test('manual levels are independent of facts, hazard flags and movement', () => {
const {game} = fixture();
assert.equal(game.rate(1, 7).code, 'rated');
assert.equal(game.rate(1, 1).code, 'rated');
assert.equal(game.rate(1, 1).code, 'unchanged');
assert.equal(game.rate(1, 0).code, 'rated');
for (const level of [8, -1, 1.5, '1', undefined]) assert.equal(game.rate(1, level).code, 'invalid-level');
const view = game.view();
assert.equal(view.marks, 0);
assert.equal(view.position, START);
assert.equal(view.cells[1].rating, 0);
assert.equal(view.cells[1].value, null);
assert.equal(game.mark(1).code, 'marked');
assert.equal(game.rate(1, null).code, 'unrated');
assert.equal(game.rate(1, null).code, 'unchanged');
assert.equal(game.view().cells[1].rating, null);
assert.equal(game.jump(1).code, 'marked');
assert.equal(game.mark(1).code, 'unmarked');
assert.equal(game.jump(1).code, 'opened');
assert.equal(game.rate(1, 3).code, 'rated');
assert.equal(game.rate(START, 3).code, 'transition');
assert.equal(game.rate(view.exit, 3).code, 'transition');
assert.equal(game.clearMarks().code, 'cleared');
assert.equal(game.view().cells[1].rating, null);
assert(game.view().cells[1].opened);
});
test('all and only hazards marked wins; terminal actions cannot change state', () => { test('all and only hazards marked wins; terminal actions cannot change state', () => {
const {game,field} = fixture(); const {game,field} = fixture();
game.mark(1); game.mark(1);
for (const id of field.hazards) game.rate(id, 7);
assert.notEqual(game.view().status, 'won');
for (const id of field.hazards) game.mark(id); for (const id of field.hazards) game.mark(id);
assert.notEqual(game.view().status, 'won'); assert.notEqual(game.view().status, 'won');
game.mark(1); game.mark(1);
@@ -109,6 +150,7 @@ test('all and only hazards marked wins; terminal actions cannot change state', (
for (const cell of ended.cells) assert.equal(typeof cell.hazard, 'boolean'); for (const cell of ended.cells) assert.equal(typeof cell.hazard, 'boolean');
assert.equal(game.jump(0).code, 'finished'); assert.equal(game.jump(0).code, 'finished');
assert.equal(game.mark(1).code, 'finished'); assert.equal(game.mark(1).code, 'finished');
assert.equal(game.rate(1, 3).code, 'finished');
assert.equal(game.clearMarks().code, 'finished'); assert.equal(game.clearMarks().code, 'finished');
assert.deepEqual(game.view(), ended); assert.deepEqual(game.view(), ended);
}); });
+1 -1
View File
@@ -38,7 +38,7 @@ class TrainerRoutesTests(unittest.TestCase):
self.assertEqual(pages[0][2], pages[1][2]) self.assertEqual(pages[0][2], pages[1][2])
def test_assets_have_browser_compatible_mime_types(self): def test_assets_have_browser_compatible_mime_types(self):
for asset, media_type in [('engine.js', 'javascript'), ('ui.js', 'javascript'), ('style.css', 'text/css'), ('assets/forest.webp', 'image/webp'), ('assets/cat.png', 'image/png')]: for asset, media_type in [('engine.js', 'javascript'), ('ui.js', 'javascript'), ('audio.js', 'javascript'), ('style.css', 'text/css'), ('assets/forest.webp', 'image/webp'), ('assets/cat.png', 'image/png')]:
with self.subTest(asset=asset): with self.subTest(asset=asset):
status, content_type, content = self.get('/lu-trainer/' + asset) status, content_type, content = self.get('/lu-trainer/' + asset)
self.assertEqual(status, 200) self.assertEqual(status, 200)
+19 -8
View File
@@ -39,6 +39,10 @@
<div class="center-column"> <div class="center-column">
<section class="location panel"> <section class="location panel">
<div class="location-heading"><h2 id="location-title" tabindex="-1">Лесные уступы</h2><span id="scene-height">Высота 1</span></div> <div class="location-heading"><h2 id="location-title" tabindex="-1">Лесные уступы</h2><span id="scene-height">Высота 1</span></div>
<div class="listen-controls">
<label class="check" for="simple-mode"><input id="simple-mode" type="checkbox"> Упрощённый режим</label>
<button id="replay-sound" type="button" disabled>Повторить звук</button>
</div>
<p id="transition-coordinates" class="scene-instructions">Вход: x1 y1 · Выход выбирается для новой попытки</p> <p id="transition-coordinates" class="scene-instructions">Вход: x1 y1 · Выход выбирается для новой попытки</p>
<p id="scene-instructions" class="scene-instructions">Клик по соседней клетке — прыжок. Правый клик — поставить или снять отметку.</p> <p id="scene-instructions" class="scene-instructions">Клик по соседней клетке — прыжок. Правый клик — поставить или снять отметку.</p>
<div class="scene" id="scene"> <div class="scene" id="scene">
@@ -53,20 +57,29 @@
</div> </div>
<p id="status" role="status" aria-atomic="true"></p> <p id="status" role="status" aria-atomic="true"></p>
</div> </div>
<p class="legend">↥ Вход / выход <span>· Проверено</span> <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">Минное поле</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 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><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> опасностей</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>
<p id="map-instructions" class="fineprint">Клетка карты только выбирается. Заметка не подтверждает опасность.</p> <p id="map-instructions" class="fineprint">Выберите клетку и поставьте оценку 0–7 кнопкой или клавишей. Ноль — рядом нет опасностей.</p>
<p id="map-selection">Выбрана x1 y1 · вход</p> <p id="map-selection">Выбрана x1 y1 · вход</p>
<p id="map-rating-status" class="visually-hidden" role="status" aria-atomic="true"></p>
<fieldset id="map-levels">
<legend>Ваша оценка</legend>
<div class="rating-buttons">
<button type="button" data-level="0" aria-label="Уровень 0: вокруг безопасно" aria-pressed="false">0</button>
<button type="button" data-level="1" aria-label="Уровень 1" aria-pressed="false">1</button><button type="button" data-level="2" aria-label="Уровень 2" aria-pressed="false">2</button><button type="button" data-level="3" aria-label="Уровень 3" aria-pressed="false">3</button><button type="button" data-level="4" aria-label="Уровень 4" aria-pressed="false">4</button><button type="button" data-level="5" aria-label="Уровень 5" aria-pressed="false">5</button><button type="button" data-level="6" aria-label="Уровень 6" aria-pressed="false">6</button><button type="button" data-level="7" aria-label="Уровень 7" aria-pressed="false">7</button>
</div>
<button id="map-clear-level" type="button">Убрать оценку</button>
</fieldset>
<button id="map-mark" type="button">Отметить опасной</button> <button id="map-mark" type="button">Отметить опасной</button>
<label class="check" for="project-marks"><input id="project-marks" type="checkbox" checked> Перенос на игровое поле</label> <label class="check" for="project-marks"><input id="project-marks" type="checkbox" checked> Перенос на игровое поле</label>
<button id="clear-marks" type="button" class="quiet">Очистить отметки</button> <button id="clear-marks" type="button" class="quiet">Очистить отметки</button>
@@ -96,14 +109,12 @@
<ul class="help-list"> <ul class="help-list">
<li>Вход всегда находится в x1 y1 — верхней левой клетке. X растёт вправо, Y — вниз. Выход выбирается случайно: на правом краю (x10, начиная с y2) или на нижнем (y6, начиная с x6). Стрелки отмечают переходы; в тренажёре по ним не прыгают.</li> <li>Вход всегда находится в x1 y1 — верхней левой клетке. X растёт вправо, Y — вниз. Выход выбирается случайно: на правом краю (x10, начиная с y2) или на нижнем (y6, начиная с x6). Стрелки отмечают переходы; в тренажёре по ним не прыгают.</li>
<li>Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. Безопасные клетки верхнего ряда начинаются сразу справа от входа: 5 на первой высоте и 3 на остальных. Идите по ним по одной.</li> <li>Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. Безопасные клетки верхнего ряда начинаются сразу справа от входа: 5 на первой высоте и 3 на остальных. Идите по ним по одной.</li>
<li>Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.</li> <li>После прыжка звучат короткие шорохи. Тишина означает нулевой уровень; число шорохов — уровень от 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>Отмеченная клетка закрыта для прыжка, пока вы не снимете отметку. Карта не показывает скрытые опасности. При ЛУ от 4 возможна подсказка «!»: координата останется в сообщениях.</li> <li>На «Минном поле» выберите клетку и поставьте свою оценку кнопкой или клавишей 0–7. Delete или Backspace снимает оценку. Оценка не мешает прыжкам и не влияет на победу. Отдельный флажок «Отметить опасной» закрывает клетку для прыжка. В упрощённом режиме при ЛУ от 4 возможна подсказка «!».</li>
<li>Победа: открыть все безопасные клетки, кроме переходов, или отметить все опасности без лишних отметок. Достижение выхода не завершает игру. Опасный прыжок заканчивается падением.</li> <li>Победа: открыть все безопасные клетки, кроме переходов, или отметить все опасности без лишних отметок. Достижение выхода не завершает игру. Опасный прыжок заканчивается падением.</li>
</ul> </ul>
<h3>Справочник звуков модели</h3>
<dl class="sound-guide"><div><dt>0</dt><dd>Звуков нет</dd></div><div><dt>1</dt><dd>Едва различимый шорох</dd></div><div><dt>2</dt><dd>Тихий шорох</dd></div><div><dt>3</dt><dd>Приглушённый шорох</dd></div><div><dt>4</dt><dd>Громкий шорох</dd></div><div><dt>5–8</dt><dd>Очень громкий шорох</dd></div></dl>
<div class="dialog-actions"><button type="button" data-close autofocus>Вернуться к тренировке</button></div> <div class="dialog-actions"><button type="button" data-close autofocus>Вернуться к тренировке</button></div>
</dialog> </dialog>
<dialog id="confirm-dialog" aria-labelledby="confirm-title"><h2 id="confirm-title">Начать заново?</h2><p id="confirm-text"></p><form method="dialog" class="dialog-actions"><button value="cancel" autofocus>Отмена</button><button value="confirm" class="primary" id="confirm-action">Начать новую игру</button></form></dialog> <dialog id="confirm-dialog" aria-labelledby="confirm-title"><h2 id="confirm-title">Начать заново?</h2><p id="confirm-text"></p><form method="dialog" class="dialog-actions"><button value="cancel" autofocus>Отмена</button><button value="confirm" class="primary" id="confirm-action">Начать новую игру</button></form></dialog>
+43
View File
@@ -0,0 +1,43 @@
// A training cue, not recorded CatWar audio: one short rustle per level.
export function rustleSamples(level, sampleRate) {
const step = Math.round(sampleRate * .23);
const pulse = Math.round(sampleRate * .095);
const samples = new Float32Array(step * level);
let seed = 521, filtered = 0;
for (let start = 0; start < samples.length; start += step) {
for (let i = 0; i < pulse; i++) {
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
filtered = .6 * filtered + .4 * (seed / 0x80000000 - 1);
samples[start + i] = .45 * filtered * Math.sin(Math.PI * i / pulse) ** 2;
}
}
return samples;
}
let context, source, request = 0;
export function stopSound() {
request++;
if (source) { source.stop(); source = null; }
}
export async function playSound(level) {
stopSound();
if (!level) return;
const id = request;
context ??= new AudioContext();
if (context.state !== 'running') await context.resume();
if (id !== request) return;
const samples = rustleSamples(level, context.sampleRate);
const buffer = context.createBuffer(1, samples.length, context.sampleRate);
buffer.copyToChannel(samples, 0);
const cue = context.createBufferSource();
cue.buffer = buffer;
cue.connect(context.destination);
cue.addEventListener('ended', () => {
cue.disconnect();
if (source === cue) source = null;
});
cue.start();
source = cue;
}
+15 -4
View File
@@ -61,6 +61,7 @@ export class Training {
#field; #field;
#opened = new Set(); #opened = new Set();
#marks = new Set(); #marks = new Set();
#ratings = new Map();
#position = START; #position = START;
#status = 'ready'; #status = 'ready';
#hit = null; #hit = null;
@@ -115,22 +116,32 @@ export class Training {
this.#win(); this.#win();
return {code: marked ? 'marked' : 'unmarked', id}; return {code: marked ? 'marked' : 'unmarked', id};
} }
rate(id, rating) {
const rejected = this.#guard(id);
if (rejected) return rejected;
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);
const code = rating === null ? 'unrated' : 'rated';
this.#history.push({type: code, id, rating});
return {code, id, rating};
}
clearMarks() { clearMarks() {
if (this.#finished()) return {code: 'finished'}; if (this.#finished()) return {code: 'finished'};
if (!this.#marks.size) return {code: 'empty'}; if (!this.#marks.size && !this.#ratings.size) return {code: 'empty'};
this.#marks.clear(); this.#history.push({type: 'cleared'}); this.#marks.clear(); this.#ratings.clear(); this.#history.push({type: 'cleared'});
return {code: 'cleared'}; return {code: 'cleared'};
} }
view() { view() {
const ended = this.#finished(); const ended = this.#finished();
return { return {
options: {...this.#options}, start: START, exit: this.#field.exit, status: this.#status, position: this.#position, hit: this.#hit, options: {...this.#options}, start: START, exit: this.#field.exit, status: this.#status, position: this.#position, hit: this.#hit,
hazards: this.#field.hazards.size, marks: this.#marks.size, opened: this.#opened.size, hazards: this.#field.hazards.size, marks: this.#marks.size, ratings: this.#ratings.size, opened: this.#opened.size,
safe: ROWS * COLS - 2 - this.#field.hazards.size, safe: ROWS * COLS - 2 - this.#field.hazards.size,
history: this.#history.map(item => ({...item})), history: this.#history.map(item => ({...item})),
cells: Array.from({length: ROWS * COLS}, (_,id) => ({ cells: Array.from({length: ROWS * COLS}, (_,id) => ({
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), 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: 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)} : {}),
+13 -4
View File
@@ -41,7 +41,7 @@ p + p { margin-top: 8px; }
.portrait { width: 84px; height: 84px; flex: 0 0 auto; background: var(--map); border-radius: 50%; border: 2px solid var(--paper); } .portrait { width: 84px; height: 84px; flex: 0 0 auto; background: var(--map); border-radius: 50%; border: 2px solid var(--paper); }
.portrait img { width: 100%; height: 100%; object-fit: contain; } .portrait img { width: 100%; height: 100%; object-fit: contain; }
.stats { margin: 0; } .stats { margin: 0; }
.stats > div, .sound-guide > div { display: flex; justify-content: space-between; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--border); } .stats > div { display: flex; justify-content: space-between; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--border); }
dd { margin: 0; text-align: right; font-weight: bold; } dd { margin: 0; text-align: right; font-weight: bold; }
.stats dt, .stats dd { font-size: var(--small); } .stats dt, .stats dd { font-size: var(--small); }
.fineprint { font-size: var(--small); color: var(--muted); } .fineprint { font-size: var(--small); color: var(--muted); }
@@ -50,6 +50,8 @@ dd { margin: 0; text-align: right; font-weight: bold; }
.location-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; padding: 12px 16px; } .location-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; padding: 12px 16px; }
.location-heading > span { font-size: var(--small); } .location-heading > span { font-size: var(--small); }
.scene-instructions { padding: 0 16px 12px; font-size: var(--small); } .scene-instructions { padding: 0 16px 12px; font-size: var(--small); }
.listen-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 16px; padding: 0 16px 12px; font-size: var(--small); }
.listen-controls .check { margin: 0; min-height: 44px; }
.scene { position: relative; aspect-ratio: 5 / 3; background: var(--map); isolation: isolate; } .scene { position: relative; aspect-ratio: 5 / 3; background: var(--map); isolation: isolate; }
.forest { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; } .forest { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; }
.cell-grid [role=row] { display: grid; grid-template-columns: repeat(10, minmax(0, 1fr)); } .cell-grid [role=row] { display: grid; grid-template-columns: repeat(10, minmax(0, 1fr)); }
@@ -69,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); }
.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; }
.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; }
.character-sprite img { position: absolute; width: 115%; height: 115%; object-fit: contain; filter: drop-shadow(0 2px 2px var(--ink)); } .character-sprite img { position: absolute; width: 115%; height: 115%; object-fit: contain; filter: drop-shadow(0 2px 2px var(--ink)); }
.character-sprite > span { border-radius: 50%; background: var(--map); color: var(--light); font-size: 10px; padding: 2px 4px; } .character-sprite > span { border-radius: 50%; background: var(--map); color: var(--light); font-size: 10px; padding: 2px 4px; }
@@ -98,6 +102,13 @@ input { accent-color: var(--map); }
.map-grid .marked button, .map-grid .hazard button { background: var(--danger); } .map-grid .marked button, .map-grid .hazard button { background: var(--danger); }
.map-grid .hint button { background: var(--active); color: var(--ink); } .map-grid .hint button { background: var(--active); color: var(--ink); }
#map-selection { margin: 12px 0; font-size: var(--small); } #map-selection { margin: 12px 0; font-size: var(--small); }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
#map-levels { min-width: 0; margin: 0 0 12px; padding: 8px; border: 1px solid var(--inner); }
#map-levels legend { padding: 0 4px; font-size: var(--small); }
.rating-buttons { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; }
.rating-buttons button { padding: 4px; }
.rating-buttons button[aria-pressed="true"] { background: var(--active); }
#map-clear-level { width: 100%; margin-top: 8px; }
#map-mark { width: 100%; } #map-mark { width: 100%; }
.check { display: flex; gap: 8px; align-items: center; font-size: var(--small); margin: 8px 0; min-height: 44px; cursor: pointer; } .check { display: flex; gap: 8px; align-items: center; font-size: var(--small); margin: 8px 0; min-height: 44px; cursor: pointer; }
.check input { width: 18px; height: 18px; flex-shrink: 0; } .check input { width: 18px; height: 18px; flex-shrink: 0; }
@@ -114,8 +125,6 @@ dialog p { margin: 12px 0; }
select { min-height: 44px; padding: 8px; width: 100%; } select { min-height: 44px; padding: 8px; width: 100%; }
.help-list { padding-left: 24px; } .help-list { padding-left: 24px; }
.help-list li { margin: 12px 0; } .help-list li { margin: 12px 0; }
.sound-guide { margin: 8px 0; }
.sound-guide dd { font-weight: normal; }
#panel-dialog:has(#map-body) { background: var(--map); color: var(--light); } #panel-dialog:has(#map-body) { background: var(--map); color: var(--light); }
#panel-dialog .map-grid button { min-height: 32px; } #panel-dialog .map-grid button { min-height: 32px; }
#history-empty { font-size: var(--small); } #history-empty { font-size: var(--small); }
@@ -171,6 +180,6 @@ select { min-height: 44px; padding: 8px; width: 100%; }
dialog { padding: 16px; } dialog { padding: 16px; }
footer { padding: 16px 12px; } footer { padding: 16px 12px; }
} }
@media (pointer: coarse) { .action-buttons button, .mobile-tools button, #map-mark { 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; } }
+107 -28
View File
@@ -1,10 +1,12 @@
import {Training, DEFAULTS, ROWS, COLS, START, coordinate, hintChance} from './engine.js'; import {Training, DEFAULTS, ROWS, COLS, START, coordinate, hintChance} from './engine.js';
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 mobile = matchMedia('(max-width: 700px)');
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 clock = null, startedAt = null, renderedHistory = 0, pendingConfirmation = null, panelReturn = null; let clock = null, startedAt = null, renderedHistory = 0, pendingConfirmation = null, panelReturn = null;
let panelOrigin = null, panelBody = null; let panelOrigin = null, panelBody = null;
const grids = []; const grids = [];
@@ -15,23 +17,45 @@ function addItem(list, text) {
} }
function sound(value) { return sounds[value] || 'Очень громкий шорох'; } function sound(value) { return sounds[value] || 'Очень громкий шорох'; }
function ended(view) { return view.status === 'won' || view.status === 'lost'; } function ended(view) { return view.status === 'won' || view.status === 'lost'; }
function describe(cell, view) { function simple() { return $('simple-mode').checked; }
function level(value) { return Math.min(7, value); }
function levelText(value) { return `Опасностей рядом: ${level(value)}${value >= 7 ? ' или больше' : ''}.`; }
function playCue(value) {
const attempt = game;
playSound(level(value)).catch(() => {
if (game === attempt && !simple()) $('status').textContent = 'Не удалось воспроизвести звук. Повторите попытку или включите упрощённый режим.';
});
}
function renderMessage(message) {
if (message.simpleOnly && !simple()) return;
const text = message.value === undefined ? message.text :
`${coordinate(message.id)} · ${simple() ? `${sound(message.value)}. ${levelText(message.value)}` : message.value ? 'Прозвучал сигнал.' : 'Звуков нет.'}`;
addItem($('messages'), text);
}
function recordMessage(message) {
messages.push(message);
renderMessage(message);
}
function describe(cell, view, showNotes = true, isMap = false) {
if (cell.entrance) return 'вход'; if (cell.entrance) return 'вход';
if (cell.exit) return 'выход'; if (cell.exit) return 'выход';
if (cell.wrong) return 'ошибочная отметка, безопасно'; const rating = showNotes && cell.rating !== null ? `, ваша оценка ${cell.rating}` : '';
if (cell.hazard) return 'опасная клетка'; if (cell.wrong) return `ошибочная отметка, безопасно${rating}`;
if (cell.opened) return `проверено, опасностей рядом: ${cell.value}${cell.available ? ', прыжок доступен' : ''}`; if (cell.hazard) return `опасная клетка${rating}`;
if (ended(view)) return `безопасная клетка, опасностей рядом: ${cell.value}`; if (cell.opened || ended(view)) {
if (cell.marked) return 'ваша отметка опасности'; const fact = simple() || ended(view) ? `, ${levelText(cell.value).slice(0, -1).toLowerCase()}` : '';
if (hints.has(cell.id)) return 'подсказка: опасность'; return `${cell.opened ? 'проверено' : 'безопасная клетка'}${fact}${rating}${!isMap && cell.available ? ', прыжок доступен' : ''}`;
return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, не рядом с персонажем'; }
if (cell.marked && showNotes) return `ваш флажок опасности${rating}`;
if (hints.has(cell.id)) return `подсказка: опасность${rating}`;
return `неизвестно${rating}${isMap ? '' : cell.available ? ', прыжок доступен' : ', не рядом с персонажем'}`;
} }
function cellValue(cell, view, showMarks) { function cellValue(cell, view, showMarks) {
if (cell.transition) return cell.entrance ? '↥' : '↗'; if (cell.transition) return cell.entrance ? '↥' : '↗';
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 '⚑';
if (cell.opened || ended(view)) return cell.value || '·'; if (cell.opened || ended(view)) return simple() || ended(view) ? level(cell.value) : '·';
if (hints.has(cell.id)) return '!'; if (hints.has(cell.id)) return '!';
return ''; return '';
} }
@@ -39,6 +63,7 @@ function selectCell(id) {
if (id === selected) return; if (id === selected) return;
selected = id; selected = id;
$('status').textContent = ''; $('status').textContent = '';
$('map-rating-status').textContent = '';
render(); render();
} }
function makeGrid(id, isMap) { function makeGrid(id, isMap) {
@@ -50,17 +75,19 @@ function makeGrid(id, isMap) {
const cell = document.createElement('div'); cell.setAttribute('role', 'gridcell'); cell.setAttribute('aria-colindex', c + 1); const cell = document.createElement('div'); cell.setAttribute('role', 'gridcell'); cell.setAttribute('aria-colindex', c + 1);
const button = document.createElement('button'); button.type = 'button'; button.dataset.id = index; button.tabIndex = index === START ? 0 : -1; const button = document.createElement('button'); button.type = 'button'; button.dataset.id = index; button.tabIndex = index === START ? 0 : -1;
const value = document.createElement('span'); value.className = 'cell-value'; value.setAttribute('aria-hidden', 'true'); const value = document.createElement('span'); value.className = 'cell-value'; value.setAttribute('aria-hidden', 'true');
const rating = document.createElement('span'); rating.className = 'cell-rating'; rating.setAttribute('aria-hidden', 'true'); rating.hidden = true;
if (!isMap) { if (!isMap) {
const label = document.createElement('span'); label.className = 'cell-coord'; label.textContent = coordinate(index); label.setAttribute('aria-hidden', 'true'); button.append(label); const label = document.createElement('span'); label.className = 'cell-coord'; label.textContent = coordinate(index); label.setAttribute('aria-hidden', 'true'); button.append(label);
} }
button.append(value); cell.append(button); row.append(cell); cells.push(cell); buttons.push(button); button.append(value, rating); cell.append(button); row.append(cell); cells.push(cell); buttons.push(button);
} }
root.append(row); root.append(row);
} }
root.addEventListener('click', event => { root.addEventListener('click', event => {
const button = event.target.closest('button[data-id]'); if (!button) return; const button = event.target.closest('button[data-id]'); if (!button) return;
selectCell(Number(button.dataset.id)); selectCell(Number(button.dataset.id));
if (!isMap && (!compact.matches || event.detail === 0)) act('jump'); if (isMap) button.focus({preventScroll:true});
else if (!compact.matches || event.detail === 0) act('jump');
}); });
root.addEventListener('contextmenu', event => { root.addEventListener('contextmenu', event => {
const button = event.target.closest('button[data-id]'); if (!button) return; const button = event.target.closest('button[data-id]'); if (!button) return;
@@ -75,6 +102,14 @@ function makeGrid(id, isMap) {
root.addEventListener('keydown', event => { root.addEventListener('keydown', event => {
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || !buttons.includes(event.target)) return; if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || !buttons.includes(event.target)) return;
const from = event.target, index = Number(from.dataset.id); const from = event.target, index = Number(from.dataset.id);
if (isMap && !event.shiftKey && (/^[0-7]$/.test(event.key) || ['Delete','Backspace'].includes(event.key))) {
event.preventDefault();
if (!event.repeat) {
selectCell(index);
rateCell(/^[0-7]$/.test(event.key) ? Number(event.key) : null);
}
return;
}
if (event.shiftKey) { if (event.shiftKey) {
if (!isMap && event.key === 'Enter') { if (!isMap && event.key === 'Enter') {
event.preventDefault(); event.preventDefault();
@@ -113,16 +148,22 @@ function updateClock() {
const seconds = startedAt === null ? 0 : Math.floor((Date.now() - startedAt) / 1000); const seconds = startedAt === null ? 0 : Math.floor((Date.now() - startedAt) / 1000);
$('timer').textContent = `${String(Math.floor(seconds / 60)).padStart(2,'0')}:${String(seconds % 60).padStart(2,'0')}`; $('timer').textContent = `${String(Math.floor(seconds / 60)).padStart(2,'0')}:${String(seconds % 60).padStart(2,'0')}`;
} }
function stopTimers() { function clearHints() {
clearInterval(clock); clock = null;
for (const timer of hintTimers.values()) clearTimeout(timer); for (const timer of hintTimers.values()) clearTimeout(timer);
hintTimers.clear(); hints.clear(); hintTimers.clear(); hints.clear();
} }
function stopTimers() {
clearInterval(clock); clock = null;
clearHints();
stopSound();
}
function start(options = DEFAULTS) { function start(options = DEFAULTS) {
stopTimers(); game = new Training(options); selected = START; startedAt = null; renderedHistory = 0; stopTimers(); game = new Training(options); selected = START; startedAt = null; renderedHistory = 0;
$('history').replaceChildren(); $('messages').replaceChildren(); $('history').replaceChildren(); $('messages').replaceChildren();
addItem($('messages'), 'Лес затих. Звуки появятся после прыжка.'); messages = [];
recordMessage({text:'Лес затих. Сигнал появится после прыжка.'});
$('status').textContent = ''; $('status').textContent = '';
$('map-rating-status').textContent = '';
updateClock(); render(); updateClock(); render();
} }
function render() { function render() {
@@ -130,12 +171,16 @@ function render() {
for (const {cells, buttons, isMap} of grids) { for (const {cells, buttons, isMap} of grids) {
for (const cell of view.cells) { for (const cell of view.cells) {
const node = cells[cell.id], button = buttons[cell.id]; const node = cells[cell.id], button = buttons[cell.id];
const projectedMark = cell.marked && (isMap || projection); const showNotes = isMap || projection;
node.className = [cell.opened && 'opened', projectedMark && 'marked', cell.available && !cell.transition && 'available', cell.transition && 'transition', cell.entrance && 'entrance', cell.exit && 'exit', cell.hazard && 'hazard', cell.wrong && 'wrong', cell.id === selected && 'selected', cell.id === view.position && 'current', hints.has(cell.id) && !finished && 'hint'].filter(Boolean).join(' '); const projectedMark = cell.marked && showNotes, rated = cell.rating !== null && showNotes;
node.className = [cell.opened && 'opened', projectedMark && 'marked', rated && 'rated', cell.available && !cell.transition && 'available', cell.transition && 'transition', cell.entrance && 'entrance', cell.exit && 'exit', cell.hazard && 'hazard', cell.wrong && 'wrong', cell.id === selected && 'selected', cell.id === view.position && 'current', hints.has(cell.id) && !finished && 'hint'].filter(Boolean).join(' ');
node.setAttribute('aria-selected', String(cell.id === selected)); node.setAttribute('aria-selected', String(cell.id === selected));
button.tabIndex = cell.id === selected ? 0 : -1; button.tabIndex = cell.id === selected ? 0 : -1;
button.querySelector('.cell-value').textContent = cellValue(cell, view, isMap || projection); button.querySelector('.cell-value').textContent = cellValue(cell, view, showNotes);
button.setAttribute('aria-label', `${coordinate(cell.id)}: ${describe(cell, view)}${cell.id === view.position ? ', персонаж здесь' : ''}`); const rating = button.querySelector('.cell-rating');
rating.hidden = !rated;
rating.textContent = rated ? cell.rating : '';
button.setAttribute('aria-label', `${coordinate(cell.id)}: ${describe(cell, view, showNotes, isMap)}${cell.id === view.position ? ', персонаж здесь' : ''}`);
} }
} }
$('character').style.left = `${view.position % COLS * 10}%`; $('character').style.left = `${view.position % COLS * 10}%`;
@@ -146,9 +191,12 @@ function render() {
$('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]; $('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]; $('growth-value').textContent = {12:'45–75%',15:'76–85%',18:'81–88%',22:'89–95%',25:'96–100%'}[view.options.growth];
$('hint-chance').textContent = `${Math.round(hintChance(view.options.lu) * 100)}%`; $('hint-chance').textContent = simple() ? `${Math.round(hintChance(view.options.lu) * 100)}%` : 'Выкл.';
$('replay-sound').disabled = finished || simple() || !view.cells[view.position].value;
$('sound-guide').textContent = simple() ? 'Число показывает опасности вокруг клетки, включая диагонали. 7 означает семь или больше.' : 'После прыжка прислушайтесь к шорохам и оцените клетку на карте.';
$('progress').textContent = `${view.opened} / ${view.safe}`; $('progress').textContent = `${view.opened} / ${view.safe}`;
$('mark-count').textContent = view.marks; $('hazard-count').textContent = view.hazards; $('mark-count').textContent = view.marks; $('hazard-count').textContent = view.hazards;
$('rating-count').textContent = view.ratings;
$('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status]; $('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status];
$('scene-instructions').textContent = compact.matches ? 'Коснитесь клетки, затем выберите действие под полем.' : 'Клик по соседней клетке — прыжок. Правый клик или Shift+Enter — поставить или снять отметку.'; $('scene-instructions').textContent = compact.matches ? 'Коснитесь клетки, затем выберите действие под полем.' : 'Клик по соседней клетке — прыжок. Правый клик или Shift+Enter — поставить или снять отметку.';
const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной'; const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной';
@@ -157,14 +205,17 @@ function render() {
!cell.available ? 'вне досягаемости' : ''; !cell.available ? 'вне досягаемости' : '';
$('touch-actions').hidden = !compact.matches; $('touch-actions').hidden = !compact.matches;
$('selection').textContent = `Клетка ${coordinate(selected)}${selectionState ? ` — ${selectionState}` : ''}`; $('selection').textContent = `Клетка ${coordinate(selected)}${selectionState ? ` — ${selectionState}` : ''}`;
$('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view)}`; $('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view, true, true)}`;
$('mark').textContent = note; $('map-mark').textContent = note; $('mark').textContent = note; $('map-mark').textContent = note;
$('jump').disabled = finished || !cell.available || cell.marked; $('jump').disabled = finished || !cell.available || cell.marked;
for (const id of ['mark','map-mark']) $(id).disabled = finished || cell.opened || cell.transition; for (const id of ['mark','map-mark']) $(id).disabled = finished || cell.opened || cell.transition;
$('clear-marks').disabled = finished || view.marks === 0; $('map-levels').disabled = finished || cell.transition;
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);
$('history-empty').hidden = view.history.length > 0; $('history-empty').hidden = view.history.length > 0;
for (const entry of view.history.slice(renderedHistory)) { for (const entry of view.history.slice(renderedHistory)) {
const text = entry.type === 'cleared' ? 'Все заметки очищены; открытые клетки сохранены.' : `${coordinate(entry.id)} · ${{opened:'Прыжок',revisited:'Повторный прыжок',fall:'Падение',marked:'Поставлена отметка',unmarked:'Снята отметка'}[entry.type]}${entry.value !== undefined ? ` · рядом ${entry.value}` : ''}`; const text = entry.type === 'cleared' ? 'Все заметки очищены; открытые клетки сохранены.' : `${coordinate(entry.id)} · ${{opened:'Прыжок',revisited:'Повторный прыжок',fall:'Падение',marked:'Поставлена отметка',unmarked:'Снята отметка',rated:`Ваша оценка: ${entry.rating}`,unrated:'Оценка снята'}[entry.type]}${simple() && entry.value !== undefined ? ` · ${levelText(entry.value)}` : ''}`;
addItem($('history'), text); addItem($('history'), text);
} }
renderedHistory = view.history.length; renderedHistory = view.history.length;
@@ -172,24 +223,24 @@ function render() {
if (finished) $('result').textContent = view.status === 'won' ? 'Карта готова! Условие победы выполнено. Поле раскрыто — можно изучить результат или начать новую игру.' : `Падение на ${coordinate(view.hit)}. Попытка завершена, поле раскрыто. Знак ≠ показывает ошибочную отметку. Попробуйте ещё раз.`; if (finished) $('result').textContent = view.status === 'won' ? 'Карта готова! Условие победы выполнено. Поле раскрыто — можно изучить результат или начать новую игру.' : `Падение на ${coordinate(view.hit)}. Попытка завершена, поле раскрыто. Знак ≠ показывает ошибочную отметку. Попробуйте ещё раз.`;
} }
function act(action) { function act(action) {
const result = action === 'jump' ? game.jump(selected) : game.mark(selected); const result = action === 'jump' ? game.jump(selected, simple() ? Math.random : () => 1) : game.mark(selected);
const view = game.view(); const view = game.view();
let text; let text;
if (action === 'jump' && ['opened','revisited'].includes(result.code)) { if (action === 'jump' && ['opened','revisited'].includes(result.code)) {
text = `Опасностей рядом: ${result.value}.`; text = simple() ? levelText(result.value) : result.value ? 'Прислушайтесь к звуку.' : 'Звуков нет.';
addItem($('messages'), `${coordinate(selected)} · ${sound(result.value)}. ${text}`); recordMessage({id:selected, value:result.value});
if (startedAt === null) { startedAt = Date.now(); clock = setInterval(updateClock,1000); } if (startedAt === null) { startedAt = Date.now(); clock = setInterval(updateClock,1000); }
if (result.hint !== null) { if (result.hint !== null) {
clearTimeout(hintTimers.get(result.hint)); clearTimeout(hintTimers.get(result.hint));
hints.add(result.hint); hints.add(result.hint);
const hintText = `Подсказка: ${coordinate(result.hint)} — опасная клетка. Значок «!» виден 2 секунды; координата остаётся здесь.`; const hintText = `Подсказка: ${coordinate(result.hint)} — опасная клетка. Значок «!» виден 2 секунды; координата остаётся здесь.`;
addItem($('messages'), hintText); text += ` Подсказка: ${coordinate(result.hint)} — опасная клетка.`; recordMessage({text:hintText, simpleOnly:true}); text += ` Подсказка: ${coordinate(result.hint)} — опасная клетка.`;
const attempt = game; const attempt = game;
const timer = setTimeout(() => { hintTimers.delete(result.hint); if (game === attempt) { hints.delete(result.hint); render(); } },2000); const timer = setTimeout(() => { hintTimers.delete(result.hint); if (game === attempt) { hints.delete(result.hint); render(); } },2000);
hintTimers.set(result.hint, timer); hintTimers.set(result.hint, timer);
} }
} else if (result.code === 'fall') { } else if (result.code === 'fall') {
addItem($('messages'), `Падение на ${coordinate(selected)}. Попытка завершена.`); recordMessage({text:`Падение на ${coordinate(selected)}. Попытка завершена.`});
text = 'Падение. Попытка завершена.'; text = 'Падение. Попытка завершена.';
} else { } else {
text = {finished:'Попытка завершена.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Выберите соседнюю клетку для прыжка.',marked: action === 'jump' ? 'Сначала снимите отметку с этой клетки.' : 'Отметка поставлена.',unmarked:'Отметка снята.',opened:'Проверенную клетку нельзя отметить опасной.'}[result.code]; text = {finished:'Попытка завершена.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Выберите соседнюю клетку для прыжка.',marked: action === 'jump' ? 'Сначала снимите отметку с этой клетки.' : 'Отметка поставлена.',unmarked:'Отметка снята.',opened:'Проверенную клетку нельзя отметить опасной.'}[result.code];
@@ -197,6 +248,17 @@ function act(action) {
if (ended(view)) { if (clock !== null) updateClock(); stopTimers(); } if (ended(view)) { if (clock !== null) updateClock(); stopTimers(); }
if (view.status === 'won') text += ' Карта готова!'; if (view.status === 'won') text += ' Карта готова!';
$('status').textContent = text; render(); $('status').textContent = text; render();
if (!ended(view) && !simple() && result.value !== undefined) playCue(result.value);
}
function rateCell(rating) {
const result = game.rate(selected, rating);
if (result.code === 'rated' || result.code === 'unrated') {
$('map-rating-status').textContent = `${coordinate(selected)}: ${rating === null ? 'оценка снята' : `ваша оценка ${rating}`}.`;
render();
}
if (rating === null && document.activeElement === $('map-clear-level') && result.code === 'unrated') {
$('map-grid').querySelector(`button[data-id="${selected}"]`).focus();
}
} }
function showDialog(dialog, opener) { function showDialog(dialog, opener) {
dialog._opener = opener; dialog._opener = opener;
@@ -248,7 +310,24 @@ $('settings-form').addEventListener('submit', event => {
$('settings-dialog').close(); start(options); $('settings-dialog').close(); start(options);
}); });
$('new-game').addEventListener('click', event => confirmAction('Начать заново?', 'Текущее поле, заметки и история будут сброшены. Условия тренировки сохранятся.', 'Начать новую игру', () => start(game.view().options), event.currentTarget)); $('new-game').addEventListener('click', event => confirmAction('Начать заново?', 'Текущее поле, заметки и история будут сброшены. Условия тренировки сохранятся.', 'Начать новую игру', () => start(game.view().options), event.currentTarget));
$('clear-marks').addEventListener('click', event => confirmAction('Очистить отметки?', 'Удалятся только ваши заметки. Проверенные клетки, история и текущая попытка сохранятся.', 'Очистить отметки', () => { game.clearMarks(); $('status').textContent = 'Отметки очищены. Попытка продолжается.'; render(); }, event.currentTarget)); $('clear-marks').addEventListener('click', event => confirmAction('Очистить отметки?', 'Удалятся ваши флажки и оценки. Проверенные клетки, история и текущая попытка сохранятся.', 'Очистить отметки', () => { game.clearMarks(); $('status').textContent = 'Отметки очищены. Попытка продолжается.'; render(); }, event.currentTarget));
$('simple-mode').addEventListener('change', () => {
stopSound(); clearHints();
$('status').textContent = simple() ? 'Упрощённый режим: уровни видны на проверенных клетках.' : 'Звуковой режим: оцените клетку по шорохам.';
$('messages').replaceChildren(); messages.forEach(renderMessage);
$('history').replaceChildren(); renderedHistory = 0;
render();
});
$('replay-sound').addEventListener('click', () => {
const view = game.view();
$('status').textContent = 'Прислушайтесь к звуку.';
playCue(view.cells[view.position].value);
});
$('map-levels').addEventListener('click', event => {
const button = event.target.closest('button[data-level]');
if (button) rateCell(Number(button.dataset.level));
});
$('map-clear-level').addEventListener('click', () => rateCell(null));
$('project-marks').addEventListener('change', render); $('project-marks').addEventListener('change', render);
$('jump').addEventListener('click', () => act('jump')); $('jump').addEventListener('click', () => act('jump'));
$('mark').addEventListener('click', () => act('mark')); $('mark').addEventListener('click', () => act('mark'));