feat(player): add mobile directional pad controls
This commit is contained in:
+69
-17
@@ -14,6 +14,7 @@
|
||||
const AVATAR_DIRECTION_HYSTERESIS = .18;
|
||||
const AVATAR_SLOW_REPEAT_MS = 360;
|
||||
const AVATAR_FAST_REPEAT_MS = 170;
|
||||
const DIRECTIONAL_PAD_REPEAT_MS = 170;
|
||||
const LATENCY_SAMPLE_LIMIT = 256;
|
||||
const ONBOARDING_STEPS = Object.freeze([
|
||||
Object.freeze({icon: "hand", title: "Потяни героя", text: "Потяни героя — лабиринт поедет под ним."}),
|
||||
@@ -147,13 +148,13 @@
|
||||
this.latest = null;
|
||||
}
|
||||
|
||||
request(direction) {
|
||||
request(direction, element) {
|
||||
if (!direction) return null;
|
||||
if (this.inFlight) {
|
||||
this.latest = direction;
|
||||
this.latest = {direction, element};
|
||||
return null;
|
||||
}
|
||||
const requestId = this.dispatch(direction);
|
||||
const requestId = this.dispatch(direction, element);
|
||||
if (requestId) this.inFlight = requestId;
|
||||
return requestId;
|
||||
}
|
||||
@@ -161,9 +162,9 @@
|
||||
complete(requestId) {
|
||||
if (!requestId || requestId !== this.inFlight) return null;
|
||||
this.inFlight = null;
|
||||
const direction = this.latest;
|
||||
const latest = this.latest;
|
||||
this.latest = null;
|
||||
return direction ? this.request(direction) : null;
|
||||
return latest ? this.request(latest.direction, latest.element) : null;
|
||||
}
|
||||
|
||||
release() { this.latest = null; }
|
||||
@@ -300,8 +301,8 @@
|
||||
|
||||
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(), latency: new LatencyTracker(() => windowObject.performance.now()), audio: null, feedbackReady: false, muted: false, reducedMotion: false, onboardingSeen: false, onboardingStep: 0, avatar: {pointerId: null, startX: null, startY: null, direction: null, repeatTimer: null, repeatMs: null}, observer: {scale: 1, x: 0, y: 0, dragging: null}};
|
||||
state.moveFlow = new LatestIntentFlow(direction => sendMoveNow(direction));
|
||||
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(), latency: new LatencyTracker(() => windowObject.performance.now()), audio: null, feedbackReady: false, muted: false, reducedMotion: false, onboardingSeen: false, onboardingStep: 0, avatar: {pointerId: null, startX: null, startY: null, direction: null, repeatTimer: null, repeatMs: null}, dpad: {pointerId: null, direction: null, repeatTimer: null}, observer: {scale: 1, x: 0, y: 0, dragging: null}};
|
||||
state.moveFlow = new LatestIntentFlow((direction, element) => sendMoveNow(direction, element));
|
||||
|
||||
function showNotice(text, kind) {
|
||||
const element = byId("notice");
|
||||
@@ -329,7 +330,7 @@
|
||||
byId("connection").dataset.state = connectionState;
|
||||
byId("connection-text").textContent = text;
|
||||
byId("details-text").textContent = connectionState === "online" ? "WebSocket подключён к локальному ESP." : "Команды временно не отправляются. Повторяем подключение автоматически.";
|
||||
if (connectionState !== "online") resetAvatarControl();
|
||||
if (connectionState !== "online") resetPlayerControls();
|
||||
}
|
||||
|
||||
renderWelcomeHeadline(randomLoginHeadline());
|
||||
@@ -502,6 +503,7 @@
|
||||
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;
|
||||
setDirectionalPadEnabled(snapshot.phase === "active" && state.socket && state.socket.readyState === windowObject.WebSocket.OPEN);
|
||||
byId("vision").textContent = snapshot.visionMoves ? `${snapshot.visionMoves} ход.` : "Нет";
|
||||
byId("vision-stat").classList.toggle("vision-active", snapshot.visionMoves > 0);
|
||||
const hint = HINTS[snapshot.hint] ? snapshot.hint : "none";
|
||||
@@ -512,7 +514,7 @@
|
||||
if (Number.isInteger(snapshot.stateSequence)) {
|
||||
windowObject.requestAnimationFrame(() => state.latency.painted(snapshot.stateSequence));
|
||||
}
|
||||
if (snapshot.phase === "paused") { resetAvatarControl(); showModal("Пауза", "Один герой потерялся между Wi‑Fi пакетами. Ждём возвращения.", "ПЕРЕРЫВ", false); }
|
||||
if (snapshot.phase === "paused") { resetPlayerControls(); showModal("Пауза", "Один герой потерялся между Wi‑Fi пакетами. Ждём возвращения.", "ПЕРЕРЫВ", false); }
|
||||
else if (snapshot.phase === "finished" || snapshot.result && snapshot.result !== "none") renderResult(snapshot.result);
|
||||
else {
|
||||
hideModal();
|
||||
@@ -615,7 +617,7 @@
|
||||
text = slot ? (winner === slot ? "Вы официально быстрее очень большого куста." : "Соперник нашёл выход. Лабиринт требует реванш.") : "Зрительный зал фиксирует героический побег без вмешательства в результат.";
|
||||
}
|
||||
showModal(title, text, "ГОНКА ЗАВЕРШЕНА", false);
|
||||
resetAvatarControl();
|
||||
resetPlayerControls();
|
||||
byId("modal-action").textContent = state.session && state.session.role === "player" && state.session.slot === 1 ? "Новая гонка" : "Вернуться в лобби";
|
||||
byId("modal-action").hidden = false;
|
||||
}
|
||||
@@ -651,7 +653,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(); resetAvatarControl(); hideModal(); setScreen("lobby"); showNotice("Лабиринт пересажен. Можно начинать новую гонку.", "success");
|
||||
} else if (message.type === "reset") { state.snapshot = null; state.viewSequence = -1; state.assembler = new SnapshotAssembler(); resetPlayerControls(); hideModal(); setScreen("lobby"); showNotice("Лабиринт пересажен. Можно начинать новую гонку.", "success");
|
||||
} else if (message.type === "ack") { state.latency.acknowledged(message.requestId, message.payload && message.payload.stateSequence); state.moveFlow.complete(message.requestId); feedback(true);
|
||||
} else if (message.type === "error") {
|
||||
state.moveFlow.complete(message.requestId);
|
||||
@@ -675,8 +677,35 @@
|
||||
if (direction) state.moveFlow.request(direction, element);
|
||||
}
|
||||
|
||||
function sendMoveNow(direction) {
|
||||
return send("move", {direction}, byId("avatar-control"));
|
||||
function sendMoveNow(direction, element) {
|
||||
return send("move", {direction}, element || byId("avatar-control"));
|
||||
}
|
||||
|
||||
function setDirectionalPadEnabled(enabled) {
|
||||
documentObject.querySelectorAll("[data-direction]").forEach(button => {
|
||||
button.disabled = !enabled;
|
||||
});
|
||||
if (!enabled) resetDirectionalPad();
|
||||
}
|
||||
|
||||
function resetDirectionalPad() {
|
||||
windowObject.clearTimeout(state.dpad.repeatTimer);
|
||||
state.dpad.pointerId = null;
|
||||
state.dpad.direction = null;
|
||||
state.dpad.repeatTimer = null;
|
||||
documentObject.querySelectorAll("[data-direction]").forEach(button => button.classList.remove("active"));
|
||||
state.moveFlow.release();
|
||||
}
|
||||
|
||||
function repeatDirectionalPadMove() {
|
||||
if (!state.dpad.direction || state.dpad.pointerId == null) return;
|
||||
move(state.dpad.direction, documentObject.querySelector(`[data-direction="${state.dpad.direction}"]`));
|
||||
state.dpad.repeatTimer = windowObject.setTimeout(repeatDirectionalPadMove, DIRECTIONAL_PAD_REPEAT_MS);
|
||||
}
|
||||
|
||||
function resetPlayerControls() {
|
||||
resetAvatarControl();
|
||||
resetDirectionalPad();
|
||||
}
|
||||
|
||||
function resetAvatarControl() {
|
||||
@@ -771,9 +800,32 @@
|
||||
byId("avatar-control").addEventListener("pointerup", stopAvatarControl);
|
||||
byId("avatar-control").addEventListener("pointercancel", stopAvatarControl);
|
||||
byId("avatar-control").addEventListener("lostpointercapture", stopAvatarControl);
|
||||
windowObject.addEventListener("blur", resetAvatarControl);
|
||||
documentObject.addEventListener("visibilitychange", () => { if (documentObject.hidden) resetAvatarControl(); });
|
||||
documentObject.querySelectorAll("[data-direction]").forEach(button => button.addEventListener("click", () => move(button.dataset.direction, button)));
|
||||
windowObject.addEventListener("blur", resetPlayerControls);
|
||||
documentObject.addEventListener("visibilitychange", () => { if (documentObject.hidden) resetPlayerControls(); });
|
||||
documentObject.querySelectorAll("[data-direction]").forEach(button => {
|
||||
button.addEventListener("pointerdown", event => {
|
||||
if (button.disabled) return;
|
||||
event.preventDefault();
|
||||
beginFeedback();
|
||||
resetDirectionalPad();
|
||||
state.dpad.pointerId = event.pointerId;
|
||||
state.dpad.direction = button.dataset.direction;
|
||||
button.classList.add("active");
|
||||
if (button.setPointerCapture) button.setPointerCapture(event.pointerId);
|
||||
move(state.dpad.direction, button);
|
||||
state.dpad.repeatTimer = windowObject.setTimeout(repeatDirectionalPadMove, DIRECTIONAL_PAD_REPEAT_MS);
|
||||
});
|
||||
const stopDirectionalPad = event => {
|
||||
if (event.pointerId === state.dpad.pointerId) resetDirectionalPad();
|
||||
};
|
||||
button.addEventListener("pointerup", stopDirectionalPad);
|
||||
button.addEventListener("pointercancel", stopDirectionalPad);
|
||||
button.addEventListener("lostpointercapture", stopDirectionalPad);
|
||||
button.addEventListener("contextmenu", event => event.preventDefault());
|
||||
button.addEventListener("click", event => {
|
||||
if (event.detail === 0 && !button.disabled) 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));
|
||||
@@ -814,7 +866,7 @@
|
||||
return {state, handleMessage, move, resetAvatarControl, latencySamples: () => state.latency.snapshot(), pointerFeedbackSamples: () => state.latency.pointerSnapshot()};
|
||||
}
|
||||
|
||||
const api = Object.freeze({TOKEN_KEY, MAX_VIEW_CHUNKS, NAME_COMBINATION_COUNT, LOGIN_HEADLINES, ONBOARDING_STEPS, LATENCY_SAMPLE_LIMIT, AVATAR_TOUCH_TARGET_SIZE, AVATAR_MAX_DEFLECTION, AVATAR_DEAD_ZONE, AVATAR_DIRECTION_HYSTERESIS, AVATAR_SLOW_REPEAT_MS, AVATAR_FAST_REPEAT_MS, LatestIntentFlow, LatencyTracker, directionFromKey, directionFromSwipe, avatarDirection, avatarRepeatMs, avatarVector, playerCellSize, playerMapOffset, nextOnboardingStep, 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, LATENCY_SAMPLE_LIMIT, AVATAR_TOUCH_TARGET_SIZE, AVATAR_MAX_DEFLECTION, AVATAR_DEAD_ZONE, AVATAR_DIRECTION_HYSTERESIS, AVATAR_SLOW_REPEAT_MS, AVATAR_FAST_REPEAT_MS, DIRECTIONAL_PAD_REPEAT_MS, LatestIntentFlow, LatencyTracker, directionFromKey, directionFromSwipe, avatarDirection, avatarRepeatMs, avatarVector, playerCellSize, playerMapOffset, 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); });
|
||||
|
||||
Reference in New Issue
Block a user