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
JavaScript49 lines2.2 KB
const args = process.argv.slice(2);const opt = (name, def) => { const i = args.indexOf('--' + name); return i >= 0 ? args[i + 1] : def; };const base = args[0] && !args[0].startsWith('--') ? args[0] : 'http://localhost:8787';const nBots = +opt('bots', 4);const seconds = +opt('seconds', 10);const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';const room = opt('room', null) || Array.from({ length: 6 }, () => alphabet[Math.floor(Math.random() * 32)]).join('');const wsBase = base.replace(/^http/, 'ws');const stats = { snaps: 0, bytes: [], rtt: [], disconnects: 0 }; const sorted = (a) => [...a].sort((x, y) => x - y);const pct = (a, p) => (a.length ? sorted(a)[Math.min(a.length - 1, Math.floor(a.length * p))] : 0);const mean = (a) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : 0); function bot(i) {  const ws = new WebSocket(wsBase + '/ws/' + room);  let tick = 0, seq = 0, r = 0, t = 1, f = 0;  const timers = [];  ws.onopen = () => {    ws.send(JSON.stringify(['j', 'bot' + i, null, null]));    timers.push(setInterval(() => {      if (Math.random() < 0.1) { r = Math.floor(Math.random() * 3) - 1; t = Math.random() < 0.7 ? 1 : 0; f = Math.random() < 0.3 ? 1 : 0; }      ws.send(JSON.stringify(['i', ++seq, r, t, f, tick]));    }, 1000 / 30));    timers.push(setInterval(() => ws.send(JSON.stringify(['p', Date.now()])), 1000));  };  ws.onmessage = (ev) => {    const m = JSON.parse(ev.data);    if (m[0] === 's') {      tick = m[1];      ws.send(JSON.stringify(['a', tick]));      if (i === 0) { stats.snaps++; stats.bytes.push(String(ev.data).length); }    } else if (m[0] === 'o' && i === 0) stats.rtt.push(Date.now() - m[1]);  };  ws.onclose = () => { stats.disconnects++; timers.forEach(clearInterval); };  return ws;} const socks = Array.from({ length: nBots }, (_, i) => bot(i));setTimeout(() => {  console.log(JSON.stringify({    room, bots: nBots, snapshotHz: +(stats.snaps / seconds).toFixed(1),    bytesMean: Math.round(mean(stats.bytes)), bytesP95: pct(stats.bytes, 0.95),    rttMean: +mean(stats.rtt).toFixed(1), rttP95: pct(stats.rtt, 0.95), disconnects: stats.disconnects,  }));  socks.forEach((s) => { s.onclose = null; s.close(); });  process.exit(0);}, seconds * 1000);