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

@@ -15,58 +15,44 @@
to: DrawPoint;
};
type Events = {
draw: DrawEvent;
mouseDraw: DrawEvent;
netDraw: DrawEvent;
};
const drawEmitter = mitt<Events>();
const emitter = mitt<Events>();
let drawing = false;
const socketUrl = "/draw/ws";
let previous: DrawPoint | null = null;
let socket = new WebSocket(socketUrl);
const socket = getSocket("/draw/ws");
socket.onerror = console.error;
socket.onclose = console.warn;
const serializeDraw = ({from, to }: DrawEvent) =>
const serializeDraw = ({ from, to }: DrawEvent) =>
`${from.x},${from.y},${to.x},${to.y}`;
const deserializeDraw = (message: string): DrawEvent => {
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: DrawEvent) => {
if (socket.readyState !== socket.OPEN) {
socket = new WebSocket(socketUrl);
}
socket.send(serializeDraw(e));
};
emitter.on("mouseDraw", (e) => sendMessage(e));
const sendMessage = (e: DrawEvent) => socket.send(serializeDraw(e));
const mouseDown = () => {
drawing = true;
previous=null
previous = null;
};
const mouseUp = () => {
drawing = false;
};
let previous: DrawPoint | null = null;
const mouseMove = (e: Pick<MouseEvent, "offsetX" | "offsetY">) => {
if (!drawing) return;
if (previous) {
drawEmitter.emit("draw", {
emitter.emit("mouseDraw", {
from: previous,
to: { x: e.offsetX, y: e.offsetY },
});
@@ -98,36 +84,30 @@
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)
const render = (data: DrawEvent) => {
const { from, to } = data;
socket.addEventListener("message", (event) => {
if(event.data==="ping" || event.data.startsWith('pong')) return
const { from, to } = deserializeDraw(event.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);
});
};
setInterval(() => {
if (socket.readyState !== socket.OPEN) {
socket = new WebSocket(socketUrl);
}
socket.send("ping");
}, 10000);
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));
});
const resizeObserver = new ResizeObserver((entries) => {
const entry = entries.at(0);