Skip to content

gitflarePublicPartly agent-ready40

sketch-rush

Multiplayer draw-and-guess game on Cloudflare Workers, Durable Objects and D1.

Add the Apache-2.0 licencedbe1e99
TypeScript53 lines1.7 KB
import { DurableObject } from "cloudflare:workers";import { randomCode } from "./room-logic.ts"; export interface RoomInfo { code: string; players: number; maxPlayers: number; open: boolean }const STALE_MS = 120000; export class Lobby extends DurableObject {  rooms = new Map<string, RoomInfo & { at: number }>();  loaded = false;   async load() {    if (this.loaded) return;    this.loaded = true;    const stored = await this.ctx.storage.get<Record<string, RoomInfo & { at: number }>>("rooms");    if (stored) for (const k in stored) this.rooms.set(k, stored[k]);  }   prune() {    const now = Date.now();    for (const [k, r] of this.rooms) if (now - r.at > STALE_MS) this.rooms.delete(k);  }   async save() {    await this.ctx.storage.put("rooms", Object.fromEntries(this.rooms));  }   async report(info: RoomInfo & { closed?: boolean }) {    await this.load();    if (info.closed || info.players <= 0) this.rooms.delete(info.code);    else this.rooms.set(info.code, { code: info.code, players: info.players, maxPlayers: info.maxPlayers, open: info.open, at: Date.now() });    this.prune();    await this.save();  }   async quickplay(): Promise<string> {    await this.load();    this.prune();    let best: RoomInfo | null = null;    for (const r of this.rooms.values()) {      if (r.open && r.players < r.maxPlayers && (!best || r.players > best.players)) best = r;    }    return best ? best.code : randomCode(Math.random);  }   async stats(): Promise<{ rooms: number; players: number }> {    await this.load();    this.prune();    let players = 0;    for (const r of this.rooms.values()) players += r.players;    return { rooms: this.rooms.size, players };  }}