feat: implement game-like LU trainer and companion map
This commit is contained in:
1 parent
87d5a6720f
commit
74c8504d52
21 files changed
+1160
-14
No files matched your search
@@ -75,6 +75,7 @@
|
||||
<div class="links">
|
||||
<p><i class="fas fa-code emoji"></i><a href="https://git.nyan404.ru/nyan404/cwshed-clone" target="_blank">Исходный код проекта</a></p>
|
||||
<p><img class="brand-icon" src="/favicon.png" alt="" aria-hidden="true"><a href="https://cat.nyan404.ru/belki" target="_blank">Калькулятор «Беличья нора»</a></p>
|
||||
<p><a href="/lu-trainer">Тренажёр ЛУ — Лесные уступы</a></p>
|
||||
<p><i class="fas fa-vk emoji"></i><a href="https://vk.ru/club240886904" target="_blank">Беличья нора во VK</a></p>
|
||||
<p><i class="fas fa-comments emoji" aria-hidden="true"></i><a href="https://matrix.to/#/!hQAD8j0wKv51OhvyeAPqRBNyBzvzoZsqBIWYR_OgNxw?via=nyan404.ru" target="_blank" rel="noopener noreferrer">Наш чат в Matrix</a></p>
|
||||
<div class="promo">
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="description" content="Учебный тренажёр лазания: лесная локация, подсказки и карта заметок. Без подключения к аккаунту CatWar.">
|
||||
<title>Тренажёр ЛУ — Лесные уступы</title>
|
||||
<link rel="icon" href="/favicon.png">
|
||||
<link rel="stylesheet" href="/lu-trainer/style.css">
|
||||
<script type="module" src="/lu-trainer/ui.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#location-title">К локации</a>
|
||||
<header class="topbar">
|
||||
<div class="brand"><h1>Тренажёр ЛУ</h1><span>Лесные уступы</span></div>
|
||||
<nav aria-label="Тренировка">
|
||||
<a href="/belki">Беличья нора</a>
|
||||
<button id="settings-open" type="button">Настройки</button>
|
||||
<button id="help-open" type="button">Помощь</button>
|
||||
<button id="new-game" type="button" class="primary">Новая игра</button>
|
||||
</nav>
|
||||
</header>
|
||||
<main class="game-layout">
|
||||
<div class="left-column">
|
||||
<section class="panel character">
|
||||
<h2>Персонаж</h2>
|
||||
<div class="identity"><div class="portrait"><img src="/lu-trainer/assets/cat.png" alt="" width="96" height="96"></div><div><strong>Лесной странник</strong><span>Учебный персонаж</span></div></div>
|
||||
<h3>Состояние</h3>
|
||||
<dl class="stats"><div><dt>Попытка</dt><dd id="attempt-state">Готов к прыжку</dd></div><div><dt>На уступах</dt><dd id="timer">00:00</dd></div><div><dt>Проверено</dt><dd id="progress">0</dd></div></dl>
|
||||
<h3>Навыки и условия</h3>
|
||||
<dl class="stats"><div><dt>Лазание</dt><dd id="lu-value">5 ЛУ</dd></div><div><dt>Высота</dt><dd id="height-value">1 из 5</dd></div><div><dt>Сезон</dt><dd id="season-value">Демисезон</dd></div><div><dt>Рост / возраст</dt><dd id="growth-value">45–75%</dd></div><div><dt>Шанс подсказки</dt><dd id="hint-chance">20%</dd></div></dl>
|
||||
<p class="fineprint">Это тренировка. Она не начисляет ЛУ и не связана с аккаунтом CatWar.</p>
|
||||
</section>
|
||||
<section class="panel history-panel" id="history-home">
|
||||
<h2>История действий</h2>
|
||||
<div id="history-body"><p id="history-empty">В этой попытке ещё нет действий.</p><ol id="history" class="journal"></ol></div>
|
||||
</section>
|
||||
</div>
|
||||
<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>
|
||||
<p id="scene-instructions" class="scene-instructions">Откройте одну из клеток А1–А5. Затем прыгайте рядом с любой проверенной клеткой.</p>
|
||||
<div class="scene" id="scene">
|
||||
<img class="forest" src="/lu-trainer/assets/forest.webp" alt="" width="1500" height="900">
|
||||
<div id="scene-grid" class="cell-grid scene-grid" role="grid" aria-label="Локация" aria-rowcount="6" aria-colcount="10" aria-describedby="scene-instructions"></div>
|
||||
<div id="character" class="character-sprite" aria-hidden="true"><span>Кот</span><img src="/lu-trainer/assets/cat.png" alt="" width="100" height="100"></div>
|
||||
</div>
|
||||
<p class="legend">↥ Вход / выход <span>· Проверено</span> <span>⚑ Ваша отметка</span> <span>× Опасность в результате</span> <span>≠ Ошибочная отметка</span></p>
|
||||
<p id="result" class="result" hidden></p>
|
||||
</section>
|
||||
<section class="panel actions">
|
||||
<h2>Действия</h2>
|
||||
<fieldset class="mode"><legend>Действие на локации</legend><label for="mode-jump"><input id="mode-jump" type="radio" name="mode" value="jump" checked> Прыжок</label><label for="mode-mark"><input id="mode-mark" type="radio" name="mode" value="mark"> Опасная</label></fieldset>
|
||||
<p id="selection">Выбрана клетка Е1 · вход</p>
|
||||
<div class="action-buttons"><button id="jump" type="button" class="primary">Прыгнуть</button><button id="mark" type="button">Отметить опасной</button></div>
|
||||
<p id="status" role="status" aria-atomic="true">Начните с клеток А1–А5. Стрелки перемещают фокус, Enter или пробел выполняет действие.</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 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>
|
||||
<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-selection">Выбрана Е1 · вход</p>
|
||||
<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>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
<footer>Учебная модель лазания · одна попытка до перезагрузки страницы. <a href="/">Файлы и сообщество</a></footer>
|
||||
<noscript><p class="noscript">Для тренажёра нужен JavaScript. Включите его и обновите страницу.</p></noscript>
|
||||
<dialog id="settings-dialog" aria-labelledby="settings-title">
|
||||
<form id="settings-form">
|
||||
<h2 id="settings-title">Условия тренировки</h2>
|
||||
<p>Параметры применятся к новой игре. Текущее поле, заметки и история будут сброшены.</p>
|
||||
<div class="settings-fields">
|
||||
<label for="setting-height">Высота<select id="setting-height" name="height"><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option></select></label>
|
||||
<label for="setting-lu">Лазание (ЛУ)<select id="setting-lu" name="lu"><option>0</option><option>1</option><option>2</option><option>3</option><option>4</option><option selected>5</option><option>6</option><option>7</option><option>8</option><option>9</option></select></label>
|
||||
<label for="setting-season">Сезон<select id="setting-season" name="season"><option value="-3">Лето · −3 опасности</option><option value="0" selected>Демисезон</option><option value="5">Зима · +5 опасностей</option></select></label>
|
||||
<label for="setting-growth">Рост / возраст<select id="setting-growth" name="growth"><option value="12">45–75% · 0–12 лун</option><option value="15">76–85% · 12–50 лун</option><option value="18">81–88% · 50–100 лун</option><option value="22">89–95% · 100–200 лун</option><option value="25">96–100% · 200–275 лун</option></select></label>
|
||||
</div>
|
||||
<p class="fineprint">Формулы относятся к модели тренажёра; точность относительно CatWar не подтверждена. ЛУ 4 / 5 / 6+ даёт шанс подсказки 10 / 20 / 30%.</p>
|
||||
<div class="dialog-actions"><button type="button" data-close>Отмена</button><button type="submit" class="primary">Начать новую игру</button></div>
|
||||
</form>
|
||||
</dialog>
|
||||
<dialog id="help-dialog" aria-labelledby="help-title">
|
||||
<h2 id="help-title">Как освоиться на уступах</h2>
|
||||
<p>Это самостоятельная учебная модель, вдохновлённая тренажёром <a href="https://github.com/tek1laa/catwar-lu-trainer" target="_blank" rel="noopener noreferrer">tek1laa</a>. Правила настоящей игры могут отличаться.</p>
|
||||
<ul class="help-list">
|
||||
<li>Начальные безопасные клетки — А1–А5 на высоте 1 и А1–А3 выше. Переходы Е1 и Г10 обозначают вход и выход: по ним не прыгают.</li>
|
||||
<li>Открывайте клетки рядом с любой проверенной, включая диагонали. Персонаж показывает последний успешный прыжок, а не ограничивает его дальность.</li>
|
||||
<li>Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.</li>
|
||||
<li>На компьютере клик выполняет выбранное действие, правая кнопка ставит заметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной».</li>
|
||||
<li>На обеих сетках стрелки перемещают фокус; Home / End — начало / конец строки. Enter и пробел выполняют действие. На карте они только выбирают клетку.</li>
|
||||
<li>Отмеченная клетка закрыта для прыжка, пока вы не снимете отметку. Карта не показывает скрытые опасности. При ЛУ от 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>
|
||||
<dialog id="panel-dialog" aria-labelledby="panel-dialog-title"><div class="panel-heading"><h2 id="panel-dialog-title">Минное поле</h2><button type="button" data-close autofocus>Закрыть</button></div><div id="panel-dialog-content"></div></dialog>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,16 @@
|
||||
# Original trainer artwork
|
||||
|
||||
Created 2026-11-17 with the built-in OpenAI imagegen tool for this project. These are original generated illustrations, not images extracted from CatWar, the owner's screenshot or `tek1laa/catwar-lu-trainer`. No upstream source code or artwork was copied. The screenshot's identifying text is not included.
|
||||
|
||||
- `forest.webp`: generated forest background, resized to at most 1500 px and encoded as WebP (quality 88) for delivery. The grid, labels and transitions are separate HTML, so missing art never prevents training.
|
||||
- `cat.png`: generated RGBA cat, reduced to at most 256 px with alpha preserved. The scene supplies a text marker if this image fails. The same sprite is used for the fictional profile portrait.
|
||||
|
||||
Generation used the built-in tool, not the API/CLI fallback. Source images were inspected before resizing. Prompts:
|
||||
|
||||
## Forest
|
||||
|
||||
> Use case: illustration-story. Asset type: original background for a browser climbing training game. Create a hand-painted woodland tree-canopy location, landscape 5:3 composition. View into an old forest, moss-covered broad horizontal branches and sturdy trunks framing left and right, oak foliage, distant misty blue-green woods, warm muted light. The entire middle and bottom are traversable-looking interwoven broad branches and leaf platforms, enough visual calm to overlay a transparent 10-column by 6-row grid. Rich storybook browser-game painting, earthy ochre bark, deep olive greens. No animals, no characters, no text, no grid, no UI, no logos, no watermark. Not a screenshot of any existing game; original forest artwork.
|
||||
|
||||
## Character
|
||||
|
||||
> Use case: stylized-concept. Asset type: original small cat character sprite for a woodland browser game. A single full-body small grey-brown tabby cat, standing sideways facing right, alert ears, slightly raised curved tail, four paws visible, calm bright amber eyes. Soft hand-painted storybook game illustration with clear silhouette and crisp readable dark outline, natural cat proportions. Isolated centered with small margin on genuinely transparent background. No ground, no scenery, no text, no logo, no watermark, no other objects.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 41 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 355 KiB |
@@ -0,0 +1,134 @@
|
||||
// Original implementation of the training model described in LU_TRAINER_PROJECT.md.
|
||||
// No DOM, storage, clock or network: the UI consumes only view() and action results.
|
||||
export const ROWS = 6;
|
||||
export const COLS = 10;
|
||||
export const START = 50;
|
||||
export const EXIT = 39;
|
||||
export const DEFAULTS = Object.freeze({ height: 1, lu: 5, growth: 12, season: 0 });
|
||||
|
||||
export function neighbors(id) {
|
||||
const row = Math.floor(id / COLS), col = id % COLS, result = [];
|
||||
for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++) {
|
||||
if (!dr && !dc) continue;
|
||||
const r = row + dr, c = col + dc;
|
||||
if (r >= 0 && r < ROWS && c >= 0 && c < COLS) result.push(r * COLS + c);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function hintChance(lu) { return lu < 4 ? 0 : lu === 4 ? .1 : lu === 5 ? .2 : .3; }
|
||||
export function coordinate(id) { return `${'АБВГДЕ'[Math.floor(id / COLS)]}${id % COLS + 1}`; }
|
||||
function settings(input) {
|
||||
const value = { ...DEFAULTS, ...input };
|
||||
if (!Number.isInteger(value.height) || value.height < 1 || value.height > 5 ||
|
||||
!Number.isInteger(value.lu) || value.lu < 0 || value.lu > 9 ||
|
||||
![12,15,18,22,25].includes(value.growth) || ![-3,0,5].includes(value.season)) {
|
||||
throw new RangeError('Недопустимые параметры тренировки');
|
||||
}
|
||||
return Object.freeze(value);
|
||||
}
|
||||
function distance(a, b) { return Math.max(Math.abs(Math.floor(a / COLS) - Math.floor(b / COLS)), Math.abs(a % COLS - b % COLS)); }
|
||||
export function generateField(input = DEFAULTS, random = Math.random) {
|
||||
const options = settings(input);
|
||||
const base = Array.from({length: options.height === 1 ? 5 : 3}, (_,i)=>i);
|
||||
const reserved = new Set([START, EXIT, ...base]);
|
||||
function connect(from, to) {
|
||||
while (from !== to) {
|
||||
const steps = neighbors(from).filter(id => distance(id, to) < distance(from, to));
|
||||
from = steps[Math.floor(random() * steps.length)];
|
||||
reserved.add(from);
|
||||
}
|
||||
}
|
||||
connect(START, base[0]);
|
||||
connect(base[Math.floor(random() * base.length)], EXIT);
|
||||
const candidates = Array.from({length: ROWS * COLS}, (_,id)=>id).filter(id => !reserved.has(id));
|
||||
for (let i = candidates.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(random() * (i + 1));
|
||||
[candidates[i], candidates[j]] = [candidates[j], candidates[i]];
|
||||
}
|
||||
const count = Math.min(Math.max(5, options.growth + options.season + 2 * (options.height - 1)), candidates.length);
|
||||
const hazards = new Set(candidates.slice(0, count));
|
||||
const values = Array.from({length: ROWS * COLS}, (_,id)=>neighbors(id).filter(n => hazards.has(n)).length);
|
||||
return { base, reserved, hazards, values };
|
||||
}
|
||||
|
||||
export class Training {
|
||||
#field;
|
||||
#opened = new Set();
|
||||
#marks = new Set();
|
||||
#position = START;
|
||||
#status = 'ready';
|
||||
#hit = null;
|
||||
#history = [];
|
||||
#options;
|
||||
constructor(input = DEFAULTS, random = Math.random) {
|
||||
this.#options = settings(input);
|
||||
this.#field = generateField(this.#options, random);
|
||||
}
|
||||
#valid(id) { return Number.isInteger(id) && id >= 0 && id < ROWS * COLS; }
|
||||
#finished() { return this.#status === 'won' || this.#status === 'lost'; }
|
||||
#transition(id) { return id === START || id === EXIT; }
|
||||
#available(id) { return this.#field.base.includes(id) || neighbors(id).some(n => this.#opened.has(n)); }
|
||||
#guard(id) {
|
||||
if (this.#finished()) return {code: 'finished'};
|
||||
if (!this.#valid(id)) return {code: 'invalid'};
|
||||
if (this.#transition(id)) return {code: 'transition'};
|
||||
return null;
|
||||
}
|
||||
#win() {
|
||||
if (this.#opened.size === ROWS * COLS - 2 - this.#field.hazards.size ||
|
||||
(this.#marks.size === this.#field.hazards.size && [...this.#marks].every(id => this.#field.hazards.has(id)))) this.#status = 'won';
|
||||
}
|
||||
jump(id, random = Math.random) {
|
||||
const rejected = this.#guard(id);
|
||||
if (rejected) return rejected;
|
||||
if (this.#marks.has(id)) return {code: 'marked'};
|
||||
if (!this.#available(id)) return {code: 'unreachable'};
|
||||
this.#status = 'playing';
|
||||
if (this.#field.hazards.has(id)) {
|
||||
this.#hit = id; this.#status = 'lost';
|
||||
this.#history.push({type: 'fall', id});
|
||||
return {code: 'fall', id, hint: null};
|
||||
}
|
||||
const code = this.#opened.has(id) ? 'revisited' : 'opened';
|
||||
this.#opened.add(id); this.#position = id;
|
||||
const value = this.#field.values[id];
|
||||
this.#history.push({type: code, id, value});
|
||||
this.#win();
|
||||
const candidates = neighbors(id).filter(n => this.#field.hazards.has(n) && !this.#marks.has(n));
|
||||
const hint = !this.#finished() && candidates.length && random() < hintChance(this.#options.lu)
|
||||
? candidates[Math.floor(random() * candidates.length)] : null;
|
||||
return {code, id, value, hint};
|
||||
}
|
||||
mark(id) {
|
||||
const rejected = this.#guard(id);
|
||||
if (rejected) return rejected;
|
||||
if (this.#opened.has(id)) return {code: 'opened'};
|
||||
const marked = !this.#marks.has(id);
|
||||
if (marked) this.#marks.add(id); else this.#marks.delete(id);
|
||||
this.#history.push({type: marked ? 'marked' : 'unmarked', id});
|
||||
this.#win();
|
||||
return {code: marked ? 'marked' : 'unmarked', id};
|
||||
}
|
||||
clearMarks() {
|
||||
if (this.#finished()) return {code: 'finished'};
|
||||
if (!this.#marks.size) return {code: 'empty'};
|
||||
this.#marks.clear(); this.#history.push({type: 'cleared'});
|
||||
return {code: 'cleared'};
|
||||
}
|
||||
view() {
|
||||
const ended = this.#finished();
|
||||
return {
|
||||
options: {...this.#options}, status: this.#status, position: this.#position, hit: this.#hit,
|
||||
hazards: this.#field.hazards.size, marks: this.#marks.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, transition: this.#transition(id), base: this.#field.base.includes(id),
|
||||
opened: this.#opened.has(id), marked: this.#marks.has(id),
|
||||
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)} : {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--scene-backdrop: #33291f; --panel: #927a57; --inner: #ad9672; --paper: #d5c19c;
|
||||
--ink: #17120d; --muted: #30271c; --border: #51402b; --light: #f4e7ca;
|
||||
--map: #222b28; --map-cell: #3f4b44; --active: #85b7be; --danger: #712c27;
|
||||
--focus: #fff5cc; --line: #e6d5ad; --shadow: 0 3px 12px #160f0b55;
|
||||
--radius: 6px; --space: 8px; --small: .8125rem; --body: 1rem; --title: 1.25rem;
|
||||
font: var(--body)/1.5 Verdana, sans-serif;
|
||||
color: var(--ink); background: var(--scene-backdrop);
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; }
|
||||
[hidden] { display: none !important; }
|
||||
a { color: inherit; text-underline-offset: .2em; }
|
||||
button, select, input { font: inherit; }
|
||||
button, select { border: 1px solid var(--border); border-radius: 4px; background: var(--paper); color: var(--ink); }
|
||||
button { padding: 8px 12px; min-height: 44px; cursor: pointer; transition: background-color .15s ease, color .15s ease; }
|
||||
button:hover { background: var(--light); }
|
||||
button:active { background: var(--active); }
|
||||
button:disabled { cursor: default; opacity: .5; }
|
||||
button.primary { background: var(--map); color: var(--light); border-color: var(--map); }
|
||||
button.primary:hover { background: var(--border); }
|
||||
:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; box-shadow: 0 0 0 5px var(--ink); }
|
||||
h1, h2, h3, p { margin: 0; }
|
||||
h1, h2, h3 { font-family: Georgia, serif; }
|
||||
h1, h2 { font-size: var(--title); line-height: 1.3; }
|
||||
h3 { font-size: 1.0625rem; margin: 16px 0 8px; }
|
||||
p + p { margin-top: 8px; }
|
||||
.topbar { max-width: 1840px; margin: auto; padding: 16px 20px; color: var(--light); display: flex; align-items: center; justify-content: space-between; gap: 16px; }
|
||||
.brand { display: flex; align-items: baseline; gap: 16px; }
|
||||
.brand > span { font-size: var(--small); color: var(--paper); }
|
||||
.topbar nav { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.topbar nav a { margin-right: 8px; font-size: var(--small); }
|
||||
.game-layout { max-width: 1840px; margin: 0 auto; padding: 0 20px; display: grid; grid-template-columns: minmax(0, 27fr) minmax(0, 46fr) minmax(0, 27fr); gap: 12px; align-items: start; }
|
||||
.left-column, .center-column, .right-column { display: flex; flex-direction: column; gap: 12px; min-width: 0; }
|
||||
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; box-shadow: var(--shadow); min-width: 0; }
|
||||
.panel > h2 { padding-bottom: 8px; margin-bottom: 12px; border-bottom: 1px solid var(--border); }
|
||||
.identity { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
|
||||
.identity strong, .identity span { display: block; }
|
||||
.identity span { font-size: var(--small); color: var(--muted); }
|
||||
.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); }
|
||||
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); }
|
||||
.character .fineprint { margin-top: 16px; }
|
||||
.location { padding: 0; overflow: hidden; }
|
||||
.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); }
|
||||
.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)); }
|
||||
.scene-grid { position: absolute; inset: 0; display: grid; grid-template-rows: repeat(6, minmax(0, 1fr)); }
|
||||
.cell-grid [role=gridcell] { position: relative; min-width: 0; min-height: 0; }
|
||||
.cell-grid button { border-radius: 0; min-height: 0; width: 100%; height: 100%; padding: 0; font-weight: bold; }
|
||||
.scene-grid button { background: #1b28192b; border: 1px solid #f4e7ca55; color: var(--light); text-shadow: 0 1px 3px var(--ink); }
|
||||
.scene-grid button:hover { background: #f4e7ca33; }
|
||||
.scene-grid .available button { border-color: var(--line); }
|
||||
.scene-grid .opened button { background: #eee0bbbd; color: var(--ink); text-shadow: none; }
|
||||
.scene-grid .marked button, .scene-grid .hazard button { background: #712c27c9; color: var(--light); }
|
||||
.cell-grid .selected button { outline: 2px solid var(--active); outline-offset: -3px; }
|
||||
.cell-grid .current button { box-shadow: inset 0 0 0 2px var(--light); }
|
||||
.scene-grid .hint button { background: var(--danger); color: var(--light); }
|
||||
.cell-grid button:focus-visible { outline: 3px solid var(--focus); outline-offset: -4px; box-shadow: inset 0 0 0 5px var(--ink); z-index: 3; position: relative; }
|
||||
.cell-grid .transition button { background: #222b28cc; color: var(--light); }
|
||||
.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); }
|
||||
.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; }
|
||||
.character-sprite:has(img:not([hidden])) > span { visibility: hidden; }
|
||||
.legend { display: flex; gap: 4px 12px; flex-wrap: wrap; padding: 12px 16px; font-size: var(--small); }
|
||||
.result { margin: 0 12px 12px; padding: 12px; background: var(--paper); border: 2px solid var(--border); font-weight: bold; }
|
||||
.mode { border: 0; padding: 0; margin: 0 0 12px; display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.mode legend { font-size: var(--small); margin-bottom: 8px; }
|
||||
.mode label { cursor: pointer; padding: 8px 12px; border: 1px solid var(--border); border-radius: 4px; min-height: 44px; display: flex; gap: 8px; align-items: center; background: var(--inner); }
|
||||
.mode label:has(:checked) { background: var(--map); color: var(--light); }
|
||||
input { accent-color: var(--map); }
|
||||
.mode input { accent-color: var(--active); }
|
||||
.action-buttons { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; }
|
||||
#status { margin-top: 12px; font-size: var(--small); min-height: 3em; }
|
||||
.mobile-tools { display: none; }
|
||||
.journal { list-style-position: inside; margin: 0; padding: 0; max-height: 280px; overflow: auto; font-size: var(--small); scrollbar-color: var(--border) var(--inner); }
|
||||
.journal li { padding: 8px 0; border-bottom: 1px solid var(--border); overflow-wrap: anywhere; }
|
||||
.messages { margin-top: 12px; max-height: 210px; }
|
||||
.map-panel { background: var(--map); color: var(--light); }
|
||||
.map-panel .fineprint, #panel-dialog:has(#map-body) .fineprint { color: var(--paper); }
|
||||
.panel-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 12px; }
|
||||
.panel-heading h2 { min-width: 0; }
|
||||
#map-toggle { color: inherit; background: none; border: 0; padding: 0 4px; text-align: left; font: inherit; }
|
||||
#map-expand { padding: 4px 8px; font-size: var(--small); }
|
||||
.map-grid { display: grid; gap: 2px; margin: 12px 0; }
|
||||
.map-grid [role=row] { gap: 2px; }
|
||||
.map-grid button { aspect-ratio: 1; min-height: 24px; background: var(--map-cell); border: 1px solid var(--inner); color: var(--light); font-size: var(--small); }
|
||||
.map-grid .opened button { background: var(--paper); color: var(--ink); }
|
||||
.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); }
|
||||
#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; }
|
||||
.quiet { background: none; border-color: var(--paper); color: inherit; width: 100%; }
|
||||
.quiet:hover { color: var(--ink); }
|
||||
footer { max-width: 1840px; padding: 16px 20px; margin: auto; color: var(--paper); font-size: var(--small); }
|
||||
dialog { padding: 24px; width: min(640px, calc(100% - 24px)); max-height: calc(100dvh - 32px); overflow: auto; background: var(--inner); color: var(--ink); border: 2px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow); }
|
||||
dialog::backdrop { background: #17120dbf; }
|
||||
dialog h2 { margin-bottom: 16px; }
|
||||
dialog p { margin: 12px 0; }
|
||||
.dialog-actions { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; margin-top: 20px; }
|
||||
.settings-fields { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 16px; margin: 20px 0; }
|
||||
.settings-fields label { display: flex; flex-direction: column; gap: 8px; }
|
||||
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); }
|
||||
.skip-link { position: absolute; z-index: 10; left: 20px; top: -100px; background: var(--paper); padding: 12px; }
|
||||
.skip-link:focus { top: 8px; }
|
||||
.noscript { position: fixed; inset: 30% 12px auto; padding: 20px; background: var(--paper); color: var(--ink); z-index: 5; }
|
||||
@media (min-width: 1500px) { .scene { aspect-ratio: 5 / 3.6; } .journal { max-height: 350px; } }
|
||||
@media (max-width: 1100px) {
|
||||
.game-layout { display: flex; flex-direction: column; }
|
||||
.left-column, .center-column { display: contents; }
|
||||
.panel { width: 100%; }
|
||||
.character { order: 0; }
|
||||
.character > h2, .character > h3, .character .portrait, .character .fineprint { display: none; }
|
||||
.identity { margin-bottom: 8px; }
|
||||
.identity strong { font-size: var(--small); }
|
||||
.identity span { display: none; }
|
||||
.character .stats { display: flex; flex-wrap: wrap; gap: 4px 16px; }
|
||||
.character .stats > div { border: 0; padding: 2px 0; }
|
||||
.location { order: 1; }
|
||||
.actions { order: 2; }
|
||||
.history-panel { display: none; }
|
||||
.right-column { order: 3; width: 100%; display: grid; grid-template-columns: 1fr 1fr; align-items: start; }
|
||||
.mobile-tools { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
|
||||
.mobile-tools button { flex: 1; }
|
||||
.brand { display: block; }
|
||||
.topbar { align-items: start; }
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.topbar { flex-direction: column; gap: 12px; padding: 12px; }
|
||||
.topbar nav { width: 100%; }
|
||||
.topbar nav > a { width: 100%; }
|
||||
.topbar nav button { flex: 1; padding: 8px; }
|
||||
.brand { display: flex; }
|
||||
.game-layout { display: flex; flex-direction: column; padding: 0 12px; gap: 12px; }
|
||||
.left-column, .center-column, .right-column { display: contents; }
|
||||
.panel { width: 100%; padding: 12px; }
|
||||
.character { order: 0; }
|
||||
.character > h2, .character > h3, .character .portrait, .character .fineprint { display: none; }
|
||||
.identity { margin-bottom: 8px; }
|
||||
.identity strong { font-size: var(--small); }
|
||||
.identity span { display: none; }
|
||||
.character .stats { display: flex; flex-wrap: wrap; gap: 4px 12px; }
|
||||
.character .stats > div { border: 0; padding: 2px 0; }
|
||||
.character .stats:first-of-type > div:last-child, .character .stats:last-of-type > div:nth-child(n+3) { display: none; }
|
||||
.location { order: 1; padding: 0; }
|
||||
.actions { order: 2; }
|
||||
.messages-panel { order: 3; }
|
||||
.map-panel, .history-panel { display: none; }
|
||||
.mobile-tools { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
|
||||
.mobile-tools button { flex: 1; }
|
||||
.cell-coord { font-size: 8px; left: 1px; top: 1px; padding: 0 1px; }
|
||||
.cell-value { font-size: 14px; }
|
||||
.scene-grid .opened .cell-coord { display: none; }
|
||||
.action-buttons button { flex: 1; }
|
||||
.legend { padding: 8px 12px; }
|
||||
.settings-fields { grid-template-columns: 1fr; }
|
||||
dialog { padding: 16px; }
|
||||
footer { padding: 16px 12px; }
|
||||
}
|
||||
@media (pointer: coarse) { .action-buttons button, .mobile-tools button, #map-mark, .mode label { 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; } }
|
||||
@@ -0,0 +1,247 @@
|
||||
import {Training, DEFAULTS, ROWS, COLS, START, EXIT, 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 describe(cell, view) {
|
||||
if (cell.id === START) return 'вход';
|
||||
if (cell.id === 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.id === START ? '↥' : '↗';
|
||||
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 = `Начните с клеток А1–А${options.height === 1 ? 5 : 3}. Стрелки перемещают фокус, 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.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}`;
|
||||
$('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 ? `Выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной». Начало: А1–А${view.options.height === 1 ? 5 : 3}.` : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Начало: А1–А${view.options.height === 1 ? 5 : 3}, затем рядом с любой проверенной клеткой.`;
|
||||
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();
|
||||
Reference in new issue
Block a user