62 lines
2.0 KiB
TypeScript
62 lines
2.0 KiB
TypeScript
// file: Web/game-snake-poc/frontend/ts/input.ts
|
|
// version: 2
|
|
|
|
import type { SnakeDirection, SnakeWebSession } from "./game";
|
|
import { webDebug } from "./logging";
|
|
|
|
const KEY_DIRECTIONS: Readonly<Record<string, SnakeDirection>> = {
|
|
arrowleft: "left",
|
|
a: "left",
|
|
q: "left",
|
|
arrowright: "right",
|
|
d: "right",
|
|
arrowup: "up",
|
|
w: "up",
|
|
z: "up",
|
|
arrowdown: "down",
|
|
s: "down",
|
|
};
|
|
|
|
function buttonDirection(button: HTMLButtonElement): SnakeDirection | null {
|
|
const direction = button.dataset.direction;
|
|
if (direction === "left" || direction === "right" || direction === "up" || direction === "down") {
|
|
return direction;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function bindInputs(session: SnakeWebSession, buttons: readonly HTMLButtonElement[]): void {
|
|
window.addEventListener("keydown", event => {
|
|
if (event.repeat) {
|
|
return;
|
|
}
|
|
const direction = KEY_DIRECTIONS[event.key.toLowerCase()];
|
|
if (direction === undefined) {
|
|
return;
|
|
}
|
|
event.preventDefault();
|
|
session.queueDirection(direction, "keyboard-mouse");
|
|
webDebug("snake-web-input", "direction", { direction, source: "keyboard-mouse" });
|
|
});
|
|
|
|
for (const button of buttons) {
|
|
const direction = buttonDirection(button);
|
|
if (direction === null) {
|
|
continue;
|
|
}
|
|
button.addEventListener("pointerdown", event => {
|
|
event.preventDefault();
|
|
const source = event.pointerType === "touch" ? "touch" : "keyboard-mouse";
|
|
session.queueDirection(direction, source);
|
|
webDebug("snake-web-input", "direction", { direction, source });
|
|
});
|
|
button.addEventListener("click", event => {
|
|
if (event.detail !== 0) {
|
|
return;
|
|
}
|
|
session.queueDirection(direction, "keyboard-mouse");
|
|
webDebug("snake-web-input", "direction", { direction, source: "keyboard-mouse" });
|
|
});
|
|
}
|
|
}
|