fix: anchor trainer entrance and generate variable exits
This commit is contained in:
1 parent
30d012de80
commit
87a9a5934a
12 files changed
+117
-53
No files matched your search
+6
-5
@@ -39,7 +39,8 @@
|
||||
<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>
|
||||
<p id="transition-coordinates" class="scene-instructions">Вход: x1 y1 · Выход выбирается для новой попытки</p>
|
||||
<p id="scene-instructions" class="scene-instructions">Откройте доступную стартовую клетку. Затем прыгайте рядом с любой проверенной клеткой.</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>
|
||||
@@ -51,9 +52,9 @@
|
||||
<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>
|
||||
<p id="selection">Выбрана клетка x1 y1 · вход</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>
|
||||
<p id="status" role="status" aria-atomic="true">Выберите доступную стартовую клетку. Стрелки перемещают фокус, Enter или пробел выполняет действие.</p>
|
||||
<div class="mobile-tools"><button id="map-open" type="button">Минное поле</button><button id="history-open" type="button">История</button></div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -65,7 +66,7 @@
|
||||
<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>
|
||||
<p id="map-selection">Выбрана x1 y1 · вход</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>
|
||||
@@ -93,7 +94,7 @@
|
||||
<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>Вход всегда находится в x1 y1 — верхней левой клетке. X растёт вправо, Y — вниз. Выход в этой модели выбирается случайно для каждой новой попытки и может занять любую другую клетку. Переходы отмечены стрелками: по ним не прыгают. В верхней строке доступны 5 безопасных стартовых клеток на высоте 1 и 3 выше, не считая переходов.</li>
|
||||
<li>Открывайте клетки рядом с любой проверенной, включая диагонали. Персонаж показывает последний успешный прыжок, а не ограничивает его дальность.</li>
|
||||
<li>Число — количество опасностей среди восьми соседей. Ноль не открывает соседние клетки автоматически. Звуки здесь только текстовые.</li>
|
||||
<li>На компьютере клик выполняет выбранное действие, правая кнопка ставит заметку. На телефоне сначала выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной».</li>
|
||||
|
||||
+12
-10
@@ -2,8 +2,7 @@
|
||||
// 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 START = 0;
|
||||
export const DEFAULTS = Object.freeze({ height: 1, lu: 5, growth: 12, season: 0 });
|
||||
|
||||
export function neighbors(id) {
|
||||
@@ -16,7 +15,7 @@ export function neighbors(id) {
|
||||
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}`; }
|
||||
export function coordinate(id) { return `x${id % COLS + 1} y${Math.floor(id / COLS) + 1}`; }
|
||||
function settings(input) {
|
||||
const value = { ...DEFAULTS, ...input };
|
||||
if (!Number.isInteger(value.height) || value.height < 1 || value.height > 5 ||
|
||||
@@ -29,8 +28,11 @@ function settings(input) {
|
||||
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]);
|
||||
const exit = 1 + Math.floor(random() * (ROWS * COLS - 1));
|
||||
// Transitions do not consume one of the 5/3 initially playable safe cells.
|
||||
const base = Array.from({length: COLS - 1}, (_,i)=>i + 1)
|
||||
.filter(id => id !== exit).slice(0, options.height === 1 ? 5 : 3);
|
||||
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));
|
||||
@@ -39,7 +41,7 @@ export function generateField(input = DEFAULTS, random = Math.random) {
|
||||
}
|
||||
}
|
||||
connect(START, base[0]);
|
||||
connect(base[Math.floor(random() * base.length)], EXIT);
|
||||
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));
|
||||
@@ -48,7 +50,7 @@ export function generateField(input = DEFAULTS, random = Math.random) {
|
||||
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 };
|
||||
return { start: START, exit, base, reserved, hazards, values };
|
||||
}
|
||||
|
||||
export class Training {
|
||||
@@ -66,7 +68,7 @@ export class Training {
|
||||
}
|
||||
#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; }
|
||||
#transition(id) { return id === START || id === this.#field.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'};
|
||||
@@ -118,12 +120,12 @@ export class Training {
|
||||
view() {
|
||||
const ended = this.#finished();
|
||||
return {
|
||||
options: {...this.#options}, status: this.#status, position: this.#position, hit: this.#hit,
|
||||
options: {...this.#options}, start: START, exit: this.#field.exit, 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),
|
||||
id, entrance: id === START, exit: id === this.#field.exit, 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,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Training, DEFAULTS, ROWS, COLS, START, EXIT, coordinate, hintChance} from './engine.js';
|
||||
import {Training, DEFAULTS, ROWS, COLS, START, coordinate, hintChance} from './engine.js';
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
const compact = matchMedia('(max-width: 700px), (pointer: coarse)');
|
||||
@@ -15,9 +15,10 @@ function addItem(list, text) {
|
||||
}
|
||||
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.id === START) return 'вход';
|
||||
if (cell.id === EXIT) return 'выход';
|
||||
if (cell.entrance) return 'вход';
|
||||
if (cell.exit) return 'выход';
|
||||
if (cell.wrong) return 'ошибочная отметка, безопасно';
|
||||
if (cell.hazard) return 'опасная клетка';
|
||||
if (cell.opened) return `проверено, опасностей рядом: ${cell.value}`;
|
||||
@@ -27,7 +28,7 @@ function describe(cell, view) {
|
||||
return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, сначала откройте соседнюю клетку';
|
||||
}
|
||||
function cellValue(cell, view, showMarks) {
|
||||
if (cell.transition) return cell.id === START ? '↥' : '↗';
|
||||
if (cell.transition) return cell.entrance ? '↥' : '↗';
|
||||
if (cell.wrong) return '≠';
|
||||
if (cell.hazard) return '×';
|
||||
if (cell.marked && showMarks) return '⚑';
|
||||
@@ -104,7 +105,7 @@ 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 или пробел выполняет действие.`;
|
||||
$('status').textContent = `Начальные клетки: ${initialCells(game.view())}. Стрелки перемещают фокус, Enter или пробел выполняет действие.`;
|
||||
updateClock(); render();
|
||||
}
|
||||
function render() {
|
||||
@@ -113,7 +114,7 @@ function render() {
|
||||
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.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);
|
||||
@@ -125,13 +126,14 @@ function render() {
|
||||
$('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 ? `Выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной». Начало: А1–А${view.options.height === 1 ? 5 : 3}.` : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Начало: А1–А${view.options.height === 1 ? 5 : 3}, затем рядом с любой проверенной клеткой.`;
|
||||
$('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)}`;
|
||||
|
||||
Reference in new issue
Block a user