250 lines
17 KiB
JavaScript
250 lines
17 KiB
JavaScript
import {Training, DEFAULTS, ROWS, COLS, START, coordinate, hintChance} from './engine.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, mode = 'jump', hints = new Set(), hintTimers = new Map();
|
||
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 initialCells(view) { return view.cells.filter(cell => cell.base).map(cell => coordinate(cell.id)).join(', '); }
|
||
function describe(cell, view) {
|
||
if (cell.entrance) return 'вход';
|
||
if (cell.exit) return 'выход';
|
||
if (cell.wrong) return 'ошибочная отметка, безопасно';
|
||
if (cell.hazard) return 'опасная клетка';
|
||
if (cell.opened) return `проверено, опасностей рядом: ${cell.value}`;
|
||
if (ended(view)) return `безопасная клетка, опасностей рядом: ${cell.value}`;
|
||
if (cell.marked) return 'ваша отметка опасности';
|
||
if (hints.has(cell.id)) return 'подсказка: опасность';
|
||
return 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 (hints.has(cell.id)) return '!';
|
||
return '';
|
||
}
|
||
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');
|
||
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);
|
||
}
|
||
root.append(row);
|
||
}
|
||
root.addEventListener('click', event => {
|
||
const button = event.target.closest('button[data-id]'); if (!button) return;
|
||
selected = Number(button.dataset.id); render();
|
||
if (!isMap && (!compact.matches || event.detail === 0)) act(mode);
|
||
});
|
||
root.addEventListener('contextmenu', event => {
|
||
const button = event.target.closest('button[data-id]'); if (!button) return;
|
||
event.preventDefault(); selected = Number(button.dataset.id); act('mark');
|
||
});
|
||
root.addEventListener('focusin', event => {
|
||
if (!event.target.matches('button[data-id]')) return;
|
||
selected = Number(event.target.dataset.id); render();
|
||
});
|
||
root.addEventListener('keydown', event => {
|
||
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || !buttons.includes(event.target)) return;
|
||
const from = event.target, index = Number(from.dataset.id);
|
||
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 stopTimers() {
|
||
clearInterval(clock); clock = null;
|
||
for (const timer of hintTimers.values()) clearTimeout(timer);
|
||
hintTimers.clear(); hints.clear();
|
||
}
|
||
function start(options = DEFAULTS) {
|
||
stopTimers(); game = new Training(options); selected = START; startedAt = null; renderedHistory = 0;
|
||
$('history').replaceChildren(); $('messages').replaceChildren();
|
||
addItem($('messages'), 'Лес затих. Звуки появятся после прыжка.');
|
||
$('status').textContent = `Начальные клетки: ${initialCells(game.view())}. Стрелки перемещают фокус, Enter или пробел выполняет действие.`;
|
||
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 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(' ');
|
||
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 ? ', персонаж здесь' : ''}`);
|
||
}
|
||
}
|
||
$('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 = `${Math.round(hintChance(view.options.lu) * 100)}%`;
|
||
$('progress').textContent = `${view.opened} / ${view.safe}`;
|
||
$('mark-count').textContent = view.marks; $('hazard-count').textContent = view.hazards;
|
||
$('attempt-state').textContent = {ready:'Готов к прыжку',playing:'На уступах',won:'Карта готова',lost:'Падение'}[view.status];
|
||
$('scene-instructions').textContent = compact.matches ? `Выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной». Начальные клетки: ${initialCells(view)}.` : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Начальные клетки: ${initialCells(view)}; затем рядом с любой проверенной клеткой.`;
|
||
const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной';
|
||
$('selection').textContent = `Выбрана клетка ${coordinate(selected)} · ${describe(cell, view)}`;
|
||
$('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view)}`;
|
||
$('mark').textContent = note; $('map-mark').textContent = note;
|
||
$('jump').disabled = finished || cell.transition;
|
||
for (const id of ['mark','map-mark']) $(id).disabled = finished || cell.opened || cell.transition;
|
||
$('clear-marks').disabled = finished || view.marks === 0;
|
||
document.querySelectorAll('input[name=mode]').forEach(input => { input.disabled = finished; });
|
||
$('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}` : ''}`;
|
||
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) : game.mark(selected);
|
||
const view = game.view();
|
||
let text;
|
||
if (action === 'jump' && ['opened','revisited'].includes(result.code)) {
|
||
text = `${coordinate(selected)} · ${sound(result.value)}. Опасностей рядом: ${result.value}.`;
|
||
addItem($('messages'), text);
|
||
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 += ` ${hintText}`;
|
||
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') {
|
||
text = `Падение на ${coordinate(selected)}. Попытка завершена.`; addItem($('messages'), text);
|
||
} else {
|
||
text = {finished:'Попытка завершена. Изучите поле или начните новую игру.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Сначала откройте соседнюю клетку или начните с безопасных клеток верхнего ряда.',marked: action === 'jump' ? 'Сначала снимите отметку опасности с этой клетки.' : `${coordinate(selected)}: поставлена ваша отметка опасности.`,unmarked:`${coordinate(selected)}: отметка снята.`,opened:'Проверенную клетку нельзя отметить опасной.'}[result.code];
|
||
}
|
||
if (ended(view)) { if (clock !== null) updateClock(); stopTimers(); }
|
||
if (view.status === 'won') text += ' Карта готова! Победа. Всё поле раскрыто.';
|
||
$('status').textContent = text; render();
|
||
}
|
||
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);
|
||
}
|
||
$('panel-dialog').addEventListener('close', () => {
|
||
if (panelBody) {
|
||
panelOrigin.append(panelBody);
|
||
if (panelBody.id === 'map-body') panelBody.hidden = $('map-toggle').getAttribute('aria-expanded') === 'false';
|
||
panelBody = null; panelOrigin = null;
|
||
}
|
||
panelReturn?.focus(); panelReturn = null;
|
||
});
|
||
$('map-open').addEventListener('click', event => openPanel('map',event.currentTarget));
|
||
$('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)); $('map-body').hidden = !open;
|
||
$('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));
|
||
$('project-marks').addEventListener('change', render);
|
||
for (const input of document.querySelectorAll('input[name=mode]')) input.addEventListener('change', () => { mode = input.value; render(); });
|
||
$('jump').addEventListener('click', () => act('jump'));
|
||
$('mark').addEventListener('click', () => act('mark'));
|
||
$('map-mark').addEventListener('click', () => act('mark'));
|
||
compact.addEventListener('change', render);
|
||
mobile.addEventListener('change', () => { if ($('panel-dialog').open) $('panel-dialog').close(); });
|
||
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();
|