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
+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