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
JavaScript238 lines11.6 KB
import { WORLD, CX, CY, PLANET_R, SHIP_R, FLAG_DEAD, FLAG_INVULN, FLAG_SHIELD } from './shared/sim.js';import { createFx } from './fx.js';import { createAudio } from './audio.js';import { input } from './input.js'; const TWO_PI = Math.PI * 2;const COLORS = [180, 320, 120, 45, 270, 20, 210, 0].map((h) => 'hsl(' + h + ',100%,65%)');const COLOR_HUE = [180, 320, 120, 45, 270, 20, 210, 0];const KIND_COLOR = ['#fff', '#4af', '#fa4', '#f4a']; export function createRenderer(canvas, net, onFrame) {  const ctx = canvas.getContext('2d');  const fx = createFx();  const audio = createAudio();  let coarse = false, dpr = 1, w = 1, h = 1, scale = 1;  let frames = 0, fpsAt = 0, last = 0, camX = CX, camY = CY, camInit = false;  const stat = { fps: 0 };  const scratch = { x: 0, y: 0, vx: 0, vy: 0, angle: 0, hp: 0, flags: 0, kills: 0 };  const flash = new Map();  const widths = new Map();  const warpAt = new Float64Array(8), bT = 6;  let exhaustAt = 0, hitStopLeft = 0;  const wp = { x: 0, y: 0 };  function distScale(x, y) {    const m = net.me; if (!m) return 0.5;    const dx = wrap(x, m.x) - m.x, dy = wrap(y, m.y) - m.y;    return Math.max(0.15, 1 - Math.sqrt(dx * dx + dy * dy) / 1200);  }  let bg = null;   function makeStars() {    const mk = (n, size, alpha) => {      const c = document.createElement('canvas'); c.width = c.height = 1024;      const g = c.getContext('2d');      for (let i = 0; i < n; i++) {        g.globalAlpha = alpha * (0.4 + Math.random() * 0.6);        g.fillStyle = Math.random() < 0.2 ? '#9cf' : '#fff';        g.fillRect(Math.random() * 1024, Math.random() * 1024, size, size);      }      return c;    };    bg = [mk(90, 1.5, 0.5), mk(50, 2.2, 0.8)];  }  function resize() {    dpr = Math.min(devicePixelRatio || 1, 2);    w = canvas.clientWidth || 1; h = canvas.clientHeight || 1;    const vh = (window.visualViewport ? window.visualViewport.height : innerHeight) || 0;    if (h < vh * 0.9 && canvas.getBoundingClientRect().top < 4) { canvas.style.height = vh + 'px'; h = vh; }    coarse = !!(window.matchMedia && matchMedia('(pointer: coarse)').matches);    canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);    scale = Math.max(w, h) / 900;  }  makeStars();  new ResizeObserver(resize).observe(canvas);  resize();  const haloGrad = ctx.createRadialGradient(0, 0, PLANET_R * 0.9, 0, 0, PLANET_R * 2.2);  haloGrad.addColorStop(0, 'rgba(80,170,255,0.55)'); haloGrad.addColorStop(1, 'rgba(80,170,255,0)');  const planetGrad = ctx.createRadialGradient(-PLANET_R * 0.35, -PLANET_R * 0.35, 5, 0, 0, PLANET_R);  planetGrad.addColorStop(0, '#8cf'); planetGrad.addColorStop(0.6, '#26a'); planetGrad.addColorStop(1, '#0a1240');   const wrap = (v, c) => v - Math.round((v - c) / WORLD) * WORLD;  const color = (id) => COLORS[(id | 0) & 7];  function nameWidth(name) {    let v = widths.get(name);    if (v === undefined) { ctx.font = '12px sans-serif'; v = ctx.measureText(name).width; widths.set(name, v); }    return v;  }  function shipPos(id) {    if (id === net.id && net.me) return net.me;    return net.sampleShip(id, last - 100, scratch) ? scratch : null;  }   function fxEvent(ev) {    const t = ev[0];    if (t === 'fire') { if (ev[2] === net.id) audio.play('fire'); }    else if (t === 'hit') {      const s = shipPos(ev[2]);      if (s) { fx.sparks(s.x, s.y, !!((s.flags | 0) & FLAG_SHIELD)); flash.set(ev[2], 0.15); }      if (ev[2] === net.id) fx.addShake(8);      audio.play('hit');    } else if (t === 'kill' || t === 'crash') {      const s = shipPos(t === 'kill' ? ev[2] : ev[1]);      const vid = t === 'kill' ? ev[2] : ev[1];      if (s) { fx.explode(s.x, s.y, COLOR_HUE[vid & 7], vid === net.id || ev[1] === net.id, distScale(s.x, s.y)); if (fx.hitStop) hitStopLeft = fx.hitStop; }      audio.play('explode');    } else if (t === 'pickup') {      const s = shipPos(ev[1]);      if (s) fx.pickup(s.x, s.y);      if (ev[1] !== net.id && s) fx.ring(s.x, s.y, 40, 150, 0.3);      audio.play('pickup');    } else if (t === 'power') audio.play('power');    else if (t === 'respawn') { audio.play('respawn'); const s = shipPos(ev[1]); warpAt[ev[1] & 7] = last; if (s) { fx.emit(s.x, s.y, 20, 120, 180, 0.6); fx.ring(s.x, s.y, 60, COLOR_HUE[ev[1] & 7], 0.3); } }    else if (t === 'phase') { if (ev[1] === 'countdown') audio.play('countdown'); }    else if (t === 'results') audio.play('win');  }   function drawShip(s, id, tNow) {    const f = s.flags | 0;    if (f & FLAG_DEAD) return;    if ((f & FLAG_INVULN) && (((tNow / 100) | 0) & 1)) return;    const col = color(id), fl = flash.get(id) || 0;    ctx.save();    ctx.translate(wrap(s.x, camX), wrap(s.y, camY));    if (id !== net.id) {      const nm = net.names[id] || '';      ctx.fillStyle = col; ctx.globalAlpha = 0.8; ctx.font = '12px sans-serif';      ctx.fillText(nm, -nameWidth(nm) / 2, -SHIP_R - 20);      ctx.globalAlpha = 1;    }    for (let i = 0; i < 3; i++) {      ctx.fillStyle = i < s.hp ? col : 'rgba(255,255,255,0.15)';      ctx.fillRect(-12 + i * 9, -SHIP_R - 14, 7, 3);    }    const wt = (tNow - warpAt[id & 7]) / 300;    if (wt >= 0 && wt < 1) { ctx.scale(wt, wt); ctx.strokeStyle = col; ctx.globalAlpha = 1 - wt; ctx.beginPath(); ctx.arc(0, 0, SHIP_R * (2.5 - 1.5 * wt), 0, TWO_PI); ctx.stroke(); ctx.globalAlpha = 1; }    if ((f & (FLAG_SHIELD)) || s.power) { ctx.globalAlpha = 0.25 + 0.15 * Math.sin(tNow / 120); ctx.strokeStyle = '#fd6'; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(0, 0, SHIP_R + 12, 0, TWO_PI); ctx.stroke(); ctx.lineWidth = 2.2; ctx.globalAlpha = 1; }    ctx.rotate(s.angle);    // thruster: accelerating along heading shows as speed; use flag-free heuristic    if (id === net.id ? input.thrusting : (s.vx * Math.cos(s.angle) + s.vy * Math.sin(s.angle)) > 60) {      const len = SHIP_R * (0.8 + 0.8 * (0.5 + 0.5 * Math.sin(tNow * 0.05 + id)));      if (tNow - exhaustAt > 16 && id === net.id) { exhaustAt = tNow; fx.trail(s.x - Math.cos(s.angle) * SHIP_R, s.y - Math.sin(s.angle) * SHIP_R); }      else if (id !== net.id && tNow - exhaustAt > 16) fx.trail(s.x - Math.cos(s.angle) * SHIP_R, s.y - Math.sin(s.angle) * SHIP_R);      ctx.fillStyle = '#fb4'; ctx.beginPath();      ctx.moveTo(-SHIP_R * 0.5, 5); ctx.lineTo(-SHIP_R * 0.5 - len, 0); ctx.lineTo(-SHIP_R * 0.5, -5); ctx.fill();    }    ctx.strokeStyle = fl > 0 ? '#fff' : col; ctx.lineWidth = 2.2;    ctx.shadowColor = col; ctx.shadowBlur = 10;    ctx.beginPath();    ctx.moveTo(SHIP_R, 0); ctx.lineTo(-SHIP_R * 0.8, SHIP_R * 0.7); ctx.lineTo(-SHIP_R * 0.4, 0); ctx.lineTo(-SHIP_R * 0.8, -SHIP_R * 0.7);    ctx.closePath(); ctx.stroke();    ctx.shadowBlur = 0;    if (f & FLAG_SHIELD) {      ctx.strokeStyle = 'rgba(100,200,255,0.8)'; ctx.fillStyle = 'rgba(100,200,255,0.12)';      ctx.beginPath(); ctx.arc(0, 0, SHIP_R + 7, 0, TWO_PI); ctx.fill(); ctx.stroke();    }    ctx.restore();  }   function frame(now) {    requestAnimationFrame(frame);    frames++;    if (now - fpsAt >= 1000) { stat.fps = frames; frames = 0; fpsAt = now; }    const dt = Math.min(0.05, last ? (now - last) / 1000 : 0.016);    last = now;    onFrame(now);    net.update(now);    if (hitStopLeft > 0) { hitStopLeft--; fx.hitStop = hitStopLeft; } else fx.update(dt);    for (const [k, v] of flash) if (v > 0) flash.set(k, v - dt);     const me = net.me;    if (me) {      if (!camInit) { camX = me.x; camY = me.y; camInit = true; }      else {        const k = 1 - Math.exp(-12 * dt);        camX += (wrap(me.x, camX) - camX) * k; camY += (wrap(me.y, camY) - camY) * k;      }    }    audio.thrust(!!(me && input.thrusting && !((me.flags | 0) & FLAG_DEAD)));     ctx.setTransform(dpr, 0, 0, dpr, 0, 0);    ctx.fillStyle = '#05060f'; ctx.fillRect(0, 0, w, h);    for (let l = 0; l < 2; l++) {      const par = 0.15 + l * 0.25, tile = 1024;      const ox = -(((camX * par) % tile) + tile) % tile, oy = -(((camY * par) % tile) + tile) % tile;      for (let x = ox - tile; x < w; x += tile) for (let y = oy - tile; y < h; y += tile) ctx.drawImage(bg[l], x, y);    }    const sh = fx.shake;    const sx = sh ? (Math.random() - 0.5) * sh : 0, sy = sh ? (Math.random() - 0.5) * sh : 0;    ctx.save();    ctx.translate(w / 2 + sx, h / 2 + sy); ctx.scale(scale, scale); ctx.translate(-camX, -camY);     ctx.save(); ctx.translate(wrap(CX, camX), wrap(CY, camY));    ctx.fillStyle = haloGrad; ctx.beginPath(); ctx.arc(0, 0, PLANET_R * 2.2, 0, TWO_PI); ctx.fill();    ctx.strokeStyle = 'rgba(120,200,255,0.12)'; ctx.lineWidth = 1;    for (let i = 1; i <= 3; i++) { ctx.beginPath(); ctx.arc(0, 0, PLANET_R + i * 70, 0, TWO_PI); ctx.stroke(); }    ctx.fillStyle = planetGrad; ctx.beginPath(); ctx.arc(0, 0, PLANET_R, 0, TWO_PI); ctx.fill();    ctx.restore();     const ups = net.ups;    for (const id in ups) {      const u = ups[id], x = wrap(u[1], camX), y = wrap(u[2], camY), pulse = 1 + 0.2 * Math.sin(now / 150);      ctx.strokeStyle = ctx.fillStyle = KIND_COLOR[u[3]] || '#fff'; ctx.lineWidth = 2;      ctx.beginPath(); ctx.arc(x, y, 12 * pulse, 0, TWO_PI); ctx.stroke();      ctx.globalAlpha = 0.5; ctx.beginPath(); ctx.arc(x, y, 5, 0, TWO_PI); ctx.fill(); ctx.globalAlpha = 1;    }    const bl = net.bullets;    ctx.globalCompositeOperation = 'lighter'; ctx.lineWidth = 3; ctx.lineCap = 'round';    for (let i = 0; i < bl.length; i++) {      const b = bl[i], x = wrap(b.x, camX), y = wrap(b.y, camY);      ctx.strokeStyle = color(b.owner); ctx.globalAlpha = 0.5;      ctx.beginPath(); ctx.moveTo(x, y);      for (let k = 1; k <= bT; k++) ctx.lineTo(x - b.vx * 0.012 * k, y - b.vy * 0.012 * k);      ctx.stroke(); ctx.globalAlpha = 1;      ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(x, y, 3, 0, TWO_PI); ctx.fill();    }    ctx.globalCompositeOperation = 'source-over';    const ids = net.shipIds;    for (let i = 0; i < ids.length; i++) {      if (ids[i] !== net.id && net.sampleShip(ids[i], now - 100, scratch)) drawShip(scratch, ids[i], now);    }    if (me) drawShip(me, net.id, now);    fx.draw(ctx, camX, camY, WORLD);    ctx.restore();     // off-screen enemy arrows    const hw = w / 2 / scale, hh = h / 2 / scale;    for (let i = 0; i < ids.length; i++) {      const id = ids[i];      if (id === net.id || !net.sampleShip(id, now - 100, scratch) || ((scratch.flags | 0) & FLAG_DEAD)) continue;      const dx = wrap(scratch.x, camX) - camX, dy = wrap(scratch.y, camY) - camY;      if (Math.abs(dx) < hw - 20 && Math.abs(dy) < hh - 20) continue;      const k = Math.min((hw - 30) / (Math.abs(dx) || 1e-6), (hh - 30) / (Math.abs(dy) || 1e-6));      const ax = w / 2 + dx * k * scale, ay = h / 2 + dy * k * scale;      ctx.save(); ctx.translate(ax, ay); ctx.rotate(Math.atan2(dy, dx));      ctx.fillStyle = color(id); ctx.globalAlpha = 0.85;      ctx.beginPath(); ctx.moveTo(12, 0); ctx.lineTo(-8, 8); ctx.lineTo(-8, -8); ctx.closePath(); ctx.fill();      ctx.restore();    }    ctx.globalAlpha = 1;    if (fx.flash > 0) { ctx.fillStyle = 'rgba(255,255,255,' + (fx.flash * 0.5) + ')'; ctx.fillRect(0, 0, w, h); }    const T = input.touch;    if (coarse || T.seen || T.active || T.fire) {      T.seen = true;      const bx = T.active ? T.baseX : 100, by = T.active ? T.baseY : h - 100;      ctx.strokeStyle = 'rgba(255,255,255,0.3)'; ctx.lineWidth = 2;      ctx.beginPath(); ctx.arc(bx, by, 48, 0, TWO_PI); ctx.stroke();      ctx.fillStyle = 'rgba(255,255,255,0.3)';      ctx.beginPath(); ctx.arc(T.active ? T.x : bx, T.active ? T.y : by, 22, 0, TWO_PI); ctx.fill();      ctx.fillStyle = T.fire ? 'rgba(255,80,120,0.55)' : 'rgba(255,80,120,0.25)';      ctx.beginPath(); ctx.arc(w - 90, h - 90, 40, 0, TWO_PI); ctx.fill();    }  }  requestAnimationFrame(frame);  stat.fx = fxEvent;  stat.resize = resize;  return stat;}