Add WASD jumps to the LU trainer

This commit is contained in:
nyan404 committed 2026-11-22 18:19:44 +03:00
1 parent ba074df4ec
commit a2751971cd
6 files changed
+59 -5

No files matched your search

+1 -1
View File
@@ -36,7 +36,7 @@
## Notes ## Notes
- LU trainer is implemented at `/trainer` and `/trainer/` through both Python and Nginx. `web/lu-trainer/engine.js` is DOM-free; UI consumes public snapshots without hidden hazards/values. Keep notes separate from facts, map selection separate from jumping, jumps limited to the eight neighbors of the current position, and transition cells outside victory counts. Entrance is fixed at x1 y1 (top-left); choose each field's exit from x10 y2–y6 or y6 x6–x10. UI/map must use snapshot transition identities, never a global exit constant. Coordinates are one-based X right/Y down. Preserve documented training formulas; do not claim they are verified CatWar rules. Original art provenance is in `web/lu-trainer/assets/README.md`. - LU trainer is implemented at `/trainer` and `/trainer/` through both Python and Nginx. `web/lu-trainer/engine.js` is DOM-free; UI consumes public snapshots without hidden hazards/values. Keep notes separate from facts, map selection separate from jumping, jumps limited to the eight neighbors of the current position, and transition cells outside victory counts. Entrance is fixed at x1 y1 (top-left); choose each field's exit from x10 y2–y6 or y6 x6–x10. UI/map must use snapshot transition identities, never a global exit constant. Coordinates are one-based X right/Y down. Preserve documented training formulas; do not claim they are verified CatWar rules. Original art provenance is in `web/lu-trainer/assets/README.md`.
- Trainer controls: click/Enter/Space jumps; right-click or Shift+Enter on the scene toggles a mark. Compact and coarse-pointer layouts use selection plus buttons under the field, without a separate action-mode switch. Keep the field status brief and the detailed jump message in the journal. - Trainer controls: click/Enter/Space jumps; with focus on the scene, physical WASD keys jump one cell from the current position in four directions, without key repeat. Arrows move focus only; right-click or Shift+Enter on the scene toggles a mark. Compact and coarse-pointer layouts use selection plus buttons under the field, without a separate action-mode switch. Keep the field status brief and the detailed jump message in the journal.
- Trainer map ratings 0–7 are independent of verified values and hazard flags; `null` means no rating, `0` means no danger around the cell. Sound mode hides numeric facts and LU hints during play; simplified mode reveals the level of opened cells and the entrance. `audio.js` generates cues locally and starts playback only via an action or replay. - Trainer map ratings 0–7 are independent of verified values and hazard flags; `null` means no rating, `0` means no danger around the cell. Sound mode hides numeric facts and LU hints during play; simplified mode reveals the level of opened cells and the entrance. `audio.js` generates cues locally and starts playback only via an action or replay.
- Keep the phone map below the scene on the same scrollable page. The safe start x1 y1 is not a transition; it can be revisited from an adjacent cell but does not count as opened or accept marks/ratings. Only the exit remains an impassable transition. The start has 0–2 neighboring hazards, x1 y2 at most 3 and x1 y3 at most 4. Apply those limits to generated hazards, not displayed values. The start number is visible in simplified mode and after the attempt. - Keep the phone map below the scene on the same scrollable page. The safe start x1 y1 is not a transition; it can be revisited from an adjacent cell but does not count as opened or accept marks/ratings. Only the exit remains an impassable transition. The start has 0–2 neighboring hazards, x1 y2 at most 3 and x1 y3 at most 4. Apply those limits to generated hazards, not displayed values. The start number is visible in simplified mode and after the attempt.
- LU checks (prefer remote test-zone MCP when exposed): Node 24 `node --test tests/lu-trainer/engine.test.mjs`; isolated Python `python -m unittest tests.test_lu_trainer tests.test_calculator_web -q`; `node --check web/lu-trainer/ui.js`; `node tests/browser/lu-trainer.cjs` with the same bundled Playwright, loopback server and temporary stores as the calculator suite. No npm install or runtime dependency is needed. Browser coverage includes 1920/1366/768/390 widths, mouse/touch/keyboard, map projection, clear/restart confirmation, result locks, hints/timers, 200% layout and failed images. Inspect screenshots outside Git. Nginx aliases must serve the same HTML and correct asset MIME types; do not deploy to validate a client-only change. - 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.
+1 -1
View File
@@ -45,7 +45,7 @@ python3 -m app.belki.vk_bot
Самостоятельная клиентская тренировка без регистрации, БД и новых runtime-зависимостей. Она не подключается к CatWar и не начисляет ЛУ. Поле, история и заметки существуют до перезагрузки страницы. Самостоятельная клиентская тренировка без регистрации, БД и новых runtime-зависимостей. Она не подключается к CatWar и не начисляет ЛУ. Поле, история и заметки существуют до перезагрузки страницы.
На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Стрелки и Home / End перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Показывать заметки на поле» меняет только их видимость на локации. Очистка отметок и новая игра имеют разные подтверждения. На компьютере клик по клетке локации — прыжок, правый клик ставит или снимает отметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной» под полем. Когда фокус на локации, WASD прыгает из текущей клетки вверх, влево, вниз или вправо. Стрелки и Home / End только перемещают фокус. На локации Enter или пробел — прыжок, Shift+Enter — отметка. На карте Enter и пробел только выбирают клетку. «Показывать заметки на поле» меняет только их видимость на локации. Очистка отметок и новая игра имеют разные подтверждения.
По умолчанию после прыжка звучат синтезированные шорохи: при уровне 0 — тишина, при 1–7 — столько же шорохов. Уровень равен числу соседних опасностей с учётом диагоналей, но 7 означает «семь и больше». «Повторить звук» воспроизводит сигнал текущей клетки. «Упрощённый режим» показывает уровни на стартовой и проверенных клетках вместо звука и включает подсказки ЛУ. По умолчанию после прыжка звучат синтезированные шорохи: при уровне 0 — тишина, при 1–7 — столько же шорохов. Уровень равен числу соседних опасностей с учётом диагоналей, но 7 означает «семь и больше». «Повторить звук» воспроизводит сигнал текущей клетки. «Упрощённый режим» показывает уровни на стартовой и проверенных клетках вместо звука и включает подсказки ЛУ.
@@ -20,3 +20,5 @@ Owner corrections: entrance fixed x1 y1 and exit variable (2026-11-17); limit ex
Additional owner correction (2026-11-22): x1 y1 is safe and has at most 2 neighboring hazards, x1 y2 at most 3, and x1 y3 at most 4. The entrance value is available as a fact without opening the entrance; keep it hidden in sound mode until the attempt ends. Additional owner correction (2026-11-22): x1 y1 is safe and has at most 2 neighboring hazards, x1 y2 at most 3, and x1 y3 at most 4. The entrance value is available as a fact without opening the entrance; keep it hidden in sound mode until the attempt ends.
Start-cell correction: x1 y1 is a safe spawn, not a floor transition. Jumping back from an adjacent cell is a revisit. Floor switching remains out of scope. Start-cell correction: x1 y1 is a safe spawn, not a floor transition. Jumping back from an adjacent cell is a revisit. Floor switching remains out of scope.
Keyboard shortcut: while a scene cell has focus, physical WASD keys jump from the cat's current position in the four cardinal directions. A held key does not repeat jumps. Arrow keys still move only the focus.
+38
View File
@@ -72,6 +72,44 @@ async function run() {
const captures = []; const captures = [];
try { try {
if (shotDir) await mkdir(shotDir,{recursive:true}); if (shotDir) await mkdir(shotDir,{recursive:true});
const shortcuts = await browser.newContext({viewport:{width:1366,height:768}});
try {
await shortcuts.addInitScript(() => {
let seed = 19;
Math.random = () => { seed = (Math.imul(seed,1664525)+1013904223) >>> 0; return seed / 2 ** 32; };
});
const page = await shortcuts.newPage();
await page.goto(`${origin}/trainer`);
const sceneCell = id => page.locator(`#scene-grid button[data-id="${id}"]`);
const current = () => cellIds(page.locator('#scene-grid .current button'));
await sceneCell(0).waitFor();
await page.locator('#simple-mode').check();
await sceneCell(0).focus();
await page.keyboard.press('d');
assert.deepEqual(await current(),[1]);
await page.keyboard.down('s');
await page.keyboard.down('s');
await page.keyboard.up('s');
assert.deepEqual(await current(),[11],'holding a key must not repeat jumps');
await sceneCell(59).focus();
await page.keyboard.press('a');
assert.deepEqual(await current(),[10],'direction starts at the cat, not keyboard focus');
await page.keyboard.press('w');
assert.deepEqual(await current(),[0]);
assert.equal(await page.locator('#history li').count(),4);
await page.keyboard.press('a');
await page.keyboard.press('w');
assert.deepEqual(await current(),[0],'edges must not wrap');
await page.keyboard.press('ArrowRight');
assert(await sceneCell(1).evaluate(n=>n===document.activeElement));
await page.locator('#map-grid button[data-id="1"]').focus();
await page.keyboard.press('d');
assert.deepEqual(await current(),[0],'map focus must not move the cat');
await page.locator('#settings-open').click();
await page.keyboard.press('d');
assert.deepEqual(await current(),[0],'dialogs must not move the cat');
console.log('PASS WASD direct jumps, repeat prevention, edges, arrows, map and dialog isolation');
} finally { await shortcuts.close(); }
for (const [width,height,touch = false] of [[1920,1080],[1366,768],[768,1024],[390,844,true],[844,390,true],[1024,768,true]]) { for (const [width,height,touch = false] of [[1920,1080],[1366,768],[768,1024],[390,844,true],[844,390,true],[1024,768,true]]) {
const mobile = width <= 700 || width === 844, compact = mobile || touch; const mobile = width <= 700 || width === 844, compact = mobile || touch;
const context = await browser.newContext({viewport:{width,height}, reducedMotion:'reduce', locale:'ru-RU', hasTouch:touch, isMobile:mobile}); const context = await browser.newContext({viewport:{width,height}, reducedMotion:'reduce', locale:'ru-RU', hasTouch:touch, isMobile:mobile});
+2 -2
View File
@@ -44,7 +44,7 @@
<button id="replay-sound" type="button" disabled>Повторить звук</button> <button id="replay-sound" type="button" disabled>Повторить звук</button>
</div> </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">Нажмите на соседнюю клетку, чтобы прыгнуть. Правая кнопка мыши или Shift+Enter ставят или снимают флажок.</p> <p id="scene-instructions" class="scene-instructions">Клик по соседней клетке или WASD при фокусе на поле: прыжок. Правая кнопка мыши или Shift+Enter ставят или снимают флажок.</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>
@@ -111,7 +111,7 @@
<li>Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. В верхнем ряду сразу справа от старта есть безопасные клетки: 5 на первой высоте и 3 на остальных. Прыгайте по ним по одной клетке за раз.</li> <li>Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. В верхнем ряду сразу справа от старта есть безопасные клетки: 5 на первой высоте и 3 на остальных. Прыгайте по ним по одной клетке за раз.</li>
<li>После прыжка прислушайтесь: тишина означает уровень 0, а число коротких шорохов подсказывает уровень от 1 до 7. На старте звук можно включить кнопкой «Повторить звук», если рядом есть опасности. В упрощённом режиме число опасностей видно на стартовой и проверенных клетках. Соседи по диагонали тоже считаются. 7 означает семь или больше.</li> <li>После прыжка прислушайтесь: тишина означает уровень 0, а число коротких шорохов подсказывает уровень от 1 до 7. На старте звук можно включить кнопкой «Повторить звук», если рядом есть опасности. В упрощённом режиме число опасностей видно на стартовой и проверенных клетках. Соседи по диагонали тоже считаются. 7 означает семь или больше.</li>
<li>Если под полем есть кнопки, сначала выберите клетку, затем нажмите «Прыгнуть», «Отметить опасной» или «Снять отметку». Если кнопок нет, нажмите на соседнюю клетку, чтобы прыгнуть. Правая кнопка мыши ставит или снимает флажок.</li> <li>Если под полем есть кнопки, сначала выберите клетку, затем нажмите «Прыгнуть», «Отметить опасной» или «Снять отметку». Если кнопок нет, нажмите на соседнюю клетку, чтобы прыгнуть. Правая кнопка мыши ставит или снимает флажок.</li>
<li>Выбирайте клетки стрелками. Нажмите Home, чтобы перейти в начало строки, или End, чтобы перейти в конец. На игровом поле Enter и пробел позволяют прыгнуть, а Shift+Enter ставит или снимает флажок. На карте Enter и пробел только выбирают клетку.</li> <li>Нажимайте Tab, пока выделение не окажется на игровом поле. W, A, S и D сразу выполняют прыжок из текущей клетки: вверх, влево, вниз и вправо. Стрелки только выбирают клетку, Home и End переводят фокус в начало и конец строки. На игровом поле Enter и пробел выполняют прыжок, Shift+Enter ставит или снимает флажок. На карте Enter и пробел только выбирают клетку.</li>
<li>На телефоне прокрутите страницу вниз до «Минного поля». На карте выберите клетку и поставьте свою оценку кнопкой или клавишей 0–7. Чтобы убрать оценку, нажмите Delete или Backspace. Оценка не мешает прыгать и не влияет на победу. Чтобы прыгнуть на клетку с флажком, сначала снимите флажок. В упрощённом режиме при 4 ЛУ и выше может появиться подсказка «!».</li> <li>На телефоне прокрутите страницу вниз до «Минного поля». На карте выберите клетку и поставьте свою оценку кнопкой или клавишей 0–7. Чтобы убрать оценку, нажмите Delete или Backspace. Оценка не мешает прыгать и не влияет на победу. Чтобы прыгнуть на клетку с флажком, сначала снимите флажок. В упрощённом режиме при 4 ЛУ и выше может появиться подсказка «!».</li>
<li>Чтобы победить, откройте все безопасные клетки, кроме старта и выхода, или отметьте флажками все опасности без ошибок. Прыжок на опасную клетку заканчивается падением.</li> <li>Чтобы победить, откройте все безопасные клетки, кроме старта и выхода, или отметьте флажками все опасности без ошибок. Прыжок на опасную клетку заканчивается падением.</li>
</ul> </ul>
+15 -1
View File
@@ -4,6 +4,7 @@ import {playSound, stopSound} from './audio.js';
const $ = id => document.getElementById(id); const $ = id => document.getElementById(id);
const compact = matchMedia('(max-width: 700px), (pointer: coarse)'); const compact = matchMedia('(max-width: 700px), (pointer: coarse)');
const phoneMap = matchMedia('(max-width: 700px), (max-width: 1100px) and (max-height: 500px) and (pointer: coarse)'); const phoneMap = matchMedia('(max-width: 700px), (max-width: 1100px) and (max-height: 500px) and (pointer: coarse)');
const jumpKeys = new Map([['KeyW',[0,-1]], ['KeyA',[-1,0]], ['KeyS',[0,1]], ['KeyD',[1,0]]]);
const sounds = ['Звуков нет', 'Едва различимый шорох', 'Тихий шорох', 'Приглушённый шорох', 'Громкий шорох']; const sounds = ['Звуков нет', 'Едва различимый шорох', 'Тихий шорох', 'Приглушённый шорох', 'Громкий шорох'];
let game, selected = START, hints = new Set(), hintTimers = new Map(); let game, selected = START, hints = new Set(), hintTimers = new Map();
let messages = []; let messages = [];
@@ -123,6 +124,19 @@ function makeGrid(id, isMap) {
return; return;
} }
let next; let next;
const step = !isMap && jumpKeys.get(event.code);
if (step && !event.isComposing) {
event.preventDefault();
const view = game.view();
if (event.repeat || ended(view)) return;
const x = view.position % COLS + step[0], y = Math.floor(view.position / COLS) + step[1];
if (x < 0 || x >= COLS || y < 0 || y >= ROWS) return;
const target = y * COLS + x;
buttons[target].focus();
selectCell(target);
act('jump');
return;
}
if (event.key === 'Home') next = buttons[Math.floor(index / COLS) * COLS]; if (event.key === 'Home') next = buttons[Math.floor(index / COLS) * COLS];
else if (event.key === 'End') next = buttons[Math.floor(index / COLS) * COLS + COLS - 1]; else if (event.key === 'End') next = buttons[Math.floor(index / COLS) * COLS + COLS - 1];
else { else {
@@ -200,7 +214,7 @@ function render() {
$('mark-count').textContent = view.marks; $('hazard-count').textContent = view.hazards; $('mark-count').textContent = view.marks; $('hazard-count').textContent = view.hazards;
$('rating-count').textContent = view.ratings; $('rating-count').textContent = view.ratings;
$('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status]; $('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status];
$('scene-instructions').textContent = compact.matches ? 'Выберите клетку, затем нажмите нужную кнопку под полем.' : 'Нажмите на соседнюю клетку, чтобы прыгнуть. Правая кнопка мыши или Shift+Enter ставят или снимают флажок.'; $('scene-instructions').textContent = compact.matches ? 'Выберите клетку, затем нажмите нужную кнопку под полем.' : 'Клик по соседней клетке или WASD при фокусе на поле: прыжок. Правая кнопка мыши или Shift+Enter ставят или снимают флажок.';
const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной'; const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной';
const selectionState = finished ? 'попытка завершена' : cell.id === view.position ? 'вы здесь' : const selectionState = finished ? 'попытка завершена' : cell.id === view.position ? 'вы здесь' :
cell.entrance ? (cell.available ? 'старт' : 'старт, вне досягаемости') : cell.entrance ? (cell.available ? 'старт' : 'старт, вне досягаемости') :