gitflarePublicPartly agent-ready40
sketch-rush
Multiplayer draw-and-guess game on Cloudflare Workers, Durable Objects and D1.
- LicenseApache-2.0
- LanguageJavaScript
- Last landed
dbe1e99Oct 23, 2026
Add the Apache-2.0 licence
dbe1e99import { DurableObject } from "cloudflare:workers";import type { Env } from "./leaderboard.ts";import { saveScores } from "./leaderboard.ts";import type { Bucket, Slot } from "./room-logic.ts";import { takeToken, newBucket, decideJoin, expiredSlots, randomHex, sanitizeName, EMPTY_CLEAR_MS } from "./room-logic.ts";import { DT, MAX_PLAYERS, TICK_HZ, addPlayer, createState, removePlayer, sanitizeInput, snapshot, step } from "../public/shared/sim.js";import { FULL_EVERY, RING, encodePong, encodeSnapshotMsg, encodeSnapshot, encodeWelcome, encodeOps, encodeStrokeMsg, encodeReplay } from "../public/shared/protocol.js"; interface Attachment { id: string; name: string; token: string; role: "player" | "spectator" | "pending"; lastAckTick: number; lastInputSeq: number; rate: Bucket;} interface Client { baseTick: number; lastFull: number; epoch: number;} const TICK_MS = 1000 / TICK_HZ;const MAX_CATCHUP = 3;const MAX_QUEUE = 8; export class Room extends DurableObject<Env> { code = ""; sim = createState((Math.random() * 4294967296) >>> 0, { maxPlayers: MAX_PLAYERS }); slots = new Map<string, Slot>(); names = new Map<string, string>(); queues = new Map<string, any[]>(); ring = new Map<number, Map<string, any>>(); clients = new Map<WebSocket, Client>(); nextTickAt = 0; ticking = false; emptySince = 0; lastPhase = "waiting"; lastReport = ""; nextId = 1; sentOps = 0; sentEpoch = 0; constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); for (const ws of ctx.getWebSockets()) { const a = ws.deserializeAttachment() as Attachment | null; if (!a) continue; this.clients.set(ws, { baseTick: -1, lastFull: -1, epoch: -1 }); if (a.role === "player") { this.slots.set(a.id, { id: a.id, token: a.token, connected: true, disconnectedAt: 0 }); this.names.set(a.id, a.name); addPlayer(this.sim, a.id, a.name); this.nextId = Math.max(this.nextId, parseInt(a.id.slice(1), 10) + 1 || 1); } } if (this.clients.size) this.startTicking(); } async fetch(request: Request): Promise<Response> { this.code = request.headers.get("x-room-code") || this.code; if (request.headers.get("Upgrade") !== "websocket") return new Response("expected websocket", { status: 426 }); const pair = new WebSocketPair(); const server = pair[1]; this.ctx.acceptWebSocket(server); const att: Attachment = { id: "", name: "", token: "", role: "pending", lastAckTick: -1, lastInputSeq: 0, rate: newBucket(Date.now()) }; server.serializeAttachment(att); this.clients.set(server, { baseTick: -1, lastFull: -1, epoch: -1 }); return new Response(null, { status: 101, webSocket: pair[0] }); } send(ws: WebSocket, msg: unknown) { try { ws.send(JSON.stringify(msg)); } catch { /* socket gone */ } } connectedCount(): number { let n = 0; for (const ws of this.ctx.getWebSockets()) { const a = ws.deserializeAttachment() as Attachment | null; if (a && a.role !== "pending") n++; } return n; } async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) { const att = ws.deserializeAttachment() as Attachment; const size = typeof message === "string" ? message.length : message.byteLength; const verdict = takeToken(att.rate, Date.now(), size); ws.serializeAttachment(att); if (verdict.close) { ws.close(1008, "rate limit"); return; } if (!verdict.ok || typeof message !== "string") return; let msg: any; try { msg = JSON.parse(message); } catch { return; } if (!Array.isArray(msg)) return; switch (msg[0]) { case "j": this.onJoin(ws, att, msg); break; case "a": { const c = this.clients.get(ws); if (c && Number.isInteger(msg[1]) && this.ring.has(msg[1])) c.baseTick = msg[1]; break; } case "p": if (typeof msg[1] === "number") this.send(ws, encodePong(msg[1], this.sim.tick)); break; default: if (att.role === "player") { const input = sanitizeInput(msg); if (!input) break; let q = this.queues.get(att.id); if (!q) this.queues.set(att.id, (q = [])); q.push(input); if (q.length > MAX_QUEUE) q.splice(0, q.length - MAX_QUEUE); } } } onJoin(ws: WebSocket, att: Attachment, msg: any[]) { const watching = att.role === "spectator" && (att as any).watch === 1; if (att.role !== "pending" && !watching) return; if (watching) { att.role = "pending"; (att as any).watch = 0; } const now = Date.now(); this.dropExpired(now); const token = typeof msg[2] === "string" ? msg[2] : null; const decision = msg[4] === 1 ? { kind: "spectator" } as any : decideJoin(this.slots, token, now, this.sim.phase, MAX_PLAYERS); if (msg[4] === 1) (att as any).watch = 1; const c = this.clients.get(ws)!; c.baseTick = -1; c.lastFull = -1; if (decision.kind === "reconnect") { const slot = decision.slot; for (const other of this.ctx.getWebSockets()) { if (other === ws) continue; const o = other.deserializeAttachment() as Attachment | null; if (o && o.id === slot.id && o.role === "player") { o.role = "spectator"; other.serializeAttachment(o); try { other.close(1000, "replaced"); } catch { /* closed */ } } } slot.connected = true; const p = this.sim.players.get(slot.id); if (p) p.connected = true; att.id = slot.id; att.token = slot.token; att.role = "player"; att.name = this.names.get(slot.id) || "Player"; } else { att.name = sanitizeName(msg[1]); att.token = randomHex(16, (a) => crypto.getRandomValues(a)); if (decision.kind === "player") { att.id = "p" + this.nextId++; att.role = "player"; this.slots.set(att.id, { id: att.id, token: att.token, connected: true, disconnectedAt: 0 }); this.names.set(att.id, att.name); addPlayer(this.sim, att.id, att.name); } else { att.id = "s" + this.nextId++; att.role = "spectator"; } } ws.serializeAttachment(att); this.send(ws, encodeWelcome(att.id, att.token, this.code, att.role, this.sim.tick, snapshot(this.sim, att.role === "player" ? att.id : ""))); this.send(ws, encodeReplay(this.sim, this.sim.opCount ?? 0)); this.clients.get(ws)!.epoch = this.sim.boardEpoch ?? 0; this.emptySince = 0; this.report(); this.startTicking(); } dropExpired(now: number) { for (const id of expiredSlots(this.slots, now)) { this.slots.delete(id); this.names.delete(id); this.queues.delete(id); removePlayer(this.sim, id); } } startTicking() { if (this.ticking) return; this.ticking = true; this.nextTickAt = Date.now() + TICK_MS; void this.ctx.storage.setAlarm(this.nextTickAt); } async webSocketClose(ws: WebSocket) { this.onLeave(ws); } async webSocketError(ws: WebSocket) { this.onLeave(ws); } onLeave(ws: WebSocket) { const a = ws.deserializeAttachment() as Attachment | null; this.clients.delete(ws); if (a && a.role === "player") { let stillThere = false; for (const other of this.ctx.getWebSockets()) { if (other === ws) continue; const o = other.deserializeAttachment() as Attachment | null; if (o && o.id === a.id && o.role === "player") stillThere = true; } const slot = this.slots.get(a.id); if (slot && !stillThere) { slot.connected = false; slot.disconnectedAt = Date.now(); const p = this.sim.players.get(a.id); if (p) p.connected = false; } } this.report(); } report() { let players = 0; for (const s of this.slots.values()) if (s.connected) players++; const open = players < MAX_PLAYERS && this.sim.phase !== "results"; const key = `${players}|${open}`; if (key === this.lastReport) return; this.lastReport = key; const stub = this.env.LOBBY.get(this.env.LOBBY.idFromName("global")) as any; this.ctx.waitUntil(Promise.resolve(stub.report({ code: this.code, players, maxPlayers: MAX_PLAYERS, open })).catch(() => {})); } async alarm() { const now = Date.now(); if (this.connectedCount() === 0) { this.ticking = false; if (!this.emptySince) this.emptySince = now; this.dropExpired(now); this.report(); if (now - this.emptySince >= EMPTY_CLEAR_MS) await this.clear(); else await this.ctx.storage.setAlarm(now + 5000); return; } this.emptySince = 0; this.ticking = true; if (!this.nextTickAt || now - this.nextTickAt > TICK_MS * 10) this.nextTickAt = now; let steps = 0; while (this.nextTickAt <= now && steps < MAX_CATCHUP) { this.tick(); this.nextTickAt += TICK_MS; steps++; } if (this.nextTickAt <= now) this.nextTickAt = now + TICK_MS; await this.ctx.storage.setAlarm(Math.ceil(this.nextTickAt)); } tick() { const inputs = this.queues; this.queues = new Map(); const events = step(this.sim, inputs, DT); if (this.sim.tick % TICK_HZ === 0) this.dropExpired(Date.now()); this.broadcast(events); if (this.sim.phase !== this.lastPhase) this.onPhase(); } onPhase() { const prev = this.lastPhase; this.lastPhase = this.sim.phase; this.report(); void this.ctx.storage.put("match", { seed: this.sim.seed, phase: this.sim.phase, round: this.sim.round }); if (this.sim.phase === "results" && prev !== "results") { const rows = [...this.sim.players.values()].map((p) => ({ name: p.name, score: p.score })); this.ctx.waitUntil(saveScores(this.env, "classic", rows)); } } broadcast(events: any[][]) { const tick = this.sim.tick; const views = new Map<string, any>(); const total = this.sim.opCount ?? 0, ep = this.sim.boardEpoch ?? 0; let kmsg: string | null = null; if (total !== this.sentOps || ep !== this.sentEpoch) { const ops = ep === this.sentEpoch ? encodeOps(this.sim, this.sentOps, total) : null; const m = ops ? [...encodeStrokeMsg(ep, this.sentOps, ops), total] : encodeReplay(this.sim, total); kmsg = JSON.stringify(m); this.sentOps = total; this.sentEpoch = ep; } this.ring.set(tick, views); this.ring.delete(tick - RING); for (const ws of this.ctx.getWebSockets()) { const a = ws.deserializeAttachment() as Attachment | null; const c = this.clients.get(ws); if (!a || !c || a.role === "pending") continue; const viewer = a.role === "player" ? a.id : ""; if (kmsg) { try { ws.send(kmsg); } catch { /* gone */ } } let view = views.get(viewer); if (!view) views.set(viewer, (view = snapshot(this.sim, viewer))); const base = c.baseTick >= 0 ? this.ring.get(c.baseTick)?.get(viewer) : undefined; const full = !base || tick - c.lastFull >= FULL_EVERY; if (full) c.lastFull = tick; this.send(ws, encodeSnapshotMsg(tick, full ? -1 : c.baseTick, this.sim.seq.get(a.id) ?? 0, encodeSnapshot(full ? null : base, view))); const batch: any[] = ["v", tick]; for (const e of events) this.filterEvent(a, e, batch); if (batch.length > 2) this.send(ws, batch); } } filterEvent(a: Attachment, e: any[], out: any[]) { const kind = e[1]; if (kind === "chat") { const me = this.sim.players.get(a.id); if (e[4] === 1 && a.id !== this.sim.drawer && !me?.guessed) return; out.push(["v", "chat", this.names.get(e[2]) || "?", e[3], e[4]]); } else if (kind === "close") { if (e[2] === a.id) out.push(["v", "close"]); } else if (kind === "correct") { out.push(["v", "correct", this.names.get(e[2]) || "?", e[3]]); } else out.push(e); } async clear() { for (const ws of this.ctx.getWebSockets()) { try { ws.close(1001, "room closed"); } catch { /* closed */ } } this.slots.clear(); this.names.clear(); this.queues.clear(); this.ring.clear(); this.sim = createState((Math.random() * 4294967296) >>> 0, { maxPlayers: MAX_PLAYERS }); await this.ctx.storage.deleteAll(); const stub = this.env.LOBBY.get(this.env.LOBBY.idFromName("global")) as any; try { await stub.report({ code: this.code, players: 0, maxPlayers: MAX_PLAYERS, open: false, closed: true }); } catch { /* lobby offline */ } }}