fix: simplify trainer controls
This commit is contained in:
1 parent
cc6bcb23c8
commit
9be0bb48c8
9 files changed
+191
-78
No files matched your search
+39
-18
@@ -4,7 +4,7 @@ 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 game, selected = START, hints = new Set(), hintTimers = new Map();
|
||||
let clock = null, startedAt = null, renderedHistory = 0, pendingConfirmation = null, panelReturn = null;
|
||||
let panelOrigin = null, panelBody = null;
|
||||
const grids = [];
|
||||
@@ -35,6 +35,12 @@ function cellValue(cell, view, showMarks) {
|
||||
if (hints.has(cell.id)) return '!';
|
||||
return '';
|
||||
}
|
||||
function selectCell(id) {
|
||||
if (id === selected) return;
|
||||
selected = id;
|
||||
$('status').textContent = '';
|
||||
render();
|
||||
}
|
||||
function makeGrid(id, isMap) {
|
||||
const root = $(id), cells = [], buttons = [];
|
||||
for (let r = 0; r < ROWS; r++) {
|
||||
@@ -53,20 +59,32 @@ function makeGrid(id, isMap) {
|
||||
}
|
||||
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);
|
||||
selectCell(Number(button.dataset.id));
|
||||
if (!isMap && (!compact.matches || event.detail === 0)) act('jump');
|
||||
});
|
||||
root.addEventListener('contextmenu', event => {
|
||||
const button = event.target.closest('button[data-id]'); if (!button) return;
|
||||
event.preventDefault(); selected = Number(button.dataset.id); act('mark');
|
||||
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;
|
||||
selected = Number(event.target.dataset.id); render();
|
||||
selectCell(Number(event.target.dataset.id));
|
||||
});
|
||||
root.addEventListener('keydown', event => {
|
||||
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || !buttons.includes(event.target)) return;
|
||||
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || !buttons.includes(event.target)) return;
|
||||
const from = event.target, index = Number(from.dataset.id);
|
||||
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];
|
||||
@@ -104,7 +122,7 @@ function start(options = DEFAULTS) {
|
||||
stopTimers(); game = new Training(options); selected = START; startedAt = null; renderedHistory = 0;
|
||||
$('history').replaceChildren(); $('messages').replaceChildren();
|
||||
addItem($('messages'), 'Лес затих. Звуки появятся после прыжка.');
|
||||
$('status').textContent = 'Начните с клетки рядом со входом. Стрелки перемещают фокус, Enter или пробел выполняет действие.';
|
||||
$('status').textContent = '';
|
||||
updateClock(); render();
|
||||
}
|
||||
function render() {
|
||||
@@ -132,15 +150,18 @@ function render() {
|
||||
$('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 ? 'Выберите соседнюю клетку и нажмите «Прыгнуть». Отметку можно поставить где угодно на уступе.' : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Прыгать можно только в соседние клетки, в том числе по диагонали.`;
|
||||
$('scene-instructions').textContent = compact.matches ? 'Коснитесь клетки, затем выберите действие под полем.' : 'Клик по соседней клетке — прыжок. Правый клик или Shift+Enter — поставить или снять отметку.';
|
||||
const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной';
|
||||
$('selection').textContent = `Выбрана клетка ${coordinate(selected)} · ${describe(cell, view)}`;
|
||||
const selectionState = finished ? 'попытка завершена' : cell.id === view.position ? 'вы здесь' :
|
||||
cell.transition ? (cell.entrance ? 'вход' : 'выход') : cell.marked ? 'есть отметка' :
|
||||
!cell.available ? 'вне досягаемости' : '';
|
||||
$('touch-actions').hidden = !compact.matches;
|
||||
$('selection').textContent = `Клетка ${coordinate(selected)}${selectionState ? ` — ${selectionState}` : ''}`;
|
||||
$('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view)}`;
|
||||
$('mark').textContent = note; $('map-mark').textContent = note;
|
||||
$('jump').disabled = finished || cell.transition;
|
||||
$('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;
|
||||
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}` : ''}`;
|
||||
@@ -155,25 +176,26 @@ function act(action) {
|
||||
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);
|
||||
text = `Опасностей рядом: ${result.value}.`;
|
||||
addItem($('messages'), `${coordinate(selected)} · ${sound(result.value)}. ${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}`;
|
||||
addItem($('messages'), hintText); 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') {
|
||||
text = `Падение на ${coordinate(selected)}. Попытка завершена.`; addItem($('messages'), text);
|
||||
addItem($('messages'), `Падение на ${coordinate(selected)}. Попытка завершена.`);
|
||||
text = 'Падение. Попытка завершена.';
|
||||
} else {
|
||||
text = {finished:'Попытка завершена. Изучите поле или начните новую игру.',transition:'Это переход. Выберите клетку уступа.',invalid:'Выберите клетку поля.',unreachable:'Прыгнуть можно только в соседнюю клетку. Выберите клетку рядом с персонажем.',marked: action === 'jump' ? 'Сначала снимите отметку опасности с этой клетки.' : `${coordinate(selected)}: поставлена ваша отметка опасности.`,unmarked:`${coordinate(selected)}: отметка снята.`,opened:'Проверенную клетку нельзя отметить опасной.'}[result.code];
|
||||
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 += ' Карта готова! Победа. Всё поле раскрыто.';
|
||||
if (view.status === 'won') text += ' Карта готова!';
|
||||
$('status').textContent = text; render();
|
||||
}
|
||||
function showDialog(dialog, opener) {
|
||||
@@ -228,7 +250,6 @@ $('settings-form').addEventListener('submit', event => {
|
||||
$('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'));
|
||||
|
||||
Reference in new issue
Block a user