Add before unload event to more consistently remove players who leave

This commit is contained in:
jude 2023-01-31 12:44:47 +00:00
parent bfb92e89b0
commit 0a1011f0e5

View File

@ -13,6 +13,16 @@ let game_state = WAITING;
let socket; let socket;
// Not totally reliable but better than nothing.
window.addEventListener("beforeunload", () => {
socket.emit("message", {
type: "DISCONNECT",
id: window.crypto.randomUUID(),
author: ID,
name: "",
});
});
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
socket = io(); socket = io();
@ -39,6 +49,10 @@ document.addEventListener("DOMContentLoaded", () => {
playerConnected(data); playerConnected(data);
break; break;
case "DISCONNECT":
playerDisconnected(data);
break;
case "KEEPALIVE": case "KEEPALIVE":
keepAlive(data); keepAlive(data);
break; break;
@ -90,6 +104,12 @@ function playerConnected(data) {
updatePlayerDom(); updatePlayerDom();
} }
function playerDisconnected(data) {
console.log("deleting player");
delete players[data.author];
updatePlayerDom();
}
/** /**
* Process keep-alive packets: these are packets that check players are still online. * Process keep-alive packets: these are packets that check players are still online.
* *