Source code

Glowline Arena

Exactly what your browser runs — written by Claude Opus 5.5. 2,676 lines across 5 files, plus the shared arcade kit (pause menu, audio, scores) every game loads.

Play it

games/play/glowline-arena.html · 1,212 lines

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<title>Glowline Arena — PromptArcade</title>
<style>
html,body{margin:0;height:100%;background:#04050c;color:#f4f1ff;overflow:hidden;font-family:Manrope,system-ui,sans-serif;touch-action:none;-webkit-user-select:none;user-select:none;cursor:crosshair}
canvas{display:block}
#c{position:fixed;inset:0}
.ga-panel{position:fixed;z-index:31;pointer-events:none;font:600 12px/1.35 Manrope,system-ui,sans-serif;color:#dfe6ff;background:rgba(6,9,22,.55);border:1px solid rgba(142,233,255,.16);border-radius:14px;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px)}
#ga-lb{top:58px;right:10px;width:196px;padding:.55rem .7rem .6rem}
#ga-lb h3{margin:0 0 .35rem;font:700 10px/1 'JetBrains Mono',monospace;letter-spacing:.18em;text-transform:uppercase;color:#8ee9ff;display:flex;justify-content:space-between}
#ga-lb ol{margin:0;padding:0;list-style:none;counter-reset:r}
#ga-lb li{display:flex;gap:.45rem;align-items:center;padding:1px 0;white-space:nowrap;overflow:hidden}
#ga-lb li i{font-style:normal;width:16px;color:#8b93b8;font:600 11px 'JetBrains Mono',monospace}
#ga-lb li span{flex:1;overflow:hidden;text-overflow:ellipsis}
#ga-lb li em{font-style:normal;font-size:11px;margin-right:2px}
#ga-lb li b{font:600 11px 'JetBrains Mono',monospace;color:#fff}
#ga-lb li.me{color:#ffe08a}#ga-lb li.me b{color:#ffe08a}
#ga-lb li u{width:8px;height:8px;border-radius:50%;flex:none;text-decoration:none}
#ga-mode{top:10px;left:10px;padding:.42rem .7rem;display:flex;align-items:center;gap:.5rem}
#ga-mode .dot{width:8px;height:8px;border-radius:50%;background:#ffb86b;box-shadow:0 0 10px #ffb86b}
#ga-mode.online .dot{background:#5dffb0;box-shadow:0 0 10px #5dffb0;animation:gap 1.6s infinite}
#ga-mode-mod{color:#ffe08a}
@keyframes gap{50%{opacity:.4}}
#ga-me{left:10px;bottom:12px;padding:.5rem .8rem;display:flex;gap:1rem;opacity:0;transition:opacity .4s}
#ga-me.on{opacity:1}
#ga-me div small{display:block;font:600 9px 'JetBrains Mono',monospace;letter-spacing:.16em;text-transform:uppercase;color:#8ee9ff}
#ga-me div b{font:700 17px 'JetBrains Mono',monospace;color:#fff}
#ga-pow{position:fixed;left:10px;bottom:72px;z-index:31;display:flex;gap:6px;pointer-events:none}
#ga-pow span{width:34px;height:34px;border-radius:50%;display:grid;place-items:center;font:800 15px Manrope,sans-serif;color:#fff;background:conic-gradient(var(--c) calc(var(--k)*1turn),rgba(255,255,255,.08) 0);position:relative}
#ga-pow span::before{content:"";position:absolute;inset:3px;border-radius:50%;background:#0a0e22}
#ga-pow span i{position:relative;font-style:normal;color:var(--c)}
#ga-ab{position:fixed;z-index:42;left:10px;bottom:112px;width:58px;height:58px;border-radius:50%;border:0;padding:0;background:none;display:none;touch-action:none;cursor:pointer}
#ga-ab.on{display:block}
#ga-ab canvas{width:58px;height:58px}
#ga-feed{position:fixed;left:50%;transform:translateX(-50%);top:10px;z-index:31;pointer-events:none;display:flex;flex-direction:column;align-items:center;gap:4px;max-width:min(60vw,520px)}
#ga-feed div{font:600 12px Manrope,sans-serif;color:#c9d2f5;background:rgba(6,9,22,.55);padding:.25rem .7rem;border-radius:999px;width:max-content;max-width:100%;animation:gf 4.2s forwards;text-align:center}
#ga-feed div.me{color:#ffe08a;border:1px solid rgba(255,224,138,.35)}
#ga-feed div.evo{color:#fff;border:1px solid rgba(185,140,255,.5)}
@keyframes gf{0%{opacity:0;transform:translateY(-8px)}8%{opacity:1;transform:none}80%{opacity:1}100%{opacity:0}}
#ga-banner{position:fixed;left:50%;top:16%;transform:translate(-50%,0);z-index:32;pointer-events:none;text-align:center;opacity:0;transition:opacity .35s,transform .35s}
#ga-banner.on{opacity:1;transform:translate(-50%,6px)}
#ga-banner b{display:block;font:800 26px Manrope,sans-serif;letter-spacing:.02em;text-shadow:0 0 22px currentColor}
#ga-banner small{display:block;font:600 13px Manrope,sans-serif;color:#dfe6ff;margin-top:.2rem}
#ga-mini{position:fixed;right:12px;bottom:12px;z-index:31;width:130px;height:130px;pointer-events:none;border-radius:50%;background:rgba(6,9,22,.55);border:1px solid rgba(142,233,255,.18)}
#ga-skin{position:fixed;left:50%;bottom:22px;transform:translateX(-50%);z-index:60;display:flex;align-items:center;gap:.5rem;background:rgba(6,9,22,.8);border:1px solid rgba(142,233,255,.25);border-radius:999px;padding:.35rem .5rem;transition:opacity .3s;max-width:calc(100vw - 20px);box-sizing:border-box}
#ga-skin.off,#ga-start-extra.off{opacity:0;pointer-events:none}
#ga-skin button{width:34px;height:34px;border-radius:50%;border:1px solid rgba(255,255,255,.18);background:rgba(255,255,255,.06);color:#fff;font-size:15px;cursor:pointer;flex:none}
#ga-skin canvas{position:static;width:120px;height:34px}
#ga-skin small{font:600 10px 'JetBrains Mono',monospace;letter-spacing:.12em;color:#8ee9ff;text-transform:uppercase;padding-right:.2rem;min-width:84px}
#ga-skin small em{display:block;font-style:normal;color:#ffb86b;letter-spacing:.04em;text-transform:none;font-size:10px}
#ga-start-extra{position:fixed;left:10px;top:52px;z-index:62;display:flex;gap:.45rem;align-items:flex-start;transition:opacity .3s;flex-wrap:wrap;max-width:min(560px,calc(100vw - 20px))}
.ga-chip{font:700 12px Manrope,sans-serif;color:#f4f1ff;background:rgba(6,9,22,.8);border:1px solid rgba(142,233,255,.28);border-radius:999px;padding:.45rem .8rem;cursor:pointer}
.ga-chip.mod{cursor:default;border-color:rgba(255,224,138,.4);color:#ffe08a}
.ga-sheet{position:fixed;inset:0;z-index:70;display:grid;place-items:center;background:rgba(4,6,16,.72);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);cursor:default}
.ga-sheet[hidden]{display:none}
.ga-card{width:min(920px,calc(100vw - 24px));max-height:calc(100vh - 40px);overflow:auto;background:#0a0e22;border:1px solid rgba(142,233,255,.22);border-radius:18px;padding:1rem 1.1rem 1.2rem;box-sizing:border-box;-webkit-user-select:text;user-select:text;touch-action:pan-y}
.ga-card h2{margin:0;font:800 20px Manrope,sans-serif}
.ga-card header{display:flex;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:.7rem}
.ga-card header button{border:1px solid rgba(255,255,255,.2);background:rgba(255,255,255,.06);color:#fff;border-radius:999px;padding:.4rem .9rem;font:700 13px Manrope,sans-serif;cursor:pointer}
.ga-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:.7rem}
.ga-tile{background:#070a1c;border:1px solid rgba(255,255,255,.08);border-radius:12px;overflow:hidden}
.ga-tile canvas{width:100%;aspect-ratio:220/130;height:auto}
.ga-tile p{margin:0;padding:.45rem .6rem .55rem;font:600 12px Manrope,sans-serif;color:#c9d2f5}
.ga-tile p b{display:block;color:#fff;font-size:13px}
.ga-opts{display:flex;gap:1rem;flex-wrap:wrap;margin:.2rem 0 .8rem;font:600 13px Manrope,sans-serif;color:#c9d2f5}
.ga-opts label{display:flex;gap:.4rem;align-items:center;cursor:pointer}
.ga-row{margin:.6rem 0 .2rem;font:700 11px 'JetBrains Mono',monospace;letter-spacing:.14em;text-transform:uppercase;color:#8ee9ff}
.ga-pick{display:flex;gap:.4rem;flex-wrap:wrap}
.ga-pick button{border:1px solid rgba(255,255,255,.16);background:rgba(255,255,255,.05);color:#fff;border-radius:10px;padding:.45rem .7rem;font:600 12px Manrope,sans-serif;cursor:pointer}
.ga-pick button.on{border-color:#ffe08a;color:#ffe08a;background:rgba(255,224,138,.1)}
.ga-pick button[disabled]{opacity:.45;cursor:not-allowed}
.ga-xp{font:700 14px Manrope,sans-serif;color:#ffe08a}
.ga-xpbar{height:6px;border-radius:999px;background:rgba(255,255,255,.08);overflow:hidden;margin:.35rem 0 .2rem}
.ga-xpbar i{display:block;height:100%;background:linear-gradient(90deg,#5ef2ff,#ff5ca8)}
#ga-tip{position:fixed;left:10px;top:52px;z-index:33;width:220px;background:#0a0e22;border:1px solid rgba(142,233,255,.3);border-radius:12px;overflow:hidden;pointer-events:none;transform:translateX(calc(-100% - 20px));transition:transform .35s ease}
#ga-tip.on{transform:none}
#ga-tip canvas{width:220px;height:130px}
#ga-tip p{margin:0;padding:.4rem .6rem .5rem;font:600 12px Manrope,sans-serif;color:#c9d2f5}
#ga-tip p b{display:block;color:#fff}
#ga-boost{position:fixed;right:150px;bottom:24px;z-index:42;width:78px;height:78px;border-radius:50%;border:2px solid rgba(255,224,138,.55);background:rgba(255,224,138,.12);color:#ffe08a;font:800 12px Manrope,sans-serif;letter-spacing:.08em;display:none;touch-action:none}
#ga-boost.on{background:rgba(255,224,138,.35)}
@media (pointer:coarse){#ga-boost{display:block}#ga-lb{width:150px;font-size:11px}#ga-mini{width:100px;height:100px}#ga-boost{right:122px}#ga-ab{left:auto;right:132px;bottom:112px}#ga-pow{bottom:74px}#ga-tip{top:52px;width:180px}#ga-tip canvas{width:180px;height:106px}}
@media (max-width:560px){#ga-lb li:nth-child(n+6){display:none}#ga-count{display:none}#ga-feed{top:auto;bottom:178px;max-width:86vw}#ga-banner{top:25%;width:86vw}#ga-banner b{font-size:20px}.ga-grid{grid-template-columns:repeat(2,1fr);gap:.5rem}.ga-tile p{font-size:11px}#ga-skin canvas{width:84px}}
</style></head><body>
<canvas id="c" aria-label="Glowline Arena playfield"></canvas>
<div class="ga-panel" id="ga-mode"><span class="dot"></span><span id="ga-mode-t">Connecting…</span><span id="ga-mode-mod"></span></div>
<div id="ga-feed" aria-live="polite"></div>
<div id="ga-banner" aria-live="polite"><b id="ga-banner-t"></b><small id="ga-banner-s"></small></div>
<div class="ga-panel" id="ga-lb"><h3><span>Leaderboard</span><span id="ga-count"></span></h3><ol id="ga-lb-list"></ol></div>
<div id="ga-pow" aria-label="Active power-ups"></div>
<button type="button" id="ga-ab" aria-label="Use evolution ability"><canvas id="ga-ab-c" width="116" height="116"></canvas></button>
<div class="ga-panel" id="ga-me"><div><small>Length</small><b id="ga-len">0</b></div><div><small>Rank</small><b id="ga-rank">–</b></div><div><small>Kills</small><b id="ga-kills">0</b></div></div>
<canvas id="ga-mini" width="260" height="260"></canvas>
<div id="ga-tip" aria-live="polite"><canvas id="ga-tip-c" width="440" height="260"></canvas><p><b id="ga-tip-t"></b><span id="ga-tip-s"></span></p></div>
<div id="ga-start-extra"><span class="ga-chip mod" id="ga-mod-chip" hidden></span><button type="button" class="ga-chip" id="ga-how-btn">? How to play</button><button type="button" class="ga-chip" id="ga-style-btn">✦ Style</button></div>
<div id="ga-skin"><button type="button" id="ga-skin-prev" aria-label="Previous skin">◀</button><canvas id="ga-skin-c" width="240" height="68"></canvas><button type="button" id="ga-skin-next" aria-label="Next skin">▶</button><small id="ga-skin-n">Skin 1</small></div>
<button type="button" id="ga-boost" aria-label="Boost (double-tap for your evolution ability)">BOOST</button>
<div class="ga-sheet" id="ga-how" hidden><div class="ga-card" role="dialog" aria-label="How to play">
  <header><h2>How to play</h2><button type="button" data-close>Close</button></header>
  <div class="ga-opts">
    <label><input type="checkbox" id="ga-opt-tips"/> Show tips during a match</label>
    <label><input type="checkbox" id="ga-opt-rm"/> Reduced motion</label>
  </div>
  <div class="ga-grid" id="ga-how-grid"></div>
</div></div>
<div class="ga-sheet" id="ga-style" hidden><div class="ga-card" role="dialog" aria-label="Style">
  <header><h2>Style</h2><button type="button" data-close>Close</button></header>
  <div class="ga-xp" id="ga-xp-t"></div><div class="ga-xpbar"><i id="ga-xp-bar"></i></div>
  <p style="margin:.2rem 0 .4rem;font:600 12px Manrope,sans-serif;color:#8b93b8">Glow XP comes from every run: 10 per minute alive, 1 per 10 peak length and 20 per kill, up to 500 a run. Everything here is looks only. It never changes how a snake plays.</p>
  <div id="ga-style-rows"></div>
</div></div>
<script>
window.paConfig = {
  slug: "glowline-arena", title: "Glowline Arena", native: true, music: "synthwave", unit: "length", pauseOnBlur: false,
  arena: "wss://arena.promptarcade.games/room?v=2",
  controls: [["Mouse", "Steer toward the cursor"], ["Hold click / Space", "Boost (costs length)"], ["Double-tap boost / E", "Evolution ability"], ["← → / A D", "Steer with keys"], ["Touch", "Point to steer · BOOST button"]]
};
</script>
<script src="/games/play/pa-score.js"></script>
<script src="/games/play/pa-gate.js"></script>
<script src="/games/play/pa-kit.js"></script>
<script type="module">
import { Sim, TICK_HZ, lengthFor, radiusFor, SKINS_V2, PK, T, MODIFIERS, EVO_ACTIVE } from "/games/play/arena/sim.js";
import { decodeFrame2, viewFor, makeViewer } from "/games/play/arena/proto.js";
import {
  SKIN, SKIN_NAMES, SKIN_XP, TRAILS, BURSTS, FRAMES, BOOSTS, FRAME_COL, EVO_PAL, EVO_GLYPH, EVO_NAMES, EVO_TEXT,
  PK_NAMES, PK_TEXT, PK_COL, strokeBody, drawHead, pelletSprites, drawPortal, GUIDES, GUIDE_ORDER, EVO_GUIDE, PK_GUIDE, playGuide
} from "/games/play/arena/art.js";
 
const TAU = Math.PI * 2;
const FRAME_MS = 1000 / TICK_HZ;
const cfg = window.paConfig;
const qs = new URLSearchParams(location.search);
const FOODC = ["#5ef2ff", "#ff5ca8", "#ffd84d", "#5dff9e", "#c77dff", "#ff8a5c", "#7aa8ff", "#ffffff"];
 
/* ---------------- prefs (per viewer, never needed for fairness) ---------------- */
const store = {
  get(k, d) { try { const v = localStorage.getItem(k); return v == null ? d : JSON.parse(v); } catch (e) { return d; } },
  set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} }
};
const prefs = {
  tips: store.get("ga_tips", true),
  rm: store.get("ga_rm", matchMedia("(prefers-reduced-motion: reduce)").matches),
  cos: store.get("ga_cos", [0, 0, 0, 0]), // trail, burst, frame, boost sound
  seen: store.get("ga_seen", {})
};
let xp = store.get("ga_xp", 0) | 0;
 
/* ---------------- DOM ---------------- */
const $ = (id) => document.getElementById(id);
const view = PA.canvas($("c"));
const ctx = view.ctx;
const mini = $("ga-mini").getContext("2d");
const fx = new PA.Particles(600);
const texts = new PA.Texts();
const psprites = pelletSprites();
const shake = (m, d) => { if (!prefs.rm) PA.shake(m, d); };
const flash = (c, ms) => { if (!prefs.rm) PA.flash(c, ms); };
 
/* glow sprites for food, one per colour */
const sprites = FOODC.map((c) => {
  const s = document.createElement("canvas"); s.width = s.height = 64;
  const g = s.getContext("2d");
  const gr = g.createRadialGradient(32, 32, 0, 32, 32, 32);
  gr.addColorStop(0, "#ffffff"); gr.addColorStop(0.18, c); gr.addColorStop(0.45, c + "66"); gr.addColorStop(1, c + "00");
  g.fillStyle = gr; g.fillRect(0, 0, 64, 64);
  return s;
});
/* hex grid tile */
const hexTile = (() => {
  const r = 34, w = Math.sqrt(3) * r, h = 3 * r;
  const s = document.createElement("canvas"); s.width = Math.round(w); s.height = Math.round(h);
  const g = s.getContext("2d");
  g.strokeStyle = "rgba(120,150,255,.09)"; g.lineWidth = 1.5;
  const hex = (cx, cy) => { g.beginPath(); for (let i = 0; i < 6; i++) { const a = Math.PI / 6 + i * Math.PI / 3; g.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r); } g.closePath(); g.stroke(); };
  hex(0, 0); hex(w, 0); hex(w / 2, h / 2); hex(0, h); hex(w, h);
  return s;
})();
/* The floor is one opaque tile (floor colour + hex lines) pre-scaled to the current zoom, so each frame
 * is a single unscaled pattern fill. Re-scaling a pattern every frame was most of the frame time on
 * big screens (full screen at 1080p and up). */
const FLOOR = [[0, [11, 16, 48]], [0.7, [8, 10, 31]], [1, [20, 8, 32]]];
function floorColor(d) {
  for (let i = 1; i < FLOOR.length; i++) {
    const [p1, c1] = FLOOR[i], [p0, c0] = FLOOR[i - 1];
    if (d <= p1) { const k = (d - p0) / (p1 - p0); return c0.map((v, j) => Math.round(v + (c1[j] - v) * k)); }
  }
  return FLOOR[FLOOR.length - 1][1];
}
/* The tile spans several hex cells (about 180 px), so its whole-pixel size tracks the zoom within
 * half a percent. Its world origin is placed from the camera at the tile's own scale, so the grid
 * stays locked to the camera (no slow slide while zooming, no jump when the tile is rebuilt).
 * Sub-pixel camera motion is baked into a copy of the tile each frame, and the full-screen fill
 * keeps a whole-pixel offset, which is the fast path. Rounding the offset alone made the grid
 * step 0, 1, 1, 0 px a frame on high-refresh screens while everything else moved smoothly. */
let floorTile = null;
const floorBake = document.createElement("canvas"), floorBakeG = floorBake.getContext("2d");
function floorMaster(z, d) {
  const shade = Math.round(Math.min(1, d) * 24);
  const nx = Math.max(1, Math.ceil(180 / (hexTile.width * z))), ny = Math.max(1, Math.ceil(180 / (hexTile.height * z)));
  const tw = Math.max(8, Math.round(hexTile.width * z * nx)), th = Math.max(8, Math.round(hexTile.height * z * ny));
  if (floorTile && floorTile.shade === shade && floorTile.tw === tw && floorTile.th === th) return floorTile;
  const c = floorTile && floorTile.c.width === tw && floorTile.c.height === th ? floorTile.c : document.createElement("canvas");
  c.width = tw; c.height = th;
  const g = c.getContext("2d"), col = floorColor(shade / 24);
  g.fillStyle = `rgb(${col})`; g.fillRect(0, 0, tw, th);
  const cw = tw / nx, ch = th / ny;
  for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) g.drawImage(hexTile, i * cw, j * ch, cw, ch);
  floorTile = { c, shade, tw, th, zx: cw / hexTile.width, zy: ch / hexTile.height, fx: -1, fy: -1, pat: null };
  return floorTile;
}
function floorPattern(ctx, ft, ox, oy) {
  const ix = Math.floor(ox), iy = Math.floor(oy);
  const fx = Math.round((ox - ix) * 16) / 16, fy = Math.round((oy - iy) * 16) / 16;
  if (!ft.pat || fx !== ft.fx || fy !== ft.fy) {
    const b = floorBake, g = floorBakeG, tw = ft.tw, th = ft.th;
    if (b.width !== tw || b.height !== th) { b.width = tw; b.height = th; }
    g.drawImage(ft.c, fx, fy); g.drawImage(ft.c, fx - tw, fy); g.drawImage(ft.c, fx, fy - th); g.drawImage(ft.c, fx - tw, fy - th);
    ft.pat = ctx.createPattern(b, "repeat"); ft.fx = fx; ft.fy = fy;
  }
  if (ft.pat.setTransform) ft.pat.setTransform(new DOMMatrix([1, 0, 0, 1, ix, iy]));
  return ft.pat;
}
/* Full-screen gradients (vignette, Blackout fog) are drawn once per size at quarter resolution. */
const overlays = {};
function overlay(name, w, h, paint) {
  const key = w + "x" + h;
  let o = overlays[name];
  if (!o || o.key !== key) {
    const c = document.createElement("canvas");
    c.width = Math.max(1, Math.ceil(w / 4)); c.height = Math.max(1, Math.ceil(h / 4));
    const g = c.getContext("2d"); g.scale(c.width / w, c.height / h); paint(g, w, h);
    o = overlays[name] = { key, c };
  }
  return o.c;
}
 
/* ---------------- world state (fed by frames) ----------------
 * meta: every snake in the room (names, skins, evolutions) · snakes: only the bodies near you
 * map: every snake's rough position for the minimap · st: your own power-up timers (ticks)
 */
const W = {
  snakes: new Map(), meta: new Map(), food: new Map(), portals: new Map(), decoys: new Map(), flares: [],
  map: [], worldR: 2600, me: 0, lb: [], tick: 0, mod: null, st: null
};
let mode = "connecting", online = 0, net = null;
let queue = [];
let myStats = null; // {peak, kills, born, bestRank}
let skin = 0;
skin = (store.get("ga_skin", (Math.random() * 12) | 0) | 0) % SKINS_V2;
if (SKIN_XP[skin] > xp) skin = 0;
 
const tnow = () => W.tick + alpha; // fractional server tick for smooth timers
 
/* ---------------- playout clock ----------------
 * The world updates at 20 Hz. Frames used to be applied whenever a 50 ms slot opened, measured
 * against their (jittery) arrival, so on many display frames the snakes froze for a frame and then
 * jumped two frames' worth (at 60 Hz the head moved 0, 6, 3 px per frame instead of an even 3).
 * Now the world plays back on its own clock that advances by the display's frame time, so the
 * steps are even at 60, 120, 144 or 240 Hz. Online, the clock runs a little behind the newest
 * frame and is nudged gently toward the server's pace; the delay adapts to the measured jitter
 * (about 1.2 to 1.5 ticks on a normal connection, more on a bumpy one). Offline, the clock steps
 * the sim itself (see advanceClock).
 */
const clock = { r: 0, on: false, offs: [], minOff: 0, spread: 0, delay: 1.3, starve: 0, starved: false };
function enqueue(ev) {
  const at = performance.now(), off = at / FRAME_MS - ev.tick, o = clock.offs;
  if (o.length && Math.abs(off - clock.minOff) > 6) o.length = 0; // a pause or a long stall: start over
  o.push(off); if (o.length > 60) o.shift();
  let mn = Infinity; for (const v of o) if (v < mn) mn = v;
  // jitter = how late the 90th-percentile frame of the last 3 s was, so a burst (like the one right
  // after joining) or one freak frame doesn't hold extra delay for long
  const sorted = o.slice().sort((x, y) => x - y);
  clock.minOff = mn; clock.spread = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.9))] - mn;
  queue.push(ev);
  if (queue.length > 200) applyFrame(queue.shift()); // tab in the background: don't pile up
}
const clockTarget = (now) => now / FRAME_MS - clock.minOff - clock.delay;
function advanceClock(now, fdt) {
  if (net && net.kind === "local") {
    // offline: a classic fixed-step loop. The sim steps at exactly 20 Hz of display time and the
    // picture is interpolated between the last two steps, so the delay is one tick and never jitters.
    if (!net.paused) {
      if (!clock.on) { clock.on = true; clock.r = W.tick - 1; }
      clock.r += fdt * TICK_HZ;
      if (clock.r - W.tick > 4) clock.r = W.tick; // a long hitch: drop the lost time instead of fast-forwarding
      while (W.tick < clock.r) applyFrame(viewFor(net.sim, net.sim.step(), net.vw, W.me));
    }
    alpha = Math.max(0, Math.min(1, clock.r - (W.tick - 1)));
    return;
  }
  if (!clock.on) { if (!queue.length) { alpha = 1; return; } clock.on = true; clock.r = clockTarget(now); }
  const want = 1.15 + Math.min(4, clock.spread) + clock.starve;
  clock.delay += (want - clock.delay) * Math.min(1, fdt * (want > clock.delay ? 4 : 1));
  clock.starve = Math.max(0, clock.starve - fdt * 0.03);
  clock.r += fdt * TICK_HZ;
  const e = clockTarget(now) - clock.r;
  if (Math.abs(e) > 3) clock.r += e; else clock.r += e * Math.min(1, fdt * 2);
  while (queue.length && queue[0].tick < clock.r + 1) applyFrame(queue.shift());
  const starving = clock.r > W.tick && !queue.length;
  if (starving && !clock.starved) clock.starve = Math.min(2, clock.starve + 0.25);
  clock.starved = starving;
  alpha = Math.max(0, Math.min(1, clock.r - (W.tick - 1)));
}
 
/* Each snake's drawn head rides a smooth curve through its last tick points (a Catmull-Rom style
 * cubic, with the next bend predicted from the last one) instead of straight 50 ms chords with a
 * corner at every tick. The body is drawn along the same kind of curve, so head and body agree.
 * hc keeps the curve from the previous tick point to the head for the body's first segment. */
function headOf(s) {
  const p = s.pts, n = p.length, x0 = s.px, y0 = s.py, x1 = s.x, y1 = s.y;
  const dx = x1 - x0, dy = y1 - y0, len = Math.hypot(dx, dy);
  if (len < 0.01 || len > 120 || n < 6 || p[n - 4] !== x0 || p[n - 3] !== y0) {
    s.hx = x0 + dx * alpha; s.hy = y0 + dy * alpha; s.ha = s.pa + angDelta(s.pa, s.a) * alpha; s.hc = null; return;
  }
  const ax = p[n - 6], ay = p[n - 5];
  let tx = x1 - ax, ty = y1 - ay, tl = Math.hypot(tx, ty);
  if (tl < 0.01 || tl > len * 4) { tx = dx; ty = dy; tl = len; }
  tx /= tl; ty /= tl;
  const th1 = Math.atan2(dy, dx), th0 = Math.atan2(y0 - ay, x0 - ax);
  const bend = Math.max(-0.6, Math.min(0.6, angDelta(th0, th1)));
  const e1 = th1 + bend / 2, k = len / 3;
  const c1x = x0 + tx * k, c1y = y0 + ty * k, c2x = x1 - Math.cos(e1) * k, c2y = y1 - Math.sin(e1) * k;
  const t = alpha, u = 1 - t;
  // de Casteljau: point, tangent and the sub-curve from the previous tick point to the head
  const ax1 = x0 + (c1x - x0) * t, ay1 = y0 + (c1y - y0) * t;
  const bx1 = c1x + (c2x - c1x) * t, by1 = c1y + (c2y - c1y) * t;
  const cx1 = c2x + (x1 - c2x) * t, cy1 = c2y + (y1 - c2y) * t;
  const ax2 = ax1 + (bx1 - ax1) * t, ay2 = ay1 + (by1 - ay1) * t;
  const bx2 = bx1 + (cx1 - bx1) * t, by2 = by1 + (cy1 - by1) * t;
  s.hx = ax2 + (bx2 - ax2) * t; s.hy = ay2 + (by2 - ay2) * t;
  s.ha = Math.atan2(by2 - ay2, bx2 - ax2);
  if (!(Math.abs(by2 - ay2) + Math.abs(bx2 - ax2) > 1e-6)) s.ha = th1;
  s.hc = s.hc || [0, 0, 0, 0, 0, 0];
  s.hc[0] = ax1; s.hc[1] = ay1; s.hc[2] = ax2; s.hc[3] = ay2; s.hc[4] = tx; s.hc[5] = ty;
  void u;
}
 
function applySnapshot(snap) {
  W.snakes.clear(); W.meta.clear(); W.food.clear(); W.portals.clear(); W.decoys.clear(); W.flares = [];
  W.worldR = snap.worldR; W.tick = snap.tick; W.mod = snap.mod || null; W.map = [];
  for (const s of snap.snakes) { W.meta.set(s.id, metaOf(s)); if (s.pts) addSnake(s); }
  for (const f of snap.food) addFood(f, 0);
  for (const p of snap.portals || []) W.portals.set(p[0], { x: p[1], y: p[2], uses: p[3], exp: p[4], born: 0 });
  for (const d of snap.decoys || []) W.decoys.set(d[0], { owner: d[1], skin: d[2], r: d[3], pts: d[4], until: performance.now() + Math.max(0, d[5] - snap.tick) * FRAME_MS });
  queue = []; clock.on = false; clock.offs.length = 0;
  showMod();
}
const metaOf = (d) => ({ id: d.id, name: d.name, skin: d.skin, bot: d.bot, evo: d.evo || 0, cos: d.cos || [0, 0, 0] });
function addSnake(d) {
  const n = d.pts.length;
  W.meta.set(d.id, metaOf(d));
  W.snakes.set(d.id, {
    id: d.id, name: d.name, skin: d.skin, bot: d.bot, evo: d.evo || 0, cos: d.cos || [0, 0, 0], m: d.m, pm: d.m, a: d.a, pa: d.a,
    pts: d.pts.slice(), x: d.pts[n - 2], y: d.pts[n - 1], px: d.pts[n - 2], py: d.pts[n - 1], boost: 0, flags: 0,
    born: performance.now(), venom: [], tell: 0, glowT: 0, glowC: "#fff", trailT: 0,
    hx: d.pts[n - 2], hy: d.pts[n - 1], ha: d.a, hc: null, path: []
  });
}
function addFood(f, born) {
  W.food.set(f[0], { x: f[1], y: f[2], v: f[3], c: f[4] & 7, k: f[4] >> 4, born, eat: 0 });
}
const nameOf = (id) => { const m = W.meta.get(id); return m ? m.name : "someone"; };
 
function applyFrame(ev) {
  W.tick = ev.tick;
  const now = performance.now();
  for (const d of ev.add) if (!W.meta.has(d.id)) W.meta.set(d.id, metaOf(d));
  for (const d of ev.enter) addSnake(d);
  for (const id of ev.leave) W.snakes.delete(id);
  for (const h of ev.heads) {
    const s = W.snakes.get(h[0]);
    if (!s) continue;
    s.px = s.x; s.py = s.y; s.pa = s.a; s.pm = s.m;
    s.x = h[1]; s.y = h[2]; s.a = h[3]; s.m = h[4]; s.flags = h[5]; s.boost = h[5] & 1;
    const evo = (h[5] >> 4) & 7;
    if (evo !== s.evo) { s.evo = evo; const m = W.meta.get(s.id); if (m) m.evo = evo; }
    // Viper venom is drawn from the boost flag and the head path, so it costs no bandwidth
    if (s.evo === 1 && s.boost && W.tick % T.VENOM_EVERY === 0) s.venom.push(s.px, s.py, now);
    while (s.venom.length && now - s.venom[2] > T.VENOM_LIFE * FRAME_MS) s.venom.splice(0, 3);
    s.pts.push(s.x, s.y);
    // trim generously; exact length is applied while drawing
    const L = lengthFor(s.m) + 60;
    let acc = 0;
    for (let i = s.pts.length - 2; i >= 2; i -= 2) {
      acc += Math.hypot(s.pts[i] - s.pts[i - 2], s.pts[i + 1] - s.pts[i - 1]);
      if (acc > L) { s.pts.splice(0, i - 2); break; }
    }
    if (s.id === W.me && myStats) {
      if (s.m > myStats.peak) myStats.peak = s.m;
      if (s.boost && Math.random() < 0.5 && q.fx) fx.burst(s.pts[0] + (Math.random() - .5) * 10, s.pts[1] + (Math.random() - .5) * 10, { n: 1, color: palOf(s)[0], speed: 30, life: .5, size: 3 });
      if (s.boost && !s.wasBoost) boostSound();
    }
    s.wasBoost = s.boost;
  }
  for (const e of ev.eat) {
    const f = W.food.get(e[0]);
    if (!f) continue;
    if (e[1] && W.snakes.has(e[1])) { f.eat = now; f.by = e[1]; if (e[1] === W.me && !f.k) PA.sfx("pop", { pitch: 0.9 + Math.min(1, f.v / 10) + Math.random() * 0.15, vol: 0.5 }); }
    else W.food.delete(e[0]);
  }
  for (const f of ev.food) addFood(f, now);
  for (const x of ev.x) onEvent(x, now);
  for (const d of ev.del) onDeath(d);
  if (ev.map) W.map = ev.map;
  if (ev.me) W.st = ev.me;
  if (ev.lb) { W.lb = ev.lb; paintBoard(); }
}
 
/* ---------------- rare events ---------------- */
function onEvent(x, now) {
  const [kind] = x;
  const s = W.snakes.get(x[1]);
  const mine = x[1] === W.me;
  switch (kind) {
    case "evo": {
      const m = W.meta.get(x[1]); if (m) m.evo = x[2];
      if (s) { s.evo = x[2]; if (q.fx) fx.burst(s.x, s.y, { n: 40, colors: ["#ffffff", EVO_PAL[x[2]][0], EVO_PAL[x[2]][2]], speed: 260, life: .9, size: 4 }); }
      if (mine) {
        banner(EVO_GLYPH[x[2]] + " You evolved into " + an(EVO_NAMES[x[2]]) + "!", EVO_TEXT[x[2]], EVO_PAL[x[2]][0], 4200);
        PA.sfx("levelup"); PA.sfx("power"); flash(EVO_PAL[x[2]][0], 400); shake(6, .3);
        tip(EVO_GUIDE[x[2]], true);
      } else feed(nameOf(x[1]) + " evolved into " + an(EVO_NAMES[x[2]]), "evo");
      break;
    }
    case "ab":
      if (s) {
        if (x[2] === 3) s.tell = now + T.EEL_TELL * FRAME_MS;
        if (x[2] === 6 && q.fx) fx.burst(s.x, s.y, { n: 14, colors: ["#ffb347", "#ff3d00"], speed: 160, life: .4, size: 4 });
        if (onScreen(s.x, s.y, 200) && !mine) PA.sfx("whoosh", { vol: 0.3 });
      }
      if (mine) PA.sfx(x[2] === 6 ? "whoosh" : "power", { vol: 0.6 });
      break;
    case "dec": W.decoys.set(x[1], { owner: x[2], skin: x[3], r: x[4], pts: x[5], until: now + T.SPLIT_LIFE * FRAME_MS }); break;
    case "decx": {
      const d = W.decoys.get(x[1]);
      if (d) { W.decoys.delete(x[1]); if (q.fx && onScreen(d.pts[0], d.pts[1], 300)) for (let i = 0; i < d.pts.length; i += 8) fx.burst(d.pts[i], d.pts[i + 1], { n: 2, colors: EVO_PAL[4], speed: 120, life: .5, size: 3 }); }
      break;
    }
    case "po": W.portals.set(x[1], { x: x[2], y: x[3], uses: x[4], exp: x[5], born: now }); break;
    case "pox": { const p = W.portals.get(x[1]); if (p) { p.gone = now; setTimeout(() => W.portals.delete(x[1]), 400); } break; }
    case "pf": {
      const p = W.portals.get(x[4]); if (p) p.uses = x[5];
      W.flares.push({ x: x[2], y: x[3], t0: now, until: now + (T.FLARE * FRAME_MS) + 500, id: x[1] });
      if (mine) PA.sfx("power", { pitch: 1.4, vol: 0.6 });
      break;
    }
    case "tp": {
      const dx = x[2], dy = x[3];
      if (s) {
        if (q.fx && onScreen(s.x, s.y, 200)) fx.burst(s.x, s.y, { n: 24, colors: ["#9b7bff", "#5ef2ff"], speed: 200, life: .6, size: 3 });
        const p = s.pts; for (let i = 0; i < p.length; i += 2) { p[i] += dx; p[i + 1] += dy; }
        s.x += dx; s.y += dy; s.px += dx; s.py += dy;
        if (q.fx) fx.burst(s.x, s.y, { n: 30, colors: ["#ffffff", "#5ef2ff"], speed: 240, life: .7, size: 3 });
      }
      if (mine) { cam.x += dx; cam.y += dy; PA.sfx("whoosh", { pitch: 1.6 }); PA.sfx("levelup", { pitch: 1.5, vol: 0.4 }); flash("#9b7bff", 260); dwellStart = 0; }
      break;
    }
    case "pr": if (mine) { banner("Portal refused", "You're circled. No escape when trapped!", "#ff4d6d", 1800); PA.sfx("hit"); dwellStart = 0; } break;
    case "pz": { const p = W.portals.get(x[1]); if (p && q.fx) fx.burst(p.x, p.y, { n: 16, color: "#8b93b8", speed: 90, life: .5, size: 3 }); if (x[2] === W.me) { banner("Portal fizzled", "Too crowded to land safely. Try again.", "#c9d2f5", 1600); PA.sfx("click", { pitch: 0.5 }); dwellStart = 0; } break; }
    case "pu": {
      if (s) { s.glowT = now + 150; s.glowC = PK_COL[x[2]]; }
      if (mine) {
        PA.sfx(x[2] === 5 ? "levelup" : "power", { pitch: 1 + x[2] * 0.06, vol: 0.6 });
        if (x[2] !== 5) texts.add(s ? s.x : cam.x, (s ? s.y : cam.y) - 30, PK_NAMES[x[2]].toUpperCase() + "!", { color: PK_COL[x[2]], size: 18, life: 1 });
        if (x[2] === 6) feed("You grabbed the Bounty!", "me");
        if (x[2] !== 5) tip(PK_GUIDE[x[2]] === "basics" ? null : PK_GUIDE[x[2]]);
      }
      break;
    }
    case "ward":
      if (s && q.fx) fx.burst(s.x, s.y, { n: 18, color: "#5ef2ff", speed: 200, life: .5, size: 3 });
      if (mine) { PA.sfx("hit", { pitch: 1.6 }); texts.add(s ? s.x : cam.x, (s ? s.y : cam.y) - 30, "WARD SAVED YOU", { color: "#5ef2ff", size: 16, life: 1.1 }); }
      break;
    case "mod": W.mod = x[1]; showMod(); break;
  }
}
 
function onDeath(d) {
  const [id, killer, cause, peak, kills, ticks, leader] = d;
  const s = W.snakes.get(id);
  const meta = W.meta.get(id);
  W.snakes.delete(id); W.meta.delete(id);
  const name = meta ? meta.name : "someone";
  if (s && cause !== "retired" && cause !== "left") {
    const c = palOf(s), style = (s.cos && s.cos[1]) | 0;
    const p = s.pts, step = Math.max(2, Math.floor(p.length / 2 / 40)) * 2;
    if (onScreen(s.x, s.y, 600) && q.fx) {
      const colors = style === 1 ? ["#ffe14d", "#ff5ca8", "#5ef2ff", "#ffffff"] : style === 2 ? ["#00ff9c", "#ff00a0", "#ffffff"] : style === 3 ? [c[0], c[2], "#ffd6f3"] : [c[0], c[2]];
      for (let i = 0; i < p.length; i += step) fx.burst(p[i], p[i + 1], { n: 3, colors, speed: style === 1 ? 260 : 160, life: style === 3 ? 1.1 : .7, size: 4, shape: style === 2 ? "square" : "dot", gravity: style === 1 ? 120 : 0 });
    }
  }
  const kname = killer ? nameOf(killer) : null;
  if (id === W.me) {
    W.me = 0;
    PA.sfx("explode"); shake(10, .5); flash("#ff5ca8", 260);
    camHold = { x: s ? s.x : cam.x, y: s ? s.y : cam.y, until: performance.now() + 1500, follow: killer };
    const alive = (performance.now() - myStats.born) / 1000;
    const how = cause === "wall" ? "Hit the arena wall" : cause === "decoy" ? "Hit a Split-tail decoy" : kname ? "Cut off by " + kname : "Crashed out";
    const gained = Math.min(500, Math.round(alive / 60 * 10 + myStats.peak / 10 + myStats.kills * 20));
    const before = xp; xp += gained; store.set("ga_xp", xp);
    const unlocked = unlocksBetween(before, xp);
    setTimeout(() => {
      const stats = [["Peak length", Math.round(myStats.peak)], ["Kills", myStats.kills], ["Survived", fmtTime(alive)], ["Best rank", myStats.bestRank === 99 ? "–" : "#" + myStats.bestRank], ["Glow XP", "+" + gained]];
      if (unlocked.length) stats.push(["Unlocked", unlocked.join(", ")]);
      PA.gameOver(Math.round(myStats.peak), {
        kicker: how, title: myStats.peak >= 500 ? "Monster run!" : myStats.peak >= 150 ? "Great run" : "Run over",
        unit: "length", stats
      });
      if (window.paXP) window.paXP.award("glowline-arena", { score: Math.round(myStats.peak), kills: myStats.kills });
    }, 900);
    $("ga-me").classList.remove("on");
    $("ga-ab").classList.remove("on");
    W.st = null;
    feed(how, "me");
  } else if (killer && killer === W.me) {
    myStats.kills++;
    $("ga-kills").textContent = myStats.kills;
    PA.sfx("combo"); shake(4, .2);
    if (s) texts.add(s.x, s.y - 30, "+" + name.toUpperCase(), { color: "#ffe08a", size: 20, life: 1.2 });
    feed("You cut off " + name + "!", "me");
  } else if (leader) {
    feed(name + " was the leader and fell. Bounty dropped!", "evo");
  } else if (kname && peak > 120 && cause === "cut") {
    feed(kname + " cut off " + name);
  }
  void kills; void ticks;
}
const an = (w) => (/^[AEIOU]/.test(w) ? "an " : "a ") + w;
const fmtTime = (s) => (s >= 60 ? Math.floor(s / 60) + "m " : "") + Math.round(s % 60) + "s";
function feed(msg, cls) {
  const el = document.createElement("div");
  el.textContent = msg; if (cls) el.className = cls;
  $("ga-feed").appendChild(el);
  setTimeout(() => el.remove(), 4300);
  while ($("ga-feed").children.length > 3) $("ga-feed").firstChild.remove();
}
let bannerTo = 0;
function banner(title, sub, color, ms) {
  $("ga-banner-t").textContent = title; $("ga-banner-t").style.color = color || "#fff";
  $("ga-banner-s").textContent = sub || "";
  $("ga-banner").classList.add("on");
  clearTimeout(bannerTo); bannerTo = setTimeout(() => $("ga-banner").classList.remove("on"), ms || 2500);
}
const esc = (t) => String(t).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
function myRank() {
  const me = W.snakes.get(W.me);
  if (!me) return 0;
  let r = 1;
  for (const e of W.map) if (e[0] !== W.me && e[3] > me.m) r++;
  return r;
}
function paintBoard() {
  let html = "", meIn = false;
  const rank = myRank();
  W.lb.forEach(([id, m], i) => {
    const s = W.meta.get(id);
    if (!s) return;
    const me = id === W.me; if (me) meIn = true;
    const glyph = s.evo ? `<em style="color:${EVO_PAL[s.evo][0]}" title="${EVO_NAMES[s.evo]}">${EVO_GLYPH[s.evo]}</em>` : "";
    html += `<li class="${me ? "me" : ""}"><i>${i === 0 ? "♛" : i + 1}</i><u style="background:${SKIN[s.skin][0]}"></u><span>${glyph}${esc(s.name)}${s.bot ? "" : " ●"}</span><b>${m}</b></li>`;
  });
  if (W.me && !meIn && rank) {
    const s = W.snakes.get(W.me);
    if (s) html += `<li class="me"><i>${rank}</i><u style="background:${SKIN[s.skin][0]}"></u><span>${esc(s.name)}</span><b>${Math.round(s.m)}</b></li>`;
  }
  $("ga-lb-list").innerHTML = html;
  $("ga-count").textContent = W.meta.size + " snakes";
  if (W.me && myStats) {
    $("ga-rank").textContent = rank ? "#" + rank : "–";
    if (rank && rank < myStats.bestRank) myStats.bestRank = rank;
  }
}
function showMod() {
  const m = W.mod && MODIFIERS[W.mod];
  $("ga-mode-mod").textContent = m ? "· " + m.name : "";
  const chip = $("ga-mod-chip");
  chip.hidden = !m;
  if (m) chip.textContent = "Today: " + m.name + " · " + m.text;
}
 
/* ---------------- networking ---------------- */
function setMode(m, n) {
  mode = m;
  const el = $("ga-mode");
  el.classList.toggle("online", m === "online");
  $("ga-mode-t").textContent = m === "online" ? `Online · ${n || 1} playing` : m === "local" ? "Offline match · bots" : "Connecting…";
}
function startLocal(reason) {
  if (net && net.kind === "local") return;
  if (net && net.close) net.close();
  const sim = new Sim({ bots: 15, features: true, modifier: qs.has("mod") ? qs.get("mod") || null : undefined });
  const vw = makeViewer();
  const n = { kind: "local", sim, vw, timer: 0, paused: false };
  n.send = (m) => {
    if (m.t === "join") { const id = sim.addPlayer(m.name, m.skin, m.cos); onYou(id); }
    else if (m.t === "in" && W.me) sim.setInput(W.me, m.a, m.b);
    else if (m.t === "ab" && W.me) sim.useAbility(W.me);
    else if (m.t === "cam") { vw.cx = m.x; vw.cy = m.y; }
  };
  // the offline sim is stepped by the playout clock (fixed 20 Hz steps, see advanceClock), so its
  // frames are never late and never bunch up the way timer-driven steps did
  n.close = () => {};
  net = n;
  applySnapshot(sim.snapshot(true));
  setMode("local");
  if (reason) console.info("Glowline Arena: offline mode (" + reason + ")");
  if (PA.state === "play" && !W.me) join();
}
function startOnline(url) {
  let opened = false, settled = false;
  let ws;
  try { ws = new WebSocket(url); } catch (e) { return startLocal("no websocket"); }
  ws.binaryType = "arraybuffer";
  const fail = (why) => { if (settled) return; settled = true; try { ws.close(); } catch (e) {} startLocal(why); };
  const to = setTimeout(() => { if (!opened) fail("timeout"); }, 3500);
  ws.onopen = () => { opened = true; };
  ws.onmessage = (e) => {
    if (typeof e.data === "string") {
      const m = JSON.parse(e.data);
      if (m.t === "snap") {
        if (m.v !== 2) return fail("server is the older version");
        settled = true; clearTimeout(to); applySnapshot(m.snap); setMode("online", m.online); online = m.online;
        if (PA.state === "play" && !W.me) join();
      }
      else if (m.t === "you") onYou(m.id);
      else if (m.t === "info") { online = m.online; setMode("online", m.online); }
      else if (m.t === "full") fail("room full");
      else if (m.t === "pong") net.rtt = performance.now() - m.c;
    } else {
      const ev = decodeFrame2(e.data);
      if (ev) enqueue(ev);
    }
  };
  ws.onclose = () => {
    if (!settled) return fail("closed");
    if (net && net.ws === ws) {
      feed("Connection lost. Switching to an offline match");
      W.me = 0;
      if (PA.state === "play") { myStats = null; }
      startLocal("dropped");
    }
  };
  ws.onerror = () => { if (!opened) fail("error"); };
  net = { kind: "online", ws, send: (m) => { if (ws.readyState === 1) ws.send(JSON.stringify(m)); }, close: () => { try { ws.close(); } catch (e) {} } };
}
function onYou(id) {
  W.me = id;
  myStats = { peak: 12, kills: 0, born: performance.now(), bestRank: 99 };
  $("ga-kills").textContent = "0";
  $("ga-me").classList.add("on");
  camHold = null;
  PA.sfx("levelup");
}
function join() {
  if (!net) return;
  const name = (window.paPlayer && window.paPlayer.getName()) || "Player";
  net.send({ t: "join", name, skin, cos: prefs.cos.slice(0, 3) });
}
 
const url = qs.get("arena") || cfg.arena;
if (qs.get("offline") === "1" || !("WebSocket" in window) || !url) startLocal("forced"); else startOnline(url);
 
PA.onStart(() => {
  $("ga-skin").classList.add("off"); $("ga-start-extra").classList.add("off");
  if (net && (net.kind === "local" || (net.ws && net.ws.readyState === 1))) join();
});
PA.onPause((p) => { if (net && net.kind === "local") net.paused = p; });
 
/* ---------------- input ---------------- */
let aim = 0, boostKey = false, boostPtr = false, boostBtn = false, mouse = null, keyTurn = 0, lastSent = { a: 99, b: false, t: 0 };
let lastBoostTap = 0;
function boostTap() {
  const now = performance.now();
  if (now - lastBoostTap < 250) { ability(); lastBoostTap = 0; } else lastBoostTap = now;
}
function ability() {
  const me = W.snakes.get(W.me);
  if (!me || !EVO_ACTIVE[me.evo] || PA.state !== "play") return;
  if (W.st && W.tick < W.st[4]) { PA.sfx("click", { pitch: 0.6, vol: 0.4 }); return; }
  net.send({ t: "ab" });
}
addEventListener("pointermove", (e) => { if (e.pointerType === "mouse" || e.buttons) mouse = { x: e.clientX, y: e.clientY }; });
addEventListener("pointerdown", (e) => {
  if (e.target.closest && e.target.closest("button,#pa-gate,.pa-layer,.pa-tb,#ga-skin,.ga-sheet,#ga-start-extra")) return;
  mouse = { x: e.clientX, y: e.clientY };
  if (e.pointerType === "mouse") { boostPtr = true; boostTap(); }
});
addEventListener("pointerup", (e) => { if (e.pointerType === "mouse") boostPtr = false; });
addEventListener("blur", () => { boostPtr = boostKey = false; });
PA.onKey((e) => {
  if (e.code === "Space") e.preventDefault();
  if (e.repeat) return;
  if (e.code === "Space" || e.code === "KeyW" || e.code === "ArrowUp") boostTap();
  if (e.code === "KeyE") ability();
});
const bb = $("ga-boost");
bb.addEventListener("pointerdown", (e) => { e.preventDefault(); e.stopPropagation(); boostBtn = true; bb.classList.add("on"); boostTap(); });
["pointerup", "pointercancel", "pointerleave"].forEach((t) => bb.addEventListener(t, () => { boostBtn = false; bb.classList.remove("on"); }));
$("ga-ab").addEventListener("pointerdown", (e) => { e.preventDefault(); e.stopPropagation(); ability(); });
 
function updateInput(dt) {
  const me = W.snakes.get(W.me);
  if (!me || PA.state !== "play") return;
  boostKey = PA.down("Space", "KeyW", "ArrowUp", "ShiftLeft");
  const kt = (PA.down("ArrowRight", "KeyD") ? 1 : 0) - (PA.down("ArrowLeft", "KeyA") ? 1 : 0);
  const head = worldToScreen(lerpHead(me));
  if (kt) { aim = (keyTurn ? aim : me.a) + kt * dt * 4.2; keyTurn = 1; mouse = null; }
  else if (mouse) { keyTurn = 0; aim = Math.atan2(mouse.y - head.y, mouse.x - head.x); }
  else if (!keyTurn) aim = me.a;
  const b = boostKey || boostPtr || boostBtn;
  const now = performance.now();
  if ((Math.abs(aim - lastSent.a) > 0.015 || b !== lastSent.b) && now - lastSent.t > (net && net.kind === "online" ? 60 : 0)) {
    net.send({ t: "in", a: +aim.toFixed(4), b });
    lastSent = { a: aim, b, t: now };
  }
}
setInterval(() => { if (net && net.kind === "online") net.send({ t: "ping", c: performance.now() }); }, 5000);
// spectators tell the server where they are looking, so it sends the snakes there
setInterval(() => { if (net && !W.me) net.send({ t: "cam", x: Math.round(cam.x), y: Math.round(cam.y) }); }, 250);
 
/* ---------------- sound cosmetics ---------------- */
function boostSound() {
  const k = prefs.cos[3] | 0;
  if (k === 1) PA.tone({ freq: 220, to: 880, type: "sawtooth", dur: .18, vol: .04 });
  else if (k === 2) { PA.tone({ freq: 1568, type: "sine", dur: .25, vol: .05 }); PA.tone({ freq: 2093, type: "sine", dur: .3, vol: .04, delay: .05 }); }
  else if (k === 3) PA.tone({ freq: 160, to: 45, type: "sine", dur: .35, vol: .12 });
  else PA.sfx("whoosh", { vol: 0.25 });
}
 
/* ---------------- skin picker + style ---------------- */
function paintSkinPicker() {
  const c = $("ga-skin-c").getContext("2d");
  c.clearRect(0, 0, 240, 68);
  const pal = SKIN[skin];
  const path = [];
  for (let x = 204; x >= 20; x -= 4) path.push(x, 34 + Math.sin(x / 26) * 12);
  c.save(); c.shadowColor = pal[0]; c.shadowBlur = 10;
  strokeBody(c, path, pal, 11, { offset: 0, glow: false });
  c.restore();
  drawHead(c, 204, 34 + Math.sin(204 / 26) * 12, Math.cos(204 / 26) * 0.4, 12, pal, 0);
  $("ga-skin-n").innerHTML = esc(SKIN_NAMES[skin]) + (skin >= 12 ? "<em>Unlocked skin</em>" : "");
}
function setSkin(d) {
  let s = skin;
  for (let i = 0; i < SKINS_V2; i++) { s = (s + d + SKINS_V2) % SKINS_V2; if (SKIN_XP[s] <= xp) break; }
  skin = s; store.set("ga_skin", skin); paintSkinPicker(); PA.sfx("click");
}
$("ga-skin-prev").onclick = () => setSkin(-1);
$("ga-skin-next").onclick = () => setSkin(1);
paintSkinPicker();
setInterval(() => {
  if (PA.state !== "play") { $("ga-skin").classList.remove("off"); $("ga-start-extra").classList.remove("off"); }
}, 500);
 
function unlocksBetween(a, b) {
  const out = [];
  SKIN_XP.forEach((v, i) => { if (v > a && v <= b) out.push(SKIN_NAMES[i] + " skin"); });
  for (const [list, label] of [[TRAILS, "trail"], [BURSTS, "burst"], [FRAMES, "frame"], [BOOSTS, "boost sound"]]) for (const [n, v] of list) if (v > a && v <= b) out.push(n + " " + label);
  return out;
}
function openSheet(id) { $(id).hidden = false; PA.sfx("click"); }
document.querySelectorAll(".ga-sheet").forEach((el) => {
  el.addEventListener("click", (e) => { if (e.target === el || e.target.closest("[data-close]")) { el.hidden = true; stopGuides(); } });
});
addEventListener("keydown", (e) => { if (e.key === "Escape") document.querySelectorAll(".ga-sheet").forEach((el) => { if (!el.hidden) { el.hidden = true; stopGuides(); } }); });
function paintStyle() {
  const all = [...SKIN_XP, ...TRAILS.map((x) => x[1]), ...BURSTS.map((x) => x[1]), ...FRAMES.map((x) => x[1]), ...BOOSTS.map((x) => x[1])].sort((a, b) => a - b);
  const next = all.find((v) => v > xp);
  $("ga-xp-t").textContent = "Glow XP " + xp.toLocaleString() + (next ? " · next unlock at " + next.toLocaleString() : " · everything unlocked");
  const prev = all.filter((v) => v <= xp).pop() || 0;
  $("ga-xp-bar").style.width = next ? Math.round((xp - prev) / (next - prev) * 100) + "%" : "100%";
  const row = (title, list, idx, onPick) => `<div class="ga-row">${title}</div><div class="ga-pick">` + list.map(([n, v], i) =>
    `<button type="button" data-k="${idx}" data-i="${i}" class="${(idx === "skin" ? skin : prefs.cos[idx]) === i ? "on" : ""}" ${v > xp ? "disabled" : ""}>${esc(n)}${v > xp ? " · " + v.toLocaleString() + " XP" : ""}</button>`).join("") + "</div>";
  $("ga-style-rows").innerHTML =
    row("Skin", SKIN_NAMES.map((n, i) => [n, SKIN_XP[i]]), "skin") +
    row("Trail", TRAILS, 0) + row("Death burst", BURSTS, 1) + row("Name frame", FRAMES, 2) + row("Boost sound", BOOSTS, 3);
}
$("ga-style-rows").addEventListener("click", (e) => {
  const b = e.target.closest("button[data-k]");
  if (!b || b.disabled) return;
  const k = b.dataset.k, i = +b.dataset.i;
  if (k === "skin") { skin = i; store.set("ga_skin", skin); paintSkinPicker(); }
  else { prefs.cos[+k] = i; store.set("ga_cos", prefs.cos); if (+k === 3) boostSound(); }
  PA.sfx("click"); paintStyle();
});
$("ga-style-btn").onclick = () => { paintStyle(); openSheet("ga-style"); };
 
/* ---------------- guides ---------------- */
let guideRuns = [];
function stopGuides() { guideRuns.forEach((r) => r.stop()); guideRuns = []; }
$("ga-how-btn").onclick = () => {
  const grid = $("ga-how-grid");
  grid.innerHTML = GUIDE_ORDER.map((id) => `<div class="ga-tile"><canvas width="440" height="260" data-g="${id}"></canvas><p><b>${GUIDES[id].title}</b>${GUIDES[id].caption}</p></div>`).join("");
  $("ga-opt-tips").checked = prefs.tips; $("ga-opt-rm").checked = prefs.rm;
  openSheet("ga-how");
  stopGuides();
  grid.querySelectorAll("canvas").forEach((c) => guideRuns.push(playGuide(c, c.dataset.g, psprites, prefs.rm)));
};
$("ga-opt-tips").onchange = (e) => { prefs.tips = e.target.checked; store.set("ga_tips", prefs.tips); };
$("ga-opt-rm").onchange = (e) => { prefs.rm = e.target.checked; store.set("ga_rm", prefs.rm); $("ga-how-btn").onclick(); };
let tipRun = null, tipTo = 0;
/** slide in a guide the first time a player meets something (never pauses the game) */
function tip(id, force) {
  if (!id || !prefs.tips || !GUIDES[id]) return;
  if (prefs.seen[id] && !force) return;
  prefs.seen[id] = 1; store.set("ga_seen", prefs.seen);
  if (tipRun) tipRun.stop();
  $("ga-tip-t").textContent = GUIDES[id].title; $("ga-tip-s").textContent = GUIDES[id].caption;
  tipRun = playGuide($("ga-tip-c"), id, psprites, prefs.rm);
  $("ga-tip").classList.add("on");
  clearTimeout(tipTo);
  tipTo = setTimeout(() => { $("ga-tip").classList.remove("on"); setTimeout(() => { if (tipRun) { tipRun.stop(); tipRun = null; } }, 400); }, 4500);
}
let tipScan = 0;
function scanForTips(now) {
  if (now - tipScan < 500 || !W.me) return; tipScan = now;
  const me = W.snakes.get(W.me); if (!me) return;
  const near = (x, y) => (x - me.x) ** 2 + (y - me.y) ** 2 < 700 * 700;
  for (const p of W.portals.values()) if (near(p.x, p.y)) return tip("portals");
  for (const f of W.food.values()) if (f.k && near(f.x, f.y)) return tip(f.k === PK.EVO ? "evo" : f.k === PK.KEY ? "portals" : f.k === PK.BOUNTY ? null : PK_GUIDE[f.k]);
  for (const s of W.snakes.values()) if (s.evo && s.id !== W.me && near(s.x, s.y)) return tip(EVO_GUIDE[s.evo]);
}
 
/* ---------------- auto quality ----------------
 * q.glow: soft glow strokes · q.fx: particles and trails · q.res: canvas resolution
 * Steps down after 2 s under 50 FPS, steps back up after 12 s of steady frames, but never back
 * to a level that was too slow in the last minute (so it doesn't flip-flop and stutter).
 * The canvas also has a pixel budget: big or high-DPI screens (full screen) render at most
 * PIXEL_BUDGET pixels and the browser scales the picture up, so cost doesn't grow with the screen.
 */
const q = { level: +(qs.get("q") || 0), glow: true, fx: true, res: 1 };
const PIXEL_BUDGET = [2.4e6, 2.1e6, 1.6e6, 1.1e6];
let slowFor = 0, fastFor = 0, resApplied = 1;
const slowAt = [0, 0, 0, 0];
function targetRes() {
  const px = view.w * view.h * view.dpr * view.dpr;
  return Math.min(1, Math.sqrt(PIXEL_BUDGET[q.level] / Math.max(1, px)));
}
function applyQuality() {
  q.glow = q.level < 1; q.fx = q.level < 2;
  fx.max = q.level >= 2 ? 300 : 600;
  fixRes();
}
addEventListener("resize", () => fixRes());
const fit0 = view.fit;
view.fit = () => { fit0(); fixRes(); };
function fixRes() {
  resApplied = q.res = targetRes();
  const c = view.canvas, cw = Math.floor(view.w * view.dpr * resApplied), ch = Math.floor(view.h * view.dpr * resApplied);
  if (c.width !== cw || c.height !== ch) { c.width = cw; c.height = ch; }
}
function watchFps(dt) {
  if (!dt) return;
  const now = performance.now();
  if (dt > 1 / 50) { slowFor += dt; fastFor = 0; } else { fastFor += dt; slowFor = Math.max(0, slowFor - dt * 0.5); }
  if (slowFor > 2 && q.level < 3) { slowAt[q.level] = now; q.level++; slowFor = 0; fastFor = 0; applyQuality(); }
  else if (fastFor > 12 && q.level > 0 && !qs.get("q") && now - slowAt[q.level - 1] > 60000) { q.level--; fastFor = 0; applyQuality(); }
}
applyQuality();
 
/* ---------------- camera ---------------- */
let cam = { x: 0, y: 0, z: 1 }, camHold = null, alpha = 0, spectate = 0, spectateT = 0;
function lerpHead(s) { return { x: s.hx, y: s.hy }; }
function worldToScreen(p) { return { x: (p.x - cam.x) * cam.z + view.w / 2, y: (p.y - cam.y) * cam.z + view.h / 2 }; }
function onScreen(x, y, pad) {
  const hw = view.w / 2 / cam.z + pad, hh = view.h / 2 / cam.z + pad;
  return x > cam.x - hw && x < cam.x + hw && y > cam.y - hh && y < cam.y + hh;
}
function viewScale(me) {
  // >1 sees more: Lens +40%, Firefly +25% (they don't stack past the Lens), Blackout −30%
  const t = W.tick;
  let k = 1;
  const lens = W.st && W.st[2] > t, fire = me && me.evo === 7;
  if (lens) k = 1.4; else if (fire) k = 1.25;
  if (W.mod === "blackout" && !fire) k *= 0.7;
  return k;
}
let zoomK = 1;
function updateCamera(dt) {
  let target = null, r = 12;
  const me = W.snakes.get(W.me);
  if (me) { target = lerpHead(me); r = radiusFor(me.m); }
  else if (camHold && performance.now() < camHold.until) target = camHold;
  else {
    // spectate: drift between the top snakes (their rough spot comes from the minimap feed)
    spectateT -= dt;
    if ((!W.meta.has(spectate)) || spectateT <= 0) {
      const top = W.lb.slice(0, 4);
      if (top.length) spectate = top[(Math.random() * top.length) | 0][0];
      spectateT = 9;
    }
    const s = W.snakes.get(spectate);
    if (s) { target = lerpHead(s); r = radiusFor(s.m); }
    else { const e = W.map.find((m) => m[0] === spectate); if (e) target = { x: e[1], y: e[2] }; }
  }
  if (target) {
    const k = me ? 1 - Math.pow(0.0005, dt) : 1 - Math.pow(0.08, dt);
    cam.x += (target.x - cam.x) * k; cam.y += (target.y - cam.y) * k;
  }
  zoomK += (viewScale(me) - zoomK) * Math.min(1, dt * 1.5);
  const base = Math.min(view.w, view.h) / 950;
  const zt = Math.max(0.42, base * (1.15 - Math.min(0.55, (r - 10) / 70))) * (view.w < 600 ? 0.9 : 1) / zoomK;
  cam.z += (zt - cam.z) * Math.min(1, dt * 2);
}
 
/* ---------------- rendering ---------------- */
const palOf = (s) => (s.evo ? EVO_PAL[s.evo] : SKIN[s.skin] || SKIN[0]);
const angDelta = (a, b) => { let d = (b - a) % TAU; if (d > Math.PI) d -= TAU; if (d < -Math.PI) d += TAU; return d; };
function bodyPath(head, p, L, path) {
  path.length = 0; path.push(head.x, head.y);
  let acc = 0, lx = head.x, ly = head.y;
  path.full1 = false;
  for (let i = p.length - 4; i >= 0; i -= 2) {
    const x = p[i], y = p[i + 1], d = Math.hypot(x - lx, y - ly);
    if (acc + d >= L) { const k = (L - acc) / (d || 1); path.push(lx + (x - lx) * k, ly + (y - ly) * k); acc = L; break; }
    acc += d; path.push(x, y); lx = x; ly = y;
    if (i === p.length - 4) path.full1 = true;
  }
  path.acc = acc;
  return path;
}
function drawSnake(s, t, isMe, now) {
  const pal = palOf(s);
  const m = s.pm + (s.m - s.pm) * alpha;
  const r = radiusFor(m) * (s.evo === 2 ? 1.35 : 1), L = lengthFor(m);
  const head = lerpHead(s);
  const path = bodyPath(head, s.pts, L, s.path);
  // cull when no part is on screen
  let vis = false;
  for (let i = 0; i < path.length; i += 16) if (onScreen(path[i], path[i + 1], r * 2)) { vis = true; break; }
  if (!vis && !onScreen(path[path.length - 2], path[path.length - 1], r * 2)) return;
 
  const f = s.flags, prot = f & 128, active = f & 4, phased = s.evo === 3 && active;
  // trail cosmetic: a few particles off the tail, drawn under bodies
  if (q.fx && s.cos && s.cos[0] && now - s.trailT > 90) {
    s.trailT = now;
    const tx = path[path.length - 2], ty = path[path.length - 1], st = s.cos[0];
    fx.burst(tx, ty, st === 1 ? { n: 1, color: pal[2], speed: 40, life: .3, size: 2.5, shape: "spark" } : st === 2 ? { n: 1, colors: ["#ffc2e0", "#ffd6f3"], speed: 25, life: .3, size: 4 } : { n: 1, color: pal[0], speed: 30, life: .3, size: 3, shape: "square" });
  }
  let alphaB = prot ? 0.45 + Math.sin(t * 20) * 0.1 : phased ? 0.3 + Math.sin(t * 25) * 0.08 : 1;
  strokeBody(ctx, path, pal, r, { t, offset: path.acc, boost: s.boost, evo: s.evo, alpha: alphaB, glow: q.glow, smooth: true, head: path.full1 && path.length > 4 ? s.hc : null });
 
  // head
  const a = s.ha;
  const look = isMe && PA.state === "play" ? angDelta(a, aim) * 0.5 : 0;
  drawHead(ctx, head.x, head.y, a, r, pal, look, alphaB);
  // status rings on the head: Ward (hexagon), Surge (chevrons), Eel tell (flicker), Magnet field
  if (f & 2) {
    ctx.strokeStyle = "#5ef2ff"; ctx.lineWidth = 2.5; ctx.globalAlpha = 0.8;
    ctx.beginPath(); for (let i = 0; i < 6; i++) { const q2 = i * Math.PI / 3 + t; ctx.lineTo(head.x + Math.cos(q2) * r * 1.9, head.y + Math.sin(q2) * r * 1.9); } ctx.closePath(); ctx.stroke();
    ctx.globalAlpha = 1;
  }
  if (f & 8) {
    ctx.strokeStyle = "#ffe14d"; ctx.lineWidth = 3; ctx.globalAlpha = 0.7 + Math.sin(t * 20) * 0.3;
    for (const k of [1.6, 2.3]) { const bx = head.x - Math.cos(a) * r * k, by = head.y - Math.sin(a) * r * k; ctx.beginPath(); ctx.moveTo(bx + Math.cos(a + 2.4) * r * .7, by + Math.sin(a + 2.4) * r * .7); ctx.lineTo(bx, by); ctx.lineTo(bx + Math.cos(a - 2.4) * r * .7, by + Math.sin(a - 2.4) * r * .7); ctx.stroke(); }
    ctx.globalAlpha = 1;
  }
  if (s.tell > now) { ctx.strokeStyle = "#ffffff"; ctx.lineWidth = 2; ctx.globalAlpha = 0.5 + Math.sin(t * 60) * 0.5; ctx.beginPath(); ctx.arc(head.x, head.y, r * 2.1, 0, TAU); ctx.stroke(); ctx.globalAlpha = 1; }
  if (s.evo === 5) { ctx.strokeStyle = "#ff4d4d"; ctx.lineWidth = 1.5; ctx.globalAlpha = 0.35; ctx.setLineDash([6, 8]); ctx.lineDashOffset = -t * 30; ctx.beginPath(); ctx.arc(head.x, head.y, (radiusFor(m) + 26) * 2.5, 0, TAU); ctx.stroke(); ctx.setLineDash([]); ctx.globalAlpha = 1; }
  if (s.evo === 6 && active) {
    ctx.globalCompositeOperation = "lighter";
    const gr = ctx.createLinearGradient(head.x - Math.cos(a) * r * 9, head.y - Math.sin(a) * r * 9, head.x, head.y);
    gr.addColorStop(0, "rgba(255,61,0,0)"); gr.addColorStop(1, "rgba(255,179,71,.85)");
    ctx.strokeStyle = gr; ctx.lineWidth = r * 1.6; ctx.lineCap = "round";
    ctx.beginPath(); ctx.moveTo(head.x - Math.cos(a) * r * 9, head.y - Math.sin(a) * r * 9); ctx.lineTo(head.x, head.y); ctx.stroke();
    ctx.globalCompositeOperation = "source-over";
  }
  if (s.glowT > now) { ctx.globalCompositeOperation = "lighter"; ctx.fillStyle = s.glowC; ctx.globalAlpha = (s.glowT - now) / 150 * 0.6; ctx.beginPath(); ctx.arc(head.x, head.y, r * 2.4, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over"; }
  // name tag (+ evolution glyph and name frame)
  if (!isMe && cam.z > 0.5) {
    const fs = Math.max(11, 12 / cam.z * 0.9);
    ctx.font = `700 ${fs}px Manrope, sans-serif`;
    ctx.textAlign = "center";
    const label = (s.evo ? EVO_GLYPH[s.evo] + " " : "") + s.name, ty = head.y - r - 12 / cam.z;
    const fr = s.cos && s.cos[2];
    if (fr) {
      const w = ctx.measureText(label).width + fs;
      ctx.strokeStyle = FRAME_COL[fr]; ctx.lineWidth = 1.5 / cam.z; ctx.globalAlpha = 0.8;
      ctx.beginPath(); ctx.roundRect ? ctx.roundRect(head.x - w / 2, ty - fs, w, fs * 1.35, fs * 0.6) : ctx.rect(head.x - w / 2, ty - fs, w, fs * 1.35); ctx.stroke(); ctx.globalAlpha = 1;
    }
    ctx.fillStyle = s.evo ? EVO_PAL[s.evo][2] : "rgba(230,236,255,.75)";
    ctx.fillText(label, head.x, ty);
  }
}
function drawVenom(s, now) {
  if (!s.venom.length) return;
  ctx.globalCompositeOperation = "lighter";
  for (let i = 0; i < s.venom.length; i += 3) {
    const age = (now - s.venom[i + 2]) / (T.VENOM_LIFE * FRAME_MS);
    if (age > 1 || !onScreen(s.venom[i], s.venom[i + 1], 30)) continue;
    ctx.globalAlpha = (1 - age) * 0.45;
    ctx.fillStyle = "#9dff3c";
    ctx.beginPath(); ctx.arc(s.venom[i], s.venom[i + 1], 11 + age * 4, 0, TAU); ctx.fill();
    ctx.globalAlpha = (1 - age) * 0.8; ctx.fillStyle = "#6a1fd1";
    ctx.beginPath(); ctx.arc(s.venom[i], s.venom[i + 1], 3.5, 0, TAU); ctx.fill();
  }
  ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
}
 
let dwell = 0, dwellStart = 0, humT = 0;
function drawPortals(t, now) {
  const me = W.snakes.get(W.me);
  let nearest = 1e9, inside = null;
  for (const [id, p] of W.portals) {
    if (me) { const d = Math.hypot(p.x - me.x, p.y - me.y); if (d < nearest) nearest = d; if (d < T.PORTAL_R) inside = p; }
    if (!onScreen(p.x, p.y, 120)) continue;
    const left = (p.exp - tnow()) / TICK_HZ;
    let a = p.born ? Math.min(1, (now - p.born) / 500) : 1;
    if (p.gone) a = Math.max(0, 1 - (now - p.gone) / 400);
    if (left < 3) a *= 0.5 + Math.sin(t * 14) * 0.3;
    if (p.uses === 1) a *= 0.75 + Math.sin(t * 9) * 0.25;
    drawPortal(ctx, p.x, p.y, T.PORTAL_R, t, { uses: p.uses, alpha: a, still: prefs.rm });
    void id;
  }
  // my dwell: the ring tightens around my head (mirrors the server's 0.35 s rule)
  if (me && inside && !me.boost && !(W.st && W.tick < W.st[6]) && PA.state === "play") {
    if (!dwellStart) dwellStart = now;
    dwell = Math.min(1, (now - dwellStart) / (T.DWELL * FRAME_MS));
    const h = lerpHead(me), r = radiusFor(me.m);
    ctx.strokeStyle = "#ffffff"; ctx.lineWidth = 3; ctx.globalAlpha = 0.9;
    ctx.beginPath(); ctx.arc(h.x, h.y, r * 1.6 + (1 - dwell) * 50, -Math.PI / 2, -Math.PI / 2 + dwell * TAU); ctx.stroke();
    ctx.globalAlpha = 1;
  } else { dwell = 0; dwellStart = 0; }
  // the hum gets louder as you approach and rises while you charge
  if (me && nearest < 450 && now - humT > 520) {
    humT = now;
    PA.tone({ freq: 110 + dwell * 220, to: 118 + dwell * 240, type: "sine", dur: .5, vol: 0.035 * (1 - nearest / 450) + dwell * 0.03 });
  }
  // arrival flares
  W.flares = W.flares.filter((fl) => fl.until > now);
  for (const fl of W.flares) {
    const k = (now - fl.t0) / (fl.until - fl.t0);
    if (onScreen(fl.x, fl.y, 100)) {
      ctx.globalCompositeOperation = "lighter";
      ctx.strokeStyle = "#5ef2ff"; ctx.lineWidth = 4; ctx.globalAlpha = 1 - k;
      ctx.beginPath(); ctx.arc(fl.x, fl.y, 20 + k * 90, 0, TAU); ctx.stroke();
      ctx.fillStyle = "#ffffff"; ctx.globalAlpha = (1 - k) * 0.5;
      ctx.beginPath(); ctx.arc(fl.x, fl.y, 26 * (1 - k) + 6, 0, TAU); ctx.fill();
      ctx.globalAlpha = 1; ctx.globalCompositeOperation = "source-over";
    }
  }
}
function drawDecoys(t, now) {
  for (const d of W.decoys.values()) {
    if (!onScreen(d.pts[0], d.pts[1], 400) && !onScreen(d.pts[d.pts.length - 2], d.pts[d.pts.length - 1], 400)) continue;
    const left = (d.until - now) / 1000;
    const path = []; for (let i = d.pts.length - 2; i >= 0; i -= 2) path.push(d.pts[i], d.pts[i + 1]);
    strokeBody(ctx, path, EVO_PAL[4], d.r, { dashed: true, t, alpha: left < 1.2 ? 0.5 + Math.sin(t * 16) * 0.3 : 1 });
  }
}
function drawArrivalArrows(now) {
  // a small arrow at the screen edge for an arrival flare just out of sight
  for (const fl of W.flares) {
    if (onScreen(fl.x, fl.y, 0) || !onScreen(fl.x, fl.y, 900)) continue;
    const p = worldToScreen(fl), cx = view.w / 2, cy = view.h / 2;
    const a = Math.atan2(p.y - cy, p.x - cx);
    const ex = cx + Math.cos(a) * (view.w / 2 - 30), ey = cy + Math.sin(a) * (view.h / 2 - 30);
    const x = Math.max(24, Math.min(view.w - 24, ex)), y = Math.max(24, Math.min(view.h - 24, ey));
    ctx.save(); ctx.translate(x, y); ctx.rotate(a);
    ctx.fillStyle = "#5ef2ff"; ctx.globalAlpha = 0.6 + Math.sin(now / 60) * 0.3;
    ctx.beginPath(); ctx.moveTo(12, 0); ctx.lineTo(-8, -9); ctx.lineTo(-8, 9); ctx.closePath(); ctx.fill();
    ctx.restore();
  }
}
 
/* the display's own frame timestamps (even steps), taken before the game loop runs each frame */
let frameTs = 0, frameDt = 0;
requestAnimationFrame(function stamp(ts) { frameDt = frameTs ? Math.max(0, Math.min(0.25, (ts - frameTs) / 1000)) : 0; frameTs = ts; requestAnimationFrame(stamp); });
let lenShown = -1;
function render(t) {
  const now = performance.now();
  advanceClock(now, frameDt);
  for (const s of W.snakes.values()) headOf(s);
  const dt = Math.min(0.05, frameDt);
  if (document.visibilityState === "visible" && !qs.has("q")) watchFps(dt);
  updateInput(dt);
  updateCamera(dt);
  fx.update(dt); texts.update(dt);
 
  const w = view.w, h = view.h, k = view.dpr * resApplied;
  const sh = PA.shakeOffset();
  // floor + hex grid in device pixels (translate-only pattern: the fast path)
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  const zDev = cam.z * k, camD = Math.hypot(cam.x, cam.y);
  const ft = floorMaster(zDev, camD / W.worldR);
  const fp = floorPattern(ctx, ft, (w / 2 + sh.x) * k - cam.x * ft.zx, (h / 2 + sh.y) * k - cam.y * ft.zy);
  ctx.fillStyle = fp; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  ctx.setTransform(k, 0, 0, k, 0, 0);
  ctx.save();
  ctx.translate(w / 2 + sh.x, h / 2 + sh.y);
  ctx.scale(cam.z, cam.z);
  ctx.translate(-cam.x, -cam.y);
 
  // outside the arena and the border, only when the edge is on screen
  const halfDiag = Math.hypot(w, h) / 2 / cam.z;
  if (camD + halfDiag > W.worldR - 80) {
    const vx = cam.x - halfDiag, vy = cam.y - halfDiag;
    ctx.beginPath(); ctx.rect(vx, vy, halfDiag * 2, halfDiag * 2); ctx.arc(0, 0, W.worldR, 0, TAU);
    ctx.fillStyle = "#04050c"; ctx.fill("evenodd");
    const pulse = 0.75 + Math.sin(t * 2) * 0.15;
    ctx.strokeStyle = "#ff3d7f";
    ctx.beginPath(); ctx.arc(0, 0, W.worldR, 0, TAU);
    if (q.glow) {
      ctx.globalCompositeOperation = "lighter";
      ctx.globalAlpha = 0.07 * pulse; ctx.lineWidth = 70; ctx.stroke();
      ctx.globalAlpha = 0.14 * pulse; ctx.lineWidth = 36; ctx.stroke();
      ctx.globalCompositeOperation = "source-over";
    }
    ctx.globalAlpha = pulse; ctx.lineWidth = 14; ctx.stroke();
    ctx.globalAlpha = 1;
  }
 
  drawPortals(t, now);
 
  // food (power pellets are stamped from their own sprites, slightly bigger, gently spinning)
  ctx.globalCompositeOperation = "lighter";
  for (const [id, f] of W.food) {
    let x = f.x, y = f.y, kk = 1;
    if (f.eat) {
      const e = W.snakes.get(f.by), qq = (now - f.eat) / 160;
      if (!e || qq >= 1) { W.food.delete(id); continue; }
      const hh = lerpHead(e); x += (hh.x - x) * qq; y += (hh.y - y) * qq; kk = 1 - qq;
    }
    if (!onScreen(x, y, 40)) continue;
    const born = f.born ? Math.min(1, (now - f.born) / 400) : 1;
    if (f.k) {
      const s = (f.k === PK.EVO ? 34 + Math.sin(t * 4) * 4 : f.k === PK.BOUNTY ? 30 : 22) * kk * born;
      ctx.save(); ctx.translate(x, y); if (!prefs.rm && f.k !== PK.EVO) ctx.rotate(Math.sin(t * 2 + id) * 0.3);
      ctx.drawImage(psprites[f.k], -s, -s, s * 2, s * 2); ctx.restore();
      continue;
    }
    const pulse = 1 + Math.sin(t * 3 + id) * 0.15;
    const s = (8 + Math.min(12, f.v) * 2.4) * pulse * kk * born * (f.v >= 12 ? 1.6 : 1);
    ctx.drawImage(sprites[f.c & 7], x - s, y - s, s * 2, s * 2);
  }
  ctx.globalCompositeOperation = "source-over";
 
  drawDecoys(t, now);
  // snakes: everyone else first, you on top; Viper venom under bodies
  const list = [...W.snakes.values()].sort((a, b) => a.m - b.m);
  for (const s of list) if (s.evo === 1) drawVenom(s, now);
  for (const s of list) if (s.id !== W.me) drawSnake(s, t, false, now);
  const me = W.snakes.get(W.me);
  if (me) drawSnake(me, t, true, now);
  fx.draw(ctx); texts.draw(ctx);
  ctx.restore();
 
  // Blackout: fog beyond a soft circle (a Firefly sees through it)
  if (W.mod === "blackout" && !(me && me.evo === 7)) {
    ctx.drawImage(overlay("fog", w, h, (g, w, h) => {
      const fg = g.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.2, w / 2, h / 2, Math.min(w, h) * 0.7);
      fg.addColorStop(0, "rgba(2,3,8,0)"); fg.addColorStop(1, "rgba(2,3,8,.93)");
      g.fillStyle = fg; g.fillRect(0, 0, w, h);
    }), 0, 0, w, h);
  }
  // vignette
  ctx.drawImage(overlay("vignette", w, h, (g, w, h) => {
    const vg = g.createRadialGradient(w / 2, h / 2, Math.min(w, h) * 0.35, w / 2, h / 2, Math.max(w, h) * 0.75);
    vg.addColorStop(0, "rgba(0,0,0,0)"); vg.addColorStop(1, "rgba(0,0,0,.55)");
    g.fillStyle = vg; g.fillRect(0, 0, w, h);
  }), 0, 0, w, h);
  drawArrivalArrows(now);
 
  if (me) {
    const len = Math.round(me.m);
    if (len !== lenShown) { lenShown = len; $("ga-len").textContent = len; }
    PA.music && PA.music.intensity && PA.music.intensity(Math.min(1, me.m / 600));
  }
  drawMini(now);
  drawHud(now, me);
  scanForTips(now);
}
 
/* ---------------- HUD: power-up row + ability pip ---------------- */
let hudT = 0, powKey = "";
function drawHud(now, me) {
  if (now - hudT < 100) return; hudT = now;
  const st = W.st, t = tnow();
  const row = [];
  if (me && st) {
    if (st[0] > t) row.push(["»", PK_COL[1], (st[0] - t) / T.SURGE, "Surge"]);
    if (st[1] > t) row.push(["⬡", PK_COL[2], (st[1] - t) / T.WARD, "Ward"]);
    if (st[2] > t) row.push(["◉", PK_COL[3], (st[2] - t) / T.LENS, "Lens"]);
    if (st[3]) row.push(["⚷", PK_COL[4], 1, "Key"]);
    if (st[5] > t) row.push(["☠", "#9dff3c", (st[5] - t) / T.SLOW, "Poisoned"]);
  }
  const key = row.map((r) => r[0] + (r[2] * 20 | 0)).join("");
  if (key !== powKey) {
    powKey = key;
    $("ga-pow").innerHTML = row.map((r) => `<span style="--c:${r[1]};--k:${Math.max(0, Math.min(1, r[2])).toFixed(3)}" title="${r[3]}"><i>${r[0]}</i></span>`).join("");
  }
  const ab = $("ga-ab");
  const evo = me ? me.evo : 0;
  ab.classList.toggle("on", !!evo && PA.state === "play");
  if (evo) {
    const c = $("ga-ab-c").getContext("2d"), pal = EVO_PAL[evo];
    c.clearRect(0, 0, 116, 116);
    c.fillStyle = "rgba(6,9,22,.8)"; c.beginPath(); c.arc(58, 58, 54, 0, TAU); c.fill();
    let ready = 1;
    if (EVO_ACTIVE[evo] && st) {
      const total = evo === 3 ? T.EEL_CD : evo === 4 ? T.SPLIT_CD : T.COMET_CD;
      ready = Math.max(0, Math.min(1, 1 - (st[4] - t) / total));
    }
    c.strokeStyle = pal[0]; c.lineWidth = 8; c.globalAlpha = ready >= 1 ? 1 : 0.6;
    c.beginPath(); c.arc(58, 58, 48, -Math.PI / 2, -Math.PI / 2 + ready * TAU); c.stroke();
    c.globalAlpha = 1;
    c.fillStyle = ready >= 1 ? pal[0] : "#8b93b8"; c.font = "800 40px Manrope, sans-serif"; c.textAlign = "center"; c.textBaseline = "middle";
    c.fillText(EVO_GLYPH[evo], 58, 56);
    ab.title = EVO_NAMES[evo] + (EVO_ACTIVE[evo] ? " · double-tap boost" : "");
  }
}
 
let miniT = 0;
function drawMini(now) {
  if (now - miniT < 120) return; miniT = now;
  const c = mini, R = 130, k = (R - 6) / W.worldR;
  c.clearRect(0, 0, 260, 260);
  c.save(); c.translate(130, 130);
  c.strokeStyle = "rgba(255,61,127,.6)"; c.lineWidth = 2; c.beginPath(); c.arc(0, 0, R - 4, 0, TAU); c.stroke();
  // portals and the Evolution Pellet
  c.lineWidth = 2;
  for (const p of W.portals.values()) { c.strokeStyle = "#9b7bff"; c.beginPath(); c.arc(p.x * k, p.y * k, 5, 0, TAU); c.stroke(); }
  for (const f of W.food.values()) if (f.k === PK.EVO) { c.fillStyle = "#ffffff"; c.save(); c.translate(f.x * k, f.y * k); c.rotate(Math.PI / 4); c.fillRect(-4, -4, 8, 8); c.restore(); }
  const blink = Math.sin(now / 160) > 0;
  const drawn = new Set();
  const dot = (id, x, y, m) => {
    const meta = W.meta.get(id); if (!meta) return;
    const me = id === W.me;
    if (meta.evo === 7 && !me && !blink) return; // Fireflies blink on everyone's minimap
    c.fillStyle = me ? "#ffe08a" : meta.evo ? EVO_PAL[meta.evo][0] : SKIN[meta.skin][0];
    c.globalAlpha = me ? 1 : meta.evo === 7 ? 1 : 0.6;
    const sz = me ? 7 : (meta.evo === 7 ? 4 : 0) + 2 + Math.min(6, Math.sqrt(m) / 5);
    c.beginPath(); c.arc(x * k, y * k, sz, 0, TAU); c.fill();
  };
  for (const s of W.snakes.values()) { drawn.add(s.id); dot(s.id, s.x, s.y, s.m); }
  for (const e of W.map) if (!drawn.has(e[0])) dot(e[0], e[1], e[2], e[3]);
  c.globalAlpha = 0.9; c.strokeStyle = "rgba(255,255,255,.4)"; c.lineWidth = 1.5;
  const hw = view.w / 2 / cam.z * k, hh = view.h / 2 / cam.z * k;
  c.strokeRect(cam.x * k - hw, cam.y * k - hh, hw * 2, hh * 2);
  c.restore();
}
 
PA.loop(null, render);
window.__ga = { W, q, clock, get floor() { return floorTile && { tw: floorTile.tw, th: floorTile.th }; }, get net() { return net; }, get queue() { return queue.length; }, get sim() { return net && net.sim; }, tip, get xp() { return xp; } };
setInterval(paintBoard, 1000);
showMod();
</script>
</body></html>
 

games/play/arena/sim.js · 740 lines

/* Glowline Arena — authoritative simulation.
 * Shared by the multiplayer server (Cloudflare Durable Object) and the in-browser
 * offline mode, so bots and rules behave identically in both.
 * Pure ES module: no DOM, no timers. Call step() at TICK_HZ.
 *
 * new Sim({ features: true }) turns on the 2026-10 upgrade: power pellets, portals, rare
 * evolutions and the daily modifier. Without it the rules are exactly the original game,
 * which the legacy room keeps serving to older clients.
 */
export const TICK_HZ = 20;
export const DT = 1 / TICK_HZ;
export const WORLD_R = 2600;
export const BASE_SPEED = 185;
export const BOOST_SPEED = 390;
export const START_MASS = 12;
 
export const lengthFor = (m) => 70 + Math.min(m, 600) * 2.4 + Math.max(0, m - 600) * 1.1;
export const radiusFor = (m) => 8 + Math.sqrt(m) * 0.82;
export const turnFor = (m) => 4.6 / (1 + m / 900);
export const SKINS = 12;
export const SKINS_V2 = 20;
 
/* evolutions (index = wire id, 0 = none) */
export const EVO = { VIPER: 1, CONSTRICTOR: 2, EEL: 3, SPLIT: 4, MAGNET: 5, COMET: 6, FIREFLY: 7 };
export const EVO_NAMES = ["", "Viper", "Constrictor", "Eel", "Split-tail", "Magnet", "Comet", "Firefly"];
export const EVO_ACTIVE = { 3: 1, 4: 1, 6: 1 }; // evolutions with a double-tap ability
/* pellet kinds (sent in the top bits of the food colour byte) */
export const PK = { STD: 0, SURGE: 1, WARD: 2, LENS: 3, KEY: 4, EVO: 5, BOUNTY: 6 };
 
/* all timings in ticks (20 per second) */
export const T = {
  SURGE: 80, WARD: 400, LENS: 240, PROTECT: 20, BOUNCE: 8,
  PORTAL_LIFE: 800, PORTAL_USES: 3, PORTAL_R: 60, DWELL: 7, FLARE: 8, PORTAL_CD: 400,
  EEL_TELL: 6, EEL_PHASE: 24, EEL_CD: 500, SPLIT_LIFE: 120, SPLIT_CD: 400, COMET_DASH: 7, COMET_CD: 240,
  VENOM_EVERY: 5, VENOM_LIFE: 60, SLOW: 30, EVO_PELLET_LIFE: 900
};
export const EVO_CAP = 4;
const MILESTONES = [400, 1200, 2500];
const POWER = [ // kind, share of random spawns, max on map
  [PK.SURGE, 0.006, 12], [PK.WARD, 0.003, 6], [PK.LENS, 0.003, 6], [PK.KEY, 0.002, 4]
];
 
/* daily modifiers, chosen from the UTC weekday so every room and player agrees */
export const MODIFIERS = {
  rift: { name: "Rift Night", text: "Six portals, free to use, shorter cooldown." },
  feather: { name: "Featherweight", text: "Boosting costs half as much." },
  venom: { name: "Venom Season", text: "Evolutions are three times as likely." },
  blackout: { name: "Blackout", text: "Fog cuts your view. Lens pellets are common." },
  gold: { name: "Gold Rush", text: "Food is worth double and power-ups are twice as common." }
};
const WEEK = [null, "rift", "feather", "venom", "blackout", "gold", "rift"]; // Sunday is a plain day
export function modifierFor(date) { return WEEK[(date || new Date()).getUTCDay()]; }
 
const CELL = 96;
const TAU = Math.PI * 2;
 
const BOT_NAMES = [
  "Neon Viper", "Byte Noodle", "Glowworm", "Sir Hiss", "Pixel Python", "Lumen", "Static", "Quasar",
  "Mamba Jamba", "Slinky", "Vector", "Noodle Prime", "Coil", "Zigzag", "Orbit", "Spline", "Comet Tail",
  "Hex", "Sidewinder", "Ribbon", "Photon", "Ziggy", "Tangle", "Echo", "Velvet", "Kaiju Jr", "Wiggles",
  "Starling", "Nova", "Loopdeloop", "Cobalt", "Fizz", "Marlin", "Drift", "Tinsel", "Sprocket"
];
 
function mulberry32(a) {
  return function () {
    a |= 0; a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
 
const angDiff = (a, b) => {
  let d = (b - a) % TAU;
  if (d > Math.PI) d -= TAU;
  if (d < -Math.PI) d += TAU;
  return d;
};
const cellKey = (cx, cy) => ((cx + 2048) << 12) | (cy + 2048);
const r1 = (v) => Math.round(v * 10) / 10;
 
export class Sim {
  constructor(opts = {}) {
    this.rand = mulberry32(opts.seed || (Date.now() & 0xffffffff));
    this.F = !!opts.features;
    this.skins = opts.skins || (this.F ? SKINS_V2 : SKINS);
    this.worldR = opts.worldR || WORLD_R;
    this.botTarget = opts.bots == null ? 14 : opts.bots;
    this.maxSnakes = opts.maxSnakes || 40;
    this.tick = 0;
    this.snakes = new Map();
    this.nextSnake = 1;
    this.food = new Map();
    this.foodGrid = new Map();
    this.nextFood = 1;
    this.usedNames = new Set();
    // upgrade state
    this.fixedMod = opts.modifier !== undefined;
    this.mod = this.F ? (this.fixedMod ? opts.modifier || null : modifierFor()) : null;
    this.pcount = [0, 0, 0, 0, 0, 0, 0];
    this.portals = new Map(); this.nextPortal = 1; this.portalNext = 40;
    this.decoys = new Map(); this.nextDecoy = 1;
    this.evoNext = this.F ? 600 + ((this.rand() * 1200) | 0) : 0;
    this.ev = this.blankEvents();
    for (let i = 0; i < this.foodTarget(); i++) this.spawnFood();
    this.ev = this.blankEvents();
    for (let i = 0; i < this.botTarget; i++) this.addBot();
    this.ev = this.blankEvents();
  }
 
  blankEvents() { return { tick: this.tick, heads: [], eat: [], food: [], add: [], del: [], lb: null, x: [] }; }
  foodTarget() { return Math.round(this.worldR * this.worldR * 0.000145) + this.snakes.size * 12; }
  rad(s) { return radiusFor(s.m) * (s.evo === EVO.CONSTRICTOR ? 1.35 : 1); }
  phased(s) { return s.evo === EVO.EEL && this.tick >= s.tellUntil && this.tick < s.abUntil; }
  /** a snake that can neither be hit nor hit anyone this tick */
  ghost(s) { return this.F && (s.protUntil > this.tick || this.phased(s)); }
  evolvedCount() { let n = 0; for (const s of this.snakes.values()) if (s.evo) n++; return n; }
 
  /* ---------------- food ---------------- */
  spawnFood(x, y, v, c, ttl, k = 0) {
    if (x == null) {
      const r = this.worldR * 0.97 * Math.sqrt(this.rand()), a = this.rand() * TAU;
      x = Math.cos(a) * r; y = Math.sin(a) * r;
      const q = this.rand();
      v = q < 0.012 ? 12 : q < 0.2 ? 3 : q < 0.5 ? 2 : 1;
      c = (this.rand() * 8) | 0;
      if (this.F) {
        if (this.mod === "gold") v *= 2;
        const p = this.rollPower();
        if (p) {
          const at = this.powerSpot();
          if (at) { x = at[0]; y = at[1]; v = 1; k = p; }
        }
      }
    }
    const f = { id: this.nextFood++, x: Math.round(x), y: Math.round(y), v, c, k, exp: ttl ? this.tick + ttl : 0 };
    this.food.set(f.id, f);
    if (k) this.pcount[k]++;
    const key = cellKey(Math.floor(f.x / CELL), Math.floor(f.y / CELL));
    let s = this.foodGrid.get(key);
    if (!s) this.foodGrid.set(key, (s = new Set()));
    s.add(f);
    this.ev.food.push([f.id, f.x, f.y, f.v, f.c | (k << 4)]);
    return f;
  }
  removeFood(f, eater) {
    if (!this.food.delete(f.id)) return;
    if (f.k) this.pcount[f.k]--;
    const s = this.foodGrid.get(cellKey(Math.floor(f.x / CELL), Math.floor(f.y / CELL)));
    if (s) s.delete(f);
    this.ev.eat.push([f.id, eater || 0]);
  }
  rollPower() {
    let q = this.rand();
    for (const [k, share, max] of POWER) {
      let p = share * (this.mod === "gold" ? 2 : 1) * (k === PK.LENS && this.mod === "blackout" ? 3 : 1);
      if (q < p) return this.pcount[k] < max * (this.mod === "gold" ? 2 : 1) ? k : 0;
      q -= p;
    }
    return 0;
  }
  /** somewhere away from the rim and at least `gap` from every head */
  powerSpot(gap = 300, rim = 0.9) {
    for (let i = 0; i < 8; i++) {
      const r = this.worldR * rim * Math.sqrt(this.rand()), a = this.rand() * TAU;
      const x = Math.cos(a) * r, y = Math.sin(a) * r;
      let ok = true;
      for (const s of this.snakes.values()) if ((s.x - x) ** 2 + (s.y - y) ** 2 < gap * gap) { ok = false; break; }
      if (ok) return [x, y];
    }
    return null;
  }
 
  /* ---------------- snakes ---------------- */
  pickName() {
    for (let i = 0; i < 40; i++) {
      const n = BOT_NAMES[(this.rand() * BOT_NAMES.length) | 0];
      if (!this.usedNames.has(n)) return n;
    }
    return "Bot " + ((this.rand() * 900 + 100) | 0);
  }
  spawnPoint() {
    let best = null, bestD = -1;
    for (let i = 0; i < 24; i++) {
      const r = this.worldR * 0.75 * Math.sqrt(this.rand()), a = this.rand() * TAU;
      const x = Math.cos(a) * r, y = Math.sin(a) * r;
      let d = 1e9;
      for (const s of this.snakes.values()) {
        const p = s.pts;
        for (let j = p.length - 2; j >= 0; j -= 8) {
          const dx = p[j] - x, dy = p[j + 1] - y, dd = dx * dx + dy * dy;
          if (dd < d) d = dd;
        }
      }
      if (d > bestD) { bestD = d; best = [x, y, a + Math.PI + (this.rand() - 0.5)]; }
      if (d > 600 * 600) break;
    }
    return best;
  }
  createSnake(name, skin, bot, cos) {
    const [x, y, a] = this.spawnPoint();
    const n = this.skins;
    const s = {
      id: this.nextSnake++, name: String(name || "Player").slice(0, 16), skin: ((skin | 0) % n + n) % n,
      bot: !!bot, x, y, a, want: a, boost: false, m: START_MASS, peak: START_MASS, kills: 0,
      born: this.tick, pts: [], dropAcc: 0, ai: bot ? { skill: 0.35 + this.rand() * 0.6, think: 0, target: null, mode: "roam", boldness: this.rand() } : null
    };
    if (this.F) {
      Object.assign(s, {
        evo: 0, rolled: 0, cdUntil: 0, abUntil: 0, tellUntil: 0, surgeUntil: 0, wardUntil: 0, lensUntil: 0, key: 0,
        protUntil: this.tick + T.PROTECT, slowUntil: 0, portCd: 0, dwell: 0, tp: null, venom: [], venomAcc: 0, pN: 0, pLast: -99,
        cos: Array.isArray(cos) ? cos.slice(0, 3).map((v) => Math.max(0, Math.min(15, v | 0))) : [0, 0, 0]
      });
    }
    // lay the initial body out behind the head
    const L = lengthFor(s.m), step = BASE_SPEED * DT;
    for (let d = L; d >= 0; d -= step) s.pts.push(x - Math.cos(a) * d, y - Math.sin(a) * d);
    this.snakes.set(s.id, s);
    this.usedNames.add(s.name);
    this.ev.add.push(this.describe(s));
    return s;
  }
  meta(s) {
    const d = { id: s.id, name: s.name, skin: s.skin, bot: s.bot };
    if (this.F) { d.evo = s.evo; d.cos = s.cos; }
    return d;
  }
  describe(s) {
    const d = this.meta(s);
    d.m = Math.round(s.m); d.a = +s.a.toFixed(3); d.pts = s.pts.map(r1);
    return d;
  }
  addBot() { return this.createSnake(this.pickName(), (this.rand() * SKINS) | 0, true); }
  addPlayer(name, skin, cos) {
    // make room: retire a bot if the arena is crowded
    if (this.snakes.size >= this.maxSnakes) {
      for (const s of this.snakes.values()) if (s.bot) { this.kill(s, 0, "retired", false); break; }
    }
    return this.createSnake(name, skin, false, cos).id;
  }
  removePlayer(id) {
    const s = this.snakes.get(id);
    if (s) this.kill(s, 0, "left", true);
  }
  setInput(id, angle, boost) {
    const s = this.snakes.get(id);
    if (!s || s.bot) return;
    if (Number.isFinite(angle)) s.want = angle;
    s.boost = !!boost;
  }
  humans() { let n = 0; for (const s of this.snakes.values()) if (!s.bot) n++; return n; }
 
  kill(s, killerId, cause, drop = true) {
    if (!this.snakes.has(s.id)) return;
    let leader = false;
    if (this.F && drop && killerId && s.m >= 100) {
      leader = true;
      for (const o of this.snakes.values()) if (o.m > s.m) { leader = false; break; }
    }
    this.snakes.delete(s.id);
    this.usedNames.delete(s.name);
    if (drop) {
      // scatter the body as food, worth ~70% of the snake's mass
      const p = s.pts, n = p.length / 2;
      let budget = Math.max(6, s.m * 0.7);
      const stride = Math.max(1, Math.floor(n / Math.min(120, Math.ceil(budget / 2))));
      for (let i = n - 1; i >= 0 && budget > 0; i -= stride) {
        const v = Math.min(10, Math.max(1, Math.round(budget / Math.ceil(i / stride + 1))));
        const r = radiusFor(s.m);
        this.spawnFood(p[i * 2] + (this.rand() - 0.5) * r * 1.6, p[i * 2 + 1] + (this.rand() - 0.5) * r * 1.6, v, s.skin % 8, TICK_HZ * 50);
        budget -= v;
      }
      if (leader) this.spawnFood(s.x, s.y, 25, 2, TICK_HZ * 60, PK.BOUNTY);
    }
    const killer = killerId ? this.snakes.get(killerId) : null;
    if (killer) killer.kills++;
    const d = [s.id, killerId || 0, cause, Math.round(s.peak), s.kills, this.tick - s.born];
    if (this.F) d.push(leader ? 1 : 0, s.evo || 0);
    this.ev.del.push(d);
  }
 
  /* ---------------- evolutions and abilities ---------------- */
  evolve(s) {
    const count = [0, 0, 0, 0, 0, 0, 0, 0];
    for (const o of this.snakes.values()) if (o.evo) count[o.evo]++;
    const low = Math.min(...count.slice(1));
    const pool = [];
    for (let t = 1; t <= 7; t++) if (count[t] === low) pool.push(t);
    s.evo = pool[(this.rand() * pool.length) | 0];
    s.cdUntil = this.tick + 40;
    this.ev.x.push(["evo", s.id, s.evo]);
  }
  checkMilestones(s) {
    while (s.rolled < MILESTONES.length && s.peak >= MILESTONES[s.rolled]) {
      s.rolled++;
      if (s.evo || this.evolvedCount() >= EVO_CAP) continue;
      const chance = 0.08 * (this.mod === "venom" ? 3 : 1) * (s.bot ? 0.5 : 1);
      if (this.rand() < chance) this.evolve(s);
    }
  }
  useAbility(id) {
    const s = typeof id === "object" ? id : this.snakes.get(id);
    if (!this.F || !s || !EVO_ACTIVE[s.evo] || this.tick < s.cdUntil || s.tp) return false;
    const t = this.tick;
    if (s.evo === EVO.EEL) {
      s.tellUntil = t + T.EEL_TELL; s.abUntil = t + T.EEL_TELL + T.EEL_PHASE; s.cdUntil = t + T.EEL_CD;
    } else if (s.evo === EVO.COMET) {
      if (s.m < 30) return false;
      s.m -= s.m * 0.06; s.abUntil = t + T.COMET_DASH; s.cdUntil = t + T.COMET_CD;
    } else if (s.evo === EVO.SPLIT) {
      if (s.m < 40) return false;
      // walk from the tail until 15% of the body length is covered
      const L = lengthFor(s.m) * 0.15, p = s.pts;
      let acc = 0, j = 2;
      for (; j < p.length - 2 && acc < L; j += 2) acc += Math.hypot(p[j] - p[j - 2], p[j + 1] - p[j - 1]);
      const pts = p.slice(0, j);
      if (pts.length < 6) return false;
      const shed = s.m * 0.15;
      s.m -= shed;
      p.splice(0, j - 2);
      const d = { id: this.nextDecoy++, owner: s.id, skin: s.skin, r: radiusFor(s.m), m: shed, pts, exp: t + T.SPLIT_LIFE };
      this.decoys.set(d.id, d);
      s.cdUntil = t + T.SPLIT_CD;
      this.ev.x.push(["dec", d.id, s.id, s.skin, r1(d.r), pts.map(r1)]);
    }
    this.ev.x.push(["ab", s.id, s.evo]);
    return true;
  }
  updateDecoys() {
    for (const d of this.decoys.values()) {
      if (d.exp > this.tick) continue;
      this.decoys.delete(d.id);
      let budget = d.m * 0.5;
      const n = d.pts.length / 2, stride = Math.max(1, Math.floor(n / Math.max(1, Math.ceil(budget / 2))));
      for (let i = 0; i < n && budget > 0; i += stride) {
        const v = Math.max(1, Math.min(6, Math.round(budget / Math.max(1, (n - i) / stride))));
        this.spawnFood(d.pts[i * 2], d.pts[i * 2 + 1], v, d.skin % 8, TICK_HZ * 40);
        budget -= v;
      }
      this.ev.x.push(["decx", d.id]);
    }
  }
 
  /* ---------------- portals ---------------- */
  portalTarget() { return this.mod === "rift" ? 6 : 2 + (this.tick % 2400 < 1200 ? 1 : 0); }
  updatePortals() {
    for (const p of this.portals.values()) {
      if (p.exp <= this.tick || p.uses <= 0) {
        this.portals.delete(p.id);
        this.ev.x.push(["pox", p.id]);
        this.portalNext = Math.max(this.portalNext, this.tick + 200 + ((this.rand() * 200) | 0));
      }
    }
    if (this.portals.size < this.portalTarget() && this.tick >= this.portalNext) {
      for (let i = 0; i < 10; i++) {
        const at = this.powerSpot(300, 0.82);
        if (!at) continue;
        let ok = true;
        for (const o of this.portals.values()) if ((o.x - at[0]) ** 2 + (o.y - at[1]) ** 2 < 900 * 900) { ok = false; break; }
        if (!ok) continue;
        const p = { id: this.nextPortal++, x: Math.round(at[0]), y: Math.round(at[1]), uses: T.PORTAL_USES, exp: this.tick + T.PORTAL_LIFE };
        this.portals.set(p.id, p);
        this.ev.x.push(["po", p.id, p.x, p.y, p.uses, p.exp]);
        break;
      }
      this.portalNext = this.tick + (this.mod === "rift" ? 20 : 60);
    }
  }
  enclosed(s) {
    let hits = 0;
    const r = this.rad(s);
    for (let k = 0; k < 8; k++) {
      const a = (k / 8) * TAU, ca = Math.cos(a), sa = Math.sin(a);
      let hit = false;
      for (let d = 50; d <= 400 && !hit; d += 50) {
        const x = s.x + ca * d, y = s.y + sa * d;
        if (Math.hypot(x, y) > this.worldR) { hit = true; break; }
        this.nearBodies(x, y, 40, (px, py, pr, sid) => {
          if (sid === s.id) return true;
          if ((px - x) ** 2 + (py - y) ** 2 < (pr + r) ** 2) { hit = true; return false; }
          return true;
        });
      }
      if (hit) hits++;
    }
    return hits >= 6;
  }
  landing(s) {
    const L = lengthFor(s.m), reach = this.worldR - (L / 2 + 300);
    if (reach < 150) return null;
    for (let i = 0; i < 24; i++) {
      const r = reach * Math.sqrt(this.rand()), a = this.rand() * TAU;
      const x = Math.cos(a) * r, y = Math.sin(a) * r;
      let ok = true;
      for (const o of this.snakes.values()) if (o !== s && (o.x - x) ** 2 + (o.y - y) ** 2 < 700 * 700) { ok = false; break; }
      if (!ok) continue;
      for (const p of this.portals.values()) if ((p.x - x) ** 2 + (p.y - y) ** 2 < 400 * 400) { ok = false; break; }
      if (!ok) continue;
      this.nearBodies(x, y, CELL * 1.5, (px, py, pr, sid) => { if (sid !== s.id) { ok = false; return false; } return true; });
      if (ok) return [x, y];
    }
    return null;
  }
  updatePortalUse(s, boosting) {
    const t = this.tick;
    if (s.tp) {
      if (t >= s.tp.at) {
        const dx = s.tp.x - s.x, dy = s.tp.y - s.y, p = s.pts;
        for (let i = 0; i < p.length; i += 2) { p[i] += dx; p[i + 1] += dy; }
        s.x += dx; s.y += dy; s.tp = null; s.protUntil = t + T.PROTECT;
        this.ev.x.push(["tp", s.id, Math.round(dx), Math.round(dy)]);
      }
      return;
    }
    if (s.bot || t < s.portCd || boosting || this.phased(s) || (s.evo === EVO.COMET && t < s.abUntil)) { s.dwell = 0; return; }
    let portal = null;
    for (const p of this.portals.values()) if ((p.x - s.x) ** 2 + (p.y - s.y) ** 2 < T.PORTAL_R * T.PORTAL_R) { portal = p; break; }
    if (!portal) { s.dwell = 0; return; }
    if (++s.dwell < T.DWELL) return;
    s.dwell = 0;
    if (this.enclosed(s)) { s.portCd = t + 40; this.ev.x.push(["pr", s.id]); return; }
    const dest = this.landing(s);
    if (!dest) { s.portCd = t + 20; this.ev.x.push(["pz", portal.id, s.id]); return; }
    if (s.key) s.key = 0;
    else if (this.mod !== "rift") s.m = Math.max(START_MASS, s.m - Math.max(5, s.m * 0.05) * (s.evo === EVO.CONSTRICTOR ? 1.5 : 1));
    portal.uses--;
    s.portCd = t + (this.mod === "rift" ? 200 : T.PORTAL_CD);
    s.tp = { at: t + T.FLARE, x: dest[0], y: dest[1] };
    this.ev.x.push(["pf", s.id, Math.round(dest[0]), Math.round(dest[1]), portal.id, portal.uses]);
  }
 
  /* ---------------- spatial index of bodies (rebuilt each tick) ---------------- */
  buildBodyGrid() {
    const g = new Map();
    const put = (x, y, r, id) => {
      const k = cellKey(Math.floor(x / CELL), Math.floor(y / CELL));
      let a = g.get(k);
      if (!a) g.set(k, (a = []));
      a.push(x, y, r, id);
    };
    for (const s of this.snakes.values()) {
      if (this.ghost(s)) continue;
      const p = s.pts, r = this.F ? this.rad(s) : radiusFor(s.m);
      for (let i = 0; i < p.length; i += 2) put(p[i], p[i + 1], r, s.id);
    }
    for (const d of this.decoys.values()) for (let i = 0; i < d.pts.length; i += 2) put(d.pts[i], d.pts[i + 1], d.r, -d.id);
    this.bodyGrid = g;
  }
  /** visit body points near (x,y) within radius rad. cb(px,py,pr,sid) — decoys have negative ids */
  nearBodies(x, y, rad, cb) {
    const c0 = Math.floor((x - rad) / CELL), c1 = Math.floor((x + rad) / CELL);
    const r0 = Math.floor((y - rad) / CELL), r1 = Math.floor((y + rad) / CELL);
    for (let cx = c0; cx <= c1; cx++) for (let cy = r0; cy <= r1; cy++) {
      const a = this.bodyGrid.get(cellKey(cx, cy));
      if (!a) continue;
      for (let i = 0; i < a.length; i += 4) if (cb(a[i], a[i + 1], a[i + 2], a[i + 3]) === false) return;
    }
  }
 
  /* ---------------- bots ---------------- */
  clearance(s, ang, dist) {
    // how far can we travel along ang before something solid? (0..dist)
    const r = radiusFor(s.m);
    const steps = 6;
    for (let i = 1; i <= steps; i++) {
      const d = (dist * i) / steps;
      const x = s.x + Math.cos(ang) * d, y = s.y + Math.sin(ang) * d;
      if (Math.hypot(x, y) > this.worldR - r - 20) return d - dist / steps;
      let hit = false;
      this.nearBodies(x, y, r + 40, (px, py, pr, sid) => {
        if (sid === s.id) return true;
        const dx = px - x, dy = py - y;
        if (dx * dx + dy * dy < (pr + r + 12) * (pr + r + 12)) { hit = true; return false; }
        return true;
      });
      if (hit) return d - dist / steps;
    }
    return dist;
  }
  thinkBot(s) {
    const ai = s.ai;
    if (--ai.think > 0) return;
    ai.think = 2 + ((1 - ai.skill) * 4) | 0;
    const r = radiusFor(s.m);
    const look = 120 + r * 5 + ai.skill * 140;
 
    // 1) pick a goal direction
    let goal = s.want;
    let boost = false;
    // hunting: cut in front of a smaller nearby snake
    let prey = null, preyD = 1e9;
    if (s.m > 40 && ai.boldness > 0.35) {
      for (const o of this.snakes.values()) {
        if (o === s || o.m > s.m * 0.9) continue;
        const d = Math.hypot(o.x - s.x, o.y - s.y);
        if (d < 380 && d < preyD) { prey = o; preyD = d; }
      }
    }
    if (prey) {
      const lead = 60 + preyD * 0.5;
      const tx = prey.x + Math.cos(prey.a) * lead, ty = prey.y + Math.sin(prey.a) * lead;
      goal = Math.atan2(ty - s.y, tx - s.x);
      boost = s.m > 30 && preyD < 260 && ai.skill > 0.5;
      ai.mode = "hunt";
    } else {
      // best food within reach, value/distance scoring on a few nearby cells
      let best = null, bestScore = 0;
      const rad = 420;
      const c0 = Math.floor((s.x - rad) / CELL), c1 = Math.floor((s.x + rad) / CELL);
      const r0 = Math.floor((s.y - rad) / CELL), r1 = Math.floor((s.y + rad) / CELL);
      for (let cx = c0; cx <= c1; cx++) for (let cy = r0; cy <= r1; cy++) {
        const set = this.foodGrid.get(cellKey(cx, cy));
        if (!set) continue;
        for (const f of set) {
          if (f.k === PK.EVO) continue; // the Evolution Pellet is a player story
          const dx = f.x - s.x, dy = f.y - s.y, d = Math.sqrt(dx * dx + dy * dy) + 30;
          const facing = Math.cos(angDiff(s.a, Math.atan2(dy, dx)));
          const sc = (f.v * (1.4 + facing)) / d;
          if (sc > bestScore) { bestScore = sc; best = f; }
        }
      }
      if (best) {
        goal = Math.atan2(best.y - s.y, best.x - s.x);
        boost = best.v >= 8 && s.m > 25 && ai.skill > 0.55;
        ai.mode = "feed";
      } else {
        // drift toward the middle-ish
        if (this.rand() < 0.08) ai.wander = (this.rand() - 0.5) * 2;
        goal = Math.atan2(-s.y, -s.x) + (ai.wander || 0);
        ai.mode = "roam";
      }
    }
 
    // 2) avoid danger: sample fan of headings, prefer clear + close to goal
    const fan = [0, -0.35, 0.35, -0.7, 0.7, -1.1, 1.1, -1.6, 1.6, -2.2, 2.2];
    const straight = this.clearance(s, s.a, look);
    if (straight < look * 0.98 || Math.abs(angDiff(s.a, goal)) > 0.2) {
      let bestA = goal, bestV = -1e9;
      for (const off of fan) {
        const a = s.a + off;
        const c = this.clearance(s, a, look);
        const v = c / look * 3 - Math.abs(angDiff(a, goal)) * 0.55 * (c >= look * 0.98 ? 1 : 0.4);
        if (v > bestV) { bestV = v; bestA = a; }
      }
      // slower bots react late
      if (this.rand() < 0.25 + ai.skill * 0.75) goal = bestA;
      if (straight < look * 0.4 && s.m > 30 && ai.skill > 0.6) boost = this.rand() < 0.5;
    }
    s.want = goal;
    s.boost = boost;
 
    // 3) evolved bots use their ability at readable moments
    if (this.F && EVO_ACTIVE[s.evo] && this.tick >= s.cdUntil) {
      if (s.evo === EVO.COMET && prey && preyD < 240 && Math.abs(angDiff(s.a, goal)) < 0.25) this.useAbility(s);
      else if (s.evo === EVO.EEL && straight < look * 0.3 && this.rand() < 0.5) this.useAbility(s);
      else if (s.evo === EVO.SPLIT && straight < look * 0.35 && s.m > 80 && this.rand() < 0.3) this.useAbility(s);
    }
  }
 
  /* ---------------- step ---------------- */
  step() {
    // events raised between ticks (joins, leaves) are already in this.ev
    this.tick++;
    this.ev.tick = this.tick;
    const F = this.F, t = this.tick;
    if (F && !this.fixedMod && t % 1200 === 0) {
      const m = modifierFor();
      if (m !== this.mod) { this.mod = m; this.ev.x.push(["mod", m]); }
    }
    this.buildBodyGrid();
 
    for (const s of this.snakes.values()) if (s.bot) this.thinkBot(s);
 
    // movement
    for (const s of this.snakes.values()) {
      const surge = F && s.surgeUntil > t;
      const dashing = F && s.evo === EVO.COMET && s.abUntil > t;
      const boosting = (s.boost && (surge || s.m > START_MASS + 2)) || dashing;
      let turn = turnFor(s.m) * DT * (boosting ? 0.8 : 1);
      if (F) turn *= (s.evo === EVO.CONSTRICTOR ? 0.8 : 1) * (dashing ? 0.25 : 1);
      const d = angDiff(s.a, s.want);
      s.a += Math.max(-turn, Math.min(turn, d));
      if (s.a > Math.PI) s.a -= TAU; else if (s.a < -Math.PI) s.a += TAU;
      let sp = dashing ? BOOST_SPEED * 2.2 : boosting ? BOOST_SPEED : BASE_SPEED;
      if (F && s.slowUntil > t) sp *= 0.7;
      s.x += Math.cos(s.a) * sp * DT;
      s.y += Math.sin(s.a) * sp * DT;
      s.boosting = boosting;
      if (boosting && !surge && !dashing) {
        let loss = Math.max(2.2, s.m * 0.012) * DT * 2.2;
        if (F) loss *= (s.evo === EVO.VIPER ? 1.25 : s.evo === EVO.CONSTRICTOR ? 1.3 : 1) * (this.mod === "feather" ? 0.5 : 1);
        s.m -= loss;
        s.dropAcc += loss;
        if (s.dropAcc >= 2) {
          s.dropAcc -= 2;
          this.spawnFood(s.pts[0] + (this.rand() - 0.5) * 8, s.pts[1] + (this.rand() - 0.5) * 8, 1, s.skin % 8, TICK_HZ * 40);
        }
      }
      if (F && s.evo === EVO.VIPER) {
        if (boosting && ++s.venomAcc >= T.VENOM_EVERY) { s.venomAcc = 0; s.venom.push([s.pts[s.pts.length - 2], s.pts[s.pts.length - 1], t + T.VENOM_LIFE]); }
        while (s.venom.length && s.venom[0][2] <= t) s.venom.shift();
      }
      // grow the trail and trim to length
      s.pts.push(s.x, s.y);
      const L = lengthFor(s.m);
      let acc = 0, cut = 0;
      for (let i = s.pts.length - 2; i >= 2; i -= 2) {
        acc += Math.hypot(s.pts[i] - s.pts[i - 2], s.pts[i + 1] - s.pts[i - 1]);
        if (acc > L) { cut = i - 2; break; }
      }
      if (cut > 0) s.pts.splice(0, cut);
      if (F) this.updatePortalUse(s, boosting);
    }
 
    // eating
    for (const s of this.snakes.values()) {
      if (F && this.phased(s)) continue;
      const r = radiusFor(s.m), reach = r + 26;
      const pull = F && s.evo === EVO.MAGNET ? 2.5 : 1, scan = reach * pull + 10;
      const c0 = Math.floor((s.x - scan) / CELL), c1 = Math.floor((s.x + scan) / CELL);
      const r0 = Math.floor((s.y - scan) / CELL), r1 = Math.floor((s.y + scan) / CELL);
      for (let cx = c0; cx <= c1; cx++) for (let cy = r0; cy <= r1; cy++) {
        const set = this.foodGrid.get(cellKey(cx, cy));
        if (!set) continue;
        for (const f of set) {
          const dx = f.x - s.x, dy = f.y - s.y, rr = reach * (f.k ? 1 : pull) + f.v * 0.8;
          if (dx * dx + dy * dy < rr * rr) {
            if (f.k && !this.eatPower(s, f)) continue;
            if (!f.k || f.k === PK.SURGE || f.k === PK.BOUNTY) s.m += f.v * 0.9;
            if (s.m > s.peak) s.peak = s.m;
            this.removeFood(f, s.id);
          }
        }
      }
      if (F) this.checkMilestones(s);
    }
 
    if (F) {
      // venom: a head touching a Viper's fresh trail is slowed and drained, 8 mass at most per contact
      for (const v of this.snakes.values()) {
        if (v.evo !== EVO.VIPER || !v.venom.length) continue;
        for (const s of this.snakes.values()) {
          if (s === v || this.phased(s) || s.protUntil > t) continue;
          const rr = radiusFor(s.m) + 12;
          for (const p of v.venom) {
            if ((p[0] - s.x) ** 2 + (p[1] - s.y) ** 2 < rr * rr) {
              if (t - s.pLast > 20) s.pN = 0;
              s.pLast = t; s.slowUntil = t + T.SLOW;
              if (t % 5 === 0 && s.pN < 8 && s.m > START_MASS + 1) { s.m -= 1; s.pN++; }
              break;
            }
          }
        }
      }
      this.updateDecoys();
    }
 
    // collisions (against the body grid built at the start of the tick, plus fresh heads)
    this.buildBodyGrid();
    const dead = [];
    for (const s of this.snakes.values()) {
      const r = radiusFor(s.m);
      if (F && s.protUntil > t) continue;
      if (Math.hypot(s.x, s.y) > this.worldR - r * 0.5) { dead.push([s, 0, "wall"]); continue; }
      if (F && this.phased(s)) continue;
      let killer = 0, hx = 0, hy = 0;
      this.nearBodies(s.x, s.y, r + 60, (px, py, pr, sid) => {
        if (sid === s.id) return true;
        const dx = px - s.x, dy = py - s.y, rr = pr + r * 0.72;
        if (dx * dx + dy * dy < rr * rr) { killer = sid; hx = px; hy = py; return false; }
        return true;
      });
      if (!killer) continue;
      if (F && s.wardUntil > t) {
        // the Ward turns a fatal touch into a bounce
        s.wardUntil = 0;
        s.a = Math.atan2(s.y - hy, s.x - hx); s.want = s.a;
        s.protUntil = t + T.BOUNCE;
        this.ev.x.push(["ward", s.id]);
        continue;
      }
      if (killer < 0) dead.push([s, 0, "decoy"]);
      else dead.push([s, killer, "cut"]);
    }
    // head-on: when two heads die into each other, the bigger one survives
    const deadIds = new Set(dead.map((d) => d[0].id));
    for (const [s, killer, cause] of dead) {
      if (cause === "cut" && deadIds.has(killer)) {
        const o = this.snakes.get(killer);
        if (o && Math.hypot(o.x - s.x, o.y - s.y) < radiusFor(o.m) + radiusFor(s.m) && o.m < s.m) continue;
      }
      this.kill(s, killer, cause, true);
    }
 
    // food upkeep: expire old drops, top up the field
    if (this.tick % 10 === 0) {
      for (const f of this.food.values()) if (f.exp && f.exp < this.tick) this.removeFood(f, 0);
    }
    let need = this.foodTarget() - this.food.size;
    for (let i = 0; i < Math.min(need, 25); i++) this.spawnFood();
 
    if (F) {
      this.updatePortals();
      // the Evolution Pellet: one at a time, every 90-150 s (half that in Venom Season)
      if (t >= this.evoNext && !this.pcount[PK.EVO]) {
        const at = this.evolvedCount() < EVO_CAP ? this.powerSpot(400, 0.8) : null;
        if (at) {
          this.spawnFood(at[0], at[1], 1, 7, T.EVO_PELLET_LIFE, PK.EVO);
          const gap = 1800 + ((this.rand() * 1200) | 0);
          this.evoNext = t + (this.mod === "venom" ? gap / 2 : gap);
        } else this.evoNext = t + 200;
      }
    }
 
    // keep the arena lively
    if (this.tick % 20 === 0) {
      const humans = this.humans();
      const wantBots = Math.max(0, Math.min(this.botTarget, this.maxSnakes - humans) - (humans > 8 ? humans - 8 : 0));
      let bots = this.snakes.size - humans;
      if (bots < wantBots) this.addBot();
      else if (bots > wantBots + 1) {
        for (const s of this.snakes.values()) if (s.bot && s.m < 40) { this.kill(s, 0, "retired", false); break; }
      }
    }
 
    for (const s of this.snakes.values()) this.ev.heads.push([s.id, s.x, s.y, s.a, s.m, F ? this.flags(s) : s.boosting ? 1 : 0]);
    if (this.tick % 10 === 0) {
      this.ev.lb = [...this.snakes.values()].sort((a, b) => b.m - a.m).slice(0, 10).map((s) => [s.id, Math.round(s.m)]);
    }
    const out = this.ev;
    this.ev = this.blankEvents();
    return out;
  }
  eatPower(s, f) {
    const t = this.tick;
    switch (f.k) {
      case PK.SURGE: s.surgeUntil = t + T.SURGE; break;
      case PK.WARD: s.wardUntil = t + T.WARD; break;
      case PK.LENS: s.lensUntil = t + T.LENS; break;
      case PK.KEY: if (s.key) return false; s.key = 1; break;
      case PK.EVO:
        if (s.bot) return false;
        if (s.evo || this.evolvedCount() >= EVO_CAP) s.m += 40; else this.evolve(s);
        break;
    }
    this.ev.x.push(["pu", s.id, f.k]);
    return true;
  }
  /* bit0 boost · bit1 ward · bit2 ability active · bit3 surge · bits4-6 evolution · bit7 arrival protection */
  flags(s) {
    const t = this.tick;
    return (s.boosting ? 1 : 0) | (s.wardUntil > t ? 2 : 0) | (this.phased(s) || (s.evo === EVO.COMET && s.abUntil > t) ? 4 : 0) |
      (s.surgeUntil > t ? 8 : 0) | ((s.evo & 7) << 4) | (s.protUntil > t ? 128 : 0);
  }
  /** what only the owner needs: power-up timers, key, ability cooldown, portal cooldown (absolute ticks) */
  status(s) { return [s.surgeUntil, s.wardUntil, s.lensUntil, s.key, s.cdUntil, s.slowUntil, s.portCd, s.evo]; }
 
  snapshot(lite) {
    const out = {
      tick: this.tick, worldR: this.worldR,
      snakes: [...this.snakes.values()].map((s) => (lite ? this.meta(s) : this.describe(s))),
      food: [...this.food.values()].map((f) => [f.id, f.x, f.y, f.v, f.c | (f.k << 4)])
    };
    if (this.F) {
      out.v = 2; out.mod = this.mod;
      out.portals = [...this.portals.values()].map((p) => [p.id, p.x, p.y, p.uses, p.exp]);
      out.decoys = [...this.decoys.values()].map((d) => [d.id, d.owner, d.skin, r1(d.r), d.pts.map(r1), d.exp]);
    }
    return out;
  }
}
 

games/play/arena/proto.js · 158 lines

/* Glowline Arena wire format. One binary frame per server tick; rare events ride along as JSON.
 * v1 (legacy room, everyone gets everything):
 * frame: u8 kind(1) | u32 tick | u16 nHeads × [u16 id, f32 x, f32 y, i16 angle*1e4, f32 mass, u8 flags]
 *        | u16 nEat × [u32 food, u16 eater] | u16 nFood × [u32 id, i16 x, i16 y, u8 value, u8 color]
 *        | u32 jsonBytes | utf8 JSON {add, del, lb}
 * v2 (upgrade room, each player gets only the snakes near them):
 * frame: u8 kind(2) | u32 tick | u16 nHeads × [u16 id, i16 x*8, i16 y*8, i16 angle*1e4, u16 mass*2, u8 flags]
 *        | eat and food as v1 | u32 jsonBytes | utf8 JSON {add, enter, leave, del, lb, map, x, me}
 *   add   = metadata of new snakes (everyone), enter = full bodies of snakes coming into view,
 *   leave = ids leaving view, map = [id, x, y, mass] of every snake for the minimap (every 10 ticks),
 *   x = rare events (evolutions, portals, abilities…), me = the owner's own timers when they change.
 */
const enc = new TextEncoder();
const dec = new TextDecoder();
 
export function encodeFrame(ev) {
  const extra = {};
  if (ev.add.length) extra.add = ev.add;
  if (ev.del.length) extra.del = ev.del;
  if (ev.lb) extra.lb = ev.lb;
  const js = Object.keys(extra).length ? enc.encode(JSON.stringify(extra)) : new Uint8Array(0);
  const size = 1 + 4 + 2 + ev.heads.length * 17 + 2 + ev.eat.length * 6 + 2 + ev.food.length * 10 + 4 + js.length;
  const buf = new ArrayBuffer(size);
  const v = new DataView(buf);
  let o = 0;
  v.setUint8(o, 1); o += 1;
  v.setUint32(o, ev.tick); o += 4;
  v.setUint16(o, ev.heads.length); o += 2;
  for (const h of ev.heads) {
    v.setUint16(o, h[0]); v.setFloat32(o + 2, h[1]); v.setFloat32(o + 6, h[2]);
    v.setInt16(o + 10, Math.round(h[3] * 10000)); v.setFloat32(o + 12, h[4]); v.setUint8(o + 16, h[5]);
    o += 17;
  }
  v.setUint16(o, ev.eat.length); o += 2;
  for (const e of ev.eat) { v.setUint32(o, e[0]); v.setUint16(o + 4, e[1]); o += 6; }
  v.setUint16(o, ev.food.length); o += 2;
  for (const f of ev.food) {
    v.setUint32(o, f[0]); v.setInt16(o + 4, f[1]); v.setInt16(o + 6, f[2]); v.setUint8(o + 8, f[3]); v.setUint8(o + 9, f[4]);
    o += 10;
  }
  v.setUint32(o, js.length); o += 4;
  new Uint8Array(buf, o, js.length).set(js);
  return buf;
}
 
export function decodeFrame(buf) {
  const v = new DataView(buf);
  let o = 0;
  if (v.getUint8(o) !== 1) return null;
  o += 1;
  const ev = { tick: v.getUint32(o), heads: [], eat: [], food: [], add: [], del: [], lb: null };
  o += 4;
  const nh = v.getUint16(o); o += 2;
  for (let i = 0; i < nh; i++) {
    ev.heads.push([v.getUint16(o), v.getFloat32(o + 2), v.getFloat32(o + 6), v.getInt16(o + 10) / 10000, v.getFloat32(o + 12), v.getUint8(o + 16)]);
    o += 17;
  }
  const ne = v.getUint16(o); o += 2;
  for (let i = 0; i < ne; i++) { ev.eat.push([v.getUint32(o), v.getUint16(o + 4)]); o += 6; }
  const nf = v.getUint16(o); o += 2;
  for (let i = 0; i < nf; i++) {
    ev.food.push([v.getUint32(o), v.getInt16(o + 4), v.getInt16(o + 6), v.getUint8(o + 8), v.getUint8(o + 9)]);
    o += 10;
  }
  const jl = v.getUint32(o); o += 4;
  if (jl) {
    const extra = JSON.parse(dec.decode(new Uint8Array(buf, o, jl)));
    if (extra.add) ev.add = extra.add;
    if (extra.del) ev.del = extra.del;
    if (extra.lb) ev.lb = extra.lb;
  }
  return ev;
}
 
/* ---------------- v2: interest management ---------------- */
export const VIEW_R = 1900;        // heads within this distance of you are sent…
export const VIEW_R_WIDE = 2500;   // …further while you hold a Lens or are a Firefly
const HYST = 300;                  // and they stay until they are this much further away
 
export function makeViewer() { return { known: new Set(), cx: 0, cy: 0, last: "" }; }
 
/** Build the frame one player should see from the tick's events. Pure: also used by offline play. */
export function viewFor(sim, ev, vw, meId) {
  const me = meId ? sim.snakes.get(meId) : null;
  const cx = me ? me.x : vw.cx, cy = me ? me.y : vw.cy;
  const wide = me && (me.lensUntil > sim.tick || me.evo === 7);
  const R = wide ? VIEW_R_WIDE : VIEW_R;
  const out = { tick: ev.tick, heads: [], eat: ev.eat, food: ev.food, add: [], enter: [], leave: [], del: ev.del, lb: ev.lb, map: null, x: ev.x || [], me: null };
  for (const d of ev.add) { const m = Object.assign({}, d); delete m.pts; delete m.a; out.add.push(m); }
  for (const d of ev.del) vw.known.delete(d[0]);
  for (const s of sim.snakes.values()) {
    const dd = (s.x - cx) ** 2 + (s.y - cy) ** 2;
    const known = vw.known.has(s.id);
    const lim = known ? R + HYST : R;
    if (dd < lim * lim || s.id === meId) {
      if (!known) { vw.known.add(s.id); out.enter.push(sim.describe(s)); }
    } else if (known) { vw.known.delete(s.id); out.leave.push(s.id); }
  }
  for (const h of ev.heads) if (vw.known.has(h[0])) out.heads.push(h);
  if (ev.tick % 10 === 0) {
    out.map = [];
    for (const s of sim.snakes.values()) out.map.push([s.id, Math.round(s.x), Math.round(s.y), Math.round(s.m)]);
  }
  if (me && sim.status) {
    const st = sim.status(me), key = st.join(",");
    if (key !== vw.last) { vw.last = key; out.me = st; }
  } else if (!me) vw.last = "";
  return out;
}
 
const clampI16 = (v) => Math.max(-32768, Math.min(32767, Math.round(v)));
 
export function encodeFrame2(vf) {
  const extra = {};
  for (const k of ["add", "enter", "leave", "del", "x"]) if (vf[k] && vf[k].length) extra[k] = vf[k];
  if (vf.lb) extra.lb = vf.lb;
  if (vf.map) extra.map = vf.map;
  if (vf.me) extra.me = vf.me;
  const js = Object.keys(extra).length ? enc.encode(JSON.stringify(extra)) : new Uint8Array(0);
  const size = 1 + 4 + 2 + vf.heads.length * 11 + 2 + vf.eat.length * 6 + 2 + vf.food.length * 10 + 4 + js.length;
  const buf = new ArrayBuffer(size);
  const v = new DataView(buf);
  let o = 0;
  v.setUint8(o, 2); o += 1;
  v.setUint32(o, vf.tick); o += 4;
  v.setUint16(o, vf.heads.length); o += 2;
  for (const h of vf.heads) {
    v.setUint16(o, h[0]); v.setInt16(o + 2, clampI16(h[1] * 8)); v.setInt16(o + 4, clampI16(h[2] * 8));
    v.setInt16(o + 6, Math.round(h[3] * 10000)); v.setUint16(o + 8, Math.min(65535, Math.round(h[4] * 2))); v.setUint8(o + 10, h[5]);
    o += 11;
  }
  v.setUint16(o, vf.eat.length); o += 2;
  for (const e of vf.eat) { v.setUint32(o, e[0]); v.setUint16(o + 4, e[1]); o += 6; }
  v.setUint16(o, vf.food.length); o += 2;
  for (const f of vf.food) {
    v.setUint32(o, f[0]); v.setInt16(o + 4, f[1]); v.setInt16(o + 6, f[2]); v.setUint8(o + 8, Math.min(255, f[3])); v.setUint8(o + 9, f[4]);
    o += 10;
  }
  v.setUint32(o, js.length); o += 4;
  new Uint8Array(buf, o, js.length).set(js);
  return buf;
}
 
export function decodeFrame2(buf) {
  const v = new DataView(buf);
  let o = 0;
  if (v.getUint8(o) !== 2) return null;
  o += 1;
  const vf = { tick: v.getUint32(o), heads: [], eat: [], food: [], add: [], enter: [], leave: [], del: [], lb: null, map: null, x: [], me: null };
  o += 4;
  const nh = v.getUint16(o); o += 2;
  for (let i = 0; i < nh; i++) {
    vf.heads.push([v.getUint16(o), v.getInt16(o + 2) / 8, v.getInt16(o + 4) / 8, v.getInt16(o + 6) / 10000, v.getUint16(o + 8) / 2, v.getUint8(o + 10)]);
    o += 11;
  }
  const ne = v.getUint16(o); o += 2;
  for (let i = 0; i < ne; i++) { vf.eat.push([v.getUint32(o), v.getUint16(o + 4)]); o += 6; }
  const nf = v.getUint16(o); o += 2;
  for (let i = 0; i < nf; i++) {
    vf.food.push([v.getUint32(o), v.getInt16(o + 4), v.getInt16(o + 6), v.getUint8(o + 8), v.getUint8(o + 9)]);
    o += 10;
  }
  const jl = v.getUint32(o); o += 4;
  if (jl) Object.assign(vf, JSON.parse(dec.decode(new Uint8Array(buf, o, jl))));
  return vf;
}
 

games/play/arena/room.js · 101 lines

/* Glowline Arena room: owns one Sim and a set of connections.
 * Transport-agnostic — the Durable Object and the local test server both wrap their sockets as
 * { send(stringOrArrayBuffer), close(code, reason) } and forward messages to the returned handlers.
 */
import { Sim, TICK_HZ } from "./sim.js";
import { encodeFrame, encodeFrame2, makeViewer, viewFor } from "./proto.js";
 
const MAX_HUMANS = 40;
const BLOCK = /(n[i1]gg|f[a@]gg?[o0]t|r[e3]t[a@]rd|k[i1]ke|sp[i1]c\b|ch[i1]nk|tr[a@]nn|wh[o0]re|c[u\*]nt|h[i1]tl[e3]r|n[a@]z[i1])/i;
 
/* `blocked` is the server's full name filter (functions/_shared/namemod.js regexCheck), passed in
 * by the Worker so this file, which also ships to the browser, stays free of server imports. */
export function cleanName(n, blocked) {
  n = String(n || "").replace(/[\u0000-\u001f\u007f<>]/g, "").replace(/\s+/g, " ").trim().slice(0, 16);
  if (!n || BLOCK.test(n.replace(/[\s._-]/g, "")) || (blocked && blocked(n))) return "Player";
  return n;
}
 
export class Room {
  constructor(opts = {}) {
    this.opts = opts;
    this.v2 = opts.proto === 2;
    this.sim = new Sim({ bots: opts.bots == null ? 14 : opts.bots, seed: opts.seed, features: this.v2, modifier: opts.modifier });
    this.conns = new Set();
    this.timer = null;
    this.idleTicks = 0;
  }
  humans() { let n = 0; for (const c of this.conns) if (c.snake) n++; return n; }
 
  connect(sock) {
    if (this.conns.size >= MAX_HUMANS + 10) {
      try { sock.send(JSON.stringify({ t: "full" })); sock.close(1013, "full"); } catch (e) {}
      return { message() {}, close() {} };
    }
    const c = { sock, snake: 0, msgs: 0, window: Date.now(), name: "Player", skin: 0, vw: this.v2 ? makeViewer() : null };
    this.conns.add(c);
    this.send(c, JSON.stringify({ t: "snap", snap: this.sim.snapshot(this.v2), online: this.conns.size, hz: TICK_HZ, v: this.v2 ? 2 : 1 }));
    this.ensureTicking();
    return {
      message: (data) => this.onMessage(c, data),
      close: () => this.onClose(c)
    };
  }
  send(c, data) {
    try { c.sock.send(data); } catch (e) { this.onClose(c); }
  }
  onMessage(c, data) {
    const now = Date.now();
    if (now - c.window > 1000) { c.window = now; c.msgs = 0; }
    if (++c.msgs > 40) return; // flood guard
    let m;
    try { m = JSON.parse(typeof data === "string" ? data : new TextDecoder().decode(data)); } catch (e) { return; }
    if (!m || typeof m.t !== "string") return;
    if (m.t === "join") {
      if (c.snake && this.sim.snakes.has(c.snake)) return;
      if (this.humans() >= MAX_HUMANS) { this.send(c, JSON.stringify({ t: "full" })); return; }
      c.name = cleanName(m.name, this.opts.nameBlocked);
      c.skin = (m.skin | 0) >>> 0;
      c.snake = this.sim.addPlayer(c.name, c.skin, this.v2 ? m.cos : undefined);
      this.send(c, JSON.stringify({ t: "you", id: c.snake }));
    } else if (m.t === "in") {
      if (c.snake) this.sim.setInput(c.snake, +m.a, !!m.b);
    } else if (m.t === "ab" && this.v2) {
      if (c.snake) this.sim.useAbility(c.snake);
    } else if (m.t === "cam" && this.v2) {
      if (Number.isFinite(+m.x) && Number.isFinite(+m.y)) { c.vw.cx = Math.max(-4000, Math.min(4000, +m.x)); c.vw.cy = Math.max(-4000, Math.min(4000, +m.y)); }
    } else if (m.t === "ping") {
      this.send(c, JSON.stringify({ t: "pong", c: m.c }));
    } else if (m.t === "leave") {
      if (c.snake) { this.sim.removePlayer(c.snake); c.snake = 0; }
    }
  }
  onClose(c) {
    if (!this.conns.has(c)) return;
    this.conns.delete(c);
    if (c.snake) this.sim.removePlayer(c.snake);
    c.snake = 0;
  }
  ensureTicking() {
    if (this.timer) return;
    this.timer = setInterval(() => this.tick(), 1000 / TICK_HZ);
  }
  tick() {
    if (!this.conns.size) {
      // nobody watching: stop the clock so the room can sleep
      if (++this.idleTicks > TICK_HZ * 5) { clearInterval(this.timer); this.timer = null; this.idleTicks = 0; }
      return;
    }
    this.idleTicks = 0;
    const ev = this.sim.step();
    for (const d of ev.del) {
      for (const c of this.conns) if (c.snake === d[0]) c.snake = 0;
    }
    if (this.v2) {
      for (const c of this.conns) this.send(c, encodeFrame2(viewFor(this.sim, ev, c.vw, c.snake)));
    } else {
      const frame = encodeFrame(ev);
      for (const c of this.conns) this.send(c, frame);
    }
    if (this.sim.tick % (TICK_HZ * 2) === 0) {
      const info = JSON.stringify({ t: "info", online: this.humans(), watching: this.conns.size });
      for (const c of this.conns) this.send(c, info);
    }
  }
}
 

games/play/arena/art.js · 465 lines

/* Glowline Arena — shared drawing: palettes, body strokes, pellet sprites and the animated guides.
 * The game and the guide loops both draw with strokeBody(), so a guide looks exactly like a match.
 */
const TAU = Math.PI * 2;
 
/* 12 original skins (always unlocked) + 8 unlockable ones. None reuses an evolution palette. */
export const SKIN = [
  ["#5ef2ff", "#1b6dff", "#bff9ff"], ["#ff5ca8", "#8a2be2", "#ffc2e0"], ["#ffd84d", "#ff7a1a", "#fff3b8"],
  ["#5dff9e", "#00a37a", "#c9ffe0"], ["#c77dff", "#3b1dff", "#ead4ff"], ["#ff6b6b", "#7a1030", "#ffd0d0"],
  ["#ffffff", "#5ef2ff", "#ffffff"], ["#ff9f43", "#2e1a47", "#ffd9b0"], ["#00ffd5", "#ff00a0", "#c9fff5"],
  ["#a3ff3c", "#1f5f00", "#e6ffc9"], ["#6ea8ff", "#ffffff", "#d6e5ff"], ["#ff3df2", "#00e1ff", "#ffd0fb"],
  ["#3fd0c9", "#0d2f5a", "#c8fbf6"], ["#8affc1", "#9b5cff", "#e3fff1"], ["#d6e2ff", "#2c3e8f", "#ffffff"], ["#ff8fa3", "#ffe3ea", "#fff1f4"],
  ["#4de1ff", "#ff9ef0", "#e4fbff"], ["#b9f3ff", "#5f8dff", "#ffffff"], ["#f6c1ff", "#4b2a7a", "#fff0ff"], ["#9cf0ff", "#123e3a", "#e6fffd"]
];
export const SKIN_NAMES = ["Glacier", "Orchid", "Sunrise", "Mint", "Ultraviolet", "Ruby", "Whiteout", "Dusk", "Arcade", "Lime", "Sky", "Prism",
  "Tide", "Aurora", "Frost", "Rose", "Cotton Candy", "Glass", "Lilac", "Lagoon"];
export const SKIN_XP = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000];
export const TRAILS = [["None", 0], ["Sparks", 2500], ["Petals", 5000], ["Pixels", 7500]];
export const BURSTS = [["Classic", 0], ["Firework", 4000], ["Glitch", 8000], ["Bloom", 12000]];
export const FRAMES = [["None", 0], ["Bronze", 5000], ["Silver", 15000], ["Gold", 40000], ["Neon", 100000]];
export const BOOSTS = [["Classic", 0], ["Synth whoosh", 3000], ["Chime", 6000], ["Bass drop", 9000]];
export const FRAME_COL = ["", "#d08a4a", "#cfd8e6", "#ffd84d", "#ff3df2"];
 
/* evolutions: reserved palettes + a shape cue each */
export const EVO_PAL = [null,
  ["#9dff3c", "#6a1fd1", "#e8ffc4"], // Viper: green-violet scales
  ["#d9a441", "#5a3410", "#ffe6a8"], // Constrictor: wide bands
  ["#7ff3ff", "#1a3d8f", "#e0fdff"], // Eel: ripple
  ["#ff7ad9", "#4a0f5c", "#ffd6f3"], // Split-tail: forked tail
  ["#ff4d4d", "#3d4dff", "#ffd6d6"], // Magnet: field ring
  ["#ffb347", "#ff3d00", "#fff0c2"], // Comet: flame streak
  ["#fff59a", "#3a7a1f", "#ffffe0"]  // Firefly: soft glow
];
export const EVO_GLYPH = ["", "◆", "■", "≈", "Ψ", "◎", "»", "✦"];
export const EVO_NAMES = ["", "Viper", "Constrictor", "Eel", "Split-tail", "Magnet", "Comet", "Firefly"];
export const EVO_TEXT = ["",
  "Boosting leaves a poison trail that slows and drains.",
  "A thicker body for deadly circles. Turns slower.",
  "Double-tap boost to phase through bodies for a moment.",
  "Double-tap boost to drop your tail as a decoy.",
  "Pulls food from further away. Power-ups won't come.",
  "Double-tap boost for a straight-line dash.",
  "You see further, but you blink on everyone's map."
];
export const PK_NAMES = ["", "Surge", "Ward", "Lens", "Key", "Evolution", "Bounty"];
export const PK_TEXT = ["", "Free boost for four seconds", "One free bump", "See further for a while", "Your next portal is free", "Triggers a random evolution", "The fallen leader's prize"];
export const PK_COL = ["", "#ffe14d", "#5ef2ff", "#b98cff", "#ffc94d", "#ffffff", "#ff4d6d"];
 
/** Stroke a body polyline (head first: [x0,y0,x1,y1,...]) in the game's style. */
export function strokeBody(g, path, pal, r, o = {}) {
  if (path.length < 4) return;
  const evo = o.evo || 0, t = o.t || 0;
  g.lineCap = "round"; g.lineJoin = "round";
  g.beginPath();
  if (o.smooth && path.length >= 6) smoothBody(g, path, o.head);
  else {
    g.moveTo(path[path.length - 2], path[path.length - 1]);
    for (let i = path.length - 4; i >= 0; i -= 2) g.lineTo(path[i], path[i + 1]);
  }
  const a0 = o.alpha == null ? 1 : o.alpha;
  if (o.glow !== false) {
    g.globalCompositeOperation = "lighter";
    g.strokeStyle = pal[0];
    let ga = o.boost ? 0.32 + Math.sin(t * 30) * 0.08 : 0.12;
    if (evo === 7) ga = 0.22 + Math.sin(t * 3) * 0.12;
    g.globalAlpha = ga * a0;
    g.lineWidth = r * (o.boost ? 3.4 : evo === 7 ? 3.8 : 2.8);
    g.stroke();
    g.globalCompositeOperation = "source-over";
  }
  if (o.dashed) {
    g.globalAlpha = 0.8 * a0;
    g.setLineDash([r * 0.9, r * 0.7]); g.strokeStyle = pal[0]; g.lineWidth = 2.5;
    g.lineDashOffset = -t * 40;
    // outline only: two thin strokes either side read as a hollow body
    g.lineWidth = r * 2; g.globalAlpha = 0.18 * a0; g.setLineDash([]); g.stroke();
    g.globalAlpha = 0.9 * a0; g.lineWidth = 3; g.setLineDash([r * 0.8, r * 0.6]); g.stroke();
    g.setLineDash([]); g.globalAlpha = 1;
    return;
  }
  g.globalAlpha = a0;
  g.strokeStyle = "rgba(0,0,0,.55)"; g.lineWidth = r * 2 + 3; g.stroke();
  g.strokeStyle = pal[0]; g.lineWidth = r * 2; g.stroke();
  // pattern: travelling stripes, shaped per evolution so evolved snakes read at a glance
  const off = -(o.offset || 0);
  if (evo === 1) { g.setLineDash([r * 0.55, r * 0.45]); g.lineWidth = r * 1.2; }        // scales
  else if (evo === 2) { g.setLineDash([r * 0.7, r * 1.1]); g.lineWidth = r * 2; }       // full-width bands
  else if (evo === 3) { g.setLineDash([r * 2.2, r * 0.6]); g.lineWidth = r * 0.9; }     // long ripples
  else if (evo === 7) { g.setLineDash([r * 0.35, r * 1.6]); g.lineWidth = r * 1.5; }    // spots
  else { g.setLineDash([r * 1.1, r * 1.3]); g.lineWidth = r * 1.35; }
  g.lineDashOffset = off + (evo === 3 ? Math.sin(t * 6) * r : 0);
  g.strokeStyle = pal[1]; g.globalAlpha = 0.85 * a0; g.stroke();
  g.setLineDash([]);
  g.globalAlpha = 0.5 * a0; g.strokeStyle = pal[2]; g.lineWidth = r * 0.35; g.stroke();
  g.globalAlpha = 1;
  if (evo === 4) {
    // forked tail
    const n = path.length, tx = path[n - 2], ty = path[n - 1], px = path[Math.max(0, n - 6)], py = path[Math.max(1, n - 5)];
    const a = Math.atan2(ty - py, tx - px);
    g.strokeStyle = pal[0]; g.lineWidth = r * 0.7; g.globalAlpha = a0;
    for (const s of [-0.6, 0.6]) { g.beginPath(); g.moveTo(tx, ty); g.lineTo(tx + Math.cos(a + s) * r * 2, ty + Math.sin(a + s) * r * 2); g.stroke(); }
    g.globalAlpha = 1;
  }
}
 
/* A body path (head first) traced tail to head as a smooth curve: each point's tangent points from
 * its tail-side neighbour to its head-side neighbour, and each segment's handles are a third of its
 * length, so uneven spacing (the short piece next to the moving head, boost-length steps) never
 * overshoots. `head` (optional) is the exact curve from the first body point to the head:
 * [handle1 x, y, handle2 x, y, tangent at that body point x, y]. */
function smoothBody(g, path, head) {
  const n = path.length >> 1;
  const X = (i) => path[i * 2], Y = (i) => path[i * 2 + 1];
  let qx = X(n - 1), qy = Y(n - 1);
  // tangent at the tail, pointing toward the head
  let tx = X(n - 2) - qx, ty = Y(n - 2) - qy, tl = Math.hypot(tx, ty) || 1;
  tx /= tl; ty /= tl;
  g.moveTo(qx, qy);
  for (let i = n - 1; i >= 1; i--) {
    const rx = X(i - 1), ry = Y(i - 1);
    if (i === 1 && head) { g.bezierCurveTo(head[0], head[1], head[2], head[3], rx, ry); break; }
    let ux, uy;
    if (i === 2 && head) { ux = head[4]; uy = head[5]; }
    else if (i - 1 === 0) { ux = rx - qx; uy = ry - qy; }
    else { ux = X(i - 2) - qx; uy = Y(i - 2) - qy; }
    const ul = Math.hypot(ux, uy) || 1; ux /= ul; uy /= ul;
    const k = Math.hypot(rx - qx, ry - qy) / 3;
    g.bezierCurveTo(qx + tx * k, qy + ty * k, rx - ux * k, ry - uy * k, rx, ry);
    qx = rx; qy = ry; tx = ux; ty = uy;
  }
}
 
/** Draw a head at (x,y) facing a. */
export function drawHead(g, x, y, a, r, pal, look = 0, alpha = 1) {
  g.save();
  g.translate(x, y); g.rotate(a); g.globalAlpha = alpha;
  g.fillStyle = pal[0];
  g.beginPath(); g.ellipse(r * 0.15, 0, r * 1.12, r * 1.02, 0, 0, TAU); g.fill();
  for (const side of [-1, 1]) {
    const ex = r * 0.45, ey = side * r * 0.48;
    g.fillStyle = "#fff"; g.beginPath(); g.arc(ex, ey, r * 0.38, 0, TAU); g.fill();
    g.fillStyle = "#0a0a14"; g.beginPath(); g.arc(ex + Math.cos(look) * r * 0.16, ey + Math.sin(look) * r * 0.16, r * 0.2, 0, TAU); g.fill();
  }
  g.restore();
}
 
/** One 64×64 sprite per pellet kind (index = kind), drawn once and stamped every frame. */
export function pelletSprites() {
  const out = [null];
  for (let k = 1; k <= 6; k++) {
    const s = document.createElement("canvas"); s.width = s.height = 64;
    const g = s.getContext("2d"), c = PK_COL[k];
    const gr = g.createRadialGradient(32, 32, 0, 32, 32, 32);
    gr.addColorStop(0, c + "aa"); gr.addColorStop(0.5, c + "33"); gr.addColorStop(1, c + "00");
    g.fillStyle = gr; g.fillRect(0, 0, 64, 64);
    g.translate(32, 32);
    g.strokeStyle = c; g.fillStyle = c; g.lineWidth = 3.5; g.lineJoin = "round"; g.lineCap = "round";
    if (k === 1) { // Surge: double chevron
      for (const dx of [-6, 5]) { g.beginPath(); g.moveTo(dx - 6, -10); g.lineTo(dx + 4, 0); g.lineTo(dx - 6, 10); g.stroke(); }
    } else if (k === 2) { // Ward: hexagon ring
      g.beginPath(); for (let i = 0; i < 6; i++) { const a = i * Math.PI / 3; g.lineTo(Math.cos(a) * 12, Math.sin(a) * 12); } g.closePath(); g.stroke();
      g.globalAlpha = 0.35; g.fill(); g.globalAlpha = 1;
    } else if (k === 3) { // Lens: eye
      g.beginPath(); g.moveTo(-14, 0); g.quadraticCurveTo(0, -12, 14, 0); g.quadraticCurveTo(0, 12, -14, 0); g.stroke();
      g.beginPath(); g.arc(0, 0, 4.5, 0, TAU); g.fill();
    } else if (k === 4) { // Key: keyhole
      g.beginPath(); g.arc(0, -4, 6, 0, TAU); g.fill();
      g.beginPath(); g.moveTo(-4, 0); g.lineTo(4, 0); g.lineTo(6, 11); g.lineTo(-6, 11); g.closePath(); g.fill();
    } else if (k === 5) { // Evolution: prism
      g.fillStyle = "#ffffff";
      g.beginPath(); g.moveTo(0, -16); g.lineTo(12, 0); g.lineTo(0, 16); g.lineTo(-12, 0); g.closePath(); g.fill();
      g.fillStyle = "#b98cff"; g.globalAlpha = 0.6; g.beginPath(); g.moveTo(0, -16); g.lineTo(12, 0); g.lineTo(0, 0); g.closePath(); g.fill();
      g.fillStyle = "#5ef2ff"; g.beginPath(); g.moveTo(0, 16); g.lineTo(-12, 0); g.lineTo(0, 0); g.closePath(); g.fill(); g.globalAlpha = 1;
    } else if (k === 6) { // Bounty: star cluster
      const star = (cx, cy, R) => { g.beginPath(); for (let i = 0; i < 10; i++) { const a = -Math.PI / 2 + i * Math.PI / 5, rr = i % 2 ? R * 0.45 : R; g.lineTo(cx + Math.cos(a) * rr, cy + Math.sin(a) * rr); } g.closePath(); g.fill(); };
      star(0, -2, 12); star(-11, 9, 5); star(11, 9, 5);
    }
    out.push(s);
  }
  return out;
}
 
/* ---------------- animated guides ----------------
 * Each guide is a 5.5 s loop of three beats drawn with the same strokeBody/drawHead as the game.
 * Actors are snakes whose body is their own head path sampled back in time.
 */
const DUR = 5.5;
const P = (i) => SKIN[i];
function body(g, head, t, len, pal, r, o = {}) {
  const path = [];
  for (let k = 0; k <= len; k += 0.04) { const p = head(t - k); path.push(p[0], p[1]); }
  strokeBody(g, path, pal, r, Object.assign({ t, offset: t * 60 }, o));
  const a = head(t), b = head(t - 0.03);
  if (o.dashed) return path;
  drawHead(g, a[0], a[1], Math.atan2(a[1] - b[1], a[0] - b[0]), r, pal, 0, o.alpha == null ? 1 : o.alpha);
  return path;
}
function dots(g, t, seed = 1, n = 14) {
  for (let i = 0; i < n; i++) {
    const x = ((i * 73 + seed * 31) % 260) - 20, y = ((i * 47 + seed * 17) % 140) - 10;
    g.globalCompositeOperation = "lighter";
    g.fillStyle = SKIN[i % 12][0]; g.globalAlpha = 0.5 + Math.sin(t * 3 + i) * 0.2;
    g.beginPath(); g.arc(x, y, 2.4, 0, TAU); g.fill();
  }
  g.globalAlpha = 1; g.globalCompositeOperation = "source-over";
}
function pellet(g, sprites, k, x, y, s = 18) { if (sprites[k]) g.drawImage(sprites[k], x - s, y - s, s * 2, s * 2); }
function ring(g, x, y, r, c, a = 1, w = 3) { g.strokeStyle = c; g.globalAlpha = a; g.lineWidth = w; g.beginPath(); g.arc(x, y, r, 0, TAU); g.stroke(); g.globalAlpha = 1; }
function burst(g, x, y, k, c) {
  g.globalCompositeOperation = "lighter";
  for (let i = 0; i < 12; i++) { const a = i / 12 * TAU, d = 6 + k * 30; g.fillStyle = c; g.globalAlpha = 1 - k; g.beginPath(); g.arc(x + Math.cos(a) * d, y + Math.sin(a) * d, 3, 0, TAU); g.fill(); }
  g.globalAlpha = 1; g.globalCompositeOperation = "source-over";
}
export function drawPortal(g, x, y, R, t, o = {}) {
  g.save(); g.translate(x, y);
  g.globalCompositeOperation = "lighter";
  const c1 = o.refused ? "#ff4d6d" : "#9b7bff", c2 = "#5ef2ff";
  const gr = g.createRadialGradient(0, 0, 0, 0, 0, R * 1.4);
  gr.addColorStop(0, c1 + "55"); gr.addColorStop(0.6, c2 + "22"); gr.addColorStop(1, c2 + "00");
  g.fillStyle = gr; g.globalAlpha = o.alpha == null ? 1 : o.alpha;
  g.beginPath(); g.arc(0, 0, R * 1.4, 0, TAU); g.fill();
  g.lineWidth = Math.max(2, R * 0.08);
  for (let i = 0; i < 3; i++) {
    g.strokeStyle = i % 2 ? c2 : c1;
    const a0 = (o.still ? 0 : t * (1.2 + i * 0.5)) + i * 2.1;
    g.beginPath(); g.arc(0, 0, R * (0.55 + i * 0.2), a0, a0 + 4.2); g.stroke();
  }
  g.globalCompositeOperation = "source-over";
  if (o.uses != null) for (let i = 0; i < 3; i++) {
    g.fillStyle = i < o.uses ? "#ffffff" : "rgba(255,255,255,.18)";
    g.beginPath(); g.arc((i - 1) * R * 0.28, R * 1.18, Math.max(2, R * 0.06), 0, TAU); g.fill();
  }
  g.restore();
}
 
const lerp = (a, b, k) => a + (b - a) * k;
const clamp01 = (v) => Math.max(0, Math.min(1, v));
const line = (x0, y0, x1, y1, k) => [lerp(x0, x1, k), lerp(y0, y1, k)];
 
/** guide id → {title, caption, draw(g, t, sprites)} on a 220×130 canvas */
export const GUIDES = {
  basics: {
    title: "Basics", caption: "Hit bodies with your side",
    draw(g, t, sp) {
      dots(g, t, 2);
      const A = (s) => [20 + clamp01(s / 3) * 130, 40 + Math.sin(s * 2) * 6];
      const B = (s) => s < 3 ? [190, 120 - s * 25] : [190 - (s - 3) * 40, 45];
      body(g, A, Math.min(t, 3), 0.9, P(0), 6);
      if (t < 3.6) body(g, B, t, 0.8, P(1), 5);
      else burst(g, 150, 45, clamp01((t - 3.6) / 1), P(1)[0]);
    }
  },
  boost: {
    title: "Boost", caption: "Boost costs mass, wins fights",
    draw(g, t) {
      dots(g, t, 3);
      const A = (s) => [10 + (s < 1.6 ? s * 40 : 64 + (s - 1.6) * 95), 80 - clamp01((s - 1.6) / 1.2) * 40];
      const B = (s) => [10 + s * 48, 45];
      const crash = t > 3.4;
      body(g, A, t, t > 1.6 ? 0.55 : 0.8, P(2), 6, { boost: t > 1.6 && t < 3.6 });
      if (!crash) body(g, B, t, 0.9, P(4), 6);
      else burst(g, B(3.4)[0], 45, clamp01((t - 3.4) / 1), P(4)[0]);
    }
  },
  surge: {
    title: "Surge", caption: "Free boost for four seconds",
    draw(g, t, spr) {
      dots(g, t, 4);
      const A = (s) => [20 + s * (s > 1.5 ? 70 : 40), 65 + Math.sin(s * 3) * 10];
      if (t < 1.5) pellet(g, spr, 1, 80, 65, 16);
      body(g, A, t, 0.9, P(3), 6, { boost: t > 1.5 });
      const C = (s) => [Math.max(-40, 10 + s * 38), 30];
      body(g, C, t, 0.8, P(5), 5);
    }
  },
  ward: {
    title: "Ward", caption: "One free bump",
    draw(g, t, spr) {
      dots(g, t, 5);
      strokeBody(g, [150, 0, 150, 130], P(1), 7, { t, offset: t * 30 });
      const hitT = 2.6;
      const A = (s) => s < hitT ? [20 + s * 47, 70] : [142 - (s - hitT) * 45, 70 - (s - hitT) * 18];
      if (t < 1.3) pellet(g, spr, 2, 80, 70, 16);
      body(g, A, t, 0.8, P(0), 6);
      if (t > 1.3 && t < hitT) { const h = A(t); ring(g, h[0], h[1], 14, "#5ef2ff", 0.9); }
      if (t > hitT && t < hitT + 0.6) ring(g, 142, 70, 10 + (t - hitT) * 50, "#5ef2ff", 1 - (t - hitT) / 0.6);
    }
  },
  lens: {
    title: "Lens", caption: "See further for a while",
    draw(g, t, spr) {
      const z = t > 1.6 ? lerp(1, 0.6, clamp01((t - 1.6) / 0.8)) : 1;
      g.save(); g.translate(110, 65); g.scale(z, z); g.translate(-110, -65);
      dots(g, t, 6, 22);
      const A = (s) => [40 + s * 30, 65];
      if (t < 1.6) pellet(g, spr, 3, 88, 65, 16);
      body(g, A, t, 0.8, P(4), 6);
      if (t > 2.6) drawPortal(g, 250, 20, 22, t);
      g.restore();
      g.fillStyle = "rgba(255,255,255,.12)"; g.beginPath(); g.arc(196, 22, 16, 0, TAU); g.fill();
      if (t > 2.6) ring(g, 196 + 8, 22 - 6, 3, "#9b7bff", 1, 2);
    }
  },
  portals: {
    title: "Portals", caption: "Glide through slowly, don't boost",
    draw(g, t) {
      dots(g, t, 7);
      drawPortal(g, 60, 65, 26, t, { uses: t > 2.2 ? 2 : 3 });
      const A = (s) => s < 1.2 ? [10 + s * 40, 65] : [58 + Math.cos((s - 1.2) * 3) * 6, 65 + Math.sin((s - 1.2) * 3) * 6];
      const arrive = 2.6;
      if (t < arrive) {
        body(g, A, t, 0.6, P(8), 6);
        if (t > 1.2) ring(g, 60, 65, lerp(30, 10, clamp01((t - 1.2) / 1)), "#ffffff", 0.8, 2);
        if (t > 2.0) ring(g, 175, 50, 4 + (t - 2) * 20, "#5ef2ff", 1 - (t - 2) / 0.6);
      } else {
        const B = (s) => [175 + (s - arrive) * 40, 50 + Math.sin(s * 3) * 4];
        body(g, B, t, 0.6, P(8), 6, { alpha: t < arrive + 1 ? 0.5 : 1 });
      }
    }
  },
  refused: {
    title: "Portal refused", caption: "No escape when trapped",
    draw(g, t) {
      dots(g, t, 8);
      drawPortal(g, 110, 65, 24, t, { refused: t > 1.6 && t < 2.6 });
      const C = (s) => [110 + Math.cos(s * 1.6) * 55, 65 + Math.sin(s * 1.6) * 48];
      body(g, C, t + 3, 3.9, P(5), 6);
      const A = (s) => t < 2.6 ? [110 + Math.cos(s * 4) * 6, 65 + Math.sin(s * 4) * 6] : [110 + (s - 2.6) * 25, 65];
      body(g, A, t, 0.3, P(10), 5);
      if (t > 1.6 && t < 2.6) { g.fillStyle = "#ff4d6d"; g.font = "700 13px Manrope,sans-serif"; g.textAlign = "center"; g.fillText("✕", 110, 32); }
    }
  },
  evo: {
    title: "Evolution", caption: "Rare, random, lasts all life",
    draw(g, t, spr) {
      dots(g, t, 9);
      const A = (s) => [20 + s * 36, 70 + Math.sin(s * 2) * 12];
      if (t < 1.8) pellet(g, spr, 5, 85, 75, 18 + Math.sin(t * 5) * 2);
      const evolved = t > 1.8;
      body(g, A, t, 1.1, evolved ? EVO_PAL[1] : P(0), 6, { evo: evolved ? 1 : 0 });
      if (t > 1.8 && t < 2.8) burst(g, A(1.8)[0], A(1.8)[1], clamp01((t - 1.8)), "#ffffff");
      if (t > 2.6) { g.fillStyle = "#e8ffc4"; g.font = "800 12px Manrope,sans-serif"; g.textAlign = "center"; g.fillText("◆ Viper", A(t)[0], A(t)[1] - 16); }
    }
  },
  viper: {
    title: "Viper", caption: "Avoid the boosting Viper",
    draw(g, t) {
      dots(g, t, 10);
      const A = (s) => [10 + s * 60, 40];
      const trail = [];
      for (let k = 0; k < 2.6; k += 0.18) { const s = Math.min(t, 2.4) - k; if (s > 0) trail.push(A(s)); }
      g.globalCompositeOperation = "lighter";
      for (const p of trail) { g.fillStyle = "#9dff3c"; g.globalAlpha = 0.35; g.beginPath(); g.arc(p[0], p[1], 6, 0, TAU); g.fill(); }
      g.globalAlpha = 1; g.globalCompositeOperation = "source-over";
      body(g, A, t, 0.8, EVO_PAL[1], 6, { evo: 1, boost: t < 2.4 });
      const slow = t > 2.8;
      const B = (s) => [100, 120 - (s < 2.8 ? s * 26 : 72.8 + (s - 2.8) * 9)];
      body(g, B, t, 0.8, P(2), 5, { alpha: slow ? 0.8 : 1 });
      if (slow) { g.fillStyle = "#9dff3c"; g.font = "700 11px Manrope,sans-serif"; g.textAlign = "center"; g.fillText("slowed", 128, B(t)[1]); }
    }
  },
  constrictor: {
    title: "Constrictor", caption: "Big, slow, deadly circles",
    draw(g, t) {
      dots(g, t, 11);
      const k = clamp01(t / 4);
      const C = (s) => { const a = s * 1.7; const R = lerp(55, 32, clamp01(s / 4)); return [110 + Math.cos(a) * R, 65 + Math.sin(a) * R * 0.9]; };
      body(g, C, t, 3.4, EVO_PAL[2], 8, { evo: 2 });
      const B = (s) => [110 + Math.cos(s * 3) * 10 * (1 - k), 65 + Math.sin(s * 3) * 10 * (1 - k)];
      if (t < 4.4) body(g, B, t, 0.35, P(11), 4);
      else burst(g, 110, 65, clamp01((t - 4.4) / 0.8), P(11)[0]);
    }
  },
  eel: {
    title: "Eel", caption: "Watch for the shimmer",
    draw(g, t) {
      dots(g, t, 12);
      strokeBody(g, [110, 0, 110, 130], P(3), 7, { t, offset: t * 30 });
      const A = (s) => [10 + s * 42, 65];
      const tell = t > 1.4 && t < 1.8, phased = t >= 1.8 && t < 3.2;
      body(g, A, t, 0.8, EVO_PAL[3], 6, { evo: 3, alpha: phased ? 0.35 : 1 });
      if (tell) { const h = A(t); ring(g, h[0], h[1], 12 + Math.sin(t * 60) * 2, "#ffffff", 0.9, 2); }
    }
  },
  split: {
    title: "Split-tail", caption: "Dashed outline means decoy",
    draw(g, t) {
      dots(g, t, 13);
      const A = (s) => [20 + s * 40, 50 + (s > 1.6 ? -(s - 1.6) * 12 : 0)];
      if (t > 1.6) {
        const D = [];
        for (let k = 0; k < 0.5; k += 0.04) { const p = A(1.6 - 0.55 - k); D.push(p[0], p[1]); }
        if (t < 4.2) strokeBody(g, D, EVO_PAL[4], 6, { dashed: true, t });
        else burst(g, D[0], D[1], clamp01((t - 4.2) / 0.8), EVO_PAL[4][0]);
      }
      body(g, A, t, t > 1.6 ? 0.55 : 1.1, EVO_PAL[4], 6, { evo: 4 });
      const B = (s) => [10 + s * 30, 90 - clamp01((s - 2) / 1.5) * 30];
      body(g, B, t, 0.8, P(5), 5);
    }
  },
  magnet: {
    title: "Magnet", caption: "Pulls food, not power-ups",
    draw(g, t, spr) {
      const A = (s) => [20 + s * 35, 65];
      const h = A(t);
      g.globalCompositeOperation = "lighter";
      for (let i = 0; i < 10; i++) {
        const q = ((t * 0.8 + i / 10) % 1), a = i * 2.4;
        const x = h[0] + Math.cos(a) * 50 * (1 - q), y = h[1] + Math.sin(a) * 50 * (1 - q);
        g.fillStyle = SKIN[i % 12][0]; g.globalAlpha = 0.8; g.beginPath(); g.arc(x, y, 2.5, 0, TAU); g.fill();
      }
      g.globalAlpha = 1; g.globalCompositeOperation = "source-over";
      ring(g, h[0], h[1], 34 + Math.sin(t * 5) * 3, "#ff4d4d", 0.5, 2);
      body(g, A, t, 0.9, EVO_PAL[5], 6, { evo: 5 });
      const px = 140 + clamp01((t - 1.8) / 2) * 40;
      pellet(g, spr, 1, px, 30, 14);
      const B = (s) => [210 - s * 12, 10 + s * 5];
      if (t > 2.6 && t < 4.6) body(g, B, t, 0.6, P(1), 5);
    }
  },
  comet: {
    title: "Comet", caption: "Dodge sideways, not back",
    draw(g, t) {
      dots(g, t, 14);
      const dash = (s) => s < 1.6 ? 10 + s * 30 : s < 2.0 ? 58 + (s - 1.6) * 260 : 162 + (s - 2) * 30;
      const A = (s) => [dash(s), 65];
      if (t > 1.6 && t < 2.1) {
        g.globalCompositeOperation = "lighter";
        const h = A(t); const gr = g.createLinearGradient(h[0] - 60, 0, h[0], 0);
        gr.addColorStop(0, "#ff3d0000"); gr.addColorStop(1, "#ffb347cc");
        g.strokeStyle = gr; g.lineWidth = 10; g.beginPath(); g.moveTo(h[0] - 60, 65); g.lineTo(h[0], 65); g.stroke();
        g.globalCompositeOperation = "source-over";
      }
      body(g, A, t, 0.5, EVO_PAL[6], 6, { evo: 6, boost: t > 1.6 && t < 2.0 });
      const B = (s) => [140, s < 1.4 ? 65 : 65 - clamp01((s - 1.4) / 0.4) * 30 - (s - 1.8) * 4];
      body(g, B, t, 0.5, P(9), 5);
    }
  },
  firefly: {
    title: "Firefly", caption: "It sees you, you see it",
    draw(g, t) {
      dots(g, t, 15);
      const A = (s) => [30 + s * 20, 65 + Math.sin(s * 2) * 14];
      body(g, A, t, 1, EVO_PAL[7], 6, { evo: 7 });
      g.fillStyle = "rgba(6,9,22,.7)"; g.strokeStyle = "rgba(142,233,255,.3)"; g.lineWidth = 1;
      g.beginPath(); g.arc(186, 32, 24, 0, TAU); g.fill(); g.stroke();
      if (Math.sin(t * 8) > 0) { g.fillStyle = "#fff59a"; g.beginPath(); g.arc(178, 34, 3.5, 0, TAU); g.fill(); }
      g.fillStyle = "#ffe08a"; g.beginPath(); g.arc(195, 26, 3, 0, TAU); g.fill();
      if (t > 2.4) { const B = (s) => [220 - (s - 2.4) * 40, 110 - (s - 2.4) * 10]; body(g, B, t, 0.6, P(2), 5); }
    }
  }
};
export const GUIDE_ORDER = ["basics", "boost", "surge", "ward", "lens", "portals", "refused", "evo", "viper", "constrictor", "eel", "split", "magnet", "comet", "firefly"];
export const EVO_GUIDE = ["", "viper", "constrictor", "eel", "split", "magnet", "comet", "firefly"];
export const PK_GUIDE = ["", "surge", "ward", "lens", "portals", "evo", "basics"];
export const GUIDE_DUR = DUR;
 
/** Run a guide on a canvas until stop() is called. Pauses itself when the canvas is hidden. */
export function playGuide(canvas, id, sprites, reduced) {
  const g = canvas.getContext("2d"), G = GUIDES[id];
  let raf = 0, t0 = performance.now(), live = true;
  const w = canvas.width, h = canvas.height, sx = w / 220, sy = h / 130;
  function frame(now) {
    if (!live) return;
    raf = requestAnimationFrame(frame);
    if (!canvas.isConnected || canvas.offsetParent === null) return;
    const t = reduced ? 2.9 : ((now - t0) / 1000) % DUR;
    g.setTransform(1, 0, 0, 1, 0, 0);
    g.fillStyle = "#070a1c"; g.fillRect(0, 0, w, h);
    g.setTransform(sx, 0, 0, sy, 0, 0);
    try { G.draw(g, t, sprites); } catch (e) { /* a guide must never break the game */ }
  }
  raf = requestAnimationFrame(frame);
  return { stop() { live = false; cancelAnimationFrame(raf); } };
}