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
TypeScript43 lines1.8 KB
import { Room } from './room.ts';import { Lobby } from './lobby.ts';import { isValidCode, randomCode } from './room-logic.ts';import { topScores } from './leaderboard.ts'; export { Room, Lobby }; interface Env { ROOM: any; LOBBY: any; DB?: any; ASSETS: { fetch(r: Request): Promise<Response> } } const json = (body: unknown, status = 200) =>  new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' } }); export default {  async fetch(request: Request, env: Env): Promise<Response> {    const url = new URL(request.url);    const lobby = () => env.LOBBY.get(env.LOBBY.idFromName('global'));    const p = url.pathname;    if (p === '/health') {      try {        const s = await lobby().stats();        return json({ ok: true, rooms: s.rooms, players: s.players });      } catch {        return json({ ok: true, rooms: 0, players: 0 });      }    }    if (p === '/api/rooms' && request.method === 'POST') {      const bytes = crypto.getRandomValues(new Uint8Array(6));      let i = 0;      return json({ code: randomCode((n) => bytes[i++ % 6] % n) });    }    if (p === '/api/quickplay') return json({ code: await lobby().quickplay() });    if (p === '/api/leaderboard') return json(await topScores(env.DB, url.searchParams.get('mode') || 'duel'));    if (p.startsWith('/ws/')) {      const code = p.slice(4).toUpperCase();      if (!isValidCode(code)) return new Response('bad code', { status: 400 });      if (request.headers.get('Upgrade') !== 'websocket') return new Response('upgrade required', { status: 426 });      return env.ROOM.get(env.ROOM.idFromName(code)).fetch(request);    }    if (p.startsWith('/api/')) return json({ error: 'not found' }, 404);    return env.ASSETS.fetch(request);  },};