fix: limit trainer jumps and exit positions
This commit is contained in:
1 parent
27b3e0aaae
commit
cc6bcb23c8
12 files changed
+174
-79
No files matched your search
@@ -35,7 +35,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. 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 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 checks (prefer remote test-zone MCP when exposed): Node 24 `node --test tests/lu-trainer/engine.test.mjs`; isolated Python `python -m unittest tests.test_lu_trainer tests.test_calculator_web -q`; `node --check web/lu-trainer/ui.js`; `node tests/browser/lu-trainer.cjs` with the same bundled Playwright, loopback server and temporary stores as the calculator suite. No npm install or runtime dependency is needed. Browser coverage includes 1920/1366/768/390 widths, mouse/touch/keyboard, map projection, clear/restart confirmation, result locks, hints/timers, 200% layout and failed images. Inspect screenshots outside Git. Nginx aliases must serve the same HTML and correct asset MIME types; do not deploy to validate a client-only change.
|
- LU checks (prefer remote test-zone MCP when exposed): Node 24 `node --test tests/lu-trainer/engine.test.mjs`; isolated Python `python -m unittest tests.test_lu_trainer tests.test_calculator_web -q`; `node --check web/lu-trainer/ui.js`; `node tests/browser/lu-trainer.cjs` with the same bundled Playwright, loopback server and temporary stores as the calculator suite. No npm install or runtime dependency is needed. Browser coverage includes 1920/1366/768/390 widths, mouse/touch/keyboard, map projection, clear/restart confirmation, result locks, hints/timers, 200% layout and failed images. Inspect screenshots outside Git. Nginx aliases must serve the same HTML and correct asset MIME types; do not deploy to validate a client-only change.
|
||||||
- `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint (3-second timeout, 64 KiB bound, 5-minute process cache, 1-minute failure cache). `/api/weather/ulli` exposes only decoration settings; shared CSS/JS live at `/api/weather/effect.css` and `/api/weather/effect.js` so the existing gateway `/api/` route handles them. Keep weather independent of reports/storage, skip trend/remark/vicinity groups, reject observations older than 2 hours, and retain leaves on failure. Do not disable TLS verification.
|
- `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint (3-second timeout, 64 KiB bound, 5-minute process cache, 1-minute failure cache). `/api/weather/ulli` exposes only decoration settings; shared CSS/JS live at `/api/weather/effect.css` and `/api/weather/effect.js` so the existing gateway `/api/` route handles them. Keep weather independent of reports/storage, skip trend/remark/vicinity groups, reject observations older than 2 hours, and retain leaves on failure. Do not disable TLS verification.
|
||||||
- VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule.
|
- VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule.
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
|
|
||||||
## Уточнение владельца о переходах — 2026-11-17
|
## Уточнение владельца о переходах — 2026-11-17
|
||||||
|
|
||||||
|
**Актуальные правила (2026-11-22):** прыгать можно только из текущей клетки в одну из восьми соседних, без скачков через безопасные или проверенные клетки. Выход по-прежнему случайный, но только в `x10 y2–y6` или `y6 x6–x10`. Вход, условия победы, отметки и назначение переходов как ориентиров не меняются. Описание ниже относится к прежней версии.
|
||||||
|
|
||||||
Владелец уточнил: «вход всегда на клетке x1 y1, выход может быть в разных местах». Это заменяет координаты переходов из исходного тренажёра в текущей реализации. `x1 y1` отображается в верхней левой клетке; X растёт вправо, Y — вниз. Генератор выбирает выход для каждой новой попытки из остальных 59 клеток — это способ реализации вариативности, а не подтверждённое распределение выходов в CatWar. Пять/три начальные безопасные клетки сохранены отдельно от переходов. Состояние попытки хранит координаты входа/выхода; локация, карта, справка и сообщения используют их совместно. Наблюдения об исходнике ниже остаются историческими.
|
Владелец уточнил: «вход всегда на клетке x1 y1, выход может быть в разных местах». Это заменяет координаты переходов из исходного тренажёра в текущей реализации. `x1 y1` отображается в верхней левой клетке; X растёт вправо, Y — вниз. Генератор выбирает выход для каждой новой попытки из остальных 59 клеток — это способ реализации вариативности, а не подтверждённое распределение выходов в CatWar. Пять/три начальные безопасные клетки сохранены отдельно от переходов. Состояние попытки хранит координаты входа/выхода; локация, карта, справка и сообщения используют их совместно. Наблюдения об исходнике ниже остаются историческими.
|
||||||
|
|
||||||
## Цель и подтверждённый объём
|
## Цель и подтверждённый объём
|
||||||
@@ -114,7 +116,7 @@
|
|||||||
5. Повторное посещение проверенной клетки воспроизводит текстовую обратную связь и предусмотренную моделью проверку подсказки.
|
5. Повторное посещение проверенной клетки воспроизводит текстовую обратную связь и предусмотренную моделью проверку подсказки.
|
||||||
6. После падения либо выполнения условия победы действия попытки прекращаются, показываются результат и раскрытие поля. Доступны осмотр результата и новая игра.
|
6. После падения либо выполнения условия победы действия попытки прекращаются, показываются результат и раскрытие поля. Доступны осмотр результата и новая игра.
|
||||||
|
|
||||||
**Рабочее допущение первой версии:** сохраняем описанную модель исходника. Персонаж визуализирует последний успешный выбор, но не меняет проверку соседства: она по-прежнему относится к любой открытой клетке. Переход к прыжкам исключительно от текущей позиции — отдельное изменение механики, требующее подтверждения реальных правил. Формулы, шансы подсказок и условия победы не менять незаметно под видом обновления интерфейса.
|
**Текущая механика тренажёра:** восемь соседей отсчитываются от позиции персонажа, а не от любой проверенной клетки, как было в первой версии. Формулы, шансы подсказок и условия победы сохранены.
|
||||||
|
|
||||||
Новый тренажёр не подключается к аккаунту CatWar, не отправляет туда действия и не начисляет ЛУ. Рейтинги, серверные профили, многопользовательский режим, аудио, достижения и интеграция с отчётами Белок не входят в текущий объём.
|
Новый тренажёр не подключается к аккаунту CatWar, не отправляет туда действия и не начисляет ЛУ. Рейтинги, серверные профили, многопользовательский режим, аудио, достижения и интеграция с отчётами Белок не входят в текущий объём.
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# MEMORY
|
# MEMORY
|
||||||
|
|
||||||
|
- 2026-11-22: `/trainer` now limits jumps to the eight cells adjoining the character, even along the safe starting strip. Each field chooses one exit from `x10 y2–y6` or `y6 x6–x10`; this replaces the unrestricted exit pool described below. The entrance remains `x1 y1`.
|
||||||
|
|
||||||
- 2026-11-21: the Nginx gateway base moved from 1.31.4 to 1.31.9. The versioned upstream image and private registry base are pinned by Linux amd64 digest. Publish a new immutable gateway base and update the release reference on future binary upgrades. The private base push and isolated gateway checks were verified. Production rollout is pending.
|
- 2026-11-21: the Nginx gateway base moved from 1.31.4 to 1.31.9. The versioned upstream image and private registry base are pinned by Linux amd64 digest. Publish a new immutable gateway base and update the release reference on future binary upgrades. The private base push and isolated gateway checks were verified. Production rollout is pending.
|
||||||
|
|
||||||
- 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 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.
|
||||||
|
|||||||
@@ -47,7 +47,9 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
На компьютере клик по локации выполняет выбранный «Прыжок» или «Опасная»; правая кнопка ставит/снимает заметку. На телефоне касание сначала выбирает клетку, затем действие подтверждается отдельной крупной кнопкой. На обеих сетках доступны стрелки, Home / End, Enter и пробел. «Минное поле» выбирает клетку для заметки и автоматически показывает результаты прыжков. «Перенос на игровое поле» меняет только видимость заметок на локации. Очистка заметок и новая игра имеют разные подтверждения.
|
На компьютере клик по локации выполняет выбранный «Прыжок» или «Опасная»; правая кнопка ставит/снимает заметку. На телефоне касание сначала выбирает клетку, затем действие подтверждается отдельной крупной кнопкой. На обеих сетках доступны стрелки, Home / End, Enter и пробел. «Минное поле» выбирает клетку для заметки и автоматически показывает результаты прыжков. «Перенос на игровое поле» меняет только видимость заметок на локации. Очистка заметок и новая игра имеют разные подтверждения.
|
||||||
|
|
||||||
Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Выход выбирается заново для каждой попытки из остальных клеток. Оба перехода безопасны, их координаты показаны над локацией и совпадают с картой. Пять начальных безопасных клеток на высоте 1 и три выше находятся в верхней строке, не считая переходов.
|
Вход всегда в `x1 y1` (верхняя левая клетка); X растёт вправо, Y — вниз. Прыгать можно только из текущей клетки в соседнюю, в том числе по диагонали. Пять безопасных клеток на первой высоте и три на остальных идут подряд справа от входа: перескакивать через них нельзя.
|
||||||
|
|
||||||
|
Выход выбирается заново для каждой попытки: `x10 y2–y6` или `y6 x6–x10`. Координаты переходов показаны на локации и на карте. В этой версии тренажёра выход обозначает место перехода, но не переключает высоту.
|
||||||
|
|
||||||
Победа — все безопасные клетки, кроме переходов, либо все опасности без лишних отметок. Падение завершает попытку. Настройки высоты, ЛУ, сезона и роста применяются явным началом новой игры. Это модель описанного исходного тренажёра, а не подтверждённые правила CatWar. Оригинальные изображения и промпты перечислены в `web/lu-trainer/assets/README.md`; код и изображения исходного тренажёра не переносились.
|
Победа — все безопасные клетки, кроме переходов, либо все опасности без лишних отметок. Падение завершает попытку. Настройки высоты, ЛУ, сезона и роста применяются явным началом новой игры. Это модель описанного исходного тренажёра, а не подтверждённые правила CatWar. Оригинальные изображения и промпты перечислены в `web/lu-trainer/assets/README.md`; код и изображения исходного тренажёра не переносились.
|
||||||
|
|
||||||
|
|||||||
@@ -14,5 +14,7 @@ Spec: ../specs/2026-11-17-lu-trainer.md and root LU_TRAINER_PROJECT.md (owner re
|
|||||||
goal: make page available through Python and gateway, document scope and checks, commit without push.
|
goal: make page available through Python and gateway, document scope and checks, commit without push.
|
||||||
files: app/main.py, nginx.conf, web/index.html, tests/test_lu_trainer.py, tests/browser/lu-trainer.cjs, README.md, AGENTS.md, MEMORY.md, structure_and_data.md, project_mind_map.md, LU_TRAINER_PROJECT.md
|
files: app/main.py, nginx.conf, web/index.html, tests/test_lu_trainer.py, tests/browser/lu-trainer.cjs, README.md, AGENTS.md, MEMORY.md, structure_and_data.md, project_mind_map.md, LU_TRAINER_PROJECT.md
|
||||||
acceptance: targeted HTTP tests, Nginx syntax/serving, JS syntax, diff check, spec/diff review; temporary environments cleaned.
|
acceptance: targeted HTTP tests, Nginx syntax/serving, JS syntax, diff check, spec/diff review; temporary environments cleaned.
|
||||||
|
- [x] Follow-up: Limit jumps to adjacent cells and restrict variable exits to the specified edges.
|
||||||
|
acceptance: model tests for current-position adjacency, all allowed exit cells and a safe route up to the exit; targeted HTTP and JS checks; browser regression for rejected jumps and synchronized exits.
|
||||||
|
|
||||||
Final review: approved root scope implemented. Spec compliance/consistency review resolved temporary hint disclosure and terminal controls. Source/diff review found and fixed overlapping hint expiry and result-inspection timer advancement. JS syntax, Python source compilation, 9 engine tests, 5 focused HTTP/calculator-page tests, Chromium acceptance and isolated Nginx syntax/alias/MIME checks passed. No runtime dependency, API, storage or production change. Check record and environment limits: root structure_and_data.md.
|
Final review: approved root scope implemented. Spec compliance/consistency review resolved temporary hint disclosure and terminal controls. Source/diff review found and fixed overlapping hint expiry and result-inspection timer advancement. JS syntax, Python source compilation, 9 engine tests, 5 focused HTTP/calculator-page tests, Chromium acceptance and isolated Nginx syntax/alias/MIME checks passed. No runtime dependency, API, storage or production change. Check record and environment limits: root structure_and_data.md.
|
||||||
@@ -5,7 +5,7 @@ Authorization: the owner requested implementation of root `LU_TRAINER_PROJECT.md
|
|||||||
contract: standalone `/trainer` and `/trainer/`, shared HTML/CSS/ES-module assets served by Python and Nginx. No new runtime dependency or storage. Gateway serves the page with `try_files`; assets use the existing static serving.
|
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, 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.
|
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 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: 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.
|
||||||
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.
|
||||||
@@ -13,4 +13,4 @@ deferred: verification of real CatWar rules, multiple saved maps, audio, server
|
|||||||
|
|
||||||
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.
|
Owner corrections: entrance fixed x1 y1 and exit variable (2026-11-17); limit exits to the specified edges and jumps to immediate neighbors (2026-11-22). Uniform random placement among permitted sites is an implementation choice, not a verified game distribution. Coordinates are one-based X right/Y down. Tests cover every allowed exit position, safe-route connectivity and matching transition labels on both grids after regeneration.
|
||||||
@@ -1,5 +1,11 @@
|
|||||||
# Structure and Data
|
# Structure and Data
|
||||||
|
|
||||||
|
## Trainer movement and exit edges — 2026-11-22
|
||||||
|
|
||||||
|
- Jumps and the grids’ availability indicators use the eight neighbors of the current character position, including from the entrance. An opened cell can be revisited only from an adjacent cell; selecting or marking a cell on the map does not move the character.
|
||||||
|
- Each field reserves one exit from the right edge (`x10 y2–y6`) or the bottom edge (`y6 x6–x10`), counting the shared corner once. Both transitions are still markers, not actions that change height.
|
||||||
|
- Verified with 10 engine tests, 6 targeted HTTP/calculator-page tests and the Chrome browser suite at 1920/1366/768/390 px. No push or deployment.
|
||||||
|
|
||||||
## Gateway Nginx security update (2026-11-21)
|
## Gateway Nginx security update (2026-11-21)
|
||||||
|
|
||||||
- The previous registry base contained Nginx 1.31.4. The rebuilt Linux amd64 gateway uses Nginx 1.31.9 on Alpine, the mainline security release from 2026-11-18. `Dockerfile.gateway-base` pins the upstream digest. `Dockerfile.gateway` pins the verified private registry digest so the next CI build picks up the new binary. [NGINX security advisories](https://nginx.org/en/security_advisories.html)
|
- The previous registry base contained Nginx 1.31.4. The rebuilt Linux amd64 gateway uses Nginx 1.31.9 on Alpine, the mainline security release from 2026-11-18. `Dockerfile.gateway-base` pins the upstream digest. `Dockerfile.gateway` pins the verified private registry digest so the next CI build picks up the new binary. [NGINX security advisories](https://nginx.org/en/security_advisories.html)
|
||||||
|
|||||||
@@ -7,14 +7,31 @@ const {chromium} = require('playwright');
|
|||||||
const origin = process.env.BELKI_TEST_URL || 'http://127.0.0.1:8876';
|
const origin = process.env.BELKI_TEST_URL || 'http://127.0.0.1:8876';
|
||||||
assert(['127.0.0.1','localhost','[::1]'].includes(new URL(origin).hostname));
|
assert(['127.0.0.1','localhost','[::1]'].includes(new URL(origin).hostname));
|
||||||
const shotDir = process.env.BELKI_SCREENSHOT_DIR;
|
const shotDir = process.env.BELKI_SCREENSHOT_DIR;
|
||||||
|
const allowedExits = [19,29,39,49,55,56,57,58,59];
|
||||||
function seeded(seed = 19) { return () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; }; }
|
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)));
|
||||||
|
async function checkTransitions(page, expectedExit) {
|
||||||
|
const sceneExit = await cellIds(page.locator('#scene-grid .exit button'));
|
||||||
|
assert.equal(sceneExit.length,1);
|
||||||
|
const [exit] = sceneExit;
|
||||||
|
assert(allowedExits.includes(exit),`unexpected exit cell: ${exit}`);
|
||||||
|
if (expectedExit !== undefined) assert.equal(exit,expectedExit);
|
||||||
|
for (const grid of ['scene-grid','map-grid']) {
|
||||||
|
assert.deepEqual(await cellIds(page.locator(`#${grid} .entrance button`)),[0]);
|
||||||
|
assert.deepEqual(await cellIds(page.locator(`#${grid} .exit button`)),[exit]);
|
||||||
|
assert.equal(await page.locator(`#${grid} .transition.available`).count(),0);
|
||||||
|
}
|
||||||
|
return exit;
|
||||||
|
}
|
||||||
|
|
||||||
async function run() {
|
async function run() {
|
||||||
const {generateField, DEFAULTS, coordinate, neighbors} = await import(pathToFileURL(path.resolve(__dirname,'../../web/lu-trainer/engine.js')));
|
const {generateField, DEFAULTS, coordinate, neighbors} = await import(pathToFileURL(path.resolve(__dirname,'../../web/lu-trainer/engine.js')));
|
||||||
const field = generateField(DEFAULTS,seeded());
|
const field = generateField(DEFAULTS,seeded());
|
||||||
const [first, second, note] = field.base;
|
const first = 1, second = 2, note = 30;
|
||||||
const hintCell = field.base.find(id => field.values[id] > 0);
|
const hintIndex = field.base.findIndex(id => field.values[id] > 0);
|
||||||
assert.notEqual(hintCell, undefined);
|
assert(hintIndex > 0,'hint fixture needs a quiet approach cell to revisit from');
|
||||||
|
const hintRoute = field.base.slice(0,hintIndex + 1);
|
||||||
|
const hintCell = hintRoute.at(-1), beforeHint = hintRoute.at(-2);
|
||||||
const hintText = `Подсказка: ${coordinate(neighbors(hintCell).find(id => field.hazards.has(id)))}`;
|
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 = [];
|
||||||
@@ -40,21 +57,33 @@ async function run() {
|
|||||||
const map = id => page.locator(`#map-grid button[data-id="${id}"]`);
|
const map = id => page.locator(`#map-grid button[data-id="${id}"]`);
|
||||||
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(); };
|
||||||
|
const assertAvailable = async ids => {
|
||||||
|
for (const grid of ['scene-grid','map-grid']) {
|
||||||
|
assert.deepEqual(await cellIds(page.locator(`#${grid} .available button`)),ids,`${grid} jump targets`);
|
||||||
|
}
|
||||||
|
};
|
||||||
await noOverflow();
|
await noOverflow();
|
||||||
assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: вход, персонаж здесь$/);
|
assert.match(await scene(0).getAttribute('aria-label'), /^x1 y1: вход, персонаж здесь$/);
|
||||||
for (const grid of ['scene-grid','map-grid']) {
|
await checkTransitions(page,field.exit);
|
||||||
assert.equal(await page.locator(`#${grid} .entrance button`).getAttribute('data-id'),'0');
|
assert(await page.locator('#jump').isDisabled());
|
||||||
assert.equal(await page.locator(`#${grid} .exit button`).getAttribute('data-id'),String(field.exit));
|
assert(await page.locator('#mark').isDisabled());
|
||||||
}
|
|
||||||
assert.match(await page.locator('#transition-coordinates').textContent(), /Вход: x1 y1/);
|
assert.match(await page.locator('#transition-coordinates').textContent(), /Вход: x1 y1/);
|
||||||
assert((await page.locator('#transition-coordinates').textContent()).includes(`Выход: ${coordinate(field.exit)}`));
|
assert((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);
|
||||||
|
await assertAvailable([1,10,11]);
|
||||||
// Modal help must not modify the field, and Escape must restore focus.
|
// Modal help must not modify the field, and Escape must restore focus.
|
||||||
await page.locator('#help-open').click();
|
await page.locator('#help-open').click();
|
||||||
assert(await page.locator('#help-dialog').isVisible());
|
assert(await page.locator('#help-dialog').isVisible());
|
||||||
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));
|
||||||
|
// Even a safe upper-row cell is out of reach two columns from the entrance.
|
||||||
|
await select(second);
|
||||||
|
assert(await page.locator('#jump').isEnabled());
|
||||||
|
assert.match(await page.locator('#status').textContent(),/соседнюю клетку/);
|
||||||
|
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[0]);
|
||||||
|
assert.equal(await page.locator('#history li').count(),0);
|
||||||
|
assert.equal(await page.locator('#scene-grid .opened').count(),0);
|
||||||
if (width === 390) {
|
if (width === 390) {
|
||||||
await scene(first).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');
|
||||||
@@ -66,6 +95,7 @@ async function run() {
|
|||||||
assert.equal(await page.locator('#history li').count(),1);
|
assert.equal(await page.locator('#history li').count(),1);
|
||||||
assert.match(await scene(first).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(),/Опасностей рядом/);
|
||||||
|
await assertAvailable([2,10,11,12]);
|
||||||
// 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(first).focus(); await page.keyboard.press('ArrowRight');
|
await scene(first).focus(); await page.keyboard.press('ArrowRight');
|
||||||
assert(await scene(second).evaluate(n=>n===document.activeElement));
|
assert(await scene(second).evaluate(n=>n===document.activeElement));
|
||||||
@@ -73,8 +103,20 @@ async function run() {
|
|||||||
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);
|
||||||
|
await assertAvailable([1,3,11,12,13]);
|
||||||
await page.keyboard.press(' ');
|
await page.keyboard.press(' ');
|
||||||
assert.equal(await page.locator('#history li').count(),3,'one keyboard action, one history item');
|
assert.equal(await page.locator('#history li').count(),2,'cannot jump to the current cell');
|
||||||
|
// Cell 10 still touches opened cell 1, but not the current position (cell 2).
|
||||||
|
await select(10);
|
||||||
|
assert.match(await page.locator('#status').textContent(),/соседнюю клетку/);
|
||||||
|
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[second]);
|
||||||
|
assert.equal(await page.locator('#history li').count(),2);
|
||||||
|
await scene(second).focus(); await page.keyboard.press('ArrowLeft');
|
||||||
|
await page.keyboard.press(' ');
|
||||||
|
assert.equal(await page.locator('#history li').count(),3,'one keyboard revisit, one history item');
|
||||||
|
assert.match(await page.locator('#history li').last().textContent(),/Повторный прыжок/);
|
||||||
|
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[first]);
|
||||||
|
assert.equal(await page.locator('#scene-grid .opened').count(),2);
|
||||||
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));
|
||||||
@@ -83,8 +125,9 @@ async function run() {
|
|||||||
await map(note).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.deepEqual(await cellIds(page.locator('#map-grid .marked button')),[note]);
|
||||||
assert.equal(await page.locator('#scene-grid .marked').count(),1);
|
assert.deepEqual(await cellIds(page.locator('#scene-grid .marked button')),[note]);
|
||||||
|
assert.deepEqual(await cellIds(page.locator('#scene-grid .current button')),[first]);
|
||||||
await page.locator('#project-marks').uncheck();
|
await page.locator('#project-marks').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);
|
||||||
@@ -94,7 +137,7 @@ async function run() {
|
|||||||
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();
|
||||||
assert.equal(await page.locator('#map-grid .marked').count(),0);
|
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 page.locator('#history li').count(),5);
|
||||||
if (width === 390) {
|
if (width === 390) {
|
||||||
@@ -125,11 +168,34 @@ async function run() {
|
|||||||
assert.equal(await page.locator('#history li').count(),0);
|
assert.equal(await page.locator('#history li').count(),0);
|
||||||
assert.equal(await page.locator('#timer').textContent(),'00:00');
|
assert.equal(await page.locator('#timer').textContent(),'00:00');
|
||||||
assert.match(await scene(0).getAttribute('aria-label'), /вход, персонаж здесь/);
|
assert.match(await scene(0).getAttribute('aria-label'), /вход, персонаж здесь/);
|
||||||
assert.equal(await page.locator('#scene-grid .exit button').getAttribute('data-id'), await page.locator('#map-grid .exit button').getAttribute('data-id'));
|
await checkTransitions(page);
|
||||||
|
await assertAvailable([1,10,11]);
|
||||||
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, adjacent jumps, keyboard/touch, synchronized map, notes, dialogs, settings, console`);
|
||||||
} finally { await context.close(); }
|
} finally { await context.close(); }
|
||||||
}
|
}
|
||||||
|
// Sample all exit buckets without coupling this test to their internal order.
|
||||||
|
const exits = new Set();
|
||||||
|
const boundary = await browser.newContext({viewport:{width:1366,height:768}});
|
||||||
|
try {
|
||||||
|
for (let i = 0; i < allowedExits.length; i++) {
|
||||||
|
const page = await boundary.newPage();
|
||||||
|
try {
|
||||||
|
await page.addInitScript(roll => { Math.random = () => roll; },(i + .5) / allowedExits.length);
|
||||||
|
await page.goto(`${origin}/trainer`);
|
||||||
|
await page.locator('#scene-grid button').last().waitFor();
|
||||||
|
const exit = await checkTransitions(page);
|
||||||
|
exits.add(exit);
|
||||||
|
await page.locator('#map-grid .exit button').click();
|
||||||
|
assert(await page.locator('#jump').isDisabled());
|
||||||
|
assert(await page.locator('#map-mark').isDisabled());
|
||||||
|
assert.equal(await page.locator('#scene-grid .opened').count(),0);
|
||||||
|
assert.equal(await page.locator('#history li').count(),0);
|
||||||
|
} finally { await page.close(); }
|
||||||
|
}
|
||||||
|
assert.deepEqual([...exits].sort((a,b)=>a-b),allowedExits);
|
||||||
|
console.log('PASS all permitted exit cells, synchronized transitions, exit cannot be jumped to or marked');
|
||||||
|
} finally { await boundary.close(); }
|
||||||
// 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 {
|
||||||
@@ -138,17 +204,17 @@ async function run() {
|
|||||||
await page.goto(`${origin}/trainer`);
|
await page.goto(`${origin}/trainer`);
|
||||||
await page.locator('#scene-grid button').last().waitFor();
|
await page.locator('#scene-grid button').last().waitFor();
|
||||||
const cell = id=>page.locator(`#scene-grid button[data-id="${id}"]`);
|
const cell = id=>page.locator(`#scene-grid button[data-id="${id}"]`);
|
||||||
// Open safe reachable cells until a known adjacent hazard can be reached.
|
// The seeded route includes a diagonal jump from the entrance.
|
||||||
let hazard;
|
const hazard = 31;
|
||||||
for (let guard=0;guard<60;guard++) {
|
for (const id of [11,20]) {
|
||||||
const ids = await page.locator('#scene-grid .available:not(.opened):not(.transition) button').evaluateAll(nodes=>nodes.map(n=>Number(n.dataset.id)));
|
assert(!field.hazards.has(id),`loss fixture: approach cell ${id} must be safe`);
|
||||||
hazard = ids.find(id=>field.hazards.has(id));
|
await cell(id).click();
|
||||||
if (hazard !== undefined) break;
|
assert.match(await cell(id).getAttribute('aria-label'),/персонаж здесь/);
|
||||||
const next = ids.find(id=>!field.hazards.has(id)); assert.notEqual(next,undefined); await cell(next).click();
|
|
||||||
}
|
}
|
||||||
assert.notEqual(hazard,undefined); await cell(hazard).click();
|
assert(field.hazards.has(hazard),'loss fixture: final cell must be hazardous');
|
||||||
|
await cell(hazard).click();
|
||||||
assert(await page.locator('#result').isVisible());
|
assert(await page.locator('#result').isVisible());
|
||||||
assert.match(await page.locator('#result').textContent(),/Падение/);
|
assert((await page.locator('#result').textContent()).includes(`Падение на ${coordinate(hazard)}`));
|
||||||
assert.equal(await page.locator('#scene-grid .hazard').count(),field.hazards.size);
|
assert.equal(await page.locator('#scene-grid .hazard').count(),field.hazards.size);
|
||||||
const count = await page.locator('#history li').count();
|
const count = await page.locator('#history li').count();
|
||||||
await cell(1).click(); assert.equal(await page.locator('#history li').count(),count);
|
await cell(1).click(); assert.equal(await page.locator('#history li').count(),count);
|
||||||
@@ -172,17 +238,18 @@ 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(hintCell).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);
|
||||||
assert.equal(await page.locator('#map-grid .hint').count(),1);
|
assert.equal(await page.locator('#map-grid .hint').count(),1);
|
||||||
assert((await page.locator('#messages').textContent()).includes(hintText));
|
assert((await page.locator('#messages').textContent()).includes(hintText));
|
||||||
await page.waitForTimeout(1100); await cell(hintCell).click();
|
const revisitHint = async () => { await cell(beforeHint).click(); await cell(hintCell).click(); };
|
||||||
|
await page.waitForTimeout(1100); await revisitHint();
|
||||||
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((await page.locator('#messages').textContent()).includes(hintText));
|
assert((await page.locator('#messages').textContent()).includes(hintText));
|
||||||
await cell(hintCell).click();
|
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('#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);
|
||||||
|
|||||||
@@ -9,28 +9,17 @@ const options = {height: 1, lu: 5, growth: 12, season: 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))};
|
||||||
}
|
}
|
||||||
function openReachableSafe(game, field) {
|
test('entrance is always x1 y1 and exits vary only on the allowed edges', () => {
|
||||||
let progress = true;
|
|
||||||
while (progress && !['won', 'lost'].includes(game.view().status)) {
|
|
||||||
progress = false;
|
|
||||||
for (const cell of game.view().cells) {
|
|
||||||
if (cell.available && !cell.opened && !cell.transition && !field.hazards.has(cell.id)) {
|
|
||||||
game.jump(cell.id); progress = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test('entrance is always x1 y1 and every other cell can host the exit', () => {
|
|
||||||
assert.equal(START, 0);
|
assert.equal(START, 0);
|
||||||
assert.equal(coordinate(START), 'x1 y1');
|
assert.equal(coordinate(START), 'x1 y1');
|
||||||
assert.equal(coordinate(59), 'x10 y6');
|
assert.equal(coordinate(59), 'x10 y6');
|
||||||
const exits = new Set();
|
const exits = new Set();
|
||||||
for (let id = 1; id < 60; id++) {
|
const allowed = [19,29,39,49,55,56,57,58,59];
|
||||||
const random = () => (id - .5) / 59;
|
for (let i = 0; i < allowed.length; i++) {
|
||||||
|
const random = () => (i + .5) / allowed.length;
|
||||||
const field = generateField(options, random);
|
const field = generateField(options, random);
|
||||||
assert.equal(field.start, 0);
|
assert.equal(field.start, 0);
|
||||||
assert.equal(field.exit, id);
|
assert(allowed.includes(field.exit));
|
||||||
exits.add(field.exit);
|
exits.add(field.exit);
|
||||||
assert(!field.hazards.has(field.start));
|
assert(!field.hazards.has(field.start));
|
||||||
assert(!field.hazards.has(field.exit));
|
assert(!field.hazards.has(field.exit));
|
||||||
@@ -47,7 +36,7 @@ test('entrance is always x1 y1 and every other cell can host the exit', () => {
|
|||||||
assert.equal(game.jump(field.exit).code, 'transition');
|
assert.equal(game.jump(field.exit).code, 'transition');
|
||||||
assert.equal(game.mark(field.exit).code, 'transition');
|
assert.equal(game.mark(field.exit).code, 'transition');
|
||||||
}
|
}
|
||||||
assert.equal(exits.size, 59);
|
assert.deepEqual([...exits].sort((a,b)=>a-b), allowed);
|
||||||
});
|
});
|
||||||
|
|
||||||
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', () => {
|
||||||
@@ -59,8 +48,10 @@ test('generation covers every settings combination with safe transitions, base a
|
|||||||
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)) {
|
||||||
assert(reached.has(field.exit));
|
if (next !== field.exit && !field.hazards.has(next)) reached.add(next);
|
||||||
|
}
|
||||||
|
assert(neighbors(field.exit).some(id => reached.has(id)));
|
||||||
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);
|
||||||
}
|
}
|
||||||
@@ -70,16 +61,27 @@ test('edge neighborhoods do not wrap rows', () => {
|
|||||||
assert.equal(neighbors(9).length, 3); assert.equal(neighbors(25).length, 8);
|
assert.equal(neighbors(9).length, 3); assert.equal(neighbors(25).length, 8);
|
||||||
assert.deepEqual(neighbors(59).sort((a,b)=>a-b), [48,49,58]);
|
assert.deepEqual(neighbors(59).sort((a,b)=>a-b), [48,49,58]);
|
||||||
});
|
});
|
||||||
test('only base or neighbors of any opened cell are available; transitions never count', () => {
|
test('only the current position’s neighbors are available, even for safe or opened cells', () => {
|
||||||
const {game} = fixture();
|
const {game} = fixture();
|
||||||
assert.equal(game.jump(START).code, 'transition');
|
assert.equal(game.jump(START).code, 'transition');
|
||||||
assert.equal(game.jump(game.view().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.jump(2).code, 'unreachable'); // safe upper-row cell, two columns away
|
||||||
|
assert.deepEqual(game.view().cells.filter(c => c.available).map(c => c.id), [1,10,11]);
|
||||||
assert.equal(game.mark(START).code, 'transition');
|
assert.equal(game.mark(START).code, 'transition');
|
||||||
assert.equal(game.jump(1).code, 'opened');
|
assert.equal(game.jump(1).code, 'opened');
|
||||||
game.jump(4); // last position differs: adjacency still belongs to any open cell
|
assert.equal(game.jump(1).code, 'unreachable');
|
||||||
assert(game.view().cells[10].available);
|
assert(game.view().cells[10].available);
|
||||||
assert.equal(game.view().position, 4);
|
assert.equal(game.jump(2).code, 'opened');
|
||||||
|
assert(!game.view().cells[10].available); // still next to opened cell 1
|
||||||
|
assert.equal(game.jump(10).code, 'unreachable');
|
||||||
|
assert.equal(game.jump(3).code, 'opened');
|
||||||
|
assert.equal(game.jump(1).code, 'unreachable'); // previously opened
|
||||||
|
assert.equal(game.view().position, 3);
|
||||||
|
assert.equal(game.jump(2).code, 'revisited');
|
||||||
|
const diagonal = fixture();
|
||||||
|
assert(!diagonal.field.hazards.has(11));
|
||||||
|
assert.equal(diagonal.game.jump(11).code, 'opened');
|
||||||
});
|
});
|
||||||
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();
|
||||||
@@ -112,7 +114,17 @@ test('all and only hazards marked wins; terminal actions cannot change state', (
|
|||||||
});
|
});
|
||||||
test('opening all safe cells wins without entering either transition', () => {
|
test('opening all safe cells wins without entering either transition', () => {
|
||||||
const {game,field} = fixture();
|
const {game,field} = fixture();
|
||||||
openReachableSafe(game, field);
|
function explore(position) {
|
||||||
|
for (const id of neighbors(position)) {
|
||||||
|
if (game.view().status === 'won') return;
|
||||||
|
const cell = game.view().cells[id];
|
||||||
|
if (cell.opened || cell.transition || field.hazards.has(id)) continue;
|
||||||
|
assert.equal(game.jump(id).code, 'opened');
|
||||||
|
explore(id);
|
||||||
|
if (game.view().status !== 'won' && position !== START) assert.equal(game.jump(position).code, 'revisited');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
explore(START);
|
||||||
assert.equal(game.view().status, 'won');
|
assert.equal(game.view().status, 'won');
|
||||||
assert.equal(game.view().opened, 58 - field.hazards.size);
|
assert.equal(game.view().opened, 58 - field.hazards.size);
|
||||||
});
|
});
|
||||||
@@ -130,20 +142,19 @@ test('hazard ends attempt, reveals wrong notes and preserves last safe position'
|
|||||||
});
|
});
|
||||||
test('LU hint probability, repeated safe visits and hidden information boundary', () => {
|
test('LU hint probability, repeated safe visits and hidden information boundary', () => {
|
||||||
assert.deepEqual(Array.from({length:10}, (_,lu)=>hintChance(lu)), [0,0,0,0,.1,.2,.3,.3,.3,.3]);
|
assert.deepEqual(Array.from({length:10}, (_,lu)=>hintChance(lu)), [0,0,0,0,.1,.2,.3,.3,.3,.3]);
|
||||||
const {game,field} = fixture();
|
const active = fixture(), noHints = fixture({...options, lu:0});
|
||||||
openReachableSafe(game, field);
|
const route = [1,2,3,4,5,4,5];
|
||||||
// Separate active game: choose an available safe base cell with adjacent hazards.
|
for (const id of route.slice(0,-1)) {
|
||||||
const active = fixture();
|
active.game.jump(id, () => 1);
|
||||||
const id = active.field.base.find(n => active.field.values[n] > 0);
|
noHints.game.jump(id, () => 0);
|
||||||
assert.notEqual(id, undefined);
|
}
|
||||||
active.game.jump(id, () => 0);
|
const revisit = active.game.jump(5, () => 0);
|
||||||
const revisit = active.game.jump(id, () => 0);
|
|
||||||
assert.equal(revisit.code, 'revisited');
|
assert.equal(revisit.code, 'revisited');
|
||||||
assert(active.field.hazards.has(revisit.hint));
|
assert(active.field.hazards.has(revisit.hint));
|
||||||
assert.equal(active.game.view().cells[revisit.hint].value, null);
|
assert.equal(active.game.view().cells[revisit.hint].value, null);
|
||||||
assert.equal(active.game.view().opened, 1);
|
assert.equal(active.game.view().opened, 5);
|
||||||
assert.equal(active.game.view().history.length, 2);
|
assert.equal(active.game.view().history.length, route.length);
|
||||||
assert.equal(new Training({...options,lu:0}, seeded()).jump(id, () => 0).hint, null);
|
assert.equal(noHints.game.jump(5, () => 0).hint, null);
|
||||||
});
|
});
|
||||||
test('invalid settings are rejected rather than corrupting generation', () => {
|
test('invalid settings are rejected rather than corrupting generation', () => {
|
||||||
for (const bad of [{height:0},{lu:10},{growth:99},{season:7}]) assert.throws(()=>new Training({...options,...bad}), RangeError);
|
for (const bad of [{height:0},{lu:10},{growth:99},{season:7}]) assert.throws(()=>new Training({...options,...bad}), RangeError);
|
||||||
|
|||||||
+4
-4
@@ -40,7 +40,7 @@
|
|||||||
<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="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">
|
||||||
<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>
|
||||||
@@ -54,7 +54,7 @@
|
|||||||
<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">Выбрана клетка x1 y1 · вход</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">Выберите доступную стартовую клетку. Стрелки перемещают фокус, 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>
|
||||||
@@ -94,8 +94,8 @@
|
|||||||
<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>Вход всегда находится в x1 y1 — верхней левой клетке. X растёт вправо, Y — вниз. Выход в этой модели выбирается случайно для каждой новой попытки и может занять любую другую клетку. Переходы отмечены стрелками: по ним не прыгают. В верхней строке доступны 5 безопасных стартовых клеток на высоте 1 и 3 выше, не считая переходов.</li>
|
<li>Вход всегда находится в x1 y1 — верхней левой клетке. X растёт вправо, Y — вниз. Выход выбирается случайно: на правом краю (x10, начиная с y2) или на нижнем (y6, начиная с x6). Стрелки отмечают переходы; в тренажёре по ним не прыгают.</li>
|
||||||
<li>Открывайте клетки рядом с любой проверенной, включая диагонали. Персонаж показывает последний успешный прыжок, а не ограничивает его дальность.</li>
|
<li>Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. Безопасные клетки верхнего ряда начинаются сразу справа от входа: 5 на первой высоте и 3 на остальных. Идите по ним по одной.</li>
|
||||||
<li>Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.</li>
|
<li>Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.</li>
|
||||||
<li>На компьютере клик выполняет выбранное действие, правая кнопка ставит заметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной».</li>
|
<li>На компьютере клик выполняет выбранное действие, правая кнопка ставит заметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной».</li>
|
||||||
<li>На обеих сетках стрелки перемещают фокус; Home / End — начало / конец строки. Enter и пробел выполняют действие. На карте они только выбирают клетку.</li>
|
<li>На обеих сетках стрелки перемещают фокус; Home / End — начало / конец строки. Enter и пробел выполняют действие. На карте они только выбирают клетку.</li>
|
||||||
|
|||||||
@@ -4,6 +4,11 @@ export const ROWS = 6;
|
|||||||
export const COLS = 10;
|
export const COLS = 10;
|
||||||
export const START = 0;
|
export const START = 0;
|
||||||
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 });
|
||||||
|
const EXIT_CELLS = Array.from({length: ROWS * COLS}, (_, id) => id)
|
||||||
|
.filter(id => {
|
||||||
|
const x = id % COLS + 1, y = Math.floor(id / COLS) + 1;
|
||||||
|
return (x === COLS && y >= 2) || (y === ROWS && x >= 6);
|
||||||
|
});
|
||||||
|
|
||||||
export function neighbors(id) {
|
export function neighbors(id) {
|
||||||
const row = Math.floor(id / COLS), col = id % COLS, result = [];
|
const row = Math.floor(id / COLS), col = id % COLS, result = [];
|
||||||
@@ -28,10 +33,9 @@ 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 exit = 1 + Math.floor(random() * (ROWS * COLS - 1));
|
const exit = EXIT_CELLS[Math.floor(random() * EXIT_CELLS.length)];
|
||||||
// Transitions do not consume one of the 5/3 initially playable safe cells.
|
// The safe strip starts next to the entrance; exits never occupy the top row.
|
||||||
const base = Array.from({length: COLS - 1}, (_,i)=>i + 1)
|
const base = Array.from({length: options.height === 1 ? 5 : 3}, (_, i) => i + 1);
|
||||||
.filter(id => id !== exit).slice(0, options.height === 1 ? 5 : 3);
|
|
||||||
const reserved = new Set([START, exit, ...base]);
|
const reserved = new Set([START, exit, ...base]);
|
||||||
function connect(from, to) {
|
function connect(from, to) {
|
||||||
while (from !== to) {
|
while (from !== to) {
|
||||||
@@ -69,7 +73,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 === this.#field.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.#transition(id) && distance(this.#position, id) === 1; }
|
||||||
#guard(id) {
|
#guard(id) {
|
||||||
if (this.#finished()) return {code: 'finished'};
|
if (this.#finished()) return {code: 'finished'};
|
||||||
if (!this.#valid(id)) return {code: 'invalid'};
|
if (!this.#valid(id)) return {code: 'invalid'};
|
||||||
|
|||||||
@@ -15,17 +15,16 @@ 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.entrance) return 'вход';
|
if (cell.entrance) return 'вход';
|
||||||
if (cell.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}${cell.available ? ', прыжок доступен' : ''}`;
|
||||||
if (ended(view)) return `безопасная клетка, опасностей рядом: ${cell.value}`;
|
if (ended(view)) return `безопасная клетка, опасностей рядом: ${cell.value}`;
|
||||||
if (cell.marked) return 'ваша отметка опасности';
|
if (cell.marked) return 'ваша отметка опасности';
|
||||||
if (hints.has(cell.id)) return 'подсказка: опасность';
|
if (hints.has(cell.id)) return 'подсказка: опасность';
|
||||||
return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, сначала откройте соседнюю клетку';
|
return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, не рядом с персонажем';
|
||||||
}
|
}
|
||||||
function cellValue(cell, view, showMarks) {
|
function cellValue(cell, view, showMarks) {
|
||||||
if (cell.transition) return cell.entrance ? '↥' : '↗';
|
if (cell.transition) return cell.entrance ? '↥' : '↗';
|
||||||
@@ -105,7 +104,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 = `Начальные клетки: ${initialCells(game.view())}. Стрелки перемещают фокус, Enter или пробел выполняет действие.`;
|
$('status').textContent = 'Начните с клетки рядом со входом. Стрелки перемещают фокус, Enter или пробел выполняет действие.';
|
||||||
updateClock(); render();
|
updateClock(); render();
|
||||||
}
|
}
|
||||||
function render() {
|
function render() {
|
||||||
@@ -133,7 +132,7 @@ function render() {
|
|||||||
$('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 ? `Выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной». Начальные клетки: ${initialCells(view)}.` : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Начальные клетки: ${initialCells(view)}; затем рядом с любой проверенной клеткой.`;
|
$('scene-instructions').textContent = compact.matches ? 'Выберите соседнюю клетку и нажмите «Прыгнуть». Отметку можно поставить где угодно на уступе.' : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Прыгать можно только в соседние клетки, в том числе по диагонали.`;
|
||||||
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)}`;
|
||||||
@@ -171,7 +170,7 @@ function act(action) {
|
|||||||
} else if (result.code === 'fall') {
|
} else if (result.code === 'fall') {
|
||||||
text = `Падение на ${coordinate(selected)}. Попытка завершена.`; addItem($('messages'), text);
|
text = `Падение на ${coordinate(selected)}. Попытка завершена.`; addItem($('messages'), text);
|
||||||
} else {
|
} else {
|
||||||
text = {finished:'Попытка завершена. Изучите поле или начните новую игру.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Сначала откройте соседнюю клетку или начните с безопасных клеток верхнего ряда.',marked: action === 'jump' ? 'Сначала снимите отметку опасности с этой клетки.' : `${coordinate(selected)}: поставлена ваша отметка опасности.`,unmarked:`${coordinate(selected)}: отметка снята.`,opened:'Проверенную клетку нельзя отметить опасной.'}[result.code];
|
text = {finished:'Попытка завершена. Изучите поле или начните новую игру.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Прыгнуть можно только в соседнюю клетку. Выберите клетку рядом с персонажем.',marked: action === 'jump' ? 'Сначала снимите отметку опасности с этой клетки.' : `${coordinate(selected)}: поставлена ваша отметка опасности.`,unmarked:`${coordinate(selected)}: отметка снята.`,opened:'Проверенную клетку нельзя отметить опасной.'}[result.code];
|
||||||
}
|
}
|
||||||
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 += ' Карта готова! Победа. Всё поле раскрыто.';
|
||||||
|
|||||||
Reference in new issue
Block a user