feat(player-ui): add pre-reader controls and onboarding

This commit is contained in:
2026-09-09 20:56:38 +03:00
parent f043b63732
commit 3827ba7ec7
9 changed files with 424 additions and 52 deletions
+188 -14
View File
@@ -8,6 +8,20 @@
const MAX_VIEW_CELLS = 1024;
const MAX_VIEW_OBJECTS = 12;
const OBSERVER_CELL_SIZE = 8;
const JOYSTICK_DEAD_ZONE = 20;
const JOYSTICK_HYSTERESIS = .18;
const JOYSTICK_SLOW_REPEAT_MS = 360;
const JOYSTICK_FAST_REPEAT_MS = 170;
const ONBOARDING_STEPS = Object.freeze([
Object.freeze({icon: "hand", title: "Потяни кружок", text: "Кружок ведёт героя по лабиринту."}),
Object.freeze({icon: "motion", title: "Отпусти — герой ждёт", text: "Рука остановилась — шаги тоже."}),
Object.freeze({icon: "maze", title: "Стена не пускает", text: "Упрись в стену — попробуй другую сторону."}),
Object.freeze({icon: "key", title: "Найди ключ", text: "Ключ открывает твой выход."}),
Object.freeze({icon: "eye", title: "Глаз расширяет карту", text: "Возьми глаз — увидишь дальше."}),
Object.freeze({icon: "arrow", title: "Стрелка знает путь", text: "Компас показывает сторону выхода."}),
Object.freeze({icon: "exit", title: "Выходи с ключом", text: "Коснись своего выхода с ключом."}),
Object.freeze({icon: "friends", title: "Встретил друга", text: "Другой герой может отдать найденный ключ."})
]);
const NAME_ADJECTIVES = Object.freeze(["Бодрый", "Хитрый", "Тихий", "Смелый", "Ловкий", "Сонный", "Шустрый", "Лунный", "Яркий", "Дикий", "Вечный", "Храбрый"]);
const NAME_NOUNS = Object.freeze(["Барсук", "Крот", "Енот", "Кабан", "Кактус", "Жук", "Тостер", "Тюлень", "Гриб", "Ежик", "Бублик", "Пингвин"]);
const NAME_COMBINATION_COUNT = NAME_ADJECTIVES.length * NAME_NOUNS.length;
@@ -88,6 +102,49 @@
return dy > 0 ? "south" : "north";
}
function clamp(value, minimum, maximum) {
return Math.min(maximum, Math.max(minimum, value));
}
function joystickDirection(dx, dy, previousDirection) {
const horizontal = Math.abs(dx);
const vertical = Math.abs(dy);
if (Math.max(horizontal, vertical) < JOYSTICK_DEAD_ZONE) return null;
const previousWasHorizontal = previousDirection === "east" || previousDirection === "west";
const previousWasVertical = previousDirection === "north" || previousDirection === "south";
if (previousWasHorizontal && horizontal >= vertical * (1 - JOYSTICK_HYSTERESIS)) return dx >= 0 ? "east" : "west";
if (previousWasVertical && vertical >= horizontal * (1 - JOYSTICK_HYSTERESIS)) return dy >= 0 ? "south" : "north";
return horizontal >= vertical ? (dx >= 0 ? "east" : "west") : (dy >= 0 ? "south" : "north");
}
function joystickRepeatMs(distance, radius) {
if (!Number.isFinite(distance) || !Number.isFinite(radius) || distance <= JOYSTICK_DEAD_ZONE || radius <= JOYSTICK_DEAD_ZONE) return null;
const strength = clamp((distance - JOYSTICK_DEAD_ZONE) / (radius - JOYSTICK_DEAD_ZONE), 0, 1);
return Math.round(JOYSTICK_SLOW_REPEAT_MS - (JOYSTICK_SLOW_REPEAT_MS - JOYSTICK_FAST_REPEAT_MS) * strength);
}
function joystickVector(dx, dy, radius, previousDirection) {
const distance = Math.hypot(dx, dy);
const boundedDistance = Math.min(distance, radius);
const ratio = distance > 0 ? boundedDistance / distance : 0;
return {
x: dx * ratio,
y: dy * ratio,
distance: boundedDistance,
direction: joystickDirection(dx, dy, previousDirection),
repeatMs: joystickRepeatMs(boundedDistance, radius)
};
}
function playerCellSize(stageWidth, stageHeight, columns, rows) {
if (![stageWidth, stageHeight, columns, rows].every(value => Number.isFinite(value) && value > 0)) return 46;
return Math.round(clamp(Math.min(stageWidth / (columns + 1), stageHeight / (rows + 1)), 32, 72));
}
function nextOnboardingStep(currentStep) {
return currentStep >= ONBOARDING_STEPS.length - 1 ? null : currentStep + 1;
}
function createEnvelope(type, sequence, requestId, payload) {
return {v: 1, type, seq: sequence, requestId, payload: payload || {}};
}
@@ -151,7 +208,7 @@
function boot(documentObject, windowObject) {
const byId = id => documentObject.getElementById(id);
const state = {socket: null, clientSequence: 0, serverSequence: 0, viewSequence: -1, session: null, lobby: null, snapshot: null, reconnectTimer: null, noticeTimer: null, touchStart: null, pending: new Map(), assembler: new SnapshotAssembler(), audio: null, feedbackReady: false, observer: {scale: 1, x: 0, y: 0, dragging: null}};
const state = {socket: null, clientSequence: 0, serverSequence: 0, viewSequence: -1, session: null, lobby: null, snapshot: null, reconnectTimer: null, noticeTimer: null, touchStart: null, pending: new Map(), assembler: new SnapshotAssembler(), audio: null, feedbackReady: false, muted: false, reducedMotion: false, onboardingSeen: false, onboardingStep: 0, joystick: {pointerId: null, direction: null, repeatTimer: null, repeatMs: null}, observer: {scale: 1, x: 0, y: 0, dragging: null}};
function showNotice(text, kind) {
const element = byId("notice");
@@ -179,6 +236,7 @@
byId("connection").dataset.state = connectionState;
byId("connection-text").textContent = text;
byId("details-text").textContent = connectionState === "online" ? "WebSocket подключён к локальному ESP." : "Команды временно не отправляются. Повторяем подключение автоматически.";
if (connectionState !== "online") resetJoystick();
}
renderWelcomeHeadline(randomLoginHeadline());
@@ -193,6 +251,7 @@
}
function feedback(success) {
if (state.muted) return;
if (windowObject.navigator && typeof windowObject.navigator.vibrate === "function") {
windowObject.navigator.vibrate(success ? 18 : [24, 35, 24]);
}
@@ -268,9 +327,9 @@
const [kind, owner, variant] = object;
let marker;
if (kind === "key") {
marker = icon("key", "object object-key"); marker.dataset.owner = `P${owner + 1}`;
marker = icon("key", "object object-key"); marker.dataset.owner = owner === 1 ? "two" : "one";
} else if (kind === "exit") {
marker = documentObject.createElement("span"); marker.className = "object object-exit"; marker.dataset.owner = `P${owner + 1}`; marker.dataset.open = String(variant);
marker = documentObject.createElement("span"); marker.className = "object object-exit"; marker.dataset.owner = owner === 1 ? "two" : "one"; marker.dataset.open = String(variant);
} else if (kind === "compass") {
marker = icon("arrow", "object object-compass");
} else if (kind === "vision") {
@@ -288,6 +347,10 @@
pawn.appendChild(text); cell.appendChild(pawn);
}
function characterForSlot(slot) {
return slot === 2 ? {symbol: "◆", name: "Мышонок"} : {symbol: "●", name: "Лисёнок"};
}
function renderMap(snapshot) {
const maze = byId("maze");
maze.replaceChildren();
@@ -298,8 +361,12 @@
const coordinates = snapshot.cells.map(cell => ({index: cell[0], x: cell[0] % snapshot.width, y: Math.floor(cell[0] / snapshot.width), passages: cell[1]}));
const minX = Math.min(...coordinates.map(cell => cell.x)); const maxX = Math.max(...coordinates.map(cell => cell.x));
const minY = Math.min(...coordinates.map(cell => cell.y)); const maxY = Math.max(...coordinates.map(cell => cell.y));
maze.style.gridTemplateColumns = `repeat(${maxX - minX + 1}, var(--cell))`;
maze.style.gridTemplateRows = `repeat(${maxY - minY + 1}, var(--cell))`;
const columns = maxX - minX + 1;
const rows = maxY - minY + 1;
const mapShell = byId("map-shell");
maze.style.setProperty("--cell", `${playerCellSize(mapShell.clientWidth, mapShell.clientHeight, columns, rows)}px`);
maze.style.gridTemplateColumns = `repeat(${columns}, var(--cell))`;
maze.style.gridTemplateRows = `repeat(${rows}, var(--cell))`;
const objects = new Map();
snapshot.objects.forEach(object => { const list = objects.get(object[3]) || []; list.push(object); objects.set(object[3], list); });
coordinates.forEach(data => {
@@ -311,8 +378,9 @@
if (!(data.passages & 4)) cell.classList.add("wall-s");
if (!(data.passages & 8)) cell.classList.add("wall-w");
(objects.get(data.index) || []).forEach(object => addObject(cell, object));
if (data.index === snapshot.self) addPawn(cell, `P${state.session ? state.session.slot : "?"}`, false);
if (data.index === snapshot.opponent) addPawn(cell, "СОП", true);
const slot = state.session ? state.session.slot : 1;
if (data.index === snapshot.self) addPawn(cell, characterForSlot(slot).symbol, false);
if (data.index === snapshot.opponent) addPawn(cell, characterForSlot(slot === 1 ? 2 : 1).symbol, true);
maze.appendChild(cell);
});
byId("map-placeholder").hidden = true;
@@ -326,12 +394,15 @@
state.snapshot = snapshot;
setScreen("match");
const slot = state.session && state.session.slot ? state.session.slot : 1;
byId("self-slot").textContent = `P${slot}`;
const character = characterForSlot(slot);
byId("self-slot").textContent = character.symbol;
byId("self-slot").setAttribute("aria-label", character.name);
byId("self-name").textContent = playerName();
byId("identity").className = `identity player-${slot === 1 ? "one" : "two"}`;
byId("match-screen").classList.toggle("player-two-mode", slot === 2);
byId("match-state").textContent = PHASES[snapshot.phase] || "Гонка идёт";
byId("inventory").textContent = snapshot.inventory == null ? "Пусто" : `Ключ P${snapshot.inventory + 1}`;
byId("inventory").textContent = snapshot.inventory == null ? "Пусто" : `Ключ ${characterForSlot(snapshot.inventory + 1).symbol}`;
byId("inventory-stat").dataset.filled = String(snapshot.inventory != null);
byId("drop-key").disabled = snapshot.inventory == null;
byId("vision").textContent = snapshot.visionMoves ? `${snapshot.visionMoves} ход.` : "Нет";
byId("vision-stat").classList.toggle("vision-active", snapshot.visionMoves > 0);
@@ -340,9 +411,12 @@
byId("compass-stat").dataset.direction = hint;
byId("compass-arrow").style.transform = `rotate(${HINT_ANGLES[hint]}deg)`;
renderMap(snapshot);
if (snapshot.phase === "paused") showModal("Пауза", "Один герой потерялся между Wi‑Fi пакетами. Ждём возвращения.", "ПЕРЕРЫВ", false);
if (snapshot.phase === "paused") { resetJoystick(); showModal("Пауза", "Один герой потерялся между Wi‑Fi пакетами. Ждём возвращения.", "ПЕРЕРЫВ", false); }
else if (snapshot.phase === "finished" || snapshot.result && snapshot.result !== "none") renderResult(snapshot.result);
else hideModal();
else {
hideModal();
if (!state.onboardingSeen) showOnboarding(0);
}
}
function applyObserverTransform() {
@@ -412,6 +486,25 @@
function hideModal() { byId("modal").hidden = true; byId("countdown").hidden = true; }
function renderOnboardingStep(step) {
const scene = ONBOARDING_STEPS[step] || ONBOARDING_STEPS[0];
byId("onboarding-icon-use").setAttribute("href", `/icons.svg#${scene.icon}`);
byId("onboarding-title").textContent = scene.title;
byId("onboarding-text").textContent = scene.text;
documentObject.querySelectorAll("#onboarding-dots span").forEach((dot, index) => dot.classList.toggle("active", index === step));
byId("onboarding-card").dataset.step = String(step);
byId("onboarding-next").textContent = step === ONBOARDING_STEPS.length - 1 ? "В лабиринт" : "Дальше";
}
function showOnboarding(step) {
state.onboardingSeen = true;
state.onboardingStep = clamp(step, 0, ONBOARDING_STEPS.length - 1);
renderOnboardingStep(state.onboardingStep);
byId("onboarding").hidden = false;
}
function hideOnboarding() { byId("onboarding").hidden = true; }
function renderResult(result) {
const slot = state.session && state.session.slot;
let title = "Ничья!"; let text = "Фотофиниш пожал плечами: оба выбрались почти одновременно.";
@@ -421,6 +514,7 @@
text = slot ? (winner === slot ? "Вы официально быстрее очень большого куста." : "Соперник нашёл выход. Лабиринт требует реванш.") : "Зрительный зал фиксирует героический побег без вмешательства в результат.";
}
showModal(title, text, "ГОНКА ЗАВЕРШЕНА", false);
resetJoystick();
byId("modal-action").textContent = state.session && state.session.role === "player" && state.session.slot === 1 ? "Новая гонка" : "Вернуться в лобби";
byId("modal-action").hidden = false;
}
@@ -456,7 +550,7 @@
} else if (message.type === "pause") { showModal("Пауза", `Игрок ${message.payload.slot || "?"} переподключается. Ноги пока не считаются.`, "ЖДЁМ СВЯЗЬ", false);
} else if (message.type === "resume") { hideModal(); showNotice("Оба героя снова на связи. Гонка продолжается.", "success");
} else if (message.type === "match_result") { renderResult(message.payload.result);
} else if (message.type === "reset") { state.snapshot = null; state.viewSequence = -1; state.assembler = new SnapshotAssembler(); hideModal(); setScreen("lobby"); showNotice("Лабиринт пересажен. Можно начинать новую гонку.", "success");
} else if (message.type === "reset") { state.snapshot = null; state.viewSequence = -1; state.assembler = new SnapshotAssembler(); resetJoystick(); hideModal(); setScreen("lobby"); showNotice("Лабиринт пересажен. Можно начинать новую гонку.", "success");
} else if (message.type === "ack") { feedback(true);
} else if (message.type === "error") {
if (message.payload.code === "invalid_token") { windowObject.localStorage.removeItem(TOKEN_KEY); state.session = null; setScreen("welcome"); }
@@ -478,6 +572,59 @@
function move(direction, element) {
if (direction) send("move", {direction}, element || documentObject.querySelector(`[data-direction="${direction}"]`));
}
function resetJoystick() {
windowObject.clearTimeout(state.joystick.repeatTimer);
state.joystick.pointerId = null;
state.joystick.direction = null;
state.joystick.repeatTimer = null;
state.joystick.repeatMs = null;
const joystick = byId("joystick");
const handle = byId("joystick-handle");
if (joystick) joystick.classList.remove("active");
if (handle) handle.style.transform = "translate(-50%, -50%)";
}
function repeatJoystickMove() {
const joystick = state.joystick;
if (!joystick.direction || joystick.pointerId == null || !joystick.repeatMs) return;
move(joystick.direction, byId("joystick"));
joystick.repeatTimer = windowObject.setTimeout(repeatJoystickMove, joystick.repeatMs);
}
function updateJoystick(event) {
const joystick = byId("joystick");
const rect = joystick.getBoundingClientRect();
const radius = Math.max(1, Math.min(rect.width, rect.height) / 2 - 33);
const vector = joystickVector(event.clientX - (rect.left + rect.width / 2), event.clientY - (rect.top + rect.height / 2), radius, state.joystick.direction);
byId("joystick-handle").style.transform = `translate(calc(-50% + ${vector.x}px), calc(-50% + ${vector.y}px))`;
const directionChanged = vector.direction !== state.joystick.direction;
state.joystick.direction = vector.direction;
state.joystick.repeatMs = vector.repeatMs;
windowObject.clearTimeout(state.joystick.repeatTimer);
state.joystick.repeatTimer = null;
if (vector.direction) {
if (directionChanged) move(vector.direction, joystick);
state.joystick.repeatTimer = windowObject.setTimeout(repeatJoystickMove, vector.repeatMs);
}
}
function setMuted(muted) {
state.muted = muted;
const button = byId("mute-toggle");
button.setAttribute("aria-pressed", String(muted));
button.setAttribute("aria-label", muted ? "Включить звук" : "Выключить звук");
button.title = muted ? "Включить звук" : "Выключить звук";
button.querySelector("use").setAttribute("href", muted ? "/icons.svg#sound" : "/icons.svg#sound");
}
function setReducedMotion(reduced) {
state.reducedMotion = reduced;
documentObject.documentElement.dataset.reducedMotion = String(reduced);
byId("motion-toggle").setAttribute("aria-pressed", String(reduced));
byId("motion-toggle").setAttribute("aria-label", reduced ? "Включить движение" : "Уменьшить движение");
}
documentObject.addEventListener("pointerdown", beginFeedback, {once: true});
documentObject.addEventListener("keydown", event => {
if (event.target instanceof windowObject.HTMLInputElement || byId("match-screen").hidden) return;
@@ -486,8 +633,35 @@
});
byId("map-shell").addEventListener("touchstart", event => { const touch = event.changedTouches[0]; state.touchStart = {x: touch.clientX, y: touch.clientY}; }, {passive: true});
byId("map-shell").addEventListener("touchend", event => { if (!state.touchStart) return; const touch = event.changedTouches[0]; move(directionFromSwipe(state.touchStart.x, state.touchStart.y, touch.clientX, touch.clientY), null); state.touchStart = null; }, {passive: true});
byId("joystick").addEventListener("pointerdown", event => {
event.preventDefault();
beginFeedback();
state.joystick.pointerId = event.pointerId;
byId("joystick").classList.add("active");
if (byId("joystick").setPointerCapture) byId("joystick").setPointerCapture(event.pointerId);
updateJoystick(event);
});
byId("joystick").addEventListener("pointermove", event => {
if (event.pointerId === state.joystick.pointerId) updateJoystick(event);
});
const stopJoystick = event => {
if (event.pointerId === state.joystick.pointerId) resetJoystick();
};
byId("joystick").addEventListener("pointerup", stopJoystick);
byId("joystick").addEventListener("pointercancel", stopJoystick);
windowObject.addEventListener("blur", resetJoystick);
documentObject.addEventListener("visibilitychange", () => { if (documentObject.hidden) resetJoystick(); });
documentObject.querySelectorAll("[data-direction]").forEach(button => button.addEventListener("click", () => move(button.dataset.direction, button)));
byId("drop-key").addEventListener("click", () => send("drop_key", {}, byId("drop-key")));
byId("mute-toggle").addEventListener("click", () => setMuted(!state.muted));
byId("motion-toggle").addEventListener("click", () => setReducedMotion(!state.reducedMotion));
byId("onboarding-replay").addEventListener("click", () => showOnboarding(0));
byId("onboarding-next").addEventListener("click", () => {
const next = nextOnboardingStep(state.onboardingStep);
if (next == null) hideOnboarding();
else { state.onboardingStep = next; renderOnboardingStep(next); }
});
byId("onboarding-skip").addEventListener("click", hideOnboarding);
byId("suggest-name").addEventListener("click", () => {
const occupiedNames = state.lobby && Array.isArray(state.lobby.players) ? state.lobby.players.filter(player => player.occupied && typeof player.name === "string").map(player => player.name) : [];
const suggestion = randomSuggestedName(occupiedNames);
@@ -515,10 +689,10 @@
}
});
connect();
return {state, handleMessage, move};
return {state, handleMessage, move, resetJoystick};
}
const api = Object.freeze({TOKEN_KEY, MAX_VIEW_CHUNKS, NAME_COMBINATION_COUNT, LOGIN_HEADLINES, directionFromKey, directionFromSwipe, randomIndex, randomSuggestedName, randomLoginHeadline, createEnvelope, snapshotIsValid, SnapshotAssembler, projectedCellIndices, clampObserverZoom, observerFitScale, boot});
const api = Object.freeze({TOKEN_KEY, MAX_VIEW_CHUNKS, NAME_COMBINATION_COUNT, LOGIN_HEADLINES, ONBOARDING_STEPS, JOYSTICK_DEAD_ZONE, JOYSTICK_HYSTERESIS, JOYSTICK_SLOW_REPEAT_MS, JOYSTICK_FAST_REPEAT_MS, directionFromKey, directionFromSwipe, joystickDirection, joystickRepeatMs, joystickVector, playerCellSize, nextOnboardingStep, randomIndex, randomSuggestedName, randomLoginHeadline, createEnvelope, snapshotIsValid, SnapshotAssembler, projectedCellIndices, clampObserverZoom, observerFitScale, boot});
if (typeof module !== "undefined" && module.exports) module.exports = api;
root.Maze32Player = api;
if (root.document) root.document.addEventListener("DOMContentLoaded", () => { root.maze32PlayerApp = boot(root.document, root); });