Files

70 lines
2.8 KiB
TypeScript

// file: crates/apps/game-reflex-poc-tauri/frontend/ts/game.ts
// version: 2
import init, { ReflexWasmGame } from "../wasm/game_reflex_poc_wasm.js";
import { tracingDebug, tracingTrace } from "./logging";
const FRAME_MS = 16;
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: ReflexWasmGame, canvas: HTMLCanvasElement, context: CanvasRenderingContext2D, score: 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()}`;
}
export async function startGame(canvas: HTMLCanvasElement, score: HTMLOutputElement): Promise<ReflexWasmGame> {
await init();
await tracingDebug("Reflex WASM module initialized");
const context = canvas.getContext("2d");
if (context === null) {
throw new Error("2D canvas context is unavailable");
}
const drawingContext: CanvasRenderingContext2D = context;
const game = new ReflexWasmGame();
canvas.addEventListener("pointerdown", event => {
const bounds = canvas.getBoundingClientRect();
const x = (event.clientX - bounds.left) / bounds.width;
const y = (event.clientY - bounds.top) / bounds.height;
game.pointer_down(x, y);
render(game, canvas, drawingContext, score);
void tracingTrace(`pointerdown x=${x.toFixed(4)} y=${y.toFixed(4)} score=${game.score()}`);
});
let previous = performance.now();
function frame(now: number): void {
while (now - previous >= FRAME_MS) {
game.tick();
previous += FRAME_MS;
}
render(game, canvas, drawingContext, score);
window.requestAnimationFrame(frame);
}
render(game, canvas, drawingContext, score);
window.requestAnimationFrame(frame);
return game;
}