Skip to content
Make the player visible with a procedural 3D humanoid132be7c
JavaScript57 lines2.4 KB
import { DurableObject } from "cloudflare:workers";import { decode, encode } from "./protocol.mjs"; export class FightRoom extends DurableObject {  constructor(ctx, env) {    super(ctx, env);    ctx.storage.sql.exec("CREATE TABLE IF NOT EXISTS score (slot INTEGER PRIMARY KEY, wins INTEGER NOT NULL DEFAULT 0)");  }   scores() {    const s = [0, 0];    for (const r of this.ctx.storage.sql.exec("SELECT slot, wins FROM score")) s[r.slot] = r.wins;    return s;  }   async fetch(request) {    if (request.headers.get("Upgrade") !== "websocket") return new Response("Expected websocket", { status: 426 });    const taken = new Set(this.ctx.getWebSockets().map((w) => w.deserializeAttachment()?.slot));    const slot = [0, 1].find((s) => !taken.has(s));    if (slot === undefined) return new Response("Room full", { status: 409 });    const pair = new WebSocketPair();    const [client, server] = Object.values(pair);    this.ctx.acceptWebSocket(server);    server.serializeAttachment({ slot });    server.send(encode({ type: "welcome", slot, scores: this.scores(), players: this.ctx.getWebSockets().length }));    this.broadcast({ type: "presence", players: this.ctx.getWebSockets().length }, server);    return new Response(null, { status: 101, webSocket: client });  }   broadcast(msg, except) {    const data = encode(msg);    for (const w of this.ctx.getWebSockets()) if (w !== except) { try { w.send(data); } catch {} }  }   async webSocketMessage(ws, raw) {    const m = decode(raw);    const att = ws.deserializeAttachment();    if (!m || !att) return;    const slot = att.slot;    if (m.type === "input") this.broadcast({ type: "input", slot, seq: m.seq, input: m.input }, ws);    else if (m.type === "join") this.broadcast({ type: "join", slot, name: m.name, level: m.level }, ws);    else if (m.type === "state" && slot === 0) this.broadcast({ type: "state", state: m.state }, ws);    else if (m.type === "gameover") {      this.ctx.storage.sql.exec(        "INSERT INTO score (slot, wins) VALUES (?, 1) ON CONFLICT(slot) DO UPDATE SET wins = wins + 1", m.winner);      this.broadcast({ type: "gameover", winner: m.winner, scores: this.scores() });    }  }   async webSocketClose(ws, code) {    try { ws.close(code); } catch {}    this.broadcast({ type: "presence", players: this.ctx.getWebSockets().length - 1 }, ws);  }   async webSocketError(ws) { try { ws.close(1011); } catch {} }}