fix: limit trainer jumps and exit positions

This commit is contained in:
nyan404 committed 2026-11-22 16:33:30 +03:00
1 parent 27b3e0aaae
commit cc6bcb23c8
12 files changed
+174 -79

No files matched your search

+9 -5
View File
@@ -4,6 +4,11 @@ export const ROWS = 6;
export const COLS = 10;
export const START = 0;
export const DEFAULTS = Object.freeze({ height: 1, lu: 5, growth: 12, season: 0 });
const EXIT_CELLS = Array.from({length: ROWS * COLS}, (_, id) => id)
.filter(id => {
const x = id % COLS + 1, y = Math.floor(id / COLS) + 1;
return (x === COLS && y >= 2) || (y === ROWS && x >= 6);
});
export function neighbors(id) {
const row = Math.floor(id / COLS), col = id % COLS, result = [];
@@ -28,10 +33,9 @@ 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 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 exit = EXIT_CELLS[Math.floor(random() * EXIT_CELLS.length)];
// The safe strip starts next to the entrance; exits never occupy the top row.
const base = Array.from({length: options.height === 1 ? 5 : 3}, (_, i) => i + 1);
const reserved = new Set([START, exit, ...base]);
function connect(from, to) {
while (from !== to) {
@@ -69,7 +73,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 === this.#field.exit; }
#available(id) { return this.#field.base.includes(id) || neighbors(id).some(n => this.#opened.has(n)); }
#available(id) { return !this.#transition(id) && distance(this.#position, id) === 1; }
#guard(id) {
if (this.#finished()) return {code: 'finished'};
if (!this.#valid(id)) return {code: 'invalid'};
+5 -6
View File
@@ -15,17 +15,16 @@ 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.entrance) return 'вход';
if (cell.exit) return 'выход';
if (cell.wrong) return 'ошибочная отметка, безопасно';
if (cell.hazard) return 'опасная клетка';
if (cell.opened) return `проверено, опасностей рядом: ${cell.value}`;
if (cell.opened) return `проверено, опасностей рядом: ${cell.value}${cell.available ? ', прыжок доступен' : ''}`;
if (ended(view)) return `безопасная клетка, опасностей рядом: ${cell.value}`;
if (cell.marked) return 'ваша отметка опасности';
if (hints.has(cell.id)) return 'подсказка: опасность';
return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, сначала откройте соседнюю клетку';
return cell.available ? 'неизвестно, прыжок доступен' : 'неизвестно, не рядом с персонажем';
}
function cellValue(cell, view, showMarks) {
if (cell.transition) return cell.entrance ? '↥' : '↗';
@@ -105,7 +104,7 @@ 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 или пробел выполняет действие.`;
$('status').textContent = 'Начните с клетки рядом со входом. Стрелки перемещают фокус, Enter или пробел выполняет действие.';
updateClock(); render();
}
function render() {
@@ -133,7 +132,7 @@ 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 ? `Выберите клетку, затем нажмите «Прыгнуть» или «Отметить опасной». Начальные клетки: ${initialCells(view)}.` : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Начальные клетки: ${initialCells(view)}; затем рядом с любой проверенной клеткой.`;
$('scene-instructions').textContent = compact.matches ? 'Выберите соседнюю клетку и нажмите «Прыгнуть». Отметку можно поставить где угодно на уступе.' : `Клик — ${mode === 'jump' ? 'прыжок' : 'отметка'}. Прыгать можно только в соседние клетки, в том числе по диагонали.`;
const cell = view.cells[selected], note = cell.marked ? 'Снять отметку' : 'Отметить опасной';
$('selection').textContent = `Выбрана клетка ${coordinate(selected)} · ${describe(cell, view)}`;
$('map-selection').textContent = `Выбрана ${coordinate(selected)} · ${describe(cell, view)}`;
@@ -171,7 +170,7 @@ function act(action) {
} 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];
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 += ' Карта готова! Победа. Всё поле раскрыто.';