feat: add trainer sound mode and manual danger ratings
This commit is contained in:
1 parent
9be0bb48c8
commit
ad8e2d1438
13 files changed
+466
-58
No files matched your search
+19
-8
@@ -39,6 +39,10 @@
|
||||
<div class="center-column">
|
||||
<section class="location panel">
|
||||
<div class="location-heading"><h2 id="location-title" tabindex="-1">Лесные уступы</h2><span id="scene-height">Высота 1</span></div>
|
||||
<div class="listen-controls">
|
||||
<label class="check" for="simple-mode"><input id="simple-mode" type="checkbox"> Упрощённый режим</label>
|
||||
<button id="replay-sound" type="button" disabled>Повторить звук</button>
|
||||
</div>
|
||||
<p id="transition-coordinates" class="scene-instructions">Вход: x1 y1 · Выход выбирается для новой попытки</p>
|
||||
<p id="scene-instructions" class="scene-instructions">Клик по соседней клетке — прыжок. Правый клик — поставить или снять отметку.</p>
|
||||
<div class="scene" id="scene">
|
||||
@@ -53,20 +57,29 @@
|
||||
</div>
|
||||
<p id="status" role="status" aria-atomic="true"></p>
|
||||
</div>
|
||||
<p class="legend">↥ Вход / выход <span>· Проверено</span> <span>⚑ Ваша отметка</span> <span>× Опасность в результате</span> <span>≠ Ошибочная отметка</span></p>
|
||||
<p class="legend">↥ Вход / выход <span>· Проверено</span> <span>⚑ Флажок опасности</span> <span><span class="rating-key">0–7</span> Ваша оценка</span> <span>× Опасность в результате</span> <span>≠ Ошибочная отметка</span></p>
|
||||
<p id="result" class="result" hidden></p>
|
||||
<div class="mobile-tools"><button id="map-open" type="button">Минное поле</button><button id="history-open" type="button">История</button></div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="right-column">
|
||||
<section class="panel messages-panel"><h2>Сообщения</h2><p class="fineprint">Прислушивайтесь к ветвям: число показывает опасности вокруг клетки, включая диагонали.</p><ol id="messages" class="journal messages"><li class="initial-message">Лес затих. Звуки появятся после прыжка.</li></ol></section>
|
||||
<section class="panel messages-panel"><h2>Сообщения</h2><p id="sound-guide" class="fineprint">После прыжка прислушайтесь к шорохам и оцените клетку на карте.</p><ol id="messages" class="journal messages"><li class="initial-message">Лес затих. Звуки появятся после прыжка.</li></ol></section>
|
||||
<section class="panel map-panel" id="map-home">
|
||||
<div class="panel-heading"><h2><button id="map-toggle" type="button" aria-expanded="true" aria-controls="map-body">Минное поле <span aria-hidden="true">−</span></button></h2><button id="map-expand" type="button">Развернуть</button></div>
|
||||
<div id="map-body">
|
||||
<p class="fineprint">Карта заметок · <span id="mark-count">0</span> отметок / <span id="hazard-count">12</span> опасностей</p>
|
||||
<p class="fineprint">Флажки: <span id="mark-count">0</span> / <span id="hazard-count">12</span> · Оценки: <span id="rating-count">0</span></p>
|
||||
<div class="map-scroll"><div id="map-grid" class="cell-grid map-grid" role="grid" aria-label="Минное поле" aria-rowcount="6" aria-colcount="10" aria-describedby="map-instructions"></div></div>
|
||||
<p id="map-instructions" class="fineprint">Клетка карты только выбирается. Заметка не подтверждает опасность.</p>
|
||||
<p id="map-instructions" class="fineprint">Выберите клетку и поставьте оценку 0–7 кнопкой или клавишей. Ноль — рядом нет опасностей.</p>
|
||||
<p id="map-selection">Выбрана x1 y1 · вход</p>
|
||||
<p id="map-rating-status" class="visually-hidden" role="status" aria-atomic="true"></p>
|
||||
<fieldset id="map-levels">
|
||||
<legend>Ваша оценка</legend>
|
||||
<div class="rating-buttons">
|
||||
<button type="button" data-level="0" aria-label="Уровень 0: вокруг безопасно" aria-pressed="false">0</button>
|
||||
<button type="button" data-level="1" aria-label="Уровень 1" aria-pressed="false">1</button><button type="button" data-level="2" aria-label="Уровень 2" aria-pressed="false">2</button><button type="button" data-level="3" aria-label="Уровень 3" aria-pressed="false">3</button><button type="button" data-level="4" aria-label="Уровень 4" aria-pressed="false">4</button><button type="button" data-level="5" aria-label="Уровень 5" aria-pressed="false">5</button><button type="button" data-level="6" aria-label="Уровень 6" aria-pressed="false">6</button><button type="button" data-level="7" aria-label="Уровень 7" aria-pressed="false">7</button>
|
||||
</div>
|
||||
<button id="map-clear-level" type="button">Убрать оценку</button>
|
||||
</fieldset>
|
||||
<button id="map-mark" type="button">Отметить опасной</button>
|
||||
<label class="check" for="project-marks"><input id="project-marks" type="checkbox" checked> Перенос на игровое поле</label>
|
||||
<button id="clear-marks" type="button" class="quiet">Очистить отметки</button>
|
||||
@@ -96,14 +109,12 @@
|
||||
<ul class="help-list">
|
||||
<li>Вход всегда находится в x1 y1 — верхней левой клетке. X растёт вправо, Y — вниз. Выход выбирается случайно: на правом краю (x10, начиная с y2) или на нижнем (y6, начиная с x6). Стрелки отмечают переходы; в тренажёре по ним не прыгают.</li>
|
||||
<li>Прыгайте только в соседнюю с персонажем клетку, в том числе по диагонали. Безопасные клетки верхнего ряда начинаются сразу справа от входа: 5 на первой высоте и 3 на остальных. Идите по ним по одной.</li>
|
||||
<li>Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.</li>
|
||||
<li>После прыжка звучат короткие шорохи. Тишина означает нулевой уровень; число шорохов — уровень от 1 до 7. Шорохи синтезированы для тренажёра. В упрощённом режиме вместо звука вы увидите уровень: это число опасностей вокруг клетки, включая диагонали (7 означает семь или больше).</li>
|
||||
<li>На компьютере клик по клетке — прыжок, правый клик ставит или снимает отметку. На телефоне сначала коснитесь клетки, затем нажмите «Прыгнуть» или «Отметить опасной» под полем.</li>
|
||||
<li>Стрелки перемещают фокус; Home / End — начало / конец строки. На локации Enter и пробел выполняют прыжок, Shift+Enter ставит или снимает отметку. На карте Enter и пробел только выбирают клетку.</li>
|
||||
<li>Отмеченная клетка закрыта для прыжка, пока вы не снимете отметку. Карта не показывает скрытые опасности. При ЛУ от 4 возможна подсказка «!»: координата останется в сообщениях.</li>
|
||||
<li>На «Минном поле» выберите клетку и поставьте свою оценку кнопкой или клавишей 0–7. Delete или Backspace снимает оценку. Оценка не мешает прыжкам и не влияет на победу. Отдельный флажок «Отметить опасной» закрывает клетку для прыжка. В упрощённом режиме при ЛУ от 4 возможна подсказка «!».</li>
|
||||
<li>Победа: открыть все безопасные клетки, кроме переходов, или отметить все опасности без лишних отметок. Достижение выхода не завершает игру. Опасный прыжок заканчивается падением.</li>
|
||||
</ul>
|
||||
<h3>Справочник звуков модели</h3>
|
||||
<dl class="sound-guide"><div><dt>0</dt><dd>Звуков нет</dd></div><div><dt>1</dt><dd>Едва различимый шорох</dd></div><div><dt>2</dt><dd>Тихий шорох</dd></div><div><dt>3</dt><dd>Приглушённый шорох</dd></div><div><dt>4</dt><dd>Громкий шорох</dd></div><div><dt>5–8</dt><dd>Очень громкий шорох</dd></div></dl>
|
||||
<div class="dialog-actions"><button type="button" data-close autofocus>Вернуться к тренировке</button></div>
|
||||
</dialog>
|
||||
<dialog id="confirm-dialog" aria-labelledby="confirm-title"><h2 id="confirm-title">Начать заново?</h2><p id="confirm-text"></p><form method="dialog" class="dialog-actions"><button value="cancel" autofocus>Отмена</button><button value="confirm" class="primary" id="confirm-action">Начать новую игру</button></form></dialog>
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// A training cue, not recorded CatWar audio: one short rustle per level.
|
||||
export function rustleSamples(level, sampleRate) {
|
||||
const step = Math.round(sampleRate * .23);
|
||||
const pulse = Math.round(sampleRate * .095);
|
||||
const samples = new Float32Array(step * level);
|
||||
let seed = 521, filtered = 0;
|
||||
for (let start = 0; start < samples.length; start += step) {
|
||||
for (let i = 0; i < pulse; i++) {
|
||||
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
||||
filtered = .6 * filtered + .4 * (seed / 0x80000000 - 1);
|
||||
samples[start + i] = .45 * filtered * Math.sin(Math.PI * i / pulse) ** 2;
|
||||
}
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
let context, source, request = 0;
|
||||
|
||||
export function stopSound() {
|
||||
request++;
|
||||
if (source) { source.stop(); source = null; }
|
||||
}
|
||||
|
||||
export async function playSound(level) {
|
||||
stopSound();
|
||||
if (!level) return;
|
||||
const id = request;
|
||||
context ??= new AudioContext();
|
||||
if (context.state !== 'running') await context.resume();
|
||||
if (id !== request) return;
|
||||
const samples = rustleSamples(level, context.sampleRate);
|
||||
const buffer = context.createBuffer(1, samples.length, context.sampleRate);
|
||||
buffer.copyToChannel(samples, 0);
|
||||
const cue = context.createBufferSource();
|
||||
cue.buffer = buffer;
|
||||
cue.connect(context.destination);
|
||||
cue.addEventListener('ended', () => {
|
||||
cue.disconnect();
|
||||
if (source === cue) source = null;
|
||||
});
|
||||
cue.start();
|
||||
source = cue;
|
||||
}
|
||||
@@ -61,6 +61,7 @@ export class Training {
|
||||
#field;
|
||||
#opened = new Set();
|
||||
#marks = new Set();
|
||||
#ratings = new Map();
|
||||
#position = START;
|
||||
#status = 'ready';
|
||||
#hit = null;
|
||||
@@ -115,22 +116,32 @@ export class Training {
|
||||
this.#win();
|
||||
return {code: marked ? 'marked' : 'unmarked', id};
|
||||
}
|
||||
rate(id, rating) {
|
||||
const rejected = this.#guard(id);
|
||||
if (rejected) return rejected;
|
||||
if (rating !== null && (!Number.isInteger(rating) || rating < 0 || rating > 7)) return {code: 'invalid-level'};
|
||||
if ((this.#ratings.get(id) ?? null) === rating) return {code: 'unchanged'};
|
||||
if (rating === null) this.#ratings.delete(id); else this.#ratings.set(id, rating);
|
||||
const code = rating === null ? 'unrated' : 'rated';
|
||||
this.#history.push({type: code, id, rating});
|
||||
return {code, id, rating};
|
||||
}
|
||||
clearMarks() {
|
||||
if (this.#finished()) return {code: 'finished'};
|
||||
if (!this.#marks.size) return {code: 'empty'};
|
||||
this.#marks.clear(); this.#history.push({type: 'cleared'});
|
||||
if (!this.#marks.size && !this.#ratings.size) return {code: 'empty'};
|
||||
this.#marks.clear(); this.#ratings.clear(); this.#history.push({type: 'cleared'});
|
||||
return {code: 'cleared'};
|
||||
}
|
||||
view() {
|
||||
const ended = this.#finished();
|
||||
return {
|
||||
options: {...this.#options}, start: START, exit: this.#field.exit, status: this.#status, position: this.#position, hit: this.#hit,
|
||||
hazards: this.#field.hazards.size, marks: this.#marks.size, opened: this.#opened.size,
|
||||
hazards: this.#field.hazards.size, marks: this.#marks.size, ratings: this.#ratings.size, opened: this.#opened.size,
|
||||
safe: ROWS * COLS - 2 - this.#field.hazards.size,
|
||||
history: this.#history.map(item => ({...item})),
|
||||
cells: Array.from({length: ROWS * COLS}, (_,id) => ({
|
||||
id, entrance: id === START, exit: id === this.#field.exit, transition: this.#transition(id), base: this.#field.base.includes(id),
|
||||
opened: this.#opened.has(id), marked: this.#marks.has(id),
|
||||
opened: this.#opened.has(id), marked: this.#marks.has(id), rating: this.#ratings.get(id) ?? null,
|
||||
available: !ended && this.#available(id),
|
||||
value: this.#opened.has(id) || ended ? this.#field.values[id] : null,
|
||||
...(ended ? {hazard: this.#field.hazards.has(id), wrong: this.#marks.has(id) && !this.#field.hazards.has(id)} : {}),
|
||||
|
||||
@@ -41,7 +41,7 @@ p + p { margin-top: 8px; }
|
||||
.portrait { width: 84px; height: 84px; flex: 0 0 auto; background: var(--map); border-radius: 50%; border: 2px solid var(--paper); }
|
||||
.portrait img { width: 100%; height: 100%; object-fit: contain; }
|
||||
.stats { margin: 0; }
|
||||
.stats > div, .sound-guide > div { display: flex; justify-content: space-between; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--border); }
|
||||
.stats > div { display: flex; justify-content: space-between; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--border); }
|
||||
dd { margin: 0; text-align: right; font-weight: bold; }
|
||||
.stats dt, .stats dd { font-size: var(--small); }
|
||||
.fineprint { font-size: var(--small); color: var(--muted); }
|
||||
@@ -50,6 +50,8 @@ dd { margin: 0; text-align: right; font-weight: bold; }
|
||||
.location-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; padding: 12px 16px; }
|
||||
.location-heading > span { font-size: var(--small); }
|
||||
.scene-instructions { padding: 0 16px 12px; font-size: var(--small); }
|
||||
.listen-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 16px; padding: 0 16px 12px; font-size: var(--small); }
|
||||
.listen-controls .check { margin: 0; min-height: 44px; }
|
||||
.scene { position: relative; aspect-ratio: 5 / 3; background: var(--map); isolation: isolate; }
|
||||
.forest { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; z-index: -1; }
|
||||
.cell-grid [role=row] { display: grid; grid-template-columns: repeat(10, minmax(0, 1fr)); }
|
||||
@@ -69,6 +71,8 @@ dd { margin: 0; text-align: right; font-weight: bold; }
|
||||
.cell-grid .wrong button { background: var(--paper); color: var(--danger); }
|
||||
.cell-coord { position: absolute; left: 4px; top: 2px; font-size: 10px; font-weight: normal; color: var(--light); background: #17120dbb; padding: 0 2px; line-height: 1.4; }
|
||||
.cell-value { font-size: clamp(14px, 1.5vw, 24px); }
|
||||
.cell-rating, .rating-key { background: var(--active); color: var(--ink); padding: 0 3px; border-radius: 2px; font-weight: bold; }
|
||||
.cell-rating { position: absolute; bottom: 1px; right: 1px; font-size: .6875rem; line-height: 1.15; text-shadow: none; }
|
||||
.character-sprite { position: absolute; width: 10%; height: 16.6667%; left: 0; top: 83.3333%; pointer-events: none; display: flex; align-items: center; justify-content: center; }
|
||||
.character-sprite img { position: absolute; width: 115%; height: 115%; object-fit: contain; filter: drop-shadow(0 2px 2px var(--ink)); }
|
||||
.character-sprite > span { border-radius: 50%; background: var(--map); color: var(--light); font-size: 10px; padding: 2px 4px; }
|
||||
@@ -98,6 +102,13 @@ input { accent-color: var(--map); }
|
||||
.map-grid .marked button, .map-grid .hazard button { background: var(--danger); }
|
||||
.map-grid .hint button { background: var(--active); color: var(--ink); }
|
||||
#map-selection { margin: 12px 0; font-size: var(--small); }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
||||
#map-levels { min-width: 0; margin: 0 0 12px; padding: 8px; border: 1px solid var(--inner); }
|
||||
#map-levels legend { padding: 0 4px; font-size: var(--small); }
|
||||
.rating-buttons { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 4px; }
|
||||
.rating-buttons button { padding: 4px; }
|
||||
.rating-buttons button[aria-pressed="true"] { background: var(--active); }
|
||||
#map-clear-level { width: 100%; margin-top: 8px; }
|
||||
#map-mark { width: 100%; }
|
||||
.check { display: flex; gap: 8px; align-items: center; font-size: var(--small); margin: 8px 0; min-height: 44px; cursor: pointer; }
|
||||
.check input { width: 18px; height: 18px; flex-shrink: 0; }
|
||||
@@ -114,8 +125,6 @@ dialog p { margin: 12px 0; }
|
||||
select { min-height: 44px; padding: 8px; width: 100%; }
|
||||
.help-list { padding-left: 24px; }
|
||||
.help-list li { margin: 12px 0; }
|
||||
.sound-guide { margin: 8px 0; }
|
||||
.sound-guide dd { font-weight: normal; }
|
||||
#panel-dialog:has(#map-body) { background: var(--map); color: var(--light); }
|
||||
#panel-dialog .map-grid button { min-height: 32px; }
|
||||
#history-empty { font-size: var(--small); }
|
||||
@@ -171,6 +180,6 @@ select { min-height: 44px; padding: 8px; width: 100%; }
|
||||
dialog { padding: 16px; }
|
||||
footer { padding: 16px 12px; }
|
||||
}
|
||||
@media (pointer: coarse) { .action-buttons button, .mobile-tools button, #map-mark { min-height: 48px; } }
|
||||
@media (pointer: coarse) { .action-buttons button, .mobile-tools button, #map-mark, #map-levels button, .listen-controls button, .listen-controls .check { min-height: 48px; } }
|
||||
@media (prefers-reduced-motion: reduce) { button { transition: none; } }
|
||||
@media (forced-colors: active) { .cell-grid .selected button, .cell-grid .current button { outline: 2px solid Highlight; outline-offset: -3px; } }
|
||||
+107
-28
@@ -1,10 +1,12 @@
|
||||
import {Training, DEFAULTS, ROWS, COLS, START, coordinate, hintChance} from './engine.js';
|
||||
import {playSound, stopSound} from './audio.js';
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
const compact = matchMedia('(max-width: 700px), (pointer: coarse)');
|
||||
const mobile = matchMedia('(max-width: 700px)');
|
||||
const sounds = ['Звуков нет', 'Едва различимый шорох', 'Тихий шорох', 'Приглушённый шорох', 'Громкий шорох'];
|
||||
let game, selected = START, hints = new Set(), hintTimers = new Map();
|
||||
let messages = [];
|
||||
let clock = null, startedAt = null, renderedHistory = 0, pendingConfirmation = null, panelReturn = null;
|
||||
let panelOrigin = null, panelBody = null;
|
||||
const grids = [];
|
||||
@@ -15,23 +17,45 @@ function addItem(list, text) {
|
||||
}
|
||||
function sound(value) { return sounds[value] || 'Очень громкий шорох'; }
|
||||
function ended(view) { return view.status === 'won' || view.status === 'lost'; }
|
||||
function describe(cell, view) {
|
||||
function simple() { return $('simple-mode').checked; }
|
||||
function level(value) { return Math.min(7, value); }
|
||||
function levelText(value) { return `Опасностей рядом: ${level(value)}${value >= 7 ? ' или больше' : ''}.`; }
|
||||
function playCue(value) {
|
||||
const attempt = game;
|
||||
playSound(level(value)).catch(() => {
|
||||
if (game === attempt && !simple()) $('status').textContent = 'Не удалось воспроизвести звук. Повторите попытку или включите упрощённый режим.';
|
||||
});
|
||||
}
|
||||
function renderMessage(message) {
|
||||
if (message.simpleOnly && !simple()) return;
|
||||
const text = message.value === undefined ? message.text :
|
||||
`${coordinate(message.id)} · ${simple() ? `${sound(message.value)}. ${levelText(message.value)}` : message.value ? 'Прозвучал сигнал.' : 'Звуков нет.'}`;
|
||||
addItem($('messages'), text);
|
||||
}
|
||||
function recordMessage(message) {
|
||||
messages.push(message);
|
||||
renderMessage(message);
|
||||
}
|
||||
function describe(cell, view, showNotes = true, isMap = false) {
|
||||
if (cell.entrance) return 'вход';
|
||||
if (cell.exit) return 'выход';
|
||||
if (cell.wrong) return 'ошибочная отметка, безопасно';
|
||||
if (cell.hazard) return 'опасная клетка';
|
||||
if (cell.opened) return `проверено, опасностей рядом: ${cell.value}${cell.available ? ', прыжок доступен' : ''}`;
|
||||
if (ended(view)) return `безопасная клетка, опасностей рядом: ${cell.value}`;
|
||||
if (cell.marked) return 'ваша отметка опасности';
|
||||
if (hints.has(cell.id)) return 'подсказка: опасность';
|
||||
return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, не рядом с персонажем';
|
||||
const rating = showNotes && cell.rating !== null ? `, ваша оценка ${cell.rating}` : '';
|
||||
if (cell.wrong) return `ошибочная отметка, безопасно${rating}`;
|
||||
if (cell.hazard) return `опасная клетка${rating}`;
|
||||
if (cell.opened || ended(view)) {
|
||||
const fact = simple() || ended(view) ? `, ${levelText(cell.value).slice(0, -1).toLowerCase()}` : '';
|
||||
return `${cell.opened ? 'проверено' : 'безопасная клетка'}${fact}${rating}${!isMap && cell.available ? ', прыжок доступен' : ''}`;
|
||||
}
|
||||
if (cell.marked && showNotes) return `ваш флажок опасности${rating}`;
|
||||
if (hints.has(cell.id)) return `подсказка: опасность${rating}`;
|
||||
return `неизвестно${rating}${isMap ? '' : cell.available ? ', прыжок доступен' : ', не рядом с персонажем'}`;
|
||||
}
|
||||
function cellValue(cell, view, showMarks) {
|
||||
if (cell.transition) return cell.entrance ? '↥' : '↗';
|
||||
if (cell.wrong) return '≠';
|
||||
if (cell.hazard) return '×';
|
||||
if (cell.marked && showMarks) return '⚑';
|
||||
if (cell.opened || ended(view)) return cell.value || '·';
|
||||
if (cell.opened || ended(view)) return simple() || ended(view) ? level(cell.value) : '·';
|
||||
if (hints.has(cell.id)) return '!';
|
||||
return '';
|
||||
}
|
||||
@@ -39,6 +63,7 @@ function selectCell(id) {
|
||||
if (id === selected) return;
|
||||
selected = id;
|
||||
$('status').textContent = '';
|
||||
$('map-rating-status').textContent = '';
|
||||
render();
|
||||
}
|
||||
function makeGrid(id, isMap) {
|
||||
@@ -50,17 +75,19 @@ function makeGrid(id, isMap) {
|
||||
const cell = document.createElement('div'); cell.setAttribute('role', 'gridcell'); cell.setAttribute('aria-colindex', c + 1);
|
||||
const button = document.createElement('button'); button.type = 'button'; button.dataset.id = index; button.tabIndex = index === START ? 0 : -1;
|
||||
const value = document.createElement('span'); value.className = 'cell-value'; value.setAttribute('aria-hidden', 'true');
|
||||
const rating = document.createElement('span'); rating.className = 'cell-rating'; rating.setAttribute('aria-hidden', 'true'); rating.hidden = true;
|
||||
if (!isMap) {
|
||||
const label = document.createElement('span'); label.className = 'cell-coord'; label.textContent = coordinate(index); label.setAttribute('aria-hidden', 'true'); button.append(label);
|
||||
}
|
||||
button.append(value); cell.append(button); row.append(cell); cells.push(cell); buttons.push(button);
|
||||
button.append(value, rating); cell.append(button); row.append(cell); cells.push(cell); buttons.push(button);
|
||||
}
|
||||
root.append(row);
|
||||
}
|
||||
root.addEventListener('click', event => {
|
||||
const button = event.target.closest('button[data-id]'); if (!button) return;
|
||||
selectCell(Number(button.dataset.id));
|
||||
if (!isMap && (!compact.matches || event.detail === 0)) act('jump');
|
||||
if (isMap) button.focus({preventScroll:true});
|
||||
else if (!compact.matches || event.detail === 0) act('jump');
|
||||
});
|
||||
root.addEventListener('contextmenu', event => {
|
||||
const button = event.target.closest('button[data-id]'); if (!button) return;
|
||||
@@ -75,6 +102,14 @@ function makeGrid(id, isMap) {
|
||||
root.addEventListener('keydown', event => {
|
||||
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || !buttons.includes(event.target)) return;
|
||||
const from = event.target, index = Number(from.dataset.id);
|
||||
if (isMap && !event.shiftKey && (/^[0-7]$/.test(event.key) || ['Delete','Backspace'].includes(event.key))) {
|
||||
event.preventDefault();
|
||||
if (!event.repeat) {
|
||||
selectCell(index);
|
||||
rateCell(/^[0-7]$/.test(event.key) ? Number(event.key) : null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.shiftKey) {
|
||||
if (!isMap && event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
@@ -113,16 +148,22 @@ function updateClock() {
|
||||
const seconds = startedAt === null ? 0 : Math.floor((Date.now() - startedAt) / 1000);
|
||||
$('timer').textContent = `${String(Math.floor(seconds / 60)).padStart(2,'0')}:${String(seconds % 60).padStart(2,'0')}`;
|
||||
}
|
||||
function stopTimers() {
|
||||
clearInterval(clock); clock = null;
|
||||
function clearHints() {
|
||||
for (const timer of hintTimers.values()) clearTimeout(timer);
|
||||
hintTimers.clear(); hints.clear();
|
||||
}
|
||||
function stopTimers() {
|
||||
clearInterval(clock); clock = null;
|
||||
clearHints();
|
||||
stopSound();
|
||||
}
|
||||
function start(options = DEFAULTS) {
|
||||
stopTimers(); game = new Training(options); selected = START; startedAt = null; renderedHistory = 0;
|
||||
$('history').replaceChildren(); $('messages').replaceChildren();
|
||||
addItem($('messages'), 'Лес затих. Звуки появятся после прыжка.');
|
||||
messages = [];
|
||||
recordMessage({text:'Лес затих. Сигнал появится после прыжка.'});
|
||||
$('status').textContent = '';
|
||||
$('map-rating-status').textContent = '';
|
||||
updateClock(); render();
|
||||
}
|
||||
function render() {
|
||||
@@ -130,12 +171,16 @@ function render() {
|
||||
for (const {cells, buttons, isMap} of grids) {
|
||||
for (const cell of view.cells) {
|
||||
const node = cells[cell.id], button = buttons[cell.id];
|
||||
const projectedMark = cell.marked && (isMap || projection);
|
||||
node.className = [cell.opened && 'opened', projectedMark && 'marked', cell.available && !cell.transition && 'available', cell.transition && 'transition', cell.entrance && 'entrance', cell.exit && 'exit', cell.hazard && 'hazard', cell.wrong && 'wrong', cell.id === selected && 'selected', cell.id === view.position && 'current', hints.has(cell.id) && !finished && 'hint'].filter(Boolean).join(' ');
|
||||
const showNotes = isMap || projection;
|
||||
const projectedMark = cell.marked && showNotes, rated = cell.rating !== null && showNotes;
|
||||
node.className = [cell.opened && 'opened', projectedMark && 'marked', rated && 'rated', cell.available && !cell.transition && 'available', cell.transition && 'transition', cell.entrance && 'entrance', cell.exit && 'exit', cell.hazard && 'hazard', cell.wrong && 'wrong', cell.id === selected && 'selected', cell.id === view.position && 'current', hints.has(cell.id) && !finished && 'hint'].filter(Boolean).join(' ');
|
||||
node.setAttribute('aria-selected', String(cell.id === selected));
|
||||
button.tabIndex = cell.id === selected ? 0 : -1;
|
||||
button.querySelector('.cell-value').textContent = cellValue(cell, view, isMap || projection);
|
||||
button.setAttribute('aria-label', `${coordinate(cell.id)}: ${describe(cell, view)}${cell.id === view.position ? ', персонаж здесь' : ''}`);
|
||||
button.querySelector('.cell-value').textContent = cellValue(cell, view, showNotes);
|
||||
const rating = button.querySelector('.cell-rating');
|
||||
rating.hidden = !rated;
|
||||
rating.textContent = rated ? cell.rating : '';
|
||||
button.setAttribute('aria-label', `${coordinate(cell.id)}: ${describe(cell, view, showNotes, isMap)}${cell.id === view.position ? ', персонаж здесь' : ''}`);
|
||||
}
|
||||
}
|
||||
$('character').style.left = `${view.position % COLS * 10}%`;
|
||||
@@ -146,9 +191,12 @@ function render() {
|
||||
$('transition-coordinates').textContent = `Вход: ${coordinate(view.start)} · Выход: ${coordinate(view.exit)}`;
|
||||
$('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];
|
||||
$('hint-chance').textContent = `${Math.round(hintChance(view.options.lu) * 100)}%`;
|
||||
$('hint-chance').textContent = simple() ? `${Math.round(hintChance(view.options.lu) * 100)}%` : 'Выкл.';
|
||||
$('replay-sound').disabled = finished || simple() || !view.cells[view.position].value;
|
||||
$('sound-guide').textContent = simple() ? 'Число показывает опасности вокруг клетки, включая диагонали. 7 означает семь или больше.' : 'После прыжка прислушайтесь к шорохам и оцените клетку на карте.';
|
||||
$('progress').textContent = `${view.opened} / ${view.safe}`;
|
||||
$('mark-count').textContent = view.marks; $('hazard-count').textContent = view.hazards;
|
||||
$('rating-count').textContent = view.ratings;
|
||||
$('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status];
|
||||
$('scene-instructions').textContent = compact.matches ? 'Коснитесь клетки, затем выберите действие под полем.' : 'Клик по соседней клетке — прыжок. Правый клик или Shift+Enter — поставить или снять отметку.';
|
||||
const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной';
|
||||
@@ -157,14 +205,17 @@ function render() {
|
||||
!cell.available ? 'вне досягаемости' : '';
|
||||
$('touch-actions').hidden = !compact.matches;
|
||||
$('selection').textContent = `Клетка ${coordinate(selected)}${selectionState ? ` — ${selectionState}` : ''}`;
|
||||
$('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view)}`;
|
||||
$('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view, true, true)}`;
|
||||
$('mark').textContent = note; $('map-mark').textContent = note;
|
||||
$('jump').disabled = finished || !cell.available || cell.marked;
|
||||
for (const id of ['mark','map-mark']) $(id).disabled = finished || cell.opened || cell.transition;
|
||||
$('clear-marks').disabled = finished || view.marks === 0;
|
||||
$('map-levels').disabled = finished || cell.transition;
|
||||
for (const button of $('map-levels').querySelectorAll('[data-level]')) button.setAttribute('aria-pressed', String(Number(button.dataset.level) === cell.rating));
|
||||
$('map-clear-level').disabled = cell.rating === null;
|
||||
$('clear-marks').disabled = finished || (view.marks === 0 && view.ratings === 0);
|
||||
$('history-empty').hidden = view.history.length > 0;
|
||||
for (const entry of view.history.slice(renderedHistory)) {
|
||||
const text = entry.type === 'cleared' ? 'Все заметки очищены; открытые клетки сохранены.' : `${coordinate(entry.id)} · ${{opened:'Прыжок',revisited:'Повторный прыжок',fall:'Падение',marked:'Поставлена отметка',unmarked:'Снята отметка'}[entry.type]}${entry.value !== undefined ? ` · рядом ${entry.value}` : ''}`;
|
||||
const text = entry.type === 'cleared' ? 'Все заметки очищены; открытые клетки сохранены.' : `${coordinate(entry.id)} · ${{opened:'Прыжок',revisited:'Повторный прыжок',fall:'Падение',marked:'Поставлена отметка',unmarked:'Снята отметка',rated:`Ваша оценка: ${entry.rating}`,unrated:'Оценка снята'}[entry.type]}${simple() && entry.value !== undefined ? ` · ${levelText(entry.value)}` : ''}`;
|
||||
addItem($('history'), text);
|
||||
}
|
||||
renderedHistory = view.history.length;
|
||||
@@ -172,24 +223,24 @@ function render() {
|
||||
if (finished) $('result').textContent = view.status === 'won' ? 'Карта готова! Условие победы выполнено. Поле раскрыто — можно изучить результат или начать новую игру.' : `Падение на ${coordinate(view.hit)}. Попытка завершена, поле раскрыто. Знак ≠ показывает ошибочную отметку. Попробуйте ещё раз.`;
|
||||
}
|
||||
function act(action) {
|
||||
const result = action === 'jump' ? game.jump(selected) : game.mark(selected);
|
||||
const result = action === 'jump' ? game.jump(selected, simple() ? Math.random : () => 1) : game.mark(selected);
|
||||
const view = game.view();
|
||||
let text;
|
||||
if (action === 'jump' && ['opened','revisited'].includes(result.code)) {
|
||||
text = `Опасностей рядом: ${result.value}.`;
|
||||
addItem($('messages'), `${coordinate(selected)} · ${sound(result.value)}. ${text}`);
|
||||
text = simple() ? levelText(result.value) : result.value ? 'Прислушайтесь к звуку.' : 'Звуков нет.';
|
||||
recordMessage({id:selected, value:result.value});
|
||||
if (startedAt === null) { startedAt = Date.now(); clock = setInterval(updateClock,1000); }
|
||||
if (result.hint !== null) {
|
||||
clearTimeout(hintTimers.get(result.hint));
|
||||
hints.add(result.hint);
|
||||
const hintText = `Подсказка: ${coordinate(result.hint)} — опасная клетка. Значок «!» виден 2 секунды; координата остаётся здесь.`;
|
||||
addItem($('messages'), hintText); text += ` Подсказка: ${coordinate(result.hint)} — опасная клетка.`;
|
||||
recordMessage({text:hintText, simpleOnly:true}); text += ` Подсказка: ${coordinate(result.hint)} — опасная клетка.`;
|
||||
const attempt = game;
|
||||
const timer = setTimeout(() => { hintTimers.delete(result.hint); if (game === attempt) { hints.delete(result.hint); render(); } },2000);
|
||||
hintTimers.set(result.hint, timer);
|
||||
}
|
||||
} else if (result.code === 'fall') {
|
||||
addItem($('messages'), `Падение на ${coordinate(selected)}. Попытка завершена.`);
|
||||
recordMessage({text:`Падение на ${coordinate(selected)}. Попытка завершена.`});
|
||||
text = 'Падение. Попытка завершена.';
|
||||
} else {
|
||||
text = {finished:'Попытка завершена.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Выберите соседнюю клетку для прыжка.',marked: action === 'jump' ? 'Сначала снимите отметку с этой клетки.' : 'Отметка поставлена.',unmarked:'Отметка снята.',opened:'Проверенную клетку нельзя отметить опасной.'}[result.code];
|
||||
@@ -197,6 +248,17 @@ function act(action) {
|
||||
if (ended(view)) { if (clock !== null) updateClock(); stopTimers(); }
|
||||
if (view.status === 'won') text += ' Карта готова!';
|
||||
$('status').textContent = text; render();
|
||||
if (!ended(view) && !simple() && result.value !== undefined) playCue(result.value);
|
||||
}
|
||||
function rateCell(rating) {
|
||||
const result = game.rate(selected, rating);
|
||||
if (result.code === 'rated' || result.code === 'unrated') {
|
||||
$('map-rating-status').textContent = `${coordinate(selected)}: ${rating === null ? 'оценка снята' : `ваша оценка ${rating}`}.`;
|
||||
render();
|
||||
}
|
||||
if (rating === null && document.activeElement === $('map-clear-level') && result.code === 'unrated') {
|
||||
$('map-grid').querySelector(`button[data-id="${selected}"]`).focus();
|
||||
}
|
||||
}
|
||||
function showDialog(dialog, opener) {
|
||||
dialog._opener = opener;
|
||||
@@ -248,7 +310,24 @@ $('settings-form').addEventListener('submit', event => {
|
||||
$('settings-dialog').close(); start(options);
|
||||
});
|
||||
$('new-game').addEventListener('click', event => confirmAction('Начать заново?', 'Текущее поле, заметки и история будут сброшены. Условия тренировки сохранятся.', 'Начать новую игру', () => start(game.view().options), event.currentTarget));
|
||||
$('clear-marks').addEventListener('click', event => confirmAction('Очистить отметки?', 'Удалятся только ваши заметки. Проверенные клетки, история и текущая попытка сохранятся.', 'Очистить отметки', () => { game.clearMarks(); $('status').textContent = 'Отметки очищены. Попытка продолжается.'; render(); }, event.currentTarget));
|
||||
$('clear-marks').addEventListener('click', event => confirmAction('Очистить отметки?', 'Удалятся ваши флажки и оценки. Проверенные клетки, история и текущая попытка сохранятся.', 'Очистить отметки', () => { game.clearMarks(); $('status').textContent = 'Отметки очищены. Попытка продолжается.'; render(); }, event.currentTarget));
|
||||
$('simple-mode').addEventListener('change', () => {
|
||||
stopSound(); clearHints();
|
||||
$('status').textContent = simple() ? 'Упрощённый режим: уровни видны на проверенных клетках.' : 'Звуковой режим: оцените клетку по шорохам.';
|
||||
$('messages').replaceChildren(); messages.forEach(renderMessage);
|
||||
$('history').replaceChildren(); renderedHistory = 0;
|
||||
render();
|
||||
});
|
||||
$('replay-sound').addEventListener('click', () => {
|
||||
const view = game.view();
|
||||
$('status').textContent = 'Прислушайтесь к звуку.';
|
||||
playCue(view.cells[view.position].value);
|
||||
});
|
||||
$('map-levels').addEventListener('click', event => {
|
||||
const button = event.target.closest('button[data-level]');
|
||||
if (button) rateCell(Number(button.dataset.level));
|
||||
});
|
||||
$('map-clear-level').addEventListener('click', () => rateCell(null));
|
||||
$('project-marks').addEventListener('change', render);
|
||||
$('jump').addEventListener('click', () => act('jump'));
|
||||
$('mark').addEventListener('click', () => act('mark'));
|
||||
|
||||
Reference in new issue
Block a user