Server authority

This commit is contained in:
2026-09-24 19:34:07 -03:00
parent 1bef94ce0c
commit 79faa556de
75 changed files with 2247 additions and 1632 deletions
+57
View File
@@ -0,0 +1,57 @@
/// <reference lib="deno.worker" />
// runs the game in a worker without any permissions, the host does files and networking
import { GameServer, TICK_MS } from "./game_server.ts";
import { GameToHost, HostToGame } from "./host_protocol.ts";
const SAVE_INTERVAL_MS = 30_000;
let game: GameServer | undefined;
function post(message: GameToHost) {
self.postMessage(message);
}
self.onmessage = (event: MessageEvent<HostToGame>) => {
const message = event.data;
if (message.type === "init") {
game = new GameServer(
{
send: (conn, data) => post({ type: "send", conn, data }),
close: (conn) => post({ type: "close", conn }),
},
message.save,
message.default_seed,
);
setInterval(() => game!.tick(), TICK_MS);
setInterval(() => {
if (game!.world.dirty) {
post({ type: "save", data: game!.save(), final: false });
}
}, SAVE_INTERVAL_MS);
post({ type: "ready", seed: game.world.seed });
return;
}
if (!game) {
return;
}
switch (message.type) {
case "connect":
game.on_connect(message.conn);
break;
case "message":
game.on_message(message.conn, message.data);
break;
case "disconnect":
game.on_disconnect(message.conn);
break;
case "shutdown":
post({ type: "save", data: game.save(), final: true });
break;
}
};