Files
knet/js/boxes.js
JurajKubrican 00c209032f game Of Life
2025-03-04 16:31:19 +01:00

65 lines
2.0 KiB
JavaScript

"use strict";
(() => {
const socket = getSocket("/boxes/ws");
const deserializeBox = (msg) => {
msg = msg.replaceAll("b:", "");
const parts = msg.split(":");
return {
id: Number(parts[0]),
value: parts[1] === "+",
};
};
const handleInstruction = (instruction) => {
if (instruction.startsWith("b:")) {
const items = instruction.split(";");
items.forEach((i) => {
const box = deserializeBox(i);
const el = document.getElementById("box-" + box.id);
el.checked = box.value;
// console.log(i,box,el)
});
return;
}
};
socket.addEventListener("message", (event) => {
const instructions = event.data.split("\n");
instructions.forEach(handleInstruction);
});
document.querySelectorAll(".boxes input").forEach((input) => {
input.addEventListener("change", (event) => {
const target = event.target;
const id = target?.id.split("-")[1];
const value = target.checked ? "+" : "-";
socket.send("b:" + id + ":" + value);
});
});
var autoPlayTimer = undefined;
const handleAutoPlay = (el) => {
if (el.checked) {
autoPlayTimer = setInterval(() => {
socket.send("random");
}, 50);
}
else {
clearInterval(autoPlayTimer);
}
};
const autoPlayEl = document.querySelector("#auto-boxes");
handleAutoPlay(autoPlayEl);
autoPlayEl?.addEventListener("change", (e) => handleAutoPlay(e.target));
var golTimer = undefined;
const handleGol = (el) => {
if (el.checked) {
golTimer = setInterval(() => {
socket.send("gol");
}, 500);
}
else {
clearInterval(golTimer);
}
};
const golEl = document.querySelector("#game-of-life");
handleGol(golEl);
golEl.addEventListener("change", (e) => handleGol(e.target));
})();