Skip to content

gitflarePublicPartly agent-ready40

neon-drift

Real-time multiplayer arcade racer on Cloudflare Workers and Durable Objects.

Add the Apache-2.0 licence3efe3da
JavaScript291 lines11.0 KB
import { createRng } from './rng.js'; export const TICK_HZ = 30;export const DT = 1 / 30;export const MAX_PLAYERS = 16;export const BASE_SPEED = 160;export const TURN_RATE = 3.2;export const BOOST_MULT = 1.7;export const CYCLE_R = 6;export const START_RADIUS = 1000;export const MIN_RADIUS = 250;export const TRAIL_CAP = 600;const CELL = 100; export function sanitizeInput(raw) {  if (!Array.isArray(raw) || raw.length < 3) return null;  const [seq, turn, boost] = raw;  if (!Number.isInteger(seq) || seq < 0 || seq > 2147483647) return null;  if (turn !== -1 && turn !== 0 && turn !== 1) return null;  if (boost !== 0 && boost !== 1) return null;  return { seq, turn, boost };} export function createState(seed, config = {}) {  return {    tick: 0, seed, rng: createRng(seed), phase: 'waiting', phaseTicks: 0, phaseTick: 0,    radius: START_RADIUS, targetRadius: START_RADIUS, shrinkTick: 0,    nextRadius: START_RADIUS, warnUntilTick: -1, matchEndTick: 0, nextShrinkTick: 0,    minRadius: config.minRadius ?? MIN_RADIUS,    players: new Map(), orbs: [], nextOrbId: 1, matchTicks: 0, scoreTick: 0,  };} export function addPlayer(state, id, name) {  const p = {    id, name, x: 0, y: 0, heading: 0, speed: BASE_SPEED, boost: 0, meter: 100,    alive: true, score: 0, trail: [], trailStart: 0, lastHeading: 0, sinceAppend: 0,    fadeTicks: -1, killer: null, trailBase: 0, deadTick: -1, kills: 0,    hue: hueFor(state, id), spawnProt: 0,  };  placePlayer(state, p, state.players.size);  state.players.set(id, p);  return p;} function hueFor(state, id) {  const used = new Set();  for (const q of state.players.values()) used.add(q.hue);  let h = (state.players.size * 137) % 360;  for (let k = 0; k < 360 && used.has(h); k++) h = (h + 23) % 360;  return h;} function placePlayer(state, p, i, n) {  n = n || state.players.size || 1;  const a = (i / Math.max(n, 1)) * Math.PI * 2 + 0.3;  const r = state.radius * 0.6;  p.x = Math.cos(a) * r; p.y = Math.sin(a) * r;  p.heading = a + Math.PI; p.lastHeading = p.heading;  p.trail = [p.x, p.y]; p.trailStart = 0; p.trailBase = 0; p.sinceAppend = 0;  p.deadTick = -1; p.kills = 0; p.spawnProt = 0;  p.alive = true; p.fadeTicks = -1; p.meter = 100; p.boost = 0; p.speed = BASE_SPEED;} export function stepCycle(p, input, dt) {  const turn = input ? input.turn : 0;  const wantBoost = input && input.boost === 1 && p.meter > 0;  p.heading += turn * TURN_RATE * dt;  p.boost = wantBoost ? 1 : 0;  p.meter = wantBoost ? Math.max(0, p.meter - 40 * dt) : Math.min(100, p.meter + 15 * dt);  p.speed = BASE_SPEED * (p.boost ? BOOST_MULT : 1);  p.x += Math.cos(p.heading) * p.speed * dt;  p.y += Math.sin(p.heading) * p.speed * dt;} export function appendTrail(p) {  p.sinceAppend++;  if (Math.abs(p.heading - p.lastHeading) > 0.05 || p.sinceAppend >= 6) {    p.trail.push(p.x, p.y);    p.lastHeading = p.heading; p.sinceAppend = 0;    if (p.trail.length > TRAIL_CAP * 2) { p.trail.splice(0, 2); p.trailStart++; p.trailBase++; }  } else if (p.trail.length >= 2) {    // head point follows the cycle between appends is NOT done: collision uses real points  }} export function removePlayer(state, id) { state.players.delete(id); } function currentRadius(state) {  const into = state.tick - state.shrinkTick;  if (state.radius > state.targetRadius && into >= 0) {    const f = Math.min(1, into / (2 * TICK_HZ));    return state.radius + (state.targetRadius - state.radius) * f;  }  return state.radius;} export function startMatch(state) {  state.phase = 'countdown'; state.phaseTicks = 3 * TICK_HZ; state.phaseTick = state.tick;  state.radius = START_RADIUS; state.targetRadius = START_RADIUS; state.nextRadius = START_RADIUS;  state.warnUntilTick = -1; state.matchEndTick = 0; state.scoreTick = 0;  state.matchTicks = 0; state.orbs.length = 0;  let i = 0; const n = state.players.size;  for (const p of state.players.values()) placePlayer(state, p, i++, n);} function pointSegDist2(px, py, ax, ay, bx, by) {  const dx = bx - ax, dy = by - ay;  const l2 = dx * dx + dy * dy;  let t = l2 > 0 ? ((px - ax) * dx + (py - ay) * dy) / l2 : 0;  t = t < 0 ? 0 : t > 1 ? 1 : t;  const cx = ax + t * dx - px, cy = ay + t * dy - py;  return cx * cx + cy * cy;} export function hitTrail(state, p) {  const r2 = CYCLE_R * CYCLE_R;  for (const o of state.players.values()) {    const t = o.trail;    const n = t.length / 2;    let last = n - 1;    if (o === p) last = n - 1 - 3;    for (let i = 0; i < last; i++) {      const j = i * 2;      if (pointSegDist2(p.x, p.y, t[j], t[j + 1], t[j + 2], t[j + 3]) <= r2) return o;    }  }  return null;} function spawnOrbs(state) {  let alive = 0;  for (const p of state.players.values()) if (p.alive) alive++;  const want = 6 + 2 * Math.max(alive, 1);  for (let k = 0; k < 64 && state.orbs.length < want; k++) {    const a = state.rng.next() * Math.PI * 2;    const r = Math.sqrt(state.rng.next()) * Math.max(0, (Number.isFinite(state.radius) ? state.radius : 0) - 30);    state.orbs.push([state.nextOrbId++, Math.round(Math.cos(a) * r), Math.round(Math.sin(a) * r)]);  }} function eliminate(state, p, by, events) {  p.alive = false; p.fadeTicks = TICK_HZ; p.boost = 0; p.deadTick = state.tick;  if (by && by !== p) { by.score += 50; by.kills++; }  events.push(['crash', p.id, by && by !== p ? by.id : -1, p.x, p.y]);} // Cheap uniform spatial hash over all trail segments, rebuilt each tick.let grid = new Map();function cellKey(cx, cy) { return (cx + 512) * 1024 + (cy + 512); }function buildGrid(state) {  grid = new Map();  for (const o of state.players.values()) {    const t = o.trail, n = t.length / 2 - 1;    for (let i = 0; i < n; i++) {      const j = i * 2;      const x0 = Math.floor((Math.min(t[j], t[j + 2]) - CYCLE_R) / CELL), x1 = Math.floor((Math.max(t[j], t[j + 2]) + CYCLE_R) / CELL);      const y0 = Math.floor((Math.min(t[j + 1], t[j + 3]) - CYCLE_R) / CELL), y1 = Math.floor((Math.max(t[j + 1], t[j + 3]) + CYCLE_R) / CELL);      for (let cx = x0; cx <= x1; cx++) for (let cy = y0; cy <= y1; cy++) {        const k = cellKey(cx, cy);        let l = grid.get(k);        if (!l) { l = []; grid.set(k, l); }        l.push(o, i);      }    }  }}function gridHit(p) {  const l = grid.get(cellKey(Math.floor(p.x / CELL), Math.floor(p.y / CELL)));  if (!l) return null;  const r2 = CYCLE_R * CYCLE_R;  for (let k = 0; k < l.length; k += 2) {    const o = l[k], i = l[k + 1], t = o.trail, j = i * 2;    if (o === p && i >= t.length / 2 - 1 - 3) continue;    if (pointSegDist2(p.x, p.y, t[j], t[j + 1], t[j + 2], t[j + 3]) <= r2) return o;  }  return null;} function endMatch(state, events) {  const list = [...state.players.values()];  list.sort((a, b) => (b.alive - a.alive) || (b.deadTick - a.deadTick) || (b.score - a.score));  const res = list.map((p, i) => [p.id, p.name, p.score, p.kills, i + 1]);  state.phase = 'results'; state.phaseTicks = 10 * TICK_HZ; state.phaseTick = state.tick;  state.warnUntilTick = -1;  events.push(['phase', 'results']);  events.push(['results', res]);} export function step(state, inputs, dt = DT) {  const events = [];  state.tick++;  const players = state.players;  const connected = players.size;   if (state.phase === 'waiting') {    if (connected >= 2) { startMatch(state); events.push(['phase', 'countdown']); }  } else if (state.phase === 'countdown') {    if (--state.phaseTicks <= 0) {      state.phase = 'playing'; state.phaseTick = state.tick;      state.matchEndTick = state.tick + 180 * TICK_HZ;      state.nextShrinkTick = state.tick + 20 * TICK_HZ;      for (const p of players.values()) p.spawnProt = 45;      events.push(['phase', 'playing']);    }  } else if (state.phase === 'results') {    if (--state.phaseTicks <= 0) {      for (const p of players.values()) p.score = 0;      if (connected >= 2) { startMatch(state); events.push(['phase', 'countdown']); }      else { state.phase = 'waiting'; state.phaseTick = state.tick; events.push(['phase', 'waiting']); }    }  }   const playing = state.phase === 'playing';  if (playing) {    state.matchTicks++;    if (!state.matchEndTick) state.matchEndTick = state.tick + 180 * TICK_HZ;    if (!state.nextShrinkTick) state.nextShrinkTick = state.tick + 20 * TICK_HZ;    const warnAt = state.nextShrinkTick - 3 * TICK_HZ;    if (state.warnUntilTick < 0 && state.tick >= warnAt && state.radius > state.minRadius + 1 && state.tick < state.nextShrinkTick) {      state.nextRadius = Math.max(state.minRadius, state.radius * 0.88);      state.warnUntilTick = state.nextShrinkTick;      events.push(['warn', state.nextRadius]);    }    if (state.warnUntilTick >= 0 && state.tick >= state.warnUntilTick) {      state.targetRadius = state.nextRadius; state.shrinkTick = state.tick;      state.warnUntilTick = -1;      events.push(['shrink', state.radius, state.targetRadius]);      state.nextShrinkTick = state.tick + 20 * TICK_HZ;    }  }  if (state.phase === 'playing' || state.phase === 'waiting') {    const radius = currentRadius(state);    // settle radius once the shrink animation has finished    if (state.radius > state.targetRadius && state.tick - state.shrinkTick >= 2 * TICK_HZ) state.radius = state.targetRadius;    for (const p of players.values()) {      if (!p.alive) continue;      const inp = inputs && inputs.get ? inputs.get(p.id) : inputs && inputs[p.id];      stepCycle(p, inp, dt);      appendTrail(p);      if (p.spawnProt > 0) p.spawnProt--;    }    if (playing) {      spawnOrbs(state);      buildGrid(state);      for (const p of players.values()) {        if (!p.alive) continue;        if (Math.hypot(p.x, p.y) > radius) { eliminate(state, p, null, events); continue; }        if (p.spawnProt <= 0) {          const owner = gridHit(p);          if (owner) { eliminate(state, p, owner, events); continue; }        }        for (let i = state.orbs.length - 1; i >= 0; i--) {          const o = state.orbs[i];          const dx = o[1] - p.x, dy = o[2] - p.y;          if (dx * dx + dy * dy <= (CYCLE_R + 10) ** 2) {            state.orbs.splice(i, 1);            p.score += 10; p.meter = Math.min(100, p.meter + 35);            events.push(['orb', p.id, o[0], o[1], o[2]]);          }        }      }      if (++state.scoreTick >= TICK_HZ) {        state.scoreTick = 0;        for (const p of players.values()) if (p.alive) p.score += 1;      }      let alive = 0;      for (const p of players.values()) if (p.alive) alive++;      if ((alive <= 1 && connected >= 2) || state.tick >= state.matchEndTick) endMatch(state, events);    }  }  for (const p of players.values()) {    if (p.fadeTicks > 0 && --p.fadeTicks === 0) { p.trail = []; p.trailStart = 0; p.trailBase = 0; }  }  return events;} export function hashState(state) {  let h = 2166136261;  const mix = (v) => {    const s = String(Math.round(v * 1000));    for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0;  };  mix(state.tick); mix(state.radius);  for (const p of state.players.values()) {    mix(p.x); mix(p.y); mix(p.heading); mix(p.score); mix(p.alive ? 1 : 0); mix(p.trail.length);  }  for (const o of state.orbs) { mix(o[1]); mix(o[2]); }  return h;}