2024-09-08 10:05:02 +00:00
|
|
|
import { Request, Response, Message, Hello } from "common.mjs";
|
2024-09-04 12:25:37 +00:00
|
|
|
|
2024-09-02 20:34:24 +00:00
|
|
|
const ws = new WebSocket("ws://localhost:1234");
|
2024-09-04 12:25:37 +00:00
|
|
|
const grid = [0, 0, 0, 0, 0, 0, 0, 0, 0]
|
|
|
|
const canvas = document.getElementById("game") as HTMLCanvasElement | null;
|
|
|
|
const ctx = canvas?.getContext("2d") as CanvasRenderingContext2D | null;
|
2024-09-02 20:34:24 +00:00
|
|
|
|
2024-09-08 10:58:00 +00:00
|
|
|
let myId: number | null = null;
|
|
|
|
|
2024-09-02 20:34:24 +00:00
|
|
|
ws.onopen = (e) => {
|
2024-09-04 12:25:37 +00:00
|
|
|
console.log("connected to server");
|
2024-09-08 10:05:02 +00:00
|
|
|
|
2024-09-04 12:25:37 +00:00
|
|
|
if (canvas) {
|
|
|
|
if (ctx) {
|
|
|
|
drawGrid(ctx, grid);
|
|
|
|
canvas.addEventListener("click", (evt: any) => {
|
|
|
|
const {clientX, clientY} = evt;
|
|
|
|
const x = Math.floor(clientX / 90);
|
|
|
|
const y = Math.floor(clientY / 90);
|
|
|
|
if (x < 3 && y < 3) {
|
|
|
|
const msg: Request = { x, y };
|
|
|
|
ws.send(JSON.stringify(msg));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2024-09-02 20:34:24 +00:00
|
|
|
};
|
|
|
|
|
2024-09-03 12:07:13 +00:00
|
|
|
ws.onmessage = (evt) => {
|
2024-09-04 12:25:37 +00:00
|
|
|
const msg: Message = JSON.parse(evt.data);
|
2024-09-08 10:58:00 +00:00
|
|
|
console.log(msg);
|
2024-09-08 10:05:02 +00:00
|
|
|
switch (msg.kind) {
|
|
|
|
case "hello": {
|
2024-09-08 10:58:00 +00:00
|
|
|
myId = (msg.data as Hello).id;
|
2024-09-08 10:05:02 +00:00
|
|
|
const h1 = document.getElementById("title") as HTMLHeadingElement | null;
|
|
|
|
if (h1) {
|
2024-09-08 10:58:00 +00:00
|
|
|
h1.innerText = `connected to server with id ${myId}`
|
2024-09-08 10:05:02 +00:00
|
|
|
}
|
2024-09-08 10:58:00 +00:00
|
|
|
break;
|
2024-09-08 10:05:02 +00:00
|
|
|
}
|
|
|
|
case "update": {
|
|
|
|
if (ctx) {
|
|
|
|
drawGrid(ctx, (msg.data as Response).grid);
|
|
|
|
}
|
2024-09-08 10:58:00 +00:00
|
|
|
break;
|
2024-09-08 10:05:02 +00:00
|
|
|
}
|
|
|
|
default: {
|
|
|
|
console.log(msg);
|
2024-09-08 10:58:00 +00:00
|
|
|
break;
|
2024-09-08 10:05:02 +00:00
|
|
|
}
|
2024-09-04 12:25:37 +00:00
|
|
|
}
|
2024-09-03 12:07:13 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
2024-09-04 12:25:37 +00:00
|
|
|
function drawGrid(ctx: CanvasRenderingContext2D, grid: number[]){
|
|
|
|
for (let y = 0; y < 3; ++y) {
|
|
|
|
for (let x = 0; x < 3; ++x) {
|
2024-09-08 10:58:00 +00:00
|
|
|
switch (grid[y*3+x]) {
|
|
|
|
case 0: ctx.fillStyle = "black"; break;
|
|
|
|
case myId: ctx.fillStyle = "green"; break;
|
|
|
|
default: ctx.fillStyle = "blue"; break;
|
2024-09-04 12:25:37 +00:00
|
|
|
}
|
2024-09-08 10:58:00 +00:00
|
|
|
|
|
|
|
const rx = x + x * 100;
|
|
|
|
const ry = y + y * 100;
|
|
|
|
ctx.fillRect(rx, ry, 90, 90);
|
2024-09-04 12:25:37 +00:00
|
|
|
}
|
|
|
|
}
|
2024-09-03 12:07:13 +00:00
|
|
|
}
|
|
|
|
|