fix: anchor trainer entrance and generate variable exits

This commit is contained in:
nyan404 committed 2026-11-17 16:44:04 +03:00
1 parent 30d012de80
commit 87a9a5934a
12 files changed
+117 -53

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@
- Public report lookup is `GET /api/reports?character_id=<cat ID>`; it searches saved report participant IDs, returns at most 100 newest rows without `actor_id`, and is covered by `tests/test_report_lookup.py`. VK `/мои-отчёты` uses the callback sender ID and the same history store; validate with `python -m unittest tests.test_report_lookup tests.test_history tests.test_vk_bot -q`. - Public report lookup is `GET /api/reports?character_id=<cat ID>`; it searches saved report participant IDs, returns at most 100 newest rows without `actor_id`, and is covered by `tests/test_report_lookup.py`. VK `/мои-отчёты` uses the callback sender ID and the same history store; validate with `python -m unittest tests.test_report_lookup tests.test_history tests.test_vk_bot -q`.
## 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, eight-neighbor availability relative to any opened cell, and transition cells outside victory counts. 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, eight-neighbor availability relative to any opened cell, and transition cells outside victory counts. Entrance is fixed at x1 y1 (top-left); exit belongs to each generated field and may be any other cell. 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 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.
+4
View File
@@ -4,6 +4,10 @@
Текущая реализация: `/trainer` и `/trainer/`, файлы из таблицы ниже, оригинальные изображения с происхождением в `web/lu-trainer/assets/README.md`. Поддерживаются параметры, прыжки, подсказки, победа/падение, синхронная карта заметок, история и адаптивное управление. Проверки и их границы записаны в `structure_and_data.md`. Подробный текст ниже сохраняет основания первоначального проекта; историческое ограничение «только документация» относилось к предыдущему этапу. Текущая реализация: `/trainer` и `/trainer/`, файлы из таблицы ниже, оригинальные изображения с происхождением в `web/lu-trainer/assets/README.md`. Поддерживаются параметры, прыжки, подсказки, победа/падение, синхронная карта заметок, история и адаптивное управление. Проверки и их границы записаны в `structure_and_data.md`. Подробный текст ниже сохраняет основания первоначального проекта; историческое ограничение «только документация» относилось к предыдущему этапу.
## Уточнение владельца о переходах — 2026-11-17
Владелец уточнил: «вход всегда на клетке x1 y1, выход может быть в разных местах». Это заменяет координаты переходов из исходного тренажёра в текущей реализации. `x1 y1` отображается в верхней левой клетке; X растёт вправо, Y — вниз. Генератор выбирает выход для каждой новой попытки из остальных 59 клеток — это способ реализации вариативности, а не подтверждённое распределение выходов в CatWar. Пять/три начальные безопасные клетки сохранены отдельно от переходов. Состояние попытки хранит координаты входа/выхода; локация, карта, справка и сообщения используют их совместно. Наблюдения об исходнике ниже остаются историческими.
## Цель и подтверждённый объём ## Цель и подтверждённый объём
Сделать тренажёр лазания на основе идеи `tek1laa/catwar-lu-trainer`, визуально и по расположению элементов приблизив его к игровому экрану CatWar. Главный ориентир — скриншот владельца, а не оформление текущего калькулятора Белок. Сделать тренажёр лазания на основе идеи `tek1laa/catwar-lu-trainer`, визуально и по расположению элементов приблизив его к игровому экрану CatWar. Главный ориентир — скриншот владельца, а не оформление текущего калькулятора Белок.
+2
View File
@@ -1,5 +1,7 @@
# MEMORY # MEMORY
- 2026-11-17 owner correction: «вход всегда на клетке x1 y1, выход может быть в разных местах». This supersedes upstream-derived fixed transition positions. Entrance is now index 0; each field owns its exit. UI labels use one-based X right/Y down with x1 y1 top-left. Random selection from the other 59 cells is the implementation choice for variable exits, not a verified CatWar distribution. Keep 5/3 initial safe cells separate from transitions and keep scene/map synchronized after restart.
- 2026-11-17: CI Python 3.12 slim returns `(None, None)` for `mimetypes.guess_type("forest.webp")`; WebP is only in its non-strict common table without system MIME data. `Handler._file` now explicitly serves `.webp` as `image/webp`, independent of host MIME tables. HTTP regression coverage simulates an absent mapping; retain it when modifying static serving. - 2026-11-17: CI Python 3.12 slim returns `(None, None)` for `mimetypes.guess_type("forest.webp")`; WebP is only in its non-strict common table without system MIME data. `Handler._file` now explicitly serves `.webp` as `image/webp`, independent of host MIME tables. HTTP regression coverage simulates an absent mapping; retain it when modifying static serving.
- 2026-11-17: owner renamed the trainer public page to `/trainer` (also `/trainer/`). Homepage navigation, Python/Nginx page aliases and browser entry URLs follow that address. Internal `web/lu-trainer.html` and `/lu-trainer/` asset URLs are unchanged; the prior `/lu-trainer` page address below is historical. No push/deployment. - 2026-11-17: owner renamed the trainer public page to `/trainer` (also `/trainer/`). Homepage navigation, Python/Nginx page aliases and browser entry URLs follow that address. Internal `web/lu-trainer.html` and `/lu-trainer/` asset URLs are unchanged; the prior `/lu-trainer` page address below is historical. No push/deployment.
+2
View File
@@ -47,6 +47,8 @@ python3 -m app.belki.vk_bot
На компьютере клик по локации выполняет выбранный «Прыжок» или «Опасная»; правая кнопка ставит/снимает заметку. На телефоне касание сначала выбирает клетку, затем действие подтверждается отдельной крупной кнопкой. На обеих сетках доступны стрелки, Home / End, Enter и пробел. «Минное поле» выбирает клетку для заметки и автоматически показывает результаты прыжков. «Перенос на игровое поле» меняет только видимость заметок на локации. Очистка заметок и новая игра имеют разные подтверждения. На компьютере клик по локации выполняет выбранный «Прыжок» или «Опасная»; правая кнопка ставит/снимает заметку. На телефоне касание сначала выбирает клетку, затем действие подтверждается отдельной крупной кнопкой. На обеих сетках доступны стрелки, Home / End, Enter и пробел. «Минное поле» выбирает клетку для заметки и автоматически показывает результаты прыжков. «Перенос на игровое поле» меняет только видимость заметок на локации. Очистка заметок и новая игра имеют разные подтверждения.
Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Выход выбирается заново для каждой попытки из остальных клеток. Оба перехода безопасны, их координаты показаны над локацией и совпадают с картой. Пять начальных безопасных клеток на высоте 1 и три выше находятся в верхней строке, не считая переходов.
Победа — все безопасные клетки, кроме переходов, либо все опасности без лишних отметок. Падение завершает попытку. Настройки высоты, ЛУ, сезона и роста применяются явным началом новой игры. Это модель описанного исходного тренажёра, а не подтверждённые правила CatWar. Оригинальные изображения и промпты перечислены в `web/lu-trainer/assets/README.md`; код и изображения исходного тренажёра не переносились. Победа — все безопасные клетки, кроме переходов, либо все опасности без лишних отметок. Падение завершает попытку. Настройки высоты, ЛУ, сезона и роста применяются явным началом новой игры. Это модель описанного исходного тренажёра, а не подтверждённые правила CatWar. Оригинальные изображения и промпты перечислены в `web/lu-trainer/assets/README.md`; код и изображения исходного тренажёра не переносились.
Страница раздаётся и `app.main`, и Nginx gateway. Для изолированных проверок используйте временные SQLite-пути по инструкции в `AGENTS.md`, затем: Страница раздаётся и `app.main`, и Nginx gateway. Для изолированных проверок используйте временные SQLite-пути по инструкции в `AGENTS.md`, затем:
+4 -2
View File
@@ -4,11 +4,13 @@ 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/radios/dialogs, CSS tokens, Verdana/Georgia, Russian copy, DOM-independent ES-module engine, no upstream code or asset copying. convention: native buttons/radios/dialogs, CSS tokens, Verdana/Georgia, Russian copy, DOM-independent ES-module engine, no upstream code or asset copying.
state: engine owns 60 cells, hazards, opened set, marks set, last successful position, ready/playing/won/lost status and action log. A public snapshot omits hidden hazards/values. UI owns selection, action mode, map visibility and mark projection. state: engine owns 60 cells, per-attempt start/exit identities, hazards, opened set, marks set, last successful position, ready/playing/won/lost status and action log. A public snapshot omits hidden hazards/values. UI owns selection, action mode, map visibility and mark projection.
invariant: 6x10, entrance (5,0), exit (3,9); transition cells do not count toward victory and cannot be opened/marked. Top-row first 5/3 cells are safe and initially available; any other cell requires an opened neighbor. 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 any of the other 59 cells; transition cells do not count toward victory and cannot be opened/marked. The first 5/3 top-row non-transition cells are safe and initially available; any other cell requires an opened neighbor. 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.
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, audio, 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 correction 2026-11-17: entrance fixed x1 y1, exit variable. Uniform random placement is an implementation choice, not a verified game distribution. Coordinates are one-based X right/Y down. Tests cover every possible exit position, safe-route connectivity and matching transition labels on both grids after regeneration.
+1
View File
@@ -14,6 +14,7 @@ mindmap
Minefield companion map Minefield companion map
Shared attempt state and action history Shared attempt state and action history
Client-side rules independent of Belki Client-side rules independent of Belki
Fixed entrance x1 y1 and per-attempt variable exit
engine.js — generation and training rules engine.js — generation and training rules
ui.js — public snapshots and two grids ui.js — public snapshots and two grids
Original generated forest and cat assets Original generated forest and cat assets
+6
View File
@@ -1,5 +1,11 @@
# Structure and Data # Structure and Data
## Trainer entrance and variable exit — 2026-11-17
- Applied the owner correction: entrance always `x1 y1`, exit can vary. `engine.js` sets start index 0 and chooses an exit per field from the other 59 cells. The fixed global exit constant is removed; `view()` exposes transition coordinates and per-cell entrance/exit flags. The generator reserves both transitions and a safe connecting path, preserving hazard formulas and 5/3 initially playable safe cells in the top row excluding transitions.
- One-based coordinates use X right/Y down and x1 y1 at the top-left. Random placement implements variability; its distribution and allowed positions are not independently verified CatWar rules. `ui.js` uses snapshot flags for both grids, arrows, selection labels and logs; current transition coordinates are shown above the scene. HTML help and regression fixtures no longer hard-code the upstream positions. No route, runtime dependency or server change.
- Validation passed: 10 Node model tests (all 59 exit positions, all 75 setting combinations, generation and victory invariants), 4 Python trainer HTTP tests, JS syntax and diff checks; Chromium scenarios at 1920/1366/768/390 widths including regenerated transition identities, XY labels, keyboard/touch, hints/timers and image fallback. Desktop/mobile screenshots were inspected. No new UI patterns were needed after the modern-web-guidance grid-label search. Remote test-zone/token-optimizer MCP are unavailable. The isolated server was stopped and temporary venv/data/screenshots removed. No push/deployment.
## Portable WebP MIME response — 2026-11-17 ## Portable WebP MIME response — 2026-11-17
- Reproduced the reported CI mismatch in stock `python:3.12-slim` (Python 3.12.16): strict `mimetypes.guess_type("forest.webp")` returns `(None, None)` while the non-strict common table contains `image/webp`. The workstation MIME database masked this during the original checks. - Reproduced the reported CI mismatch in stock `python:3.12-slim` (Python 3.12.16): strict `mimetypes.guess_type("forest.webp")` returns `(None, None)` while the non-strict common table contains `image/webp`. The workstation MIME database masked this during the original checks.
+27 -14
View File
@@ -10,8 +10,12 @@ const shotDir = process.env.BELKI_SCREENSHOT_DIR;
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; }; }
async function run() { async function run() {
const {generateField, DEFAULTS} = 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());
const [first, second, note] = field.base;
const hintCell = field.base.find(id => field.values[id] > 0);
assert.notEqual(hintCell, undefined);
const hintText = `Подсказка: ${coordinate(neighbors(hintCell).find(id => field.hazards.has(id)))}`;
const browser = await chromium.launch({headless:true, ...(process.env.CHROMIUM_PATH ? {executablePath:process.env.CHROMIUM_PATH} : {})}); const browser = await chromium.launch({headless:true, ...(process.env.CHROMIUM_PATH ? {executablePath:process.env.CHROMIUM_PATH} : {})});
const captures = []; const captures = [];
try { try {
@@ -37,6 +41,13 @@ async function run() {
const noOverflow = async () => assert(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth),`overflow at ${width}`); const noOverflow = async () => assert(await page.evaluate(()=>document.documentElement.scrollWidth <= innerWidth),`overflow at ${width}`);
const select = async id => { await scene(id).click(); if (width === 390) await page.locator('#jump').click(); }; const select = async id => { await scene(id).click(); if (width === 390) await page.locator('#jump').click(); };
await noOverflow(); await noOverflow();
assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: вход, персонаж здесь$/);
for (const grid of ['scene-grid','map-grid']) {
assert.equal(await page.locator(`#${grid} .entrance button`).getAttribute('data-id'),'0');
assert.equal(await page.locator(`#${grid} .exit button`).getAttribute('data-id'),String(field.exit));
}
assert.match(await page.locator('#transition-coordinates').textContent(), /Вход: x1 y1/);
assert((await page.locator('#transition-coordinates').textContent()).includes(`Выход: ${coordinate(field.exit)}`));
assert.equal(await page.locator('#scene-grid .hazard').count(),0); assert.equal(await page.locator('#scene-grid .hazard').count(),0);
assert.equal(await page.locator('#scene-grid .opened').count(),0); assert.equal(await page.locator('#scene-grid .opened').count(),0);
// Modal help must not modify the field, and Escape must restore focus. // Modal help must not modify the field, and Escape must restore focus.
@@ -45,20 +56,20 @@ async function run() {
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
assert(await page.locator('#help-open').evaluate(n=>n===document.activeElement)); assert(await page.locator('#help-open').evaluate(n=>n===document.activeElement));
if (width === 390) { if (width === 390) {
await scene(0).tap(); await scene(first).tap();
assert.equal(await page.locator('#scene-grid .opened').count(),0,'touch overview must only select'); assert.equal(await page.locator('#scene-grid .opened').count(),0,'touch overview must only select');
const box = await page.locator('#jump').boundingBox(); assert(box.height >= 44 && box.width >= 44); const box = await page.locator('#jump').boundingBox(); assert(box.height >= 44 && box.width >= 44);
await page.locator('#jump').tap(); await page.locator('#jump').tap();
} else await select(0); } else await select(first);
assert.equal(await page.locator('#scene-grid .opened').count(),1); assert.equal(await page.locator('#scene-grid .opened').count(),1);
assert.equal(await page.locator('#map-grid .opened').count(),1); assert.equal(await page.locator('#map-grid .opened').count(),1);
assert.equal(await page.locator('#history li').count(),1); assert.equal(await page.locator('#history li').count(),1);
assert.match(await scene(0).getAttribute('aria-label'),/персонаж здесь/); assert.match(await scene(first).getAttribute('aria-label'),/персонаж здесь/);
assert.match(await page.locator('#messages').textContent(),/Опасностей рядом/); assert.match(await page.locator('#messages').textContent(),/Опасностей рядом/);
// Native button keyboard actions and spatial focus; focus is not character position. // Native button keyboard actions and spatial focus; focus is not character position.
await scene(0).focus(); await page.keyboard.press('ArrowRight'); await scene(first).focus(); await page.keyboard.press('ArrowRight');
assert(await scene(1).evaluate(n=>n===document.activeElement)); assert(await scene(second).evaluate(n=>n===document.activeElement));
assert.match(await scene(0).getAttribute('aria-label'),/персонаж здесь/); assert.match(await scene(first).getAttribute('aria-label'),/персонаж здесь/);
await page.keyboard.press('Enter'); await page.keyboard.press('Enter');
assert.equal(await page.locator('#scene-grid .opened').count(),2); assert.equal(await page.locator('#scene-grid .opened').count(),2);
assert.equal(await page.locator('#history li').count(),2); assert.equal(await page.locator('#history li').count(),2);
@@ -69,7 +80,7 @@ async function run() {
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. // Notes select on the map without jumping. One DOM map is moved into the modal on phone.
if (width === 390) await page.locator('#map-open').click(); if (width === 390) await page.locator('#map-open').click();
await map(2).click(); await map(note).click();
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(); await page.locator('#map-mark').click();
assert.equal(await page.locator('#map-grid .marked').count(),1); assert.equal(await page.locator('#map-grid .marked').count(),1);
@@ -113,6 +124,8 @@ async function run() {
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.equal(await page.locator('#scene-grid .exit button').getAttribute('data-id'), await page.locator('#map-grid .exit button').getAttribute('data-id'));
assert.deepEqual(errors,[]); assert.deepEqual(errors,[]);
console.log(`PASS ${width}x${height}: render, keyboard/touch, synchronized map, notes, dialogs, settings, console`); console.log(`PASS ${width}x${height}: render, keyboard/touch, synchronized map, notes, dialogs, settings, console`);
} finally { await context.close(); } } finally { await context.close(); }
@@ -159,17 +172,17 @@ async function run() {
await page.setViewportSize({width:1366,height:768}); await page.setViewportSize({width:1366,height:768});
await page.reload(); await page.locator('#scene-grid button').last().waitFor(); await page.reload(); await page.locator('#scene-grid button').last().waitFor();
await page.evaluate(()=>Math.random=()=>0); await page.evaluate(()=>Math.random=()=>0);
await cell(2).click(); await cell(hintCell).click();
assert.equal(await page.locator('#scene-grid .hint').count(),1); assert.equal(await page.locator('#scene-grid .hint').count(),1);
assert.equal(await page.locator('#map-grid .hint').count(),1); assert.equal(await page.locator('#map-grid .hint').count(),1);
assert.match(await page.locator('#messages').textContent(),/Подсказка: Б4/); assert((await page.locator('#messages').textContent()).includes(hintText));
await page.waitForTimeout(1100); await cell(2).click(); await page.waitForTimeout(1100); await cell(hintCell).click();
await page.waitForTimeout(1100); await page.waitForTimeout(1100);
assert.equal(await page.locator('#scene-grid .hint').count(),1,'repeat hint renews the full display duration'); assert.equal(await page.locator('#scene-grid .hint').count(),1,'repeat hint renews the full display duration');
await page.waitForTimeout(1000); await page.waitForTimeout(1000);
assert.equal(await page.locator('#scene-grid .hint').count(),0); assert.equal(await page.locator('#scene-grid .hint').count(),0);
assert.match(await page.locator('#messages').textContent(),/Подсказка: Б4/); assert((await page.locator('#messages').textContent()).includes(hintText));
await cell(2).click(); await cell(hintCell).click();
assert.equal(await page.locator('#scene-grid .hint').count(),1); 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);
@@ -196,7 +209,7 @@ async function run() {
await page.locator('#scene-grid button').last().waitFor(); await page.locator('#scene-grid button').last().waitFor();
assert(await page.locator('.forest').isHidden()); assert(await page.locator('.forest').isHidden());
assert(await page.locator('#character > span').isVisible()); assert(await page.locator('#character > span').isVisible());
await page.locator('#scene-grid button[data-id="0"]').tap(); await page.locator('#jump').tap(); await page.locator('#scene-grid button[data-id="1"]').tap(); await page.locator('#jump').tap();
assert.equal(await page.locator('#scene-grid .opened').count(),1); assert.equal(await page.locator('#scene-grid .opened').count(),1);
console.log('PASS failed-image fallback retains training controls and character marker'); console.log('PASS failed-image fallback retains training controls and character marker');
} finally { await broken.close(); } } finally { await broken.close(); }
+43 -14
View File
@@ -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, EXIT } from '../../web/lu-trainer/engine.js'; import { Training, generateField, neighbors, hintChance, START, coordinate } from '../../web/lu-trainer/engine.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; };
@@ -21,17 +21,46 @@ function openReachableSafe(game, field) {
} }
} }
test('entrance is always x1 y1 and every other cell can host the exit', () => {
assert.equal(START, 0);
assert.equal(coordinate(START), 'x1 y1');
assert.equal(coordinate(59), 'x10 y6');
const exits = new Set();
for (let id = 1; id < 60; id++) {
const random = () => (id - .5) / 59;
const field = generateField(options, random);
assert.equal(field.start, 0);
assert.equal(field.exit, id);
exits.add(field.exit);
assert(!field.hazards.has(field.start));
assert(!field.hazards.has(field.exit));
assert(!field.base.includes(field.start));
assert(!field.base.includes(field.exit));
const game = new Training(options, random);
const view = game.view();
assert.equal(view.position, 0);
assert.equal(view.start, field.start);
assert.equal(view.exit, field.exit);
assert.equal(view.cells.filter(cell => cell.entrance).length, 1);
assert.equal(view.cells.filter(cell => cell.exit).length, 1);
assert.equal(view.cells.filter(cell => cell.transition).length, 2);
assert.equal(game.jump(field.exit).code, 'transition');
assert.equal(game.mark(field.exit).code, 'transition');
}
assert.equal(exits.size, 59);
});
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));
assert.equal(field.values.length, 60); assert.equal(field.values.length, 60);
assert(!field.hazards.has(START) && !field.hazards.has(EXIT)); assert(!field.hazards.has(START) && !field.hazards.has(field.exit));
for (const id of field.base) assert(!field.hazards.has(id)); for (const id of field.base) assert(!field.hazards.has(id));
assert.equal(field.base.length, height === 1 ? 5 : 3); assert.equal(field.base.length, height === 1 ? 5 : 3);
assert.equal(field.hazards.size, Math.min(Math.max(5, growth + season + 2 * (height - 1)), 60 - field.reserved.size)); assert.equal(field.hazards.size, Math.min(Math.max(5, growth + season + 2 * (height - 1)), 60 - field.reserved.size));
const reached = new Set([START]); const reached = new Set([START]);
for (const id of reached) for (const next of neighbors(id)) if (!field.hazards.has(next)) reached.add(next); for (const id of reached) for (const next of neighbors(id)) if (!field.hazards.has(next)) reached.add(next);
assert(reached.has(EXIT)); assert(reached.has(field.exit));
for (const id of field.base) assert(reached.has(id)); for (const id of field.base) assert(reached.has(id));
for (let id = 0; id < 60; id++) assert.equal(field.values[id], neighbors(id).filter(n => field.hazards.has(n)).length); for (let id = 0; id < 60; id++) assert.equal(field.values[id], neighbors(id).filter(n => field.hazards.has(n)).length);
} }
@@ -44,24 +73,24 @@ test('edge neighborhoods do not wrap rows', () => {
test('only base or neighbors of any opened cell are available; transitions never count', () => { test('only base or neighbors of any opened cell are available; transitions never count', () => {
const {game} = fixture(); const {game} = fixture();
assert.equal(game.jump(START).code, 'transition'); assert.equal(game.jump(START).code, 'transition');
assert.equal(game.jump(EXIT).code, 'transition'); assert.equal(game.jump(game.view().exit).code, 'transition');
assert.equal(game.jump(25).code, 'unreachable'); assert.equal(game.jump(25).code, 'unreachable');
assert.equal(game.mark(START).code, 'transition'); assert.equal(game.mark(START).code, 'transition');
assert.equal(game.jump(0).code, 'opened'); assert.equal(game.jump(1).code, 'opened');
game.jump(4); // last position differs: adjacency still belongs to any open cell game.jump(4); // last position differs: adjacency still belongs to any open cell
assert(game.view().cells[10].available); assert(game.view().cells[10].available);
assert.equal(game.view().position, 4); assert.equal(game.view().position, 4);
}); });
test('notes hide no facts, block jumps, clear independently and reject invalid IDs', () => { test('notes hide no facts, block jumps, clear independently and reject invalid IDs', () => {
const {game} = fixture(); const {game} = fixture();
game.jump(0); game.mark(1); game.jump(1); game.mark(2);
const before = game.view(); const before = game.view();
assert.equal(game.jump(1).code, 'marked'); assert.equal(game.jump(2).code, 'marked');
assert.equal(before.cells[1].value, null); assert.equal(before.cells[2].value, null);
assert(!Object.hasOwn(before.cells[1], 'hazard')); assert(!Object.hasOwn(before.cells[2], 'hazard'));
assert.equal(game.mark(0).code, 'opened'); assert.equal(game.mark(1).code, 'opened');
game.clearMarks(); game.clearMarks();
assert(game.view().cells[0].opened); assert(game.view().cells[1].opened);
assert.equal(game.view().marks, 0); assert.equal(game.view().marks, 0);
assert.equal(game.view().position, before.position); assert.equal(game.view().position, before.position);
assert(game.view().history.length > before.history.length); assert(game.view().history.length > before.history.length);
@@ -69,10 +98,10 @@ test('notes hide no facts, block jumps, clear independently and reject invalid I
}); });
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(0); game.mark(1);
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(0); game.mark(1);
assert.equal(game.view().status, 'won'); assert.equal(game.view().status, 'won');
const ended = game.view(); const ended = game.view();
for (const cell of ended.cells) assert.equal(typeof cell.hazard, 'boolean'); for (const cell of ended.cells) assert.equal(typeof cell.hazard, 'boolean');
@@ -89,7 +118,7 @@ test('opening all safe cells wins without entering either transition', () => {
}); });
test('hazard ends attempt, reveals wrong notes and preserves last safe position', () => { test('hazard ends attempt, reveals wrong notes and preserves last safe position', () => {
const {game,field} = fixture(); const {game,field} = fixture();
game.mark(4); game.jump(0); game.mark(4); game.jump(1);
while (game.view().status !== 'lost') { while (game.view().status !== 'lost') {
const cell = game.view().cells.find(c => c.available && !c.opened && !c.transition && !c.marked); const cell = game.view().cells.find(c => c.available && !c.opened && !c.transition && !c.marked);
assert(cell); game.jump(cell.id); assert(cell); game.jump(cell.id);
+6 -5
View File
@@ -39,7 +39,8 @@
<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>
<p id="scene-instructions" class="scene-instructions">Откройте одну из клеток А1–А5. Затем прыгайте рядом с любой проверенной клеткой.</p> <p id="transition-coordinates" class="scene-instructions">Вход: x1 y1 · Выход выбирается для новой попытки</p>
<p id="scene-instructions" class="scene-instructions">Откройте доступную стартовую клетку. Затем прыгайте рядом с любой проверенной клеткой.</p>
<div class="scene" id="scene"> <div class="scene" id="scene">
<img class="forest" src="/lu-trainer/assets/forest.webp" alt="" width="1500" height="900"> <img class="forest" src="/lu-trainer/assets/forest.webp" alt="" width="1500" height="900">
<div id="scene-grid" class="cell-grid scene-grid" role="grid" aria-label="Локация" aria-rowcount="6" aria-colcount="10" aria-describedby="scene-instructions"></div> <div id="scene-grid" class="cell-grid scene-grid" role="grid" aria-label="Локация" aria-rowcount="6" aria-colcount="10" aria-describedby="scene-instructions"></div>
@@ -51,9 +52,9 @@
<section class="panel actions"> <section class="panel actions">
<h2>Действия</h2> <h2>Действия</h2>
<fieldset class="mode"><legend>Действие на локации</legend><label for="mode-jump"><input id="mode-jump" type="radio" name="mode" value="jump" checked> Прыжок</label><label for="mode-mark"><input id="mode-mark" type="radio" name="mode" value="mark"> Опасная</label></fieldset> <fieldset class="mode"><legend>Действие на локации</legend><label for="mode-jump"><input id="mode-jump" type="radio" name="mode" value="jump" checked> Прыжок</label><label for="mode-mark"><input id="mode-mark" type="radio" name="mode" value="mark"> Опасная</label></fieldset>
<p id="selection">Выбрана клетка Е1 · вход</p> <p id="selection">Выбрана клетка x1 y1 · вход</p>
<div class="action-buttons"><button id="jump" type="button" class="primary">Прыгнуть</button><button id="mark" type="button">Отметить опасной</button></div> <div class="action-buttons"><button id="jump" type="button" class="primary">Прыгнуть</button><button id="mark" type="button">Отметить опасной</button></div>
<p id="status" role="status" aria-atomic="true">Начните с клеток А1–А5. Стрелки перемещают фокус, Enter или пробел выполняет действие.</p> <p id="status" role="status" aria-atomic="true">Выберите доступную стартовую клетку. Стрелки перемещают фокус, Enter или пробел выполняет действие.</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>
@@ -65,7 +66,7 @@
<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> опасностей</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">Клетка карты только выбирается. Заметка не подтверждает опасность.</p>
<p id="map-selection">Выбрана Е1 · вход</p> <p id="map-selection">Выбрана x1 y1 · вход</p>
<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>
@@ -93,7 +94,7 @@
<h2 id="help-title">Как освоиться на уступах</h2> <h2 id="help-title">Как освоиться на уступах</h2>
<p>Это самостоятельная учебная модель, вдохновлённая тренажёром <a href="https://github.com/tek1laa/catwar-lu-trainer" target="_blank" rel="noopener noreferrer">tek1laa</a>. Правила настоящей игры могут отличаться.</p> <p>Это самостоятельная учебная модель, вдохновлённая тренажёром <a href="https://github.com/tek1laa/catwar-lu-trainer" target="_blank" rel="noopener noreferrer">tek1laa</a>. Правила настоящей игры могут отличаться.</p>
<ul class="help-list"> <ul class="help-list">
<li>Начальные безопасные клетки — А1–А5 на высоте 1 и А1–А3 выше. Переходы Е1 и Г10 обозначают вход и выход: по ним не прыгают.</li> <li>Вход всегда находится в x1 y1 — верхней левой клетке. X растёт вправо, Y — вниз. Выход в этой модели выбирается случайно для каждой новой попытки и может занять любую другую клетку. Переходы отмечены стрелками: по ним не прыгают. В верхней строке доступны 5 безопасных стартовых клеток на высоте 1 и 3 выше, не считая переходов.</li>
<li>Открывайте клетки рядом с любой проверенной, включая диагонали. Персонаж показывает последний успешный прыжок, а не ограничивает его дальность.</li> <li>Открывайте клетки рядом с любой проверенной, включая диагонали. Персонаж показывает последний успешный прыжок, а не ограничивает его дальность.</li>
<li>Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.</li> <li>Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.</li>
<li>На компьютере клик выполняет выбранное действие, правая кнопка ставит заметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной».</li> <li>На компьютере клик выполняет выбранное действие, правая кнопка ставит заметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной».</li>
+12 -10
View File
@@ -2,8 +2,7 @@
// No DOM, storage, clock or network: the UI consumes only view() and action results. // No DOM, storage, clock or network: the UI consumes only view() and action results.
export const ROWS = 6; export const ROWS = 6;
export const COLS = 10; export const COLS = 10;
export const START = 50; export const START = 0;
export const EXIT = 39;
export const DEFAULTS = Object.freeze({ height: 1, lu: 5, growth: 12, season: 0 }); export const DEFAULTS = Object.freeze({ height: 1, lu: 5, growth: 12, season: 0 });
export function neighbors(id) { export function neighbors(id) {
@@ -16,7 +15,7 @@ export function neighbors(id) {
return result; return result;
} }
export function hintChance(lu) { return lu < 4 ? 0 : lu === 4 ? .1 : lu === 5 ? .2 : .3; } export function hintChance(lu) { return lu < 4 ? 0 : lu === 4 ? .1 : lu === 5 ? .2 : .3; }
export function coordinate(id) { return `${'АБВГДЕ'[Math.floor(id / COLS)]}${id % COLS + 1}`; } export function coordinate(id) { return `x${id % COLS + 1} y${Math.floor(id / COLS) + 1}`; }
function settings(input) { function settings(input) {
const value = { ...DEFAULTS, ...input }; const value = { ...DEFAULTS, ...input };
if (!Number.isInteger(value.height) || value.height < 1 || value.height > 5 || if (!Number.isInteger(value.height) || value.height < 1 || value.height > 5 ||
@@ -29,8 +28,11 @@ function settings(input) {
function distance(a, b) { return Math.max(Math.abs(Math.floor(a / COLS) - Math.floor(b / COLS)), Math.abs(a % COLS - b % COLS)); } function distance(a, b) { return Math.max(Math.abs(Math.floor(a / COLS) - Math.floor(b / COLS)), Math.abs(a % COLS - b % COLS)); }
export function generateField(input = DEFAULTS, random = Math.random) { export function generateField(input = DEFAULTS, random = Math.random) {
const options = settings(input); const options = settings(input);
const base = Array.from({length: options.height === 1 ? 5 : 3}, (_,i)=>i); const exit = 1 + Math.floor(random() * (ROWS * COLS - 1));
const reserved = new Set([START, EXIT, ...base]); // Transitions do not consume one of the 5/3 initially playable safe cells.
const base = Array.from({length: COLS - 1}, (_,i)=>i + 1)
.filter(id => id !== exit).slice(0, options.height === 1 ? 5 : 3);
const reserved = new Set([START, exit, ...base]);
function connect(from, to) { function connect(from, to) {
while (from !== to) { while (from !== to) {
const steps = neighbors(from).filter(id => distance(id, to) < distance(from, to)); const steps = neighbors(from).filter(id => distance(id, to) < distance(from, to));
@@ -39,7 +41,7 @@ export function generateField(input = DEFAULTS, random = Math.random) {
} }
} }
connect(START, base[0]); connect(START, base[0]);
connect(base[Math.floor(random() * base.length)], EXIT); connect(base[Math.floor(random() * base.length)], exit);
const candidates = Array.from({length: ROWS * COLS}, (_,id)=>id).filter(id => !reserved.has(id)); const candidates = Array.from({length: ROWS * COLS}, (_,id)=>id).filter(id => !reserved.has(id));
for (let i = candidates.length - 1; i > 0; i--) { for (let i = candidates.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1)); const j = Math.floor(random() * (i + 1));
@@ -48,7 +50,7 @@ export function generateField(input = DEFAULTS, random = Math.random) {
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)); const hazards = new Set(candidates.slice(0, count));
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 { base, reserved, hazards, values }; return { start: START, exit, base, reserved, hazards, values };
} }
export class Training { export class Training {
@@ -66,7 +68,7 @@ export class Training {
} }
#valid(id) { return Number.isInteger(id) && id >= 0 && id < ROWS * COLS; } #valid(id) { return Number.isInteger(id) && id >= 0 && id < ROWS * COLS; }
#finished() { return this.#status === 'won' || this.#status === 'lost'; } #finished() { return this.#status === 'won' || this.#status === 'lost'; }
#transition(id) { return id === START || id === EXIT; } #transition(id) { return id === START || id === this.#field.exit; }
#available(id) { return this.#field.base.includes(id) || neighbors(id).some(n => this.#opened.has(n)); } #available(id) { return this.#field.base.includes(id) || neighbors(id).some(n => this.#opened.has(n)); }
#guard(id) { #guard(id) {
if (this.#finished()) return {code: 'finished'}; if (this.#finished()) return {code: 'finished'};
@@ -118,12 +120,12 @@ export class Training {
view() { view() {
const ended = this.#finished(); const ended = this.#finished();
return { return {
options: {...this.#options}, 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, 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, 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),
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,
+9 -7
View File
@@ -1,4 +1,4 @@
import {Training, DEFAULTS, ROWS, COLS, START, EXIT, coordinate, hintChance} from './engine.js'; import {Training, DEFAULTS, ROWS, COLS, START, coordinate, hintChance} from './engine.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)');
@@ -15,9 +15,10 @@ 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 initialCells(view) { return view.cells.filter(cell => cell.base).map(cell => coordinate(cell.id)).join(', '); }
function describe(cell, view) { function describe(cell, view) {
if (cell.id === START) return 'вход'; if (cell.entrance) return 'вход';
if (cell.id === EXIT) return 'выход'; if (cell.exit) return 'выход';
if (cell.wrong) return 'ошибочная отметка, безопасно'; if (cell.wrong) return 'ошибочная отметка, безопасно';
if (cell.hazard) return 'опасная клетка'; if (cell.hazard) return 'опасная клетка';
if (cell.opened) return `проверено, опасностей рядом: ${cell.value}`; if (cell.opened) return `проверено, опасностей рядом: ${cell.value}`;
@@ -27,7 +28,7 @@ function describe(cell, view) {
return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, сначала откройте соседнюю клетку'; return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, сначала откройте соседнюю клетку';
} }
function cellValue(cell, view, showMarks) { function cellValue(cell, view, showMarks) {
if (cell.transition) return cell.id === START ? '↥' : '↗'; 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 '⚑';
@@ -104,7 +105,7 @@ 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'), 'Лес затих. Звуки появятся после прыжка.'); addItem($('messages'), 'Лес затих. Звуки появятся после прыжка.');
$('status').textContent = `Начните с клеток А1–А${options.height === 1 ? 5 : 3}. Стрелки перемещают фокус, Enter или пробел выполняет действие.`; $('status').textContent = `Начальные клетки: ${initialCells(game.view())}. Стрелки перемещают фокус, Enter или пробел выполняет действие.`;
updateClock(); render(); updateClock(); render();
} }
function render() { function render() {
@@ -113,7 +114,7 @@ function render() {
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 projectedMark = cell.marked && (isMap || projection);
node.className = [cell.opened && 'opened', projectedMark && 'marked', cell.available && !cell.transition && 'available', cell.transition && 'transition', 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.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(' ');
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, isMap || projection);
@@ -125,13 +126,14 @@ function render() {
$('lu-value').textContent = `${view.options.lu} ЛУ`; $('lu-value').textContent = `${view.options.lu} ЛУ`;
$('height-value').textContent = `${view.options.height} из 5`; $('height-value').textContent = `${view.options.height} из 5`;
$('scene-height').textContent = `Высота ${view.options.height}`; $('scene-height').textContent = `Высота ${view.options.height}`;
$('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 = `${Math.round(hintChance(view.options.lu) * 100)}%`;
$('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;
$('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status]; $('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status];
$('scene-instructions').textContent = compact.matches ? `Выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной». Начало: А1–А${view.options.height === 1 ? 5 : 3}.` : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Начало: А1–А${view.options.height === 1 ? 5 : 3}, затем рядом с любой проверенной клеткой.`; $('scene-instructions').textContent = compact.matches ? `Выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной». Начальные клетки: ${initialCells(view)}.` : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Начальные клетки: ${initialCells(view)}; затем рядом с любой проверенной клеткой.`;
const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной'; const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной';
$('selection').textContent = `Выбрана клетка ${coordinate(selected)} · ${describe(cell, view)}`; $('selection').textContent = `Выбрана клетка ${coordinate(selected)} · ${describe(cell, view)}`;
$('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view)}`; $('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view)}`;