gitflarePublicPartly agent-ready40
orbit-duel
Real-time two-player orbital combat game on Cloudflare Workers and Durable Objects.
- LicenseApache-2.0
- LanguageJavaScript
- Last landed
0413e56Oct 23, 2026
Add the Apache-2.0 licence
0413e56import { DurableObject } from 'cloudflare:workers';import { createState, addPlayer, removePlayer, step, sanitizeInput, snapshotOf, TICK_HZ, MAX_PLAYERS } from '../public/shared/sim.js';import * as sim from '../public/shared/sim.js';import { encodeSnapshot, encodeSnapshotMsg, encodeWelcome, encodePong, encodeEvents, encodeUps, parseMessage, FULL_EVERY, RING } from '../public/shared/protocol.js';import { sanitizeName, newBucket, checkBucket, planTick, newRoster, join, planJoin, disconnect, expire, connectedCount, isValidCode } from './room-logic.ts';import type { Bucket } from './room-logic.ts';import { writeScores } from './leaderboard.ts'; const TICK_MS = 1000 / TICK_HZ;const extrasOf = (st: any): any => ((sim as any).extrasOf ? (sim as any).extrasOf(st) : { ups: {}, names: {} });const bulletRecs = (st: any): any[] => st.bullets.map((b: any) => [b.id, b.owner, b.spawn, b.x, b.y, b.vx, b.vy]);const EMPTY_MS = 60000; interface Att { id: number; role: 'player' | 'spectator'; name: string; token: string; ack: number; seq: number; rate: Bucket; joined: boolean;} export class Room extends DurableObject<any> { state = createState((Math.random() * 2 ** 32) >>> 0); roster = newRoster(MAX_PLAYERS); code = ''; nextTickAt = 0; ticking = false; emptySince = 0; ring = new Map<number, any>(); pending = new Map<number, any[]>(); lastInput = new Map<number, any>(); lastSeq = new Map<number, number>(); lastPhase = ''; exRing = new Map<number, any>(); async fetch(request: Request): Promise<Response> { const m = new URL(request.url).pathname.match(/^\/ws\/([A-Z0-9]{6})$/); if (!m || !isValidCode(m[1])) return new Response('bad code', { status: 400 }); this.code = m[1]; const pair = new WebSocketPair(); const server = pair[1]; this.ctx.acceptWebSocket(server); const att: Att = { id: 0, role: 'spectator', name: '', token: '', ack: -1, seq: 0, rate: newBucket(Date.now()), joined: false }; server.serializeAttachment(att); return new Response(null, { status: 101, webSocket: pair[0] }); } async webSocketMessage(ws: WebSocket, data: string | ArrayBuffer) { const att = ws.deserializeAttachment() as Att; const size = typeof data === 'string' ? data.length : data.byteLength; const c = checkBucket(att.rate, Date.now(), size); ws.serializeAttachment(att); if (c.close) { ws.close(1008, 'rate limit'); return; } if (!c.ok || typeof data !== 'string') return; const msg = parseMessage(data); if (!msg) return; if (msg[0] === 'j') { this.onJoin(ws, att, msg); return; } if (!att.joined) return; if (msg[0] === 'p') { ws.send(JSON.stringify(encodePong(msg[1], this.state.tick))); return; } if (msg[0] === 'a') { if (Number.isInteger(msg[1])) { att.ack = msg[1]; ws.serializeAttachment(att); } return; } if (msg[0] === 'i' && att.role === 'player') { const inp = sanitizeInput(msg); if (!inp) return; let q = this.pending.get(att.id); if (!q) this.pending.set(att.id, (q = [])); q.push(inp); if (q.length > 8) q.splice(0, q.length - 8); if (inp.tick !== null && inp.tick > att.ack) { att.ack = inp.tick; ws.serializeAttachment(att); } } } onJoin(ws: WebSocket, att: Att, msg: any[]) { const watch = msg[4] === 1; const plan = planJoin(att, watch); if (plan === 'upgrade') this.upgrade(ws, att, msg); if (plan === 'upgrade' || plan === 'ignore') return; this.restore(); const token = typeof msg[2] === 'string' ? msg[2] : null; const bytes = crypto.getRandomValues(new Uint8Array(16)); const newToken = () => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); const res: any = watch ? { role: 'spectator' } : join(this.roster, token, newToken, Date.now(), this.state.phase === 'results'); att.name = sanitizeName(msg[1]); att.joined = true; att.ack = -1; if (res.role === 'player') { att.role = 'player'; att.id = res.slot.id; att.token = res.slot.token; if (!this.state.ships.has(att.id)) addPlayer(this.state, att.id, att.name); this.lastInput.delete(att.id); } else { att.role = 'spectator'; att.id = 0; att.token = ''; } ws.serializeAttachment(att); this.emptySince = 0; const snap = snapshotOf(this.state); ws.send(JSON.stringify(encodeWelcome(att.id, att.token, this.code, att.role, this.state.tick, encodeSnapshot(null, snap), extrasOf(this.state), bulletRecs(this.state)))); this.report(); void this.startTicking(); } upgrade(ws: WebSocket, att: Att, msg: any[]) { const token = typeof msg[2] === 'string' ? msg[2] : null; const bytes = crypto.getRandomValues(new Uint8Array(16)); const res: any = join(this.roster, token, () => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''), Date.now(), this.state.phase === 'results'); if (res.role !== 'player') return; att.name = sanitizeName(msg[1]); att.role = 'player'; att.id = res.slot.id; att.token = res.slot.token; att.ack = -1; if (!this.state.ships.has(att.id)) addPlayer(this.state, att.id, att.name); this.lastInput.delete(att.id); ws.serializeAttachment(att); ws.send(JSON.stringify(encodeWelcome(att.id, att.token, this.code, att.role, this.state.tick, encodeSnapshot(null, snapshotOf(this.state)), extrasOf(this.state), bulletRecs(this.state)))); this.report(); } restore() { if (this.state.ships.size === 0 && this.roster.slots.length === 0) { for (const ws of this.ctx.getWebSockets()) { const a = ws.deserializeAttachment() as Att | null; if (a && a.joined && a.role === 'player') { this.roster.slots.push({ id: a.id, token: a.token, connected: true, disconnectedAt: 0 }); this.roster.nextId = Math.max(this.roster.nextId, a.id + 1); addPlayer(this.state, a.id, a.name); } } } } async startTicking() { if (this.ticking) return; this.ticking = true; const now = Date.now(); this.nextTickAt = now + TICK_MS; await this.ctx.storage.setAlarm(Math.max(Math.ceil(this.nextTickAt), now + 1)); } async alarm() { const now = Date.now(); this.restore(); const live = this.ctx.getWebSockets(); if (connectedCount(this.roster) === 0 && live.length === 0) { this.ticking = false; if (!this.emptySince) this.emptySince = now; if (now - this.emptySince >= EMPTY_MS) { await this.closeRoom(); return; } await this.ctx.storage.setAlarm(now + EMPTY_MS); return; } this.ticking = true; this.emptySince = 0; const plan = planTick(now, this.nextTickAt); for (let i = 0; i < plan.steps; i++) this.tickOnce(live); this.nextTickAt = plan.nextTickAt; await this.ctx.storage.setAlarm(plan.alarmAt); } tickOnce(live: WebSocket[]) { const gone = expire(this.roster, Date.now()); for (const id of gone) { removePlayer(this.state, id); this.pending.delete(id); this.lastInput.delete(id); this.lastSeq.delete(id); } if (gone.length) this.report(); const inputs: Record<number, any> = {}; for (const slot of this.roster.slots) { if (!slot.connected) continue; const q = this.pending.get(slot.id); if (q && q.length) { const last = q[q.length - 1]; this.lastInput.set(slot.id, last); this.lastSeq.set(slot.id, last.seq); q.length = 0; } const li = this.lastInput.get(slot.id); if (li) inputs[slot.id] = li; } const events = step(this.state, inputs); const snap = snapshotOf(this.state); this.ring.set(this.state.tick, snap); this.ring.delete(this.state.tick - RING); const ex = extrasOf(this.state); this.exRing.set(this.state.tick, ex); this.exRing.delete(this.state.tick - RING); const full = this.state.tick % FULL_EVERY === 0; const evMsg = events.length ? JSON.stringify(encodeEvents(this.state.tick, events)) : ''; for (const ws of live) { const att = ws.deserializeAttachment() as Att | null; if (!att || !att.joined) continue; const base = full ? undefined : this.ring.get(att.ack); const delta = encodeSnapshot(base ?? null, snap); const exBase = base ? this.exRing.get(att.ack) : undefined; const names = !exBase || JSON.stringify(exBase.names) !== JSON.stringify(ex.names) ? ex.names : null; const ups = encodeUps(exBase ? exBase.ups : null, ex.ups); const seq = this.lastSeq.get(att.id) ?? 0; try { ws.send(JSON.stringify(encodeSnapshotMsg(this.state.tick, base ? att.ack : -1, seq, delta, ups, names, full ? bulletRecs(this.state) : null))); if (evMsg) ws.send(evMsg); } catch {} } if (this.state.phase !== this.lastPhase) { const was = this.lastPhase; this.lastPhase = this.state.phase; this.report(); if (this.state.phase === 'results' && was === 'playing') { const rows = (this.state.results ?? []).map((r: any) => ({ name: r.name, score: r.kills })); this.ctx.waitUntil(writeScores(this.env.DB, 'duel', rows)); } } } async webSocketClose(ws: WebSocket, code: number) { this.onGone(ws); try { ws.close(code === 1005 ? 1000 : code, 'bye'); } catch {} } async webSocketError(ws: WebSocket) { this.onGone(ws); } onGone(ws: WebSocket) { const att = ws.deserializeAttachment() as Att | null; if (att && att.joined && att.role === 'player') disconnect(this.roster, att.id, Date.now()); this.report(); } report() { const players = connectedCount(this.roster); const info = { code: this.code, players, maxPlayers: MAX_PLAYERS, open: players > 0 && this.state.phase !== 'results' && players < MAX_PLAYERS, closed: false }; try { const lobby = this.env.LOBBY.get(this.env.LOBBY.idFromName('global')); this.ctx.waitUntil(lobby.report(info)); } catch {} } async closeRoom() { try { const lobby = this.env.LOBBY.get(this.env.LOBBY.idFromName('global')); await lobby.report({ code: this.code, players: 0, maxPlayers: MAX_PLAYERS, open: false, closed: true }); } catch {} this.state = createState((Math.random() * 2 ** 32) >>> 0); this.roster = newRoster(MAX_PLAYERS); this.ring.clear(); this.pending.clear(); this.lastInput.clear(); this.lastSeq.clear(); await this.ctx.storage.deleteAll(); }}