0.3.0-0-pre.4
This commit is contained in:
103
Web/game-snake-poc/frontend/ts/game.ts
Normal file
103
Web/game-snake-poc/frontend/ts/game.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
// file: Web/game-snake-poc/frontend/ts/game.ts
|
||||
// version: 1
|
||||
|
||||
import init, { SnakeWasmGame } from "@snake-wasm";
|
||||
|
||||
const FRAME_MILLIS = 16;
|
||||
const MAX_FRAME_ELAPSED_MILLIS = 250;
|
||||
|
||||
export type SnakeDirection = "left" | "right" | "up" | "down";
|
||||
|
||||
export interface SnakeWebSession {
|
||||
queueDirection(direction: SnakeDirection): void;
|
||||
}
|
||||
|
||||
function color(red: number, green: number, blue: number): string {
|
||||
return `rgb(${red} ${green} ${blue})`;
|
||||
}
|
||||
|
||||
function resizeCanvas(canvas: HTMLCanvasElement): void {
|
||||
const ratio = window.devicePixelRatio || 1;
|
||||
const width = Math.max(1, Math.floor(canvas.clientWidth * ratio));
|
||||
const height = Math.max(1, Math.floor(canvas.clientHeight * ratio));
|
||||
if (canvas.width !== width || canvas.height !== height) {
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
}
|
||||
}
|
||||
|
||||
function render(
|
||||
game: SnakeWasmGame,
|
||||
canvas: HTMLCanvasElement,
|
||||
context: CanvasRenderingContext2D,
|
||||
score: HTMLOutputElement,
|
||||
length: HTMLOutputElement,
|
||||
): void {
|
||||
resizeCanvas(canvas);
|
||||
context.fillStyle = color(game.background_red(), game.background_green(), game.background_blue());
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
const count = game.rectangle_count();
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
context.fillStyle = color(game.rectangle_red(index), game.rectangle_green(index), game.rectangle_blue(index));
|
||||
context.fillRect(
|
||||
game.rectangle_x(index) * canvas.width,
|
||||
game.rectangle_y(index) * canvas.height,
|
||||
game.rectangle_width(index) * canvas.width,
|
||||
game.rectangle_height(index) * canvas.height,
|
||||
);
|
||||
}
|
||||
score.value = `Score : ${game.score()}`;
|
||||
length.value = `Longueur : ${game.length()}`;
|
||||
}
|
||||
|
||||
function queueDirection(game: SnakeWasmGame, direction: SnakeDirection): void {
|
||||
switch (direction) {
|
||||
case "left":
|
||||
game.left();
|
||||
return;
|
||||
case "right":
|
||||
game.right();
|
||||
return;
|
||||
case "up":
|
||||
game.up();
|
||||
return;
|
||||
case "down":
|
||||
game.down();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export async function startGame(
|
||||
canvas: HTMLCanvasElement,
|
||||
score: HTMLOutputElement,
|
||||
length: HTMLOutputElement,
|
||||
): Promise<SnakeWebSession> {
|
||||
await init();
|
||||
const context = canvas.getContext("2d");
|
||||
if (context === null) {
|
||||
throw new Error("Le contexte Canvas 2D est indisponible.");
|
||||
}
|
||||
const game = new SnakeWasmGame();
|
||||
let previous = performance.now();
|
||||
let accumulator = 0;
|
||||
|
||||
function frame(now: number): void {
|
||||
const elapsed = Math.min(Math.max(0, now - previous), MAX_FRAME_ELAPSED_MILLIS);
|
||||
previous = now;
|
||||
accumulator += elapsed;
|
||||
while (accumulator >= FRAME_MILLIS) {
|
||||
game.tick();
|
||||
accumulator -= FRAME_MILLIS;
|
||||
}
|
||||
render(game, canvas, context, score, length);
|
||||
window.requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
render(game, canvas, context, score, length);
|
||||
window.requestAnimationFrame(frame);
|
||||
return {
|
||||
queueDirection(direction: SnakeDirection): void {
|
||||
queueDirection(game, direction);
|
||||
},
|
||||
};
|
||||
}
|
||||
56
Web/game-snake-poc/frontend/ts/input.ts
Normal file
56
Web/game-snake-poc/frontend/ts/input.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
// file: Web/game-snake-poc/frontend/ts/input.ts
|
||||
// version: 1
|
||||
|
||||
import type { SnakeDirection, SnakeWebSession } from "./game";
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
for (const button of buttons) {
|
||||
const direction = buttonDirection(button);
|
||||
if (direction === null) {
|
||||
continue;
|
||||
}
|
||||
button.addEventListener("pointerdown", event => {
|
||||
event.preventDefault();
|
||||
session.queueDirection(direction);
|
||||
});
|
||||
button.addEventListener("click", event => {
|
||||
if (event.detail !== 0) {
|
||||
return;
|
||||
}
|
||||
session.queueDirection(direction);
|
||||
});
|
||||
}
|
||||
}
|
||||
44
Web/game-snake-poc/frontend/ts/main.ts
Normal file
44
Web/game-snake-poc/frontend/ts/main.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
// file: Web/game-snake-poc/frontend/ts/main.ts
|
||||
// version: 1
|
||||
|
||||
import { startGame } from "./game";
|
||||
import { bindInputs } from "./input";
|
||||
|
||||
function requireElement<T extends Element>(selector: string): T {
|
||||
const element = document.querySelector<T>(selector);
|
||||
if (element === null) {
|
||||
throw new Error(`Élément frontend requis absent : ${selector}`);
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const canvas = requireElement<HTMLCanvasElement>("#game");
|
||||
const score = requireElement<HTMLOutputElement>("#score");
|
||||
const length = requireElement<HTMLOutputElement>("#length");
|
||||
const status = requireElement<HTMLSpanElement>("#runtime-status");
|
||||
const error = requireElement<HTMLParagraphElement>("#startup-error");
|
||||
const buttons = Array.from(document.querySelectorAll<HTMLButtonElement>("[data-direction]"));
|
||||
|
||||
status.textContent = "Chargement WASM…";
|
||||
const session = await startGame(canvas, score, length);
|
||||
bindInputs(session, buttons);
|
||||
status.className = "badge text-bg-success";
|
||||
status.textContent = "Prêt";
|
||||
error.hidden = true;
|
||||
canvas.focus();
|
||||
}
|
||||
|
||||
void main().catch(caughtError => {
|
||||
const status = document.querySelector<HTMLSpanElement>("#runtime-status");
|
||||
const error = document.querySelector<HTMLParagraphElement>("#startup-error");
|
||||
const message = caughtError instanceof Error ? caughtError.message : String(caughtError);
|
||||
if (status !== null) {
|
||||
status.className = "badge text-bg-danger";
|
||||
status.textContent = "Erreur";
|
||||
}
|
||||
if (error !== null) {
|
||||
error.textContent = `Impossible de démarrer Snake : ${message}`;
|
||||
error.hidden = false;
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user