Source code

Echo Maze

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

Play it

games/play/echo-maze.html · 788 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>Echo Maze — PromptArcade</title>
<style>
html,body{margin:0;height:100%;background:#05060b;color:#eef6ff;overflow:hidden;font-family:Manrope,system-ui,sans-serif;touch-action:none;-webkit-user-select:none;user-select:none}
#c{display:block;position:fixed;inset:0}
</style></head><body>
<canvas id="c" aria-label="Echo Maze cave"></canvas>
<script>
window.paConfig = {
  slug: "echo-maze", title: "Echo Maze", native: true, music: "spooky", unit: "points",
  controls: [["← → ↑ ↓ / WASD", "Fly"], ["Space / tap", "Sonar ping: lights the cave, but makes noise"], ["Touch", "Swipe to fly"], ["Crystals", "Find them all to open the way out"], ["Glowcaps", "Flash that stuns everything nearby"]]
};
</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>
(() => {
"use strict";
// A young bat in a pitch-black cave. You only see a little way around you; a sonar ping races down the
// tunnels and lights them for a moment, but every ping is noise, and the blind things in the cave hunt by
// sound. Spiders come to where they heard you, stone lurkers stalk you and freeze only while lit, owls
// glide over the rock toward your last ping. Find every crystal, then get out through the moonlit exit.
const W = 31, H = 17, TAU = Math.PI * 2;
const DIRS = [[1, 0], [0, 1], [-1, 0], [0, -1]];       // right, down, left, up
const ANG = [0, Math.PI / 2, Math.PI, -Math.PI / 2];
const PATH = 0, WALL = 1, EXIT = 2;
const PING_SPEED = 15, PING_GLOW = 2.8, PING_CD = 1.1;
const fx = new PA.Particles(1200), texts = new PA.Texts();
 
let grid, start, exitY, gateOpen, crystals, crystalsLeft, crystalsTotal, caps, flies, player, foes, pings, blips, flash;
let mem, light, pingLight, level, score, shownScore, lives, best = 0, phase, phaseT, levelT, pingCd, pingsUsed, totalPings;
let crystalsFound, foesStunned, invuln, lastPing, deathBy = "", seed = 1, caveCanvas;
try { best = +localStorage.getItem("em_best") || 0; } catch (e) {}
 
const idx = (x, y) => y * W + x;
function rng(s) { return () => { s |= 0; s = (s + 0x6D2B79F5) | 0; let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
 
/* ---------- cave generation ---------- */
function genCave() {
  const g = Array.from({ length: H }, () => Array(W).fill(WALL));
  const seen = new Set(), key = (x, y) => x + "," + y;
  const sy = 1 + 2 * ((Math.random() * ((H - 1) / 2)) | 0);
  const stack = [[1, sy]]; seen.add(key(1, sy)); g[sy][1] = PATH;
  // depth-first carve with a bias toward long horizontal runs, so tunnels feel like a cave, not a grid
  while (stack.length) {
    const [x, y] = stack[stack.length - 1];
    const nb = DIRS.map(([dx, dy]) => [x + dx * 2, y + dy * 2, dx, dy]).filter(([nx, ny]) => nx >= 1 && nx <= W - 2 && ny >= 1 && ny <= H - 2 && !seen.has(key(nx, ny)));
    if (!nb.length) { stack.pop(); continue; }
    const pick = nb.find((n) => n[2] && Math.random() < .35) || nb[(Math.random() * nb.length) | 0];
    const [nx, ny, dx, dy] = pick;
    g[y + dy][x + dx] = PATH; g[ny][nx] = PATH; seen.add(key(nx, ny)); stack.push([nx, ny]);
  }
  // open up most dead ends into loops, but keep a few nooks: crystals like to hide in them
  const deg = (x, y) => DIRS.reduce((n, [dx, dy]) => n + (g[y + dy] && g[y + dy][x + dx] === PATH ? 1 : 0), 0);
  for (let y = 1; y < H - 1; y += 2) for (let x = 1; x < W - 1; x += 2) {
    if (deg(x, y) > 1 || Math.random() < .3) continue;
    const opts = DIRS.filter(([dx, dy]) => { const nx = x + dx * 2, ny = y + dy * 2; return nx >= 1 && nx <= W - 2 && ny >= 1 && ny <= H - 2 && g[y + dy][x + dx] === WALL; });
    if (opts.length) { const [dx, dy] = opts[(Math.random() * opts.length) | 0]; g[y + dy][x + dx] = PATH; }
  }
  // a few small caverns: knock out single walls between parallel tunnels
  for (let k = 0; k < 10; k++) {
    const x = 2 + ((Math.random() * (W - 4)) | 0), y = 2 + ((Math.random() * (H - 4)) | 0);
    if (g[y][x] === WALL && ((g[y][x - 1] === PATH && g[y][x + 1] === PATH) || (g[y - 1][x] === PATH && g[y + 1][x] === PATH))) g[y][x] = PATH;
  }
  grid = g; start = [1, sy];
  // the exit is the right-edge opening farthest from where you start
  const d = bfs(1, sy, false);
  let by = 1, bd = -1;
  for (let y = 1; y < H - 1; y += 2) if (d[idx(W - 2, y)] > bd) { bd = d[idx(W - 2, y)]; by = y; }
  exitY = by; g[by][W - 1] = EXIT;
}
function passable(x, y, who) {
  if (x < 0 || y < 0 || x >= W || y >= H) return false;
  const t = grid[y][x];
  return t === PATH || (t === EXIT && gateOpen && who === player);
}
// Breadth-first distances over the tunnels. Used for creature pathing and for how far a ping travels.
function bfs(sx, sy, withExit, maxD) {
  const d = new Int16Array(W * H).fill(32767), q = [sx, sy];
  d[idx(sx, sy)] = 0; maxD = maxD == null ? 32767 : maxD;
  for (let h = 0; h < q.length; h += 2) {
    const x = q[h], y = q[h + 1], nd = d[idx(x, y)] + 1;
    if (nd > maxD) continue;
    for (const [dx, dy] of DIRS) {
      const nx = x + dx, ny = y + dy;
      if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue;
      const t = grid[ny][nx];
      if (!(t === PATH || (withExit && t === EXIT)) || d[idx(nx, ny)] <= nd) continue;
      d[idx(nx, ny)] = nd; q.push(nx, ny);
    }
  }
  return d;
}
let distCache = new Map();
function distTo(x, y) {
  const k = idx(x, y);
  let d = distCache.get(k);
  if (!d) { d = bfs(x, y, false); distCache.set(k, d); }
  return d;
}
 
/* ---------- level setup ---------- */
function placeItems() {
  const d = bfs(start[0], start[1], false), taken = new Set([idx(start[0], start[1])]);
  const tiles = [];
  for (let y = 1; y < H - 1; y++) for (let x = 1; x < W - 1; x++) if (grid[y][x] === PATH && d[idx(x, y)] >= 5) tiles.push([x, y]);
  const deg = (x, y) => DIRS.reduce((n, [dx, dy]) => n + (grid[y + dy][x + dx] === PATH ? 1 : 0), 0);
  const nooks = tiles.filter(([x, y]) => deg(x, y) === 1).sort(() => Math.random() - .5);
  const rest = tiles.filter(([x, y]) => deg(x, y) !== 1).sort(() => Math.random() - .5);
  const far = (x, y, list, m) => list.every((c) => Math.hypot(c.x - x, c.y - y) >= m);
  crystalsTotal = Math.min(18, 7 + level * 2);
  crystals = [];
  for (const [x, y] of nooks.concat(rest)) {
    if (crystals.length >= crystalsTotal) break;
    if (far(x, y, crystals, 3.2)) { crystals.push({ x, y, hue: Math.random(), got: false }); taken.add(idx(x, y)); }
  }
  crystalsTotal = crystalsLeft = crystals.length;
  caps = [];
  for (const [x, y] of rest) {
    if (caps.length >= 2) break;
    if (!taken.has(idx(x, y)) && d[idx(x, y)] >= 10 && far(x, y, caps, 9)) { caps.push({ x, y, got: false }); taken.add(idx(x, y)); }
  }
  flies = [];
  for (const [x, y] of rest.slice().reverse()) {
    if (flies.length >= 6) break;
    if (!taken.has(idx(x, y)) && far(x, y, flies, 5)) flies.push({ x, y, dir: (Math.random() * 4) | 0, moving: true, got: false, ph: Math.random() * TAU });
  }
}
function foeRoster() {
  const r = ["spider", "spider"];
  if (level >= 2) r.push("lurker");
  if (level >= 3) r.push("spider");
  if (level >= 4) r.push("owl");
  if (level >= 6) r.push("lurker");
  if (level >= 8) r.push("spider", "owl");
  return r;
}
function spawnFoes() {
  const d = bfs(start[0], start[1], false), spots = [];
  for (let y = 1; y < H - 1; y++) for (let x = 1; x < W - 1; x++) if (grid[y][x] === PATH && d[idx(x, y)] >= 16) spots.push([x, y]);
  spots.sort(() => Math.random() - .5);
  const used = [];
  foes = foeRoster().map((type, i) => {
    let s = spots.find(([x, y]) => used.every(([ux, uy]) => Math.hypot(ux - x, uy - y) > 5)) || spots[i % spots.length] || [W - 2, exitY];
    used.push(s);
    return { type, x: s[0], y: s[1], hx: s[0], hy: s[1], dir: (Math.random() * 4) | 0, moving: true, ph: Math.random() * TAU,
      state: "wander", target: null, huntT: 0, stun: 0, frozen: false, wake: type === "lurker" ? 4 : 2, ang: 0, vx: 0, vy: 0 };
  });
}
function newLevel() {
  gateOpen = false; distCache = new Map(); seed = (Math.random() * 1e9) | 0;
  genCave(); placeItems(); spawnFoes();
  mem = new Float32Array(W * H); light = new Float32Array(W * H); pingLight = new Float32Array(W * H);
  pings = []; blips = []; flash = null; levelT = 0; pingsUsed = 0; lastPing = null;
  drawCave();
  startLife();
}
function startLife() {
  player = { x: start[0], y: start[1], dir: 0, next: 0, moving: false, ang: 0, flap: 0 };
  for (const f of foes) Object.assign(f, { x: f.hx, y: f.hy, state: "wander", target: null, huntT: 0, stun: 0, wake: f.type === "lurker" ? 4 : 2, moving: true, vx: 0, vy: 0 });
  pings = []; pingCd = 0; invuln = 1.5; lastPing = null;
  phase = "ready"; phaseT = 0;
}
function reset() {
  level = 1; score = 0; shownScore = 0; lives = 3; crystalsFound = 0; foesStunned = 0; totalPings = 0;
  fx.clear(); texts.clear();
  newLevel();
  PA.music.intensity(0);
}
 
/* ---------- movement ---------- */
function opp(d) { return (d + 2) % 4; }
function atCenter(e) { return Math.abs(e.x - Math.round(e.x)) < 1e-4 && Math.abs(e.y - Math.round(e.y)) < 1e-4; }
function canGo(e, d) { return passable(Math.round(e.x) + DIRS[d][0], Math.round(e.y) + DIRS[d][1], e); }
// Moves an entity along its direction, stopping at each tile centre to let decide() pick the next one.
function step(e, dist, decide) {
  let guard = 0;
  while (dist > 1e-6 && guard++ < 8) {
    if (atCenter(e)) {
      e.x = Math.round(e.x); e.y = Math.round(e.y);
      decide(e);
      if (e.dir == null || !canGo(e, e.dir)) { e.moving = false; return; }
    }
    e.moving = true;
    const [dx, dy] = DIRS[e.dir];
    const pos = dx ? e.x : e.y, s = dx || dy;
    const nextC = s > 0 ? Math.floor(pos + 1e-6) + 1 : Math.ceil(pos - 1e-6) - 1;
    const d = Math.abs(nextC - pos), m = Math.min(d, dist);
    if (dx) e.x += dx * m; else e.y += dy * m;
    if (m >= d - 1e-9) { if (dx) e.x = nextC; else e.y = nextC; }
    dist -= m;
  }
}
function playerDecide(e) { if (e.next != null && canGo(e, e.next)) e.dir = e.next; }
function wanderDecide(e) {
  const opts = [0, 1, 2, 3].filter((d) => d !== opp(e.dir) && canGo(e, d));
  e.dir = opts.length ? opts[(Math.random() * opts.length) | 0] : opp(e.dir);
}
function seekDecide(e) {
  const dm = distTo(e.target[0], e.target[1]), cx = Math.round(e.x), cy = Math.round(e.y);
  let bd = dm[idx(cx, cy)], bestDir = null;
  for (let d = 0; d < 4; d++) {
    if (!canGo(e, d)) continue;
    const v = dm[idx(cx + DIRS[d][0], cy + DIRS[d][1])] + Math.random() * .1;
    if (v < bd) { bd = v; bestDir = d; }
  }
  if (bestDir == null) wanderDecide(e); else e.dir = bestDir;
}
 
/* ---------- sonar ---------- */
function pingRadius() { return 9 + Math.min(3, Math.floor(level / 3)); }
function ping() {
  if (phase !== "play" || pingCd > 0) return;
  const px = Math.round(player.x), py = Math.round(player.y), R = pingRadius();
  pings.push({ x: px, y: py, t: 0, R, d: bfs(px, py, true, R), hit: new Set() });
  pingCd = PING_CD; pingsUsed++; totalPings++;
  lastPing = { x: px, y: py, t: levelT };
  PA.sfx("pop", { pitch: 1.6 }); PA.tone({ freq: 1800, to: 2600, type: "sine", dur: .09, vol: .06, delay: .02 });
  // anything that can hear it comes looking
  for (const f of foes) {
    if (f.type === "lurker") continue;
    if (Math.hypot(f.x - px, f.y - py) <= R + 3) hear(f, px, py, 8);
  }
}
function hear(f, x, y, t) {
  if (f.type === "owl") { f.target = [x, y]; f.huntT = t; f.state = "hunt"; return; }
  if (f.type !== "spider") return;
  f.target = [x, y]; f.huntT = t; f.state = "hunt";
}
 
/* ---------- update ---------- */
function update(dt) {
  fx.update(dt); texts.update(dt);
  if (!grid || PA.state !== "play") return;
  phaseT += dt;
  for (const f of flies) f.ph += dt * 6;
  if (phase === "ready") { computeLight(dt); if (phaseT > 1.8) { phase = "play"; phaseT = 0; } return; }
  if (phase === "dying") { computeLight(dt); if (phaseT > 1.5) afterDeath(); return; }
  if (phase === "clear") { if (phaseT > 2.2) { level++; newLevel(); } return; }
  levelT += dt; pingCd = Math.max(0, pingCd - dt); invuln = Math.max(0, invuln - dt);
  const k = Math.min(1, (level - 1) / 7);
 
  // player
  if (player.next != null && player.dir != null && player.next === opp(player.dir)) player.dir = player.next;
  if (!player.moving && player.next != null && atCenter(player) && canGo(player, player.next)) player.dir = player.next;
  step(player, (5.4 + k * .6) * dt, playerDecide);
  player.flap += dt * (player.moving ? 16 : 7);
  player.ang = turnTo(player.ang, ANG[player.dir], dt * 14);
  collect();
  if (phase !== "play") return;
  if (gateOpen && Math.round(player.x) === W - 1 && Math.abs(player.y - exitY) < .3) { clearLevel(); return; }
 
  // pings travel and fade
  for (const p of pings) {
    p.t += dt;
    // a ping that sweeps past a creature leaves a red blip where it was
    for (const f of foes) {
      if (p.hit.has(f)) continue;
      const fd = p.d[idx(Math.round(f.x), Math.round(f.y))];
      if ((fd < 32767 && fd <= p.t * PING_SPEED) || (f.type === "owl" && Math.hypot(f.x - p.x, f.y - p.y) <= Math.min(p.R, p.t * PING_SPEED))) {
        p.hit.add(f); blips.push({ x: f.x, y: f.y, t: 0, type: f.type });
      }
    }
  }
  pings = pings.filter((p) => p.t < p.R / PING_SPEED + PING_GLOW);
  for (const b of blips) b.t += dt;
  blips = blips.filter((b) => b.t < 2.6);
  if (flash) { flash.t += dt; if (flash.t > 2.2) flash = null; }
  computeLight(dt);
 
  // creatures
  for (const f of foes) {
    f.ph += dt * (f.type === "owl" ? 5 : 9);
    if (f.wake > 0) { f.wake -= dt; continue; }
    if (f.stun > 0) { f.stun -= dt; continue; }
    const near = Math.hypot(f.x - player.x, f.y - player.y);
    if (f.type === "spider") {
      // wingbeats close by give you away
      if (near < 2.7 && player.moving) hear(f, Math.round(player.x), Math.round(player.y), 1.6);
      if (f.state === "hunt") {
        f.huntT -= dt;
        if (f.huntT <= 0 || (atCenter(f) && Math.round(f.x) === f.target[0] && Math.round(f.y) === f.target[1])) { f.state = "search"; f.huntT = 2.5; }
      } else if (f.state === "search") { f.huntT -= dt; if (f.huntT <= 0) f.state = "wander"; }
      const v = f.state === "hunt" ? 4 + k * .9 : f.state === "search" ? 3.2 : 2.3 + k * .5;
      step(f, v * dt, f.state === "hunt" ? seekDecide : wanderDecide);
    } else if (f.type === "lurker") {
      // stone lurkers always know where you are, but can't move while light is on them
      f.frozen = pingLight[idx(Math.round(f.x), Math.round(f.y))] > .25;
      if (f.frozen) continue;
      f.target = [Math.round(player.x), Math.round(player.y)];
      step(f, (2.9 + k * 1.1) * dt, seekDecide);
    } else {
      // owls glide straight over the rock toward the last sound they heard
      if (f.state === "hunt") { f.huntT -= dt; if (f.huntT <= 0 || Math.hypot(f.x - f.target[0], f.y - f.target[1]) < .3) { f.state = "wander"; f.target = null; } }
      if (!f.target) f.target = [1 + Math.random() * (W - 3), 1 + Math.random() * (H - 3)];
      const tx = f.target[0] - f.x, ty = f.target[1] - f.y, td = Math.hypot(tx, ty) || 1;
      const sp = f.state === "hunt" ? 3 + k * .8 : 1.6;
      f.vx += (tx / td * sp - f.vx) * Math.min(1, dt * 2); f.vy += (ty / td * sp - f.vy) * Math.min(1, dt * 2);
      f.x = PA.clamp(f.x + f.vx * dt, .5, W - 1.5); f.y = PA.clamp(f.y + f.vy * dt, .5, H - 1.5);
      if (td < .4 && f.state !== "hunt") f.target = null;
    }
  }
  // fireflies drift along the tunnels
  for (const fl of flies) if (!fl.got) step(fl, 1.1 * dt, wanderDecide);
  collide();
  PA.music.intensity(Math.min(1, (level - 1) / 7 + (1 - crystalsLeft / crystalsTotal) * .3));
}
function turnTo(a, b, k) { let d = ((b - a + Math.PI * 3) % TAU) - Math.PI; return a + d * Math.min(1, k); }
 
function computeLight(dt) {
  light.fill(0); pingLight.fill(0);
  const add = (i, v, arr) => { if (v > arr[i]) arr[i] = v; };
  const litWalls = (arr) => {
    for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
      if (grid[y][x] !== WALL) continue;
      let m = 0;
      for (let oy = -1; oy <= 1; oy++) for (let ox = -1; ox <= 1; ox++) {
        const nx = x + ox, ny = y + oy;
        if (nx >= 0 && ny >= 0 && nx < W && ny < H && grid[ny][nx] !== WALL) m = Math.max(m, arr[idx(nx, ny)]);
      }
      arr[idx(x, y)] = m * .9;
    }
  };
  // pings: lit where the wave has passed, fading after
  for (const p of pings) {
    const front = p.t * PING_SPEED;
    for (let i = 0; i < W * H; i++) {
      const d = p.d[i]; if (d > p.R || d > front) continue;
      const age = p.t - d / PING_SPEED;
      add(i, Math.max(0, 1 - age / PING_GLOW) * (.65 + .35 * (1 - d / p.R)), pingLight);
    }
  }
  if (flash) {
    for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
      const dd = Math.hypot(x - flash.x, y - flash.y); if (dd > 7) continue;
      add(idx(x, y), Math.max(0, 1 - flash.t / 2.2) * (1 - dd / 9), pingLight);
    }
  }
  litWalls(pingLight);
  for (let i = 0; i < W * H; i++) light[i] = pingLight[i];
  // your own faint glow, a short way along the tunnels
  const near = new Float32Array(W * H);
  const pd = bfs(Math.round(player.x), Math.round(player.y), true, 3);
  for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
    if (pd[idx(x, y)] > 3) continue;
    near[idx(x, y)] = PA.clamp(1.25 - Math.hypot(x - player.x, y - player.y) / 2.9, 0, 1);
  }
  for (const fl of flies) if (!fl.got) {
    for (let y = Math.max(0, Math.round(fl.y) - 2); y <= Math.min(H - 1, Math.round(fl.y) + 2); y++)
      for (let x = Math.max(0, Math.round(fl.x) - 2); x <= Math.min(W - 1, Math.round(fl.x) + 2); x++)
        if (grid[y][x] !== WALL) add(idx(x, y), PA.clamp(.75 - Math.hypot(x - fl.x, y - fl.y) / 2.4, 0, 1), near);
  }
  if (gateOpen) for (let y = exitY - 2; y <= exitY + 2; y++) for (let x = W - 3; x < W; x++) if (y >= 0 && y < H && grid[y][x] !== WALL) add(idx(x, y), .8 - Math.hypot(x - W + 1, y - exitY) / 4, near);
  litWalls(near);
  for (let i = 0; i < W * H; i++) {
    if (near[i] > light[i]) light[i] = near[i];
    if (light[i] > .45) mem[i] = Math.min(1, mem[i] + dt * 4);
    light[i] = Math.max(light[i], mem[i] * .15);
  }
}
 
function collect() {
  const x = Math.round(player.x), y = Math.round(player.y);
  if (Math.abs(player.x - x) > .35 || Math.abs(player.y - y) > .35) return;
  const s = toScreen(x, y);
  for (const c of crystals) {
    if (c.got || c.x !== x || c.y !== y) continue;
    c.got = true; crystalsLeft--; crystalsFound++;
    score += 100 * level;
    texts.add(s.x, s.y - T * .4, "+" + 100 * level, { color: "#9ff6ff", size: 16 });
    fx.burst(s.x, s.y, { n: 20, colors: ["#9ff6ff", "#fff", "#d6a8ff"], speed: 200, life: .6, shape: "spark" });
    PA.sfx("coin", { pitch: 1 + (crystalsTotal - crystalsLeft) * .03 });
    // crystals ring when you pull them out: spiders nearby hear it
    for (const f of foes) if (f.type === "spider" && Math.hypot(f.x - x, f.y - y) < 6) hear(f, x, y, 5);
    if (!crystalsLeft) {
      gateOpen = true;
      PA.sfx("power");
      texts.add(view.w / 2, view.h * .32, "THE WAY OUT IS OPEN", { color: "#e8f2ff", size: 26, life: 1.8, vy: -14 });
      const e = toScreen(W - 1, exitY); fx.burst(e.x, e.y, { n: 40, colors: ["#e8f2ff", "#9fc6ff"], speed: 260, life: 1 });
    }
  }
  for (const c of caps) {
    if (c.got || c.x !== x || c.y !== y) continue;
    c.got = true; score += 250;
    flash = { x, y, t: 0 };
    let n = 0;
    for (const f of foes) if (Math.hypot(f.x - x, f.y - y) < 7) { f.stun = 4.5; f.state = "wander"; n++; }
    foesStunned += n;
    texts.add(s.x, s.y - T * .4, n ? "FLASH! " + n + " STUNNED" : "FLASH!", { color: "#9dffcb", size: 18 });
    PA.flash("#c9ffe4", 260); PA.sfx("levelup", { pitch: 1.3 });
  }
  for (const fl of flies) {
    if (fl.got || Math.hypot(fl.x - player.x, fl.y - player.y) > .6) continue;
    fl.got = true; score += 50 * level;
    const fs = toScreen(fl.x, fl.y);
    texts.add(fs.x, fs.y - T * .4, "+" + 50 * level, { color: "#f4ff8a", size: 14 });
    fx.burst(fs.x, fs.y, { n: 10, colors: ["#f4ff8a", "#fff"], speed: 120, life: .5 });
    PA.sfx("blip", { pitch: 1.4, vol: .2 });
  }
}
function collide() {
  if (invuln > 0) return;
  for (const f of foes) {
    if (f.wake > 0 || f.stun > 0) continue;
    if (Math.hypot(f.x - player.x, f.y - player.y) < (f.type === "owl" ? .55 : .62)) { die(f.type); return; }
  }
}
function clearLevel() {
  phase = "clear"; phaseT = 0;
  const par = 50 + level * 12, time = Math.max(0, Math.round((par - levelT) * 10 * level)), quiet = Math.max(0, 10 - pingsUsed) * 40 * level;
  const bonus = 500 * level + time + quiet;
  score += bonus;
  texts.add(view.w / 2, view.h * .38, "ESCAPED +" + bonus.toLocaleString(), { color: "#e8f2ff", size: 28, life: 2, vy: -16 });
  if (quiet) texts.add(view.w / 2, view.h * .38 + 34, "quiet flying +" + quiet.toLocaleString(), { color: "#9ff6ff", size: 16, life: 2, vy: -16 });
  if (level % 3 === 0) { lives++; texts.add(view.w / 2, view.h * .38 + 58, "+1 LIFE", { color: "#ffd36b", size: 18, life: 2, vy: -16 }); }
  PA.sfx("levelup");
}
function die(by) {
  phase = "dying"; phaseT = 0; deathBy = by;
  PA.sfx("lose"); PA.shake(6, .3);
  const s = toScreen(player.x, player.y);
  fx.burst(s.x, s.y, { n: 36, colors: ["#b9a3ff", "#fff", "#ff6a7a"], speed: 240, life: .9 });
}
function afterDeath() {
  lives--;
  if (lives <= 0) {
    phase = "over";
    if (score > best) { best = score; try { localStorage.setItem("em_best", best); } catch (e) {} }
    PA.sfx("gameover");
    PA.gameOver(score, {
      kicker: { spider: "A spider heard you", lurker: "A stone lurker caught up", owl: "An owl swooped down" }[deathBy] || "Lost in the dark",
      title: level >= 6 ? "Deep cave legend" : level >= 3 ? "Far underground" : "Lost in the cave",
      stats: [["Cave", level], ["Crystals", crystalsFound], ["Pings", totalPings]]
    });
    return;
  }
  startLife();
}
 
/* ---------- input ---------- */
// rot: the board is drawn turned a quarter-turn on tall screens, so screen directions map to board ones
let rot = false;
function steer(sd) { if (player && phase !== "dying") player.next = rot ? (sd + 3) % 4 : sd; }
PA.onKey((e) => {
  const c = e.code;
  if (c === "ArrowRight" || c === "KeyD") steer(0);
  else if (c === "ArrowDown" || c === "KeyS") steer(1);
  else if (c === "ArrowLeft" || c === "KeyA") steer(2);
  else if (c === "ArrowUp" || c === "KeyW") steer(3);
  else if ((c === "Space" || c === "Enter" || c === "KeyE") && !e.repeat) { e.preventDefault && e.preventDefault(); ping(); }
});
let sw = null;
addEventListener("pointerdown", (e) => {
  if (PA.state !== "play" || PA.isPaused()) return;
  if (e.target.closest && e.target.closest("button,input,#pa-gate,.pa-layer,.pa-tb,.pa-touch")) return;
  sw = { id: e.pointerId, x: e.clientX, y: e.clientY, t: performance.now(), moved: false };
});
addEventListener("pointermove", (e) => {
  if (!sw || e.pointerId !== sw.id) return;
  const dx = e.clientX - sw.x, dy = e.clientY - sw.y;
  if (Math.max(Math.abs(dx), Math.abs(dy)) < 18) return;
  steer(Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? 0 : 2) : (dy > 0 ? 1 : 3));
  sw.x = e.clientX; sw.y = e.clientY; sw.moved = true;   // keep steering with the same finger
});
addEventListener("pointerup", (e) => {
  if (sw && e.pointerId === sw.id && !sw.moved && performance.now() - sw.t < 320) ping();
  sw = null;
});
addEventListener("pointercancel", () => { sw = null; });
 
/* ---------- drawing ---------- */
let view, ctx, T = 24, bx = 0, by = 0;
const mask = document.createElement("canvas"); mask.width = W; mask.height = H;
const mctx = mask.getContext("2d"), mimg = mctx.createImageData(W, H);
function layout(v) {
  const top = 74, bottom = PA.isTouch ? 30 : 18;
  const fit = (bw, bh) => Math.floor(Math.min((v.w - 16) / bw, (v.h - top - bottom) / bh));
  rot = fit(H, W) > fit(W, H) * 1.15;
  T = Math.max(8, rot ? fit(H, W) : fit(W, H));
  const bw = (rot ? H : W) * T, bh = (rot ? W : H) * T;
  bx = Math.round((v.w - bw) / 2); by = Math.round(top + (v.h - top - bottom - bh) / 2);
  if (grid) drawCave();
}
function toScreen(x, y) { return rot ? { x: bx + (H - y - .5) * T, y: by + (x + .5) * T } : { x: bx + (x + .5) * T, y: by + (y + .5) * T }; }
function boardSpace() { ctx.translate(bx, by); if (rot) { ctx.translate(H * T, 0); ctx.rotate(Math.PI / 2); } }
 
// The cave is drawn once per level into an offscreen canvas: rock, mossy rims, and an earthy tunnel floor.
function drawCave() {
  if (!view) return;
  const dpr = view.dpr, c = document.createElement("canvas"), r = rng(seed);
  c.width = Math.ceil(W * T * dpr); c.height = Math.ceil(H * T * dpr);
  const g = c.getContext("2d"); g.scale(dpr, dpr);
  const rock = g.createLinearGradient(0, 0, 0, H * T); rock.addColorStop(0, "#1c2230"); rock.addColorStop(1, "#121620");
  g.fillStyle = rock; g.fillRect(0, 0, W * T, H * T);
  for (let i = 0; i < W * H * 2; i++) {
    g.fillStyle = r() < .5 ? "rgba(70,84,110,.22)" : "rgba(0,0,0,.28)";
    g.beginPath(); g.ellipse(r() * W * T, r() * H * T, T * (.1 + r() * .35), T * (.08 + r() * .22), r() * 3, 0, TAU); g.fill();
  }
  const open = (x, y) => x >= 0 && y >= 0 && x < W && y < H && grid[y][x] !== WALL;
  const tunnels = (w, col) => {
    g.strokeStyle = col; g.fillStyle = col; g.lineWidth = w; g.lineCap = "round";
    g.beginPath();
    for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
      if (!open(x, y)) continue;
      const cx = (x + .5) * T, cy = (y + .5) * T;
      g.moveTo(cx, cy); g.lineTo(cx, cy);
      if (open(x + 1, y)) { g.moveTo(cx, cy); g.lineTo(cx + T, cy); }
      if (open(x, y + 1)) { g.moveTo(cx, cy); g.lineTo(cx, cy + T); }
      if (grid[y][x] === EXIT) { g.moveTo(cx, cy); g.lineTo(cx + T, cy); }
    }
    g.stroke();
  };
  tunnels(T * 1.02, "#33504a");      // moss on the tunnel rims
  tunnels(T * .9, "#24302c");
  tunnels(T * .8, "#2c241d");        // earthy floor
  tunnels(T * .42, "#352b22");
  // pebbles and glowing lichen
  for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
    if (!open(x, y)) continue;
    for (let k = 0; k < 3; k++) {
      g.fillStyle = r() < .5 ? "#4a3d30" : "#1c1712";
      g.beginPath(); g.arc((x + .2 + r() * .6) * T, (y + .2 + r() * .6) * T, T * (.03 + r() * .05), 0, TAU); g.fill();
    }
    if (r() < .18) {
      g.fillStyle = r() < .5 ? "rgba(90,255,190,.5)" : "rgba(150,170,255,.45)";
      const a = r() * TAU;
      for (let k = 0; k < 4; k++) { g.beginPath(); g.arc((x + .5 + Math.cos(a) * .42) * T + (r() - .5) * T * .2, (y + .5 + Math.sin(a) * .42) * T + (r() - .5) * T * .2, T * .035, 0, TAU); g.fill(); }
    }
  }
  caveCanvas = c;
}
 
function drawBat(x, y, ang, flap, s, body, wing) {
  ctx.save(); ctx.translate(x, y); ctx.rotate(ang);
  const span = s * (.55 + .45 * Math.abs(Math.sin(flap)));
  for (const side of [-1, 1]) {
    ctx.fillStyle = wing;
    ctx.beginPath(); ctx.moveTo(s * .12, 0);
    ctx.quadraticCurveTo(s * .25, side * span * .55, -s * .02, side * span);
    // scalloped trailing edge
    ctx.quadraticCurveTo(-s * .2, side * span * .78, -s * .3, side * span * .72);
    ctx.quadraticCurveTo(-s * .26, side * span * .5, -s * .42, side * span * .42);
    ctx.quadraticCurveTo(-s * .3, side * span * .25, -s * .3, 0);
    ctx.closePath(); ctx.fill();
    ctx.strokeStyle = "rgba(255,255,255,.25)"; ctx.lineWidth = Math.max(1, s * .04);
    ctx.beginPath(); ctx.moveTo(s * .08, side * s * .05); ctx.lineTo(-s * .02, side * span * .95);
    ctx.moveTo(s * .04, side * s * .05); ctx.lineTo(-s * .28, side * span * .7); ctx.stroke();
  }
  ctx.fillStyle = body;
  ctx.beginPath(); ctx.ellipse(-s * .06, 0, s * .3, s * .17, 0, 0, TAU); ctx.fill();
  ctx.beginPath(); ctx.arc(s * .22, 0, s * .14, 0, TAU); ctx.fill();
  // ears
  for (const side of [-1, 1]) { ctx.beginPath(); ctx.moveTo(s * .22, side * s * .05); ctx.lineTo(s * .42, side * s * .17); ctx.lineTo(s * .26, side * s * .14); ctx.fill(); }
  ctx.fillStyle = "#ffd36b";
  for (const side of [-1, 1]) { ctx.beginPath(); ctx.arc(s * .29, side * s * .055, s * .035, 0, TAU); ctx.fill(); }
  ctx.restore();
}
function drawSpider(f, x, y, s, t) {
  ctx.save(); ctx.translate(x, y);
  const a = f.dir == null ? 0 : ANG[f.dir]; ctx.rotate(a);
  ctx.strokeStyle = f.stun > 0 ? "#6b5a70" : "#2a0d14"; ctx.lineWidth = Math.max(1.2, s * .07); ctx.lineCap = "round";
  for (let i = 0; i < 4; i++) for (const side of [-1, 1]) {
    const w = Math.sin(f.ph + i * 1.7 + (side > 0 ? Math.PI : 0)) * (f.moving && f.stun <= 0 ? .14 : 0);
    const bx0 = s * (.12 - i * .1), kx = bx0 + s * (.14 - i * .08) + w * s, ky = side * s * .42, ex = kx + s * (.1 - i * .1), ey = side * s * .62;
    ctx.beginPath(); ctx.moveTo(bx0, side * s * .08); ctx.lineTo(kx, ky); ctx.lineTo(ex, ey); ctx.stroke();
  }
  ctx.fillStyle = "#5a1e2a"; ctx.beginPath(); ctx.ellipse(-s * .2, 0, s * .26, s * .21, 0, 0, TAU); ctx.fill();
  ctx.fillStyle = "#c4344e"; ctx.beginPath(); ctx.moveTo(-s * .32, 0); ctx.lineTo(-s * .2, -s * .08); ctx.lineTo(-s * .08, 0); ctx.lineTo(-s * .2, s * .08); ctx.fill();
  ctx.fillStyle = "#3d1219"; ctx.beginPath(); ctx.arc(s * .12, 0, s * .15, 0, TAU); ctx.fill();
  ctx.fillStyle = f.state === "hunt" ? "#ff4d6a" : "#b8324a";
  for (const [ex, ey] of [[.22, -.06], [.22, .06], [.17, -.1], [.17, .1]]) { ctx.beginPath(); ctx.arc(s * ex, s * ey, s * .035, 0, TAU); ctx.fill(); }
  ctx.restore();
  if (f.stun > 0) stunStars(x, y - s * .5, s, t);
}
function drawLurker(f, x, y, s, t) {
  ctx.save(); ctx.translate(x, y);
  const r = s * .42, frozen = f.frozen || f.stun > 0;
  ctx.fillStyle = frozen ? "#8a96a8" : "#6b5e55";
  ctx.beginPath();
  for (let i = 0; i < 9; i++) { const a = i / 9 * TAU, rr = r * (.86 + .14 * Math.sin(i * 2.3 + 1)); ctx.lineTo(Math.cos(a) * rr, Math.sin(a) * rr); }
  ctx.closePath(); ctx.fill();
  ctx.fillStyle = frozen ? "#a9b6c8" : "#82746a"; ctx.beginPath(); ctx.ellipse(-r * .2, -r * .25, r * .45, r * .3, -.4, 0, TAU); ctx.fill();
  ctx.strokeStyle = "rgba(20,14,12,.7)"; ctx.lineWidth = Math.max(1, s * .04);
  ctx.beginPath(); ctx.moveTo(-r * .5, r * .1); ctx.lineTo(-r * .1, r * .3); ctx.lineTo(0, r * .7); ctx.moveTo(r * .2, -r * .7); ctx.lineTo(r * .35, -r * .2); ctx.stroke();
  if (!frozen) {
    const glow = .7 + .3 * Math.sin(t * 6);
    ctx.fillStyle = `rgba(255,140,60,${glow})`; ctx.shadowColor = "#ff7a2a"; ctx.shadowBlur = s * .3;
    for (const side of [-1, 1]) { ctx.beginPath(); ctx.ellipse(side * r * .32, r * .05, r * .16, r * .07, side * .3, 0, TAU); ctx.fill(); }
    ctx.shadowBlur = 0;
  } else {
    ctx.fillStyle = "rgba(220,240,255,.8)";
    for (let i = 0; i < 5; i++) { ctx.beginPath(); ctx.arc(Math.cos(i * 2.4) * r * .6, Math.sin(i * 2.4) * r * .6, s * .03, 0, TAU); ctx.fill(); }
  }
  ctx.restore();
  if (f.stun > 0) stunStars(x, y - s * .5, s, t);
}
function drawOwl(f, x, y, s, t) {
  ctx.save(); ctx.translate(x, y);
  ctx.rotate(Math.atan2(f.vy, f.vx) || 0);
  const span = s * (.9 + .25 * Math.sin(f.ph));
  ctx.fillStyle = "rgba(0,0,0,.25)"; ctx.beginPath(); ctx.ellipse(s * .1, s * .25, s * .4, span * .9, 0, 0, TAU); ctx.fill();
  for (const side of [-1, 1]) {
    ctx.fillStyle = "#7a5a3c";
    ctx.beginPath(); ctx.moveTo(s * .15, side * s * .1); ctx.quadraticCurveTo(s * .1, side * span, -s * .2, side * span);
    ctx.lineTo(-s * .35, side * span * .7); ctx.lineTo(-s * .25, side * s * .1); ctx.closePath(); ctx.fill();
    ctx.strokeStyle = "#c9a77a"; ctx.lineWidth = Math.max(1, s * .035);
    for (let k = 1; k <= 3; k++) { ctx.beginPath(); ctx.moveTo(-s * .05 * k, side * span * (.3 + k * .18)); ctx.lineTo(-s * (.12 + .06 * k), side * span * (.28 + k * .18)); ctx.stroke(); }
  }
  ctx.fillStyle = "#9c7a54"; ctx.beginPath(); ctx.ellipse(-s * .05, 0, s * .32, s * .2, 0, 0, TAU); ctx.fill();
  ctx.fillStyle = "#d9c3a0"; ctx.beginPath(); ctx.arc(s * .2, 0, s * .17, 0, TAU); ctx.fill();
  ctx.fillStyle = f.stun > 0 ? "#888" : "#ffcf3a";
  for (const side of [-1, 1]) { ctx.beginPath(); ctx.arc(s * .26, side * s * .07, s * .05, 0, TAU); ctx.fill(); }
  ctx.restore();
  if (f.stun > 0) stunStars(x, y - s * .5, s, t);
}
function stunStars(x, y, s, t) {
  ctx.fillStyle = "#fff6b0";
  for (let i = 0; i < 3; i++) { const a = t * 4 + i * TAU / 3; ctx.beginPath(); ctx.arc(x + Math.cos(a) * s * .3, y + Math.sin(a) * s * .1, s * .05, 0, TAU); ctx.fill(); }
}
function drawCrystal(cx, cy, s, t, hue) {
  const tw = .85 + .15 * Math.sin(t * 3 + hue * 9);
  ctx.save(); ctx.translate(cx, cy);
  ctx.globalCompositeOperation = "lighter";
  const g = ctx.createRadialGradient(0, 0, 0, 0, 0, s * .9); g.addColorStop(0, "rgba(120,240,255,.35)"); g.addColorStop(1, "rgba(120,240,255,0)");
  ctx.fillStyle = g; ctx.fillRect(-s, -s, s * 2, s * 2);
  ctx.globalCompositeOperation = "source-over";
  const pts = [[0, -.42], [.22, -.14], [.17, .3], [-.17, .3], [-.22, -.14]];
  ctx.fillStyle = hue < .5 ? "#62e6ff" : "#c79bff";
  ctx.beginPath(); pts.forEach(([px, py], i) => i ? ctx.lineTo(px * s * tw, py * s) : ctx.moveTo(px * s * tw, py * s)); ctx.closePath(); ctx.fill();
  ctx.fillStyle = "rgba(255,255,255,.55)"; ctx.beginPath(); ctx.moveTo(0, -.42 * s); ctx.lineTo(.22 * s * tw, -.14 * s); ctx.lineTo(0, .05 * s); ctx.closePath(); ctx.fill();
  ctx.strokeStyle = "rgba(255,255,255,.45)"; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(0, .05 * s); ctx.lineTo(0, .3 * s); ctx.stroke();
  ctx.restore();
}
function drawCap(cx, cy, s, t) {
  ctx.save(); ctx.translate(cx, cy);
  ctx.globalCompositeOperation = "lighter";
  const g = ctx.createRadialGradient(0, -s * .1, 0, 0, -s * .1, s); g.addColorStop(0, `rgba(120,255,190,${.35 + .15 * Math.sin(t * 4)})`); g.addColorStop(1, "rgba(120,255,190,0)");
  ctx.fillStyle = g; ctx.fillRect(-s, -s, s * 2, s * 2);
  ctx.globalCompositeOperation = "source-over";
  ctx.fillStyle = "#e9e1cf"; ctx.fillRect(-s * .07, -s * .05, s * .14, s * .34);
  ctx.fillStyle = "#5dffb2"; ctx.beginPath(); ctx.ellipse(0, -s * .06, s * .3, s * .2, 0, Math.PI, 0); ctx.fill();
  ctx.fillStyle = "#e8fff3"; for (const [px, py] of [[-.13, -.14], [.06, -.2], [.16, -.1]]) { ctx.beginPath(); ctx.arc(px * s, py * s, s * .035, 0, TAU); ctx.fill(); }
  ctx.restore();
}
 
function render(t) {
  const w = view.w, h = view.h;
  ctx.setTransform(view.dpr, 0, 0, view.dpr, 0, 0);
  const bg = ctx.createRadialGradient(w / 2, h * .5, 0, w / 2, h * .5, Math.max(w, h) * .7);
  bg.addColorStop(0, "#0d1220"); bg.addColorStop(1, "#04050a");
  ctx.fillStyle = bg; ctx.fillRect(0, 0, w, h);
  if (!grid) return;
  const sh = PA.shakeOffset(), bw = W * T, bh = H * T;
  ctx.save(); ctx.translate(sh.x, sh.y); boardSpace();
  ctx.save(); ctx.beginPath(); ctx.rect(0, 0, bw, bh); ctx.clip();
  if (caveCanvas) ctx.drawImage(caveCanvas, 0, 0, bw, bh);
  const C = (x) => (x + .5) * T;
  // exit: moonlight through a gap in the rock, sealed by a crystal lattice until every crystal is found
  {
    const ex = C(W - 1), ey = C(exitY);
    const g = ctx.createRadialGradient(bw, ey, 0, bw, ey, T * 2.2); g.addColorStop(0, "rgba(200,220,255,.55)"); g.addColorStop(1, "rgba(200,220,255,0)");
    ctx.fillStyle = g; ctx.fillRect(bw - T * 2.2, ey - T * 2.2, T * 2.2, T * 4.4);
    if (!gateOpen) {
      ctx.strokeStyle = "rgba(140,230,255,.85)"; ctx.lineWidth = Math.max(1.5, T * .07);
      for (let k = -1; k <= 1; k++) { ctx.beginPath(); ctx.moveTo(ex + k * T * .18, ey - T * .42); ctx.lineTo(ex + k * T * .18 + T * .05, ey + T * .42); ctx.stroke(); }
    }
  }
  for (const c of crystals) if (!c.got) drawCrystal(C(c.x), C(c.y), T, t, c.hue);
  for (const c of caps) if (!c.got) drawCap(C(c.x), C(c.y), T, t);
  // creatures (under the dark, so they're only visible where there's light)
  for (const f of foes) {
    const L = light[idx(PA.clamp(Math.round(f.x), 0, W - 1), PA.clamp(Math.round(f.y), 0, H - 1))];
    const a = PA.clamp((L - .12) / .4, 0, 1); if (a <= 0 || f.type === "owl") continue;
    ctx.globalAlpha = a;
    if (f.type === "spider") drawSpider(f, C(f.x), C(f.y), T * 1.05, t); else drawLurker(f, C(f.x), C(f.y), T * 1.05, t);
    ctx.globalAlpha = 1;
  }
  // player
  if (phase !== "over") {
    const px = C(player.x), py = C(player.y);
    if (phase === "dying") {
      const k = Math.min(1, phaseT / 1.2);
      ctx.globalAlpha = 1 - k; drawBat(px, py, player.ang + k * 9, player.flap, T * (1 - k * .5), "#6b5a9e", "#43356e"); ctx.globalAlpha = 1;
    } else if (!(invuln > 0 && Math.sin(t * 30) > .3)) drawBat(px, py, player.ang, player.flap, T * .95, "#7a68b5", "#4b3c7c");
  }
  // darkness: one value per tile, scaled up with smoothing so the light falls off softly
  const data = mimg.data;
  for (let i = 0; i < W * H; i++) { data[i * 4] = 3; data[i * 4 + 1] = 4; data[i * 4 + 2] = 10; data[i * 4 + 3] = (1 - Math.min(1, light[i])) * 248; }
  mctx.putImageData(mimg, 0, 0);
  ctx.imageSmoothingEnabled = true;
  ctx.drawImage(mask, 0, 0, bw, bh);
  // owls fly above everything; only their silhouettes show in the dark
  for (const f of foes) if (f.type === "owl") {
    const L = light[idx(PA.clamp(Math.round(f.x), 0, W - 1), PA.clamp(Math.round(f.y), 0, H - 1))];
    ctx.globalAlpha = .25 + .75 * PA.clamp((L - .12) / .4, 0, 1); drawOwl(f, C(f.x), C(f.y), T * 1.3, t); ctx.globalAlpha = 1;
  }
  ctx.globalCompositeOperation = "lighter";
  // the ping wavefront racing down the tunnels
  for (const p of pings) {
    const front = p.t * PING_SPEED; if (front > p.R + 1) continue;
    for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
      const d = p.d[idx(x, y)]; if (d > p.R) continue;
      const k = 1 - Math.abs(d - front) / 1.2; if (k <= 0) continue;
      // soft overlapping glows, so the front reads as one band of sound rather than a row of dots
      const cx = C(x), cy = C(y), g = ctx.createRadialGradient(cx, cy, 0, cx, cy, T * .8);
      g.addColorStop(0, `rgba(80,200,255,${k * .42 * (1 - d / (p.R + 2))})`); g.addColorStop(1, "rgba(80,200,255,0)");
      ctx.fillStyle = g; ctx.fillRect(cx - T * .8, cy - T * .8, T * 1.6, T * 1.6);
    }
  }
  // eyes you can make out in the dark when something is close
  for (const f of foes) {
    if (f.type === "owl" || f.wake > 0) continue;
    const d = Math.hypot(f.x - player.x, f.y - player.y);
    if (d > 5.5) continue;
    const a = (1 - d / 5.5) * (.5 + .5 * Math.sin(t * 3 + f.ph)) * (f.frozen ? .2 : 1);
    ctx.fillStyle = f.type === "lurker" ? `rgba(255,130,50,${a})` : `rgba(255,60,90,${a})`;
    const [dx, dy] = f.dir == null ? [0, 0] : DIRS[f.dir];
    for (const s of [-1, 1]) { ctx.beginPath(); ctx.arc(C(f.x) + dx * T * .2 - dy * s * T * .09, C(f.y) + dy * T * .2 + dx * s * T * .09, T * .06, 0, TAU); ctx.fill(); }
  }
  // sonar blips: where a ping found something
  for (const b of blips) {
    const k = 1 - b.t / 2.6, col = b.type === "owl" ? "255,200,80" : b.type === "lurker" ? "255,140,70" : "255,80,110";
    ctx.strokeStyle = `rgba(${col},${k * .8})`; ctx.lineWidth = Math.max(1.2, T * .06);
    ctx.beginPath(); ctx.arc(C(b.x), C(b.y), T * (.3 + b.t * .15), 0, TAU); ctx.stroke();
  }
  // crystals catch a glint now and then, even in the dark, so you know there's something to find
  for (const c of crystals) {
    if (c.got) continue;
    const g = Math.pow(Math.max(0, Math.sin(t * 1.3 + c.hue * 40)), 24) * (1 - Math.min(1, light[idx(c.x, c.y)]));
    if (g < .03) continue;
    const cx = C(c.x), cy = C(c.y) - T * .12, r = T * .38 * g;
    ctx.strokeStyle = `rgba(190,245,255,${.75 * g})`; ctx.lineWidth = Math.max(1, T * .05);
    ctx.beginPath(); ctx.moveTo(cx - r, cy); ctx.lineTo(cx + r, cy); ctx.moveTo(cx, cy - r); ctx.lineTo(cx, cy + r); ctx.stroke();
  }
  // fireflies glow through the dark
  for (const fl of flies) {
    if (fl.got) continue;
    const fx0 = C(fl.x) + Math.sin(fl.ph * .7) * T * .15, fy0 = C(fl.y) + Math.cos(fl.ph * .5) * T * .15, k = .6 + .4 * Math.sin(fl.ph);
    const g = ctx.createRadialGradient(fx0, fy0, 0, fx0, fy0, T * .7); g.addColorStop(0, `rgba(230,255,120,${.5 * k})`); g.addColorStop(1, "rgba(230,255,120,0)");
    ctx.fillStyle = g; ctx.fillRect(fx0 - T * .7, fy0 - T * .7, T * 1.4, T * 1.4);
    ctx.fillStyle = `rgba(250,255,200,${.6 + .4 * k})`; ctx.beginPath(); ctx.arc(fx0, fy0, T * .07, 0, TAU); ctx.fill();
  }
  // moonlight at the exit always shows, so you know where you're heading
  {
    const ey = C(exitY), k = gateOpen ? .8 + .2 * Math.sin(t * 4) : .35;
    const g = ctx.createRadialGradient(bw, ey, 0, bw, ey, T * 1.6); g.addColorStop(0, `rgba(190,215,255,${k})`); g.addColorStop(1, "rgba(190,215,255,0)");
    ctx.fillStyle = g; ctx.fillRect(bw - T * 1.6, ey - T * 1.6, T * 1.6, T * 3.2);
  }
  ctx.globalCompositeOperation = "source-over";
  ctx.restore();
  // frame
  ctx.strokeStyle = "rgba(120,150,190,.25)"; ctx.lineWidth = 1.5; rrect(-1, -1, bw + 2, bh + 2, 6); ctx.stroke();
  ctx.restore();
  fx.draw(ctx); texts.draw(ctx);
  // banners
  ctx.textAlign = "center";
  if (phase === "ready") {
    const cy = by + ((rot ? W : H) * T) / 2;
    ctx.font = `800 ${Math.round(Math.min(40, Math.max(22, T * 1.1)))}px Manrope, sans-serif`; ctx.fillStyle = "#e8f2ff"; ctx.shadowColor = "#6ee1ff"; ctx.shadowBlur = 16;
    ctx.fillText("CAVE " + level, w / 2, cy - 6); ctx.shadowBlur = 0;
    ctx.font = `600 ${Math.max(12, Math.min(16, Math.round(T * .55)))}px Manrope, sans-serif`; ctx.fillStyle = "#b8d8ff";
    ctx.fillText("Find " + crystalsTotal + " crystals, then fly out into the moonlight", w / 2, cy + 22);
    if (level === 1 && lives === 3) ctx.fillText((PA.isTouch ? "Tap" : "Space") + " to ping. Pings light the cave, but spiders hear them", w / 2, cy + 44);
  }
  drawHud(w, t);
}
function rrect(x, y, w, h, r) { ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath(); }
function drawHud(w, t) {
  shownScore += (score - shownScore) * .25;
  ctx.textAlign = "left";
  ctx.font = `800 ${w < 500 ? 26 : 30}px Manrope, sans-serif`;
  ctx.fillStyle = "#fff"; ctx.shadowColor = "#6ee1ff"; ctx.shadowBlur = 14;
  ctx.fillText(Math.round(shownScore).toLocaleString(), 16, 38); ctx.shadowBlur = 0;
  ctx.font = "700 11px 'JetBrains Mono', monospace"; ctx.fillStyle = "#a9c4e8";
  const narrow = w < 640, got = (crystalsTotal - crystalsLeft) + "/" + crystalsTotal;
  ctx.fillText("CAVE " + level + (narrow ? " · " + got + " · BEST " : "  ·  CRYSTALS " + got + "  ·  BEST ") + Math.max(best, score).toLocaleString(), 17, 56);
  for (let i = 0; i < lives - 1; i++) drawBat(26 + i * 26, 68, -Math.PI / 2, 1.2 + t * 3, 18, "#7a68b5", "#4b3c7c");
  // sonar charge
  // sonar charge: top centre, or just left of the pause and sound buttons on narrow screens
  const k = 1 - pingCd / PING_CD, x = narrow ? w - 172 : w / 2, y = 36;
  ctx.strokeStyle = "rgba(110,225,255,.2)"; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(x, y, 16, 0, TAU); ctx.stroke();
  ctx.strokeStyle = k >= 1 ? "#6ee1ff" : "rgba(110,225,255,.6)"; ctx.beginPath(); ctx.arc(x, y, 16, -Math.PI / 2, -Math.PI / 2 + TAU * k); ctx.stroke();
  ctx.fillStyle = k >= 1 ? "#d8f6ff" : "#5d7e99";
  for (let r = 4; r <= 10; r += 3) { ctx.beginPath(); ctx.arc(x - 4, y, r, -.6, .6); ctx.strokeStyle = ctx.fillStyle; ctx.lineWidth = 1.6; ctx.stroke(); }
  ctx.beginPath(); ctx.arc(x - 6, y, 2.2, 0, TAU); ctx.fill();
}
 
view = PA.canvas(document.getElementById("c"), { onResize: layout });
ctx = view.ctx;
reset();
PA.onStart(reset);
PA.loop(update, render);
window.__em = {
  get grid() { return grid; }, get player() { return player; }, get foes() { return foes; }, get crystals() { return crystals; },
  get phase() { return phase; }, get level() { return level; }, get score() { return score; }, get lives() { return lives; },
  get crystalsLeft() { return crystalsLeft; }, get gateOpen() { return gateOpen; }, get exitY() { return exitY; }, get rot() { return rot; },
  steer, ping, bfs, distTo, W, H, DIRS,
  setInvuln(s) { invuln = s; },
  clearAll() { for (const c of crystals) if (!c.got) { c.got = true; crystalsLeft--; } gateOpen = true; }
};
})();
</script>
</body></html>