Files
cwshed-clone/web/lu-trainer/ui.js
T

363 lines
23 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 phoneMap = matchMedia('(max-width: 700px), (max-width: 1100px) and (max-height: 500px) and (pointer: coarse)');
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 = [];
function addItem(list, text) {
const li = document.createElement('li'); li.textContent = text; list.append(li);
list.scrollTop = list.scrollHeight;
}
function sound(value) { return sounds[value] || 'Очень громкий шорох'; }
function ended(view) { return view.status === 'won' || view.status === 'lost'; }
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.exit) return 'выход';
const rating = showNotes && cell.rating !== null ? `, ваша оценка ${cell.rating}` : '';
if (cell.wrong) return `ошибочная отметка, безопасно${rating}`;
if (cell.hazard) return `опасная клетка${rating}`;
if (cell.entrance || cell.opened || ended(view)) {
const fact = simple() || ended(view) ? `, ${levelText(cell.value).slice(0, -1).toLowerCase()}` : '';
const jump = !isMap && cell.available ? ', можно прыгнуть' : '';
if (cell.entrance) return `стартовая клетка${fact}${jump}`;
return `${cell.opened ? 'проверено' : 'безопасная клетка'}${fact}${rating}${jump}`;
}
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.entrance) return simple() || ended(view) ? `↥ ${cell.value}` : '↥';
if (cell.exit) return '↗';
if (cell.wrong) return '≠';
if (cell.hazard) return '×';
if (cell.marked && showMarks) return '⚑';
if (cell.opened || ended(view)) return simple() || ended(view) ? level(cell.value) : '·';
if (hints.has(cell.id)) return '!';
return '';
}
function selectCell(id) {
if (id === selected) return;
selected = id;
$('status').textContent = '';
$('map-rating-status').textContent = '';
render();
}
function makeGrid(id, isMap) {
const root = $(id), cells = [], buttons = [];
for (let r = 0; r < ROWS; r++) {
const row = document.createElement('div'); row.setAttribute('role', 'row'); row.setAttribute('aria-rowindex', r + 1);
for (let c = 0; c < COLS; c++) {
const index = r * COLS + c;
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, 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) 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;
event.preventDefault();
selectCell(Number(button.dataset.id));
if (event.pointerType !== 'touch') act('mark');
});
root.addEventListener('focusin', event => {
if (!event.target.matches('button[data-id]')) return;
selectCell(Number(event.target.dataset.id));
});
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();
if (!event.repeat) {
selectCell(index);
act('mark');
}
}
return;
}
let next;
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 {
const direction = {ArrowRight:'right', ArrowLeft:'left', ArrowUp:'up', ArrowDown:'down'}[event.key];
if (!direction) return;
// Use current geometry so zoom and responsive resizing keep spatial focus correct.
const box = from.getBoundingClientRect();
const horizontal = direction === 'right' || direction === 'left';
const forward = direction === 'right' || direction === 'down';
const candidates = buttons.filter(button => button !== from).map(button => {
const rect = button.getBoundingClientRect();
const gap = horizontal ? (forward ? rect.left - box.right : box.left - rect.right) : (forward ? rect.top - box.bottom : box.top - rect.bottom);
const aligned = horizontal ? rect.top < box.bottom - 1 && rect.bottom > box.top + 1 : rect.left < box.right - 1 && rect.right > box.left + 1;
return {button, gap, aligned};
}).filter(item => item.gap >= -1 && item.aligned).sort((a,b) => a.gap - b.gap);
next = candidates[0]?.button;
}
if (next && next !== from) {
event.preventDefault(); next.focus(); next.scrollIntoView({block:'nearest', inline:'nearest'});
}
});
grids.push({root, cells, buttons, isMap});
}
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 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();
messages = [];
recordMessage({text:'Лес затих. Прислушайтесь после прыжка.'});
$('status').textContent = '';
$('map-rating-status').textContent = '';
updateClock(); render();
}
function render() {
const view = game.view(), finished = ended(view), projection = $('project-marks').checked;
for (const {cells, buttons, isMap} of grids) {
for (const cell of view.cells) {
const node = cells[cell.id], button = buttons[cell.id];
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, 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}%`;
$('character').style.top = `${Math.floor(view.position / COLS) * 100 / ROWS}%`;
$('lu-value').textContent = `${view.options.lu} ЛУ`;
$('height-value').textContent = `${view.options.height} из 5`;
$('scene-height').textContent = `Высота ${view.options.height}`;
$('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 = 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 ? 'Снять отметку' : 'Отметить опасной';
const selectionState = finished ? 'попытка завершена' : cell.id === view.position ? 'вы здесь' :
cell.entrance ? (cell.available ? 'старт' : 'старт, вне досягаемости') :
cell.transition ? 'выход' : cell.marked ? 'есть отметка' :
!cell.available ? 'вне досягаемости' : '';
$('touch-actions').hidden = !compact.matches;
$('selection').textContent = `Клетка ${coordinate(selected)}${selectionState ? ` (${selectionState})` : ''}`;
$('map-selection').textContent = `Клетка ${coordinate(selected)} · ${describe(cell, view, true, true)}`;
$('mark').textContent = note; $('map-mark').textContent = note;
$('jump').disabled = finished || !cell.available || cell.marked;
const notesLocked = finished || cell.entrance || cell.transition;
for (const id of ['mark','map-mark']) $(id).disabled = notesLocked || cell.opened;
$('map-levels').disabled = notesLocked;
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:'Снята отметка',rated:`Ваша оценка: ${entry.rating}`,unrated:'Оценка снята'}[entry.type]}${simple() && entry.value !== undefined ? ` · ${levelText(entry.value)}` : ''}`;
addItem($('history'), text);
}
renderedHistory = view.history.length;
$('result').hidden = !finished;
if (finished) $('result').textContent = view.status === 'won' ? 'Карта готова! Вы победили. Теперь видно всё поле. Можно посмотреть результат или начать новую игру.' : `Падение на ${coordinate(view.hit)}. Попытка закончилась. Теперь видно всё поле. Знак ≠ показывает ошибочную отметку. Попробуйте ещё раз.`;
}
function act(action) {
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 = 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 секунды. Координаты останутся в сообщениях.`;
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') {
recordMessage({text:`Падение на ${coordinate(selected)}. Попытка завершена.`});
text = 'Падение. Попытка завершена.';
} else {
text = {finished:'Попытка завершена.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Выберите соседнюю клетку для прыжка.',marked: action === 'jump' ? 'Сначала снимите отметку с этой клетки.' : 'Отметка поставлена.',unmarked:'Отметка снята.',opened:'Проверенную клетку нельзя отметить опасной.'}[result.code];
}
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;
dialog.showModal();
}
for (const dialog of document.querySelectorAll('dialog')) {
dialog.addEventListener('close', () => { dialog._opener?.focus(); });
for (const button of dialog.querySelectorAll('[data-close]')) button.addEventListener('click', () => dialog.close());
}
function confirmAction(title, text, label, action, opener) {
$('confirm-title').textContent = title; $('confirm-text').textContent = text; $('confirm-action').textContent = label;
pendingConfirmation = action; $('confirm-dialog').returnValue = '';
showDialog($('confirm-dialog'), opener);
}
$('confirm-dialog').addEventListener('close', () => {
const action = pendingConfirmation; pendingConfirmation = null;
if ($('confirm-dialog').returnValue === 'confirm') action?.();
});
function openPanel(kind, opener) {
panelBody = $(kind === 'map' ? 'map-body' : 'history-body'); panelOrigin = panelBody.parentElement;
panelReturn = opener; panelBody.hidden = false;
$('panel-dialog-title').textContent = kind === 'map' ? 'Минное поле' : 'История действий';
$('panel-dialog-content').append(panelBody); showDialog($('panel-dialog'), opener);
}
function syncMapVisibility() {
$('map-body').hidden = !phoneMap.matches && $('map-toggle').getAttribute('aria-expanded') === 'false';
}
$('panel-dialog').addEventListener('close', () => {
if (panelBody) {
panelOrigin.append(panelBody);
if (panelBody.id === 'map-body') syncMapVisibility();
panelBody = null; panelOrigin = null;
}
panelReturn?.focus(); panelReturn = null;
});
$('map-open').addEventListener('click', event => {
if (!phoneMap.matches) { openPanel('map',event.currentTarget); return; }
$('map-title').focus({preventScroll:true});
$('map-title').scrollIntoView({block:'start'});
});
$('map-expand').addEventListener('click', event => openPanel('map',event.currentTarget));
$('history-open').addEventListener('click', event => openPanel('history',event.currentTarget));
$('map-toggle').addEventListener('click', () => {
const open = $('map-toggle').getAttribute('aria-expanded') !== 'true';
$('map-toggle').setAttribute('aria-expanded',String(open)); syncMapVisibility();
$('map-toggle').querySelector('span').textContent = open ? '−' : '+';
});
$('help-open').addEventListener('click', event => showDialog($('help-dialog'),event.currentTarget));
$('settings-open').addEventListener('click', event => {
for (const [name,value] of Object.entries(game.view().options)) $(`setting-${name}`).value = value;
showDialog($('settings-dialog'),event.currentTarget);
});
$('settings-form').addEventListener('submit', event => {
event.preventDefault();
const options = Object.fromEntries([...new FormData(event.currentTarget)].map(([key,value])=>[key,Number(value)]));
$('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));
$('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'));
$('map-mark').addEventListener('click', () => act('mark'));
compact.addEventListener('change', render);
phoneMap.addEventListener('change', () => {
if ($('panel-dialog').open) $('panel-dialog').close();
syncMapVisibility();
});
for (const img of document.images) {
img.addEventListener('error', () => { img.hidden = true; });
if (img.complete && !img.naturalWidth) img.hidden = true;
}
window.addEventListener('pagehide', stopTimers);
window.addEventListener('pageshow', () => {
if (startedAt !== null && !ended(game.view()) && clock === null) {
updateClock(); clock = setInterval(updateClock, 1000);
}
render();
});
makeGrid('scene-grid',false); makeGrid('map-grid',true); start();