Skip to content

gitflarePublicPartly agent-ready40

orbit-duel

Real-time two-player orbital combat game on Cloudflare Workers and Durable Objects.

Add the Apache-2.0 licence0413e56
TypeScript50 lines1.5 KB
import { DurableObject } from 'cloudflare:workers';import { randomCode } from './room-logic.ts'; export interface RoomInfo { code: string; players: number; maxPlayers: number; open: boolean; closed?: boolean }const TTL = 120000; export class Lobby extends DurableObject {  rooms = new Map<string, RoomInfo & { at: number }>();   async load() {    if (this.rooms.size) return;    const saved = await this.ctx.storage.get<[string, RoomInfo & { at: number }][]>('rooms');    if (saved) this.rooms = new Map(saved);  }   prune() {    const now = Date.now();    for (const [k, v] of this.rooms) if (now - v.at > TTL) this.rooms.delete(k);  }   async report(info: RoomInfo) {    await this.load();    if (info.closed) this.rooms.delete(info.code);    else this.rooms.set(info.code, { ...info, at: Date.now() });    this.prune();    await this.ctx.storage.put('rooms', [...this.rooms]);  }   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 > 0 && r.players < r.maxPlayers && (!best || r.players > best.players)) best = r;    }    return best ? best.code : randomCode((n) => Math.floor(Math.random() * n));  }   async stats() {    await this.load();    this.prune();    let players = 0;    let rooms = 0;    for (const r of this.rooms.values()) {      if (r.players > 0) { rooms++; players += r.players; }    }    return { rooms, players };  }}