game Of Life

This commit is contained in:
JurajKubrican
2025-03-04 16:31:19 +01:00
parent 7ed413648c
commit 00c209032f
16 changed files with 540 additions and 346 deletions

View File

@@ -4,33 +4,20 @@
if (!drawElement) {
throw new Error("canvas not found");
}
const drawEmitter = mitt();
const emitter = mitt();
let drawing = false;
const socketUrl = "/draw/ws";
let socket = new WebSocket(socketUrl);
socket.onerror = console.error;
socket.onclose = console.warn;
let previous = null;
const socket = getSocket("/draw/ws");
const serializeDraw = ({ from, to }) => `${from.x},${from.y},${to.x},${to.y}`;
const deserializeDraw = (message) => {
const parts = message.split(",");
return {
from: {
x: Number(parts[0]),
y: Number(parts[1]),
},
to: {
x: Number(parts[2]),
y: Number(parts[3]),
},
from: { x: Number(parts[0]), y: Number(parts[1]) },
to: { x: Number(parts[2]), y: Number(parts[3]) },
};
};
drawEmitter.on("draw", (e) => sendMessage(e));
const sendMessage = (e) => {
if (socket.readyState !== socket.OPEN) {
socket = new WebSocket(socketUrl);
}
socket.send(serializeDraw(e));
};
emitter.on("mouseDraw", (e) => sendMessage(e));
const sendMessage = (e) => socket.send(serializeDraw(e));
const mouseDown = () => {
drawing = true;
previous = null;
@@ -38,12 +25,11 @@
const mouseUp = () => {
drawing = false;
};
let previous = null;
const mouseMove = (e) => {
if (!drawing)
return;
if (previous) {
drawEmitter.emit("draw", {
emitter.emit("mouseDraw", {
from: previous,
to: { x: e.offsetX, y: e.offsetY },
});
@@ -68,30 +54,26 @@
if (!recCtx || !receiveCanvas) {
throw new Error("canvas not found");
}
//@ts-expect-error
window.ctx = recCtx;
setTimeout(() => {
recCtx.lineWidth = 2;
recCtx.lineCap = "round";
recCtx.strokeStyle = "white";
}, 10);
socket.addEventListener("message", (event) => {
if (event.data === "ping" || event.data.startsWith('pong'))
return;
const { from, to } = deserializeDraw(event.data);
const render = (data) => {
const { from, to } = data;
if (recCtx.strokeStyle != "white") {
recCtx.lineWidth = 2;
recCtx.lineCap = "round";
recCtx.strokeStyle = "white";
}
recCtx.beginPath();
recCtx.moveTo(from.x, from.y);
recCtx.lineTo(to.x, to.y);
recCtx.closePath();
recCtx.stroke();
console.log(from, to);
};
emitter.on("mouseDraw", render);
emitter.on("netDraw", render);
socket.addEventListener("message", (event) => {
if (event.data === "ping" || event.data.startsWith("pong"))
return;
emitter.emit("netDraw", deserializeDraw(event.data));
});
setInterval(() => {
if (socket.readyState !== socket.OPEN) {
socket = new WebSocket(socketUrl);
}
socket.send("ping");
}, 10000);
const resizeObserver = new ResizeObserver((entries) => {
const entry = entries.at(0);
receiveCanvas.height = entry?.contentRect.height ?? 500;