Back to Arañas Pistoleras
SOURCE / PINNED RELEASE

Made of little things.

Arañas Pistoleras

Release
2578a037ceaf…
Author-recorded commit
e35cc0733a7b…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-7bf0a402584

Archive hash verified: 52cdda8c063eaf88…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/main.ts
import { MEDIA_DOMAIN, STORAGE_DOMAIN, media, storage } from '@napplet/sdk';
import { assetBlob, assetUrl } from '../soy-assets.js';
import * as A from './audio.js';
import { drawButterfly, drawButterflyGlow, WINGS } from './butterfly.js';
import { type AudioMediaClient, CoordinatedAudio } from './coordinated-audio.js';
import { runtimeHasDomain } from './domain-availability.js';
import { Fx, heartPath } from './fx.js';
import { Game, type GameEvent, LEVELS, MAX_HEARTS, type Spider, type View } from './game.js';
import { buildScene, type Scene, type SceneSound } from './scenes.js';
import { drawSpider, drawSpiderGlow, glow, makeGlowSprite, PALETTES, type SpiderPose } from './spider.js';
import './styles.css';

type Ctx = CanvasRenderingContext2D;
const TAU = Math.PI * 2;

const canvas = document.querySelector<HTMLCanvasElement>('#game') as HTMLCanvasElement;
const ctx = canvas.getContext('2d') as Ctx;
const bg = document.createElement('canvas');
const dark = document.createElement('canvas');
const glowSprite = makeGlowSprite();

/** Colours of the interface: slime on a night of purples. */
const UI = {
  night: '#120a24',
  panel: 'rgba(22,12,40,0.94)',
  edge: '#5a3b8a',
  slime: '#9be84a',
  slimeDark: '#3f7a1c',
  ink: '#1a0f24',
  bone: '#f4efe0',
  pink: '#ff5ad8',
  gold: '#ffd23f',
  heart: '#ff4a6a',
  dim: '#8c7aa8',
};
let FONT = '"Chalkboard SE", "Comic Sans MS", "Trebuchet MS", sans-serif';

// ------------------------------------------------------------------ frame

let cssW = 0;
let cssH = 0;
/** Canvas pixels per world unit. */
let px = 1;
/** CSS pixels per world unit. */
let unit = 1;
let view: View = { w: 1265, h: 790 };

type Screen = 'menu' | 'play';
type Overlay = null | 'pause' | 'won' | 'lost';
let screen: Screen = 'menu';
let overlay: Overlay = null;
let overlayT = 0;
let level = 0;
let game: Game | null = null;
let scene: Scene | null = null;
const fx = new Fx();
let time = 0;
let playTime = 0;
let pointer = { x: 600, y: 400 };
let attempts = 0;
let starsShown = 0;
/** Seconds until the lost panel opens, so the last crack can be seen. */
let lostIn = -1;
const warned = new Set<number>();

// --------------------------------------------------------------- progress

interface Progress {
  stars: number[];
  /** 2 everything, 1 effects only, 0 silent. */
  sound: number;
  /** 0 spiders to pop, 1 butterflies to collect. Same rules, another look and sound. */
  mode: number;
}
const progress: Progress = { stars: LEVELS.map(() => 0), sound: 2, mode: 0 };

function butterflies(): boolean {
  return progress.mode === 1;
}

function drawCreature(pose: SpiderPose): void {
  if (butterflies()) drawButterfly(ctx, pose);
  else drawSpider(ctx, pose);
}

function drawCreatureGlow(pose: SpiderPose): void {
  if (butterflies()) drawButterflyGlow(ctx, pose, glowSprite);
  else drawSpiderGlow(ctx, pose, glowSprite);
}
/** Lost attempts in a row on each level, for this session. */
const mercy = LEVELS.map(() => 0);
const PROGRESS_KEY = 'aranas-pistoleras-progress';
/** Levels opened for this session by tapping a locked card five times, for testing. */
const testOpen = new Set<number>();
const lockedTaps = new Map<number, number>();

function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> {
  return Promise.race([p, new Promise<T>((_, reject) => setTimeout(() => reject(new Error('timeout')), ms))]);
}

async function loadProgress(): Promise<void> {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return;
  try {
    const raw = await withTimeout(storage.getItem(PROGRESS_KEY), 3000);
    if (!raw) return;
    const data = JSON.parse(raw) as Partial<Progress>;
    if (Array.isArray(data.stars)) {
      // Keep whatever was won while the saved state was on its way.
      progress.stars = LEVELS.map((_, i) => Math.max(progress.stars[i], Math.max(0, Math.min(3, Number(data.stars?.[i]) || 0))));
    }
    if (typeof data.sound === 'number') progress.sound = Math.max(0, Math.min(2, Math.round(data.sound)));
    if (data.mode === 1 && !modeChosen) setMode(1);
    applySound();
  } catch {
    // Storage is optional; progress then lasts for this session only.
  }
}

function saveProgress(): void {
  if (!runtimeHasDomain(STORAGE_DOMAIN)) return;
  try {
    void withTimeout(storage.setItem(PROGRESS_KEY, JSON.stringify(progress)), 3000).catch(() => undefined);
  } catch {
    // Not saved; the game goes on.
  }
}

/** True once the player has used the switch, so a late saved state does not undo it. */
let modeChosen = false;

function setMode(mode: number): void {
  progress.mode = mode;
  A.setTheme(mode === 1);
  menuSpider = null;
  menuSpiderIn = 0.25;
}

function toggleMode(): void {
  modeChosen = true;
  setMode(progress.mode === 1 ? 0 : 1);
  A.sfx.chime(0);
  saveProgress();
}

function unlocked(i: number): boolean {
  return i === 0 || progress.stars[i - 1] > 0 || testOpen.has(i);
}

// ------------------------------------------------------------------ sound

/** A host without the media domain gets no sound: audio that the host cannot
 *  pause or turn down must not play. The plain dev server has no host, so it
 *  grants itself a session. */
const devMedia: AudioMediaClient = {
  createSession: async () => ({ owner: 'napplet', sessionId: 'dev' }),
  onCommand: () => ({ close: () => undefined }),
  reportState: () => undefined,
  destroySession: () => undefined,
};

function mediaAvailable(): boolean {
  return import.meta.env.DEV || runtimeHasDomain(MEDIA_DOMAIN);
}

/** Made on the first gesture, when the host has surely injected its domains. */
let sound: CoordinatedAudio | null = null;
function coordinated(): CoordinatedAudio {
  const client = runtimeHasDomain(MEDIA_DOMAIN) ? (media as unknown as AudioMediaClient) : import.meta.env.DEV ? devMedia : undefined;
  return (sound ??= new CoordinatedAudio(client, 'Arañas Pistoleras'));
}

/** False once the host has refused or ended the session. */
function soundAlive(): boolean {
  return mediaAvailable() && sound?.context?.state !== 'closed';
}

/** Starts audio on a tap or key; browsers allow it only from a gesture. It
 *  never overrides a pause from the host. */
function ensureAudio(): void {
  if (progress.sound === 0 || !mediaAvailable()) return;
  const s = coordinated();
  s.activate();
  if (s.context && s.output && A.init(s.context, s.output)) applySound();
}

function applySound(): void {
  A.setEnabled(progress.sound > 0, progress.sound > 1);
  sound?.setMuted(progress.sound === 0);
}

/** Steps through everything on, effects only and silent. */
function cycleSound(): void {
  if (!soundAlive()) return;
  progress.sound = (progress.sound + 2) % 3;
  ensureAudio();
  applySound();
  A.sfx.click();
  saveProgress();
}

function panAt(x: number): number {
  return (x / view.w - 0.5) * 1.3;
}

document.addEventListener('visibilitychange', () => {
  if (document.hidden && screen === 'play' && overlay === null) openOverlay('pause');
  if (!sound?.context || sound.context.state === 'closed') return;
  if (document.hidden) void sound.context.suspend().catch(() => undefined);
  else sound.activate();
});
window.addEventListener('pagehide', () => sound?.dispose());

// ----------------------------------------------------------------- stages

function resize(): void {
  const w = canvas.clientWidth;
  const h = canvas.clientHeight;
  if (w < 2 || h < 2) return;
  const dpr = Math.min(window.devicePixelRatio || 1, 2);
  const cw = Math.round(w * dpr);
  const ch = Math.round(h * dpr);
  if (cw === canvas.width && ch === canvas.height && w === cssW && h === cssH) return;
  cssW = w;
  cssH = h;
  canvas.width = bg.width = cw;
  canvas.height = bg.height = ch;
  unit = Math.sqrt(w * h) / 1000;
  px = unit * dpr;
  view = { w: w / unit, h: h / unit };
  fx.view = view;
  dark.width = Math.max(8, Math.round(cw / 6));
  dark.height = Math.max(8, Math.round(ch / 6));
  stage();
}

/** Builds the scene for the current screen and view, and bakes its background. */
function stage(): void {
  const b = bg.getContext('2d') as Ctx;
  b.setTransform(px, 0, 0, px, 0, 0);
  b.clearRect(0, 0, view.w, view.h);
  if (screen === 'play') {
    scene = buildScene(level, view);
    scene.paintStatic(b);
    game?.setStage(view, scene.spots, scene.floorY);
  } else {
    scene = null;
    paintMenuBackground(b);
  }
}

function startLevel(i: number): void {
  level = i;
  screen = 'play';
  overlay = null;
  lostIn = -1;
  attempts++;
  game = new Game(i, mercy[i], attempts);
  fx.clear();
  warned.clear();
  playTime = 0;
  stage();
  A.sfx.banner();
}

function toMenu(): void {
  screen = 'menu';
  overlay = null;
  game = null;
  fx.clear();
  menuSpider = null;
  menuSpiderIn = 0.4;
  stage();
}

function openOverlay(o: Overlay): void {
  overlay = o;
  overlayT = 0;
  focusI = 0;
  starsShown = 0;
}

// ---------------------------------------------------------- game to show

function muzzleOf(s: Spider, side: number): { x: number; y: number } {
  return { x: s.x + side * 46 * s.scale, y: s.y + 44 * s.scale };
}

const CAUGHT_WORDS = ['¡LINDA!', '¡BRAVO!', '¡TE TENGO!', '¡QUÉ BELLA!', '¡WOW!', '¡SÍ!'];
let lastCaughtWord = -1;

/** Where caught butterflies fly to: the bar at the top. */
function jar(): { x: number; y: number } {
  return { x: view.w / 2, y: hudSize() * 0.75 };
}

/** The butterfly version of what an event looks and sounds like. False when
 *  the event is the same in both modes. */
function handleButterfly(ev: GameEvent): boolean {
  const g = game as Game;
  switch (ev.type) {
    case 'spawn':
      if (ev.s.kind !== 'boss') A.bsfx.flutter(panAt(ev.s.x), ev.s.kind === 'mini');
      return true;
    case 'aim':
      warned.delete(ev.s.id);
      A.bsfx.ready(panAt(ev.s.x));
      return true;
    case 'fire': {
      A.bsfx.away(panAt(ev.s.x), ev.s.kind === 'boss');
      fx.flee(ev.s.x, ev.s.y, WINGS[ev.s.kind].glow);
      fx.word(ev.s.x, ev.s.y - 150 * ev.s.scale, 54, '¡ADIÓS!', '#ffffff');
      const hp = heartPos(g.hearts);
      fx.heartBreak(hp.x, hp.y, hp.s);
      return true;
    }
    case 'hit':
      fx.impact(ev.x, ev.y, true);
      A.bsfx.tap(panAt(ev.x), ev.s.kind === 'boss');
      if (ev.s.kind === 'boss' && ev.s.hp > 0) fx.sparkle(ev.x, ev.y, WINGS.boss.glow, 8);
      return true;
    case 'die': {
      const s = ev.s;
      const to = jar();
      fx.collect(s.x, s.y, s.scale, s.kind, WINGS[s.kind].glow, to.x, to.y);
      let i = Math.floor(Math.random() * CAUGHT_WORDS.length);
      if (i === lastCaughtWord) i = (i + 1) % CAUGHT_WORDS.length;
      lastCaughtWord = i;
      const label = ev.combo === 1 ? '¡DOBLE!' : ev.combo === 2 ? '¡TRIPLE!' : ev.combo >= 3 ? '¡COMBO!' : CAUGHT_WORDS[i];
      fx.word(s.x, s.y - 120 * s.scale, ev.combo > 0 ? 66 : 54, label, ev.combo > 0 ? UI.pink : UI.gold);
      A.bsfx.caught(panAt(s.x), ev.combo, s.scale);
      warned.delete(s.id);
      return true;
    }
    case 'bossIntro':
      A.bsfx.queenIntro();
      return true;
    case 'bossSummon':
      A.bsfx.queenCalls();
      return true;
    case 'bossDie': {
      const s = ev.s;
      const to = jar();
      fx.collect(s.x, s.y, s.scale, 'boss', WINGS.boss.glow, to.x, to.y, true);
      fx.word(s.x, s.y - 160 * s.scale, 84, '¡LA ATRAPASTE!', UI.pink);
      fx.confetti(view);
      A.bsfx.queenCaught();
      return true;
    }
    default:
      return false;
  }
}

function handle(ev: GameEvent): void {
  const g = game as Game;
  if (butterflies() && handleButterfly(ev)) return;
  switch (ev.type) {
    case 'spawn':
      A.sfx.spawn(panAt(ev.s.x), ev.s.mode, ev.s.kind);
      break;
    case 'aim':
      warned.delete(ev.s.id);
      A.sfx.cock(panAt(ev.s.x));
      break;
    case 'fire': {
      const boss = ev.s.kind === 'boss';
      A.sfx.bang(panAt(ev.s.x), boss);
      A.sfx.ouch();
      fx.crack(view);
      for (const side of [-1, 1]) {
        const m = muzzleOf(ev.s, side);
        fx.gunSmoke(m.x, m.y);
      }
      const hp = heartPos(g.hearts);
      fx.heartBreak(hp.x, hp.y, hp.s);
      break;
    }
    case 'hit': {
      const boss = ev.s.kind === 'boss';
      fx.impact(ev.x, ev.y, true);
      A.sfx.hit(panAt(ev.x), boss);
      if (boss && ev.s.hp > 0) {
        fx.sparkle(ev.x, ev.y, PALETTES.boss.goo, 6);
        if (ev.s.hp % 3 === 0) fx.word(ev.s.x, ev.s.y - 150 * ev.s.scale, 54);
      }
      break;
    }
    case 'hatOff':
      fx.hat(ev.s.x, ev.s.y - 60 * ev.s.scale, ev.s.scale, level, g.floorY);
      fx.word(ev.s.x, ev.s.y - 130 * ev.s.scale, 44, '¡UY!', '#ffffff');
      A.sfx.hatOff(panAt(ev.s.x));
      break;
    case 'die': {
      const s = ev.s;
      fx.burst(s.x, s.y, s.scale, PALETTES[s.kind], g.floorY);
      const label = ev.combo === 1 ? '¡DOBLE!' : ev.combo === 2 ? '¡TRIPLE!' : ev.combo >= 3 ? '¡COMBO!' : undefined;
      fx.word(s.x, s.y - 110 * s.scale, label ? 66 : 56, label, label ? UI.pink : UI.gold);
      A.sfx.pop(panAt(s.x), ev.combo, s.scale);
      A.sfx.squeal(panAt(s.x), s.kind);
      warned.delete(s.id);
      break;
    }
    case 'leave':
      if (ev.s.shots < g.def.shots && g.phase !== 'lost') A.sfx.giggle(panAt(ev.s.x));
      break;
    case 'miss': {
      const toy = scene?.toys.find((t) => Math.hypot(ev.x - t.x, ev.y - t.y) < t.r);
      const snd = toy ? scene?.poke(toy.id, playTime) : null;
      if (toy && snd) {
        playScene(snd, toy.x);
        fx.sparkle(toy.x, toy.y, '#fff0b0', 5);
      } else {
        fx.impact(ev.x, ev.y, false);
        A.sfx.miss(panAt(ev.x));
      }
      break;
    }
    case 'heart':
      A.sfx.heartAppear(panAt(ev.p.x));
      fx.sparkle(ev.p.x, ev.p.y, UI.heart, 8);
      break;
    case 'heal':
      A.sfx.heal();
      fx.sparkle(ev.p.x, ev.p.y, UI.heart, 16);
      fx.word(ev.p.x, ev.p.y - 50, 50, '+1', UI.heart);
      break;
    case 'bossIntro':
      A.sfx.bossIntro();
      fx.shake = 1;
      break;
    case 'bossStun':
      A.sfx.bossStun(panAt(ev.s.x));
      fx.word(ev.s.x, ev.s.y - 170 * ev.s.scale, 60, '¡MAREADA!', '#ffffff');
      break;
    case 'bossSummon':
      A.sfx.bossSummon();
      break;
    case 'bossDie': {
      const s = ev.s;
      fx.burst(s.x, s.y, s.scale, PALETTES.boss, g.floorY, { hat: 9, pistols: 4, big: true });
      fx.word(s.x, s.y - 160 * s.scale, 90, '¡CATAPLUM!', UI.pink);
      fx.confetti(view);
      A.sfx.bossDie();
      A.sfx.squeal(panAt(s.x), 'boss');
      break;
    }
    case 'win':
      progress.stars[level] = Math.max(progress.stars[level], ev.stars);
      mercy[level] = 0;
      saveProgress();
      openOverlay('won');
      fx.confetti(view, 50);
      A.sfx.win();
      break;
    case 'lose':
      mercy[level]++;
      lostIn = 1.3;
      break;
    default:
      break;
  }
}

function playScene(s: SceneSound, x: number): void {
  const pan = panAt(x);
  switch (s) {
    case 'thunder':
      A.sfx.thunder();
      break;
    case 'flicker':
      A.sfx.flicker();
      break;
    default:
      A.sfx[s](pan);
  }
}

function poseOf(s: Spider): SpiderPose {
  const aiming = s.state === 'aim';
  let aim = 0;
  if (aiming) aim = smooth(Math.min(1, s.t / 0.42));
  else if (s.state === 'fire') aim = 1 - smooth(Math.max(0, Math.min(1, (s.t - 0.28) / 0.27)));
  const heat = aiming ? Math.min(1, s.t / s.dur) : 0;
  const moving = s.state === 'enter' || s.state === 'leave';
  let squashX = 1;
  let squashY = 1;
  if (s.flinch > 0) {
    squashX = 1.14;
    squashY = 0.86;
  } else if (s.state === 'lurk' && s.t < 0.3 && s.age < 2) {
    // It settles after arriving.
    const k = Math.sin((s.t / 0.3) * Math.PI);
    squashX = 1 + 0.07 * k;
    squashY = 1 - 0.07 * k;
  }
  return {
    kind: s.kind,
    x: s.x,
    y: s.y,
    scale: s.scale,
    time: s.age,
    seed: s.seed,
    hanging: s.mode === 'drop',
    grounded: s.mode === 'crawl',
    walk: s.mode === 'crawl' && moving ? 1 : s.state === 'move' ? 0.5 : 0.06,
    aim,
    heat,
    flash: s.sinceShot < 0.18 ? 1 - s.sinceShot / 0.18 : 0,
    hurt: s.flinch > 0.07,
    dizzy: s.state === 'stun',
    hat: s.hat ? level : -1,
    lookX: clamp((pointer.x - s.x) / 300, -1, 1),
    lookY: clamp((pointer.y - s.y) / 300, -1, 1),
    squashX,
    squashY,
    threadTop: s.mode === 'drop' ? -30 : undefined,
  };
}

function smooth(p: number): number {
  return p * p * (3 - 2 * p);
}

function clamp(v: number, lo: number, hi: number): number {
  return Math.max(lo, Math.min(hi, v));
}

// ------------------------------------------------------------------- menu

interface MenuSpider {
  kind: Spider['kind'];
  hat: number;
  age: number;
  seed: number;
  flinch: number;
}
let menuSpider: MenuSpider | null = null;
let menuSpiderIn = 0.6;
let menuKills = 0;
const thumbs: HTMLCanvasElement[] = [];

function thumb(i: number): HTMLCanvasElement {
  if (!thumbs[i]) {
    const c = document.createElement('canvas');
    c.width = 400;
    c.height = 250;
    const t = c.getContext('2d') as Ctx;
    const v = { w: 1265, h: 790 };
    t.scale(c.width / v.w, c.height / v.h);
    const s = buildScene(i, v);
    s.paintStatic(t);
    s.paintLive(t, 3);
    s.paintFront(t, 3);
    thumbs[i] = c;
  }
  return thumbs[i];
}

interface MenuLayout {
  titleSize: number;
  titleX: number;
  titleY: number;
  spider: { x: number; y: number; scale: number };
  cards: { x: number; y: number; w: number; h: number }[];
}

function menuLayout(): MenuLayout {
  const m = Math.max(18, Math.min(view.w, view.h) * 0.04);
  const wide = view.w >= view.h * 1.12;
  const cards: MenuLayout['cards'] = [];
  if (wide) {
    const titleSize = Math.min(view.h * 0.17, view.w * 0.1);
    const titleY = m + titleSize * 0.62;
    const top = titleY + titleSize * 1.55;
    const gap = m * 0.6;
    const areaH = view.h - top - m;
    const w = Math.min((view.w - 2 * m - 4 * gap) / 5, areaH * 1.12);
    const h = w / 1.12;
    const total = 5 * w + 4 * gap;
    const y = top + (areaH - h) * 0.5;
    for (let i = 0; i < 5; i++) cards.push({ x: (view.w - total) / 2 + i * (w + gap), y, w, h });
    const sScale = Math.min(1.25, (top - m) / 300);
    return { titleSize, titleX: view.w * 0.4, titleY, spider: { x: view.w * 0.76, y: m + 150 * sScale, scale: sScale }, cards };
  }
  const titleSize = Math.min(view.w * 0.19, view.h * 0.1);
  // Below the buttons in the corners.
  const titleY = m + titleSize * 0.62 + hudSize() * 0.75;
  const top = titleY + titleSize * 1.6;
  const gap = m * 0.6;
  const areaH = view.h - top - m;
  const w = Math.min((view.w - 2 * m - gap) / 2, ((areaH - 2 * gap) / 3) * 1.12);
  const h = w / 1.12;
  const totalW = 2 * w + gap;
  const totalH = 3 * h + 2 * gap;
  const y0 = top + (areaH - totalH) / 2;
  for (let i = 0; i < 5; i++) {
    cards.push({ x: (view.w - totalW) / 2 + (i % 2) * (w + gap), y: y0 + Math.floor(i / 2) * (h + gap), w, h });
  }
  // The sixth place in the grid belongs to a spider.
  const sScale = Math.min(1, h / 330);
  return {
    titleSize,
    titleX: view.w / 2,
    titleY,
    spider: { x: (view.w - totalW) / 2 + w + gap + w / 2, y: y0 + 2 * (h + gap) + h * 0.5, scale: sScale },
    cards,
  };
}

function paintMenuBackground(c: Ctx): void {
  const g = c.createLinearGradient(0, 0, 0, view.h);
  g.addColorStop(0, '#0d0720');
  g.addColorStop(0.55, '#231040');
  g.addColorStop(1, '#3a1a50');
  c.fillStyle = g;
  c.fillRect(0, 0, view.w, view.h);
  // Stars.
  let seed = 7;
  const rnd = (): number => {
    seed = (seed * 16807) % 2147483647;
    return seed / 2147483647;
  };
  for (let i = 0; i < 110; i++) {
    c.fillStyle = `rgba(255,255,255,${0.2 + rnd() * 0.6})`;
    c.beginPath();
    c.arc(rnd() * view.w, rnd() * view.h, 0.8 + rnd() * 1.8, 0, TAU);
    c.fill();
  }
  // A big pale moon behind the title.
  const mx = view.w * 0.16;
  const my = view.h * 0.2;
  const mr = Math.min(view.w, view.h) * 0.2;
  const halo = c.createRadialGradient(mx, my, mr * 0.7, mx, my, mr * 2.6);
  halo.addColorStop(0, 'rgba(190,160,255,0.3)');
  halo.addColorStop(1, 'rgba(190,160,255,0)');
  c.fillStyle = halo;
  c.fillRect(0, 0, view.w, view.h);
  c.fillStyle = '#d9cdf0';
  c.beginPath();
  c.arc(mx, my, mr, 0, TAU);
  c.fill();
  c.fillStyle = 'rgba(120,95,170,0.35)';
  for (const [ox, oy, r] of [[-0.3, -0.2, 0.2], [0.34, 0.3, 0.26], [0.2, -0.46, 0.12], [-0.4, 0.4, 0.1]]) {
    c.beginPath();
    c.arc(mx + ox * mr, my + oy * mr, r * mr, 0, TAU);
    c.fill();
  }
  // Webs from the corners.
  const web = (x: number, y: number, r: number, a0: number, a1: number): void => {
    c.strokeStyle = 'rgba(230,225,255,0.3)';
    c.lineWidth = 2;
    const n = 7;
    for (let i = 0; i <= n; i++) {
      const a = a0 + ((a1 - a0) * i) / n;
      c.beginPath();
      c.moveTo(x, y);
      c.lineTo(x + Math.cos(a) * r, y + Math.sin(a) * r);
      c.stroke();
    }
    for (let ring = 1; ring <= 6; ring++) {
      const rad = (r * ring) / 6.4;
      c.beginPath();
      for (let i = 0; i < n; i++) {
        const b0 = a0 + ((a1 - a0) * i) / n;
        const b1 = a0 + ((a1 - a0) * (i + 1)) / n;
        const mid = (b0 + b1) / 2;
        if (i === 0) c.moveTo(x + Math.cos(b0) * rad, y + Math.sin(b0) * rad);
        c.quadraticCurveTo(x + Math.cos(mid) * rad * 0.84, y + Math.sin(mid) * rad * 0.84, x + Math.cos(b1) * rad, y + Math.sin(b1) * rad);
      }
      c.stroke();
    }
  };
  web(view.w, 0, Math.min(view.w, view.h) * 0.75, Math.PI / 2, Math.PI);
  // A hill with a crooked fence and a bare tree along the bottom.
  const hy = view.h - Math.min(view.h * 0.09, 70);
  c.fillStyle = '#0b0618';
  c.beginPath();
  c.moveTo(0, view.h);
  c.lineTo(0, hy + 10);
  c.quadraticCurveTo(view.w * 0.3, hy - 34, view.w * 0.6, hy + 6);
  c.quadraticCurveTo(view.w * 0.85, hy + 30, view.w, hy - 8);
  c.lineTo(view.w, view.h);
  c.closePath();
  c.fill();
  c.strokeStyle = '#0b0618';
  c.lineCap = 'round';
  for (let x = view.w * 0.04; x < view.w * 0.5; x += 46) {
    c.lineWidth = 7;
    const lean = (rnd() - 0.5) * 12;
    c.beginPath();
    c.moveTo(x, hy + 14);
    c.lineTo(x + lean, hy - 38 - rnd() * 14);
    c.stroke();
  }
  c.lineWidth = 4;
  c.beginPath();
  c.moveTo(view.w * 0.03, hy - 16);
  c.lineTo(view.w * 0.5, hy - 22);
  c.stroke();
  const tx = view.w * 0.7;
  c.lineWidth = 13;
  c.beginPath();
  c.moveTo(tx, hy + 20);
  c.quadraticCurveTo(tx - 8, hy - 50, tx + 10, hy - 104);
  c.stroke();
  c.lineWidth = 6;
  c.beginPath();
  c.moveTo(tx + 2, hy - 60);
  c.quadraticCurveTo(tx + 40, hy - 80, tx + 58, hy - 124);
  c.moveTo(tx + 6, hy - 84);
  c.quadraticCurveTo(tx - 30, hy - 104, tx - 40, hy - 140);
  c.moveTo(tx + 44, hy - 96);
  c.lineTo(tx + 74, hy - 102);
  c.stroke();
  web(0, 0, Math.min(view.w, view.h) * 0.3, 0, Math.PI / 2);
  const vg = c.createRadialGradient(view.w / 2, view.h / 2, Math.min(view.w, view.h) * 0.3, view.w / 2, view.h / 2, Math.hypot(view.w, view.h) * 0.62);
  vg.addColorStop(0, 'rgba(5,2,12,0)');
  vg.addColorStop(1, 'rgba(5,2,12,0.6)');
  c.fillStyle = vg;
  c.fillRect(0, 0, view.w, view.h);
}

function menuSpiderPose(L: MenuLayout): SpiderPose | null {
  const m = menuSpider;
  if (!m) return null;
  const drop = Math.min(1, m.age / 0.9);
  const e = 1 - Math.pow(1 - drop, 3);
  const scale = L.spider.scale * (m.kind === 'mini' ? 0.62 : m.kind === 'boss' ? 1.15 : 1);
  const x = L.spider.x + Math.sin(m.age * 1.2) * 10;
  const y = -200 + (L.spider.y + 200) * e + Math.sin(m.age * 1.9) * 5;
  // It practises its aim while it waits.
  const cycle = m.age % 5;
  const aim = cycle > 3 ? smooth(Math.min(1, (cycle - 3) / 0.4)) * (cycle > 4.6 ? smooth((5 - cycle) / 0.4) : 1) : 0;
  return {
    kind: m.kind,
    x,
    y,
    scale,
    time: m.age,
    seed: m.seed,
    hanging: true,
    grounded: false,
    walk: 0,
    aim,
    heat: 0,
    flash: 0,
    hurt: m.flinch > 0,
    dizzy: false,
    hat: m.kind === 'hat' ? m.hat : -1,
    lookX: clamp((pointer.x - x) / 300, -1, 1),
    lookY: clamp((pointer.y - y) / 300, -1, 1),
    squashX: 1,
    squashY: 1,
    threadTop: -30,
  };
}

function drawTitle(L: MenuLayout): void {
  const s = L.titleSize;
  ctx.save();
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.lineJoin = 'round';
  const bf = butterflies();
  const lines = bf ? ['MARIPOSAS', 'MÁGICAS'] : ['ARAÑAS', 'PISTOLERAS'];
  // A long word must not run into the corners, where the buttons are.
  const limit = view.w >= view.h * 1.12 ? view.w * 0.46 : view.w * 0.86;
  lines.forEach((text, i) => {
    let size = i === 0 ? s : s * 0.78;
    ctx.font = `${size}px ${FONT}`;
    const wide = ctx.measureText(text).width;
    if (wide > limit) size *= limit / wide;
    const y = L.titleY + (i === 0 ? 0 : s * 0.86);
    const wob = Math.sin(time * 1.4 + i * 1.3) * 0.012;
    ctx.save();
    ctx.translate(L.titleX, y);
    ctx.rotate(-0.035 + wob);
    ctx.font = `${size}px ${FONT}`;
    ctx.strokeStyle = UI.ink;
    ctx.lineWidth = size * 0.2;
    ctx.strokeText(text, 0, size * 0.04);
    const g = ctx.createLinearGradient(0, -size * 0.45, 0, size * 0.5);
    if (bf) {
      g.addColorStop(0, i === 0 ? '#fff29a' : '#a8f0ff');
      g.addColorStop(1, i === 0 ? '#ff9a3a' : '#4a8cf0');
    } else if (i === 0) {
      g.addColorStop(0, '#e2ff8a');
      g.addColorStop(1, '#6fcf2a');
    } else {
      g.addColorStop(0, '#ffc0f0');
      g.addColorStop(1, '#ff4fc4');
    }
    ctx.fillStyle = g;
    ctx.fillText(text, 0, 0);
    // Slime dripping from the first word.
    if (i === 0 && !bf) {
      const w = ctx.measureText(text).width;
      ctx.fillStyle = '#6fcf2a';
      for (const [f, len, ph] of [[-0.36, 0.34, 0], [-0.08, 0.5, 2], [0.2, 0.28, 4], [0.41, 0.42, 1]]) {
        const l = size * len * (0.75 + 0.25 * Math.sin(time * 0.9 + ph));
        const dw = size * 0.075;
        ctx.beginPath();
        ctx.roundRect(f * w - dw / 2, size * 0.3, dw, l, dw / 2);
        ctx.fill();
        ctx.beginPath();
        ctx.arc(f * w, size * 0.3 + l, dw * 0.8, 0, TAU);
        ctx.fill();
      }
    }
    ctx.restore();
  });
  ctx.restore();
}

function star(c: Ctx, x: number, y: number, r: number, fill: string, stroke?: string): void {
  c.beginPath();
  for (let i = 0; i < 10; i++) {
    const a = (i / 10) * TAU - Math.PI / 2;
    const rr = i % 2 ? r * 0.46 : r;
    c.lineTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr);
  }
  c.closePath();
  c.fillStyle = fill;
  c.fill();
  if (stroke) {
    c.strokeStyle = stroke;
    c.lineWidth = Math.max(1.5, r * 0.14);
    c.stroke();
  }
}

const SHORT_NAMES = ['Colegio', 'Cocina', 'Dormitorio', 'Bodega', 'Bosque'];

function drawMenu(dt: number): void {
  ctx.drawImage(bg, 0, 0, view.w, view.h);
  const L = menuLayout();

  // The spider beside the title; it can be popped, and another one comes.
  if (!menuSpider) {
    menuSpiderIn -= dt;
    if (menuSpiderIn <= 0) {
      const kinds: Spider['kind'][] = ['widow', 'hat', 'mini', 'widow', 'hat', 'boss'];
      menuSpider = { kind: kinds[menuKills % kinds.length], hat: menuKills % 5, age: 0, seed: Math.random(), flinch: 0 };
    }
  } else {
    menuSpider.age += dt;
    menuSpider.flinch = Math.max(0, menuSpider.flinch - dt);
  }
  const pose = menuSpiderPose(L);
  if (pose) drawCreature(pose);

  drawTitle(L);

  const next = LEVELS.findIndex((_, i) => unlocked(i) && progress.stars[i] === 0);
  L.cards.forEach((c, i) => {
    const open = unlocked(i);
    const focused = showFocus && focusI === i;
    const hot = i === next;
    const bob = hot ? Math.sin(time * 3.2) * c.h * 0.012 : 0;
    ctx.save();
    ctx.translate(c.x + c.w / 2, c.y + c.h / 2 + bob);
    ctx.rotate((i % 2 ? 1 : -1) * 0.012);
    const x = -c.w / 2;
    const y = -c.h / 2;
    // Frame.
    ctx.fillStyle = 'rgba(0,0,0,0.4)';
    ctx.beginPath();
    ctx.roundRect(x + c.w * 0.02, y + c.w * 0.035, c.w, c.h, c.w * 0.07);
    ctx.fill();
    ctx.fillStyle = hot ? UI.slime : open ? '#6a4a9a' : '#3a2a52';
    ctx.beginPath();
    ctx.roundRect(x, y, c.w, c.h, c.w * 0.07);
    ctx.fill();
    const pad = c.w * 0.035;
    const th = (c.w - 2 * pad) / 1.6;
    ctx.save();
    ctx.beginPath();
    ctx.roundRect(x + pad, y + pad, c.w - 2 * pad, th, c.w * 0.045);
    ctx.clip();
    ctx.drawImage(thumb(i), x + pad, y + pad, c.w - 2 * pad, th);
    if (!open) {
      ctx.fillStyle = 'rgba(14,8,26,0.78)';
      ctx.fillRect(x + pad, y + pad, c.w - 2 * pad, th);
    }
    ctx.restore();
    if (!open) drawLock(0, y + pad + th / 2, th * 0.26);
    // Number.
    const nr = c.w * 0.085;
    ctx.fillStyle = UI.ink;
    ctx.beginPath();
    ctx.arc(x + pad + nr * 1.1, y + pad + nr * 1.1, nr, 0, TAU);
    ctx.fill();
    ctx.fillStyle = open ? UI.bone : UI.dim;
    ctx.font = `${nr * 1.5}px ${FONT}`;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(String(i + 1), x + pad + nr * 1.1, y + pad + nr * 1.16);
    // Name and stars.
    const stripY = y + pad + th;
    const stripH = c.h - pad - th;
    ctx.fillStyle = hot ? UI.ink : open ? UI.bone : UI.dim;
    const fs = Math.min(stripH * 0.52, c.w * 0.13);
    ctx.font = `${fs}px ${FONT}`;
    ctx.textAlign = 'left';
    ctx.fillText(SHORT_NAMES[i], x + pad * 1.6, stripY + stripH * 0.54, c.w * 0.5);
    const sr = Math.min(stripH * 0.25, c.w * 0.046);
    for (let s = 0; s < 3; s++) {
      const on = progress.stars[i] > s;
      star(ctx, x + c.w - pad * 1.6 - sr - (2 - s) * sr * 2.2, stripY + stripH * 0.5, sr, on ? UI.gold : 'rgba(0,0,0,0.35)', on ? UI.ink : undefined);
    }
    if (focused) {
      ctx.strokeStyle = UI.bone;
      ctx.lineWidth = Math.max(3, c.w * 0.02);
      ctx.beginPath();
      ctx.roundRect(x - 5, y - 5, c.w + 10, c.h + 10, c.w * 0.08);
      ctx.stroke();
    }
    ctx.restore();
    btns.push({ id: `level${i}`, x: c.x, y: c.y, w: c.w, h: c.h, tap: () => tapCard(i) });
  });

  fx.draw(ctx);
  ctx.globalCompositeOperation = 'lighter';
  if (pose) drawCreatureGlow(pose);
  fx.drawGlow(ctx, glowSprite);
  ctx.globalCompositeOperation = 'source-over';
  fx.drawWords(ctx, FONT);

  const b = hudSize();
  iconButton('sound', view.w - b * 1.25, b * 0.25, b, soundIcon(), cycleSound, 5);
  // Spiders or butterflies: beside the sound button, or in the other corner when the frame is narrow.
  const wide = view.w >= view.h * 1.12;
  modeSwitch(wide ? view.w - b * 3.7 : b * 0.25, b * 0.25, b, 6);
}

function tapCard(i: number): void {
  if (unlocked(i)) {
    A.sfx.start();
    startLevel(i);
    return;
  }
  // Five taps open a locked level for this session.
  const n = (lockedTaps.get(i) ?? 0) + 1;
  lockedTaps.set(i, n);
  A.sfx.bonk(0);
  if (n >= 5) {
    testOpen.add(i);
    A.sfx.chime(0);
  }
}

function drawLock(x: number, y: number, s: number): void {
  ctx.strokeStyle = UI.bone;
  ctx.lineWidth = s * 0.26;
  ctx.beginPath();
  ctx.arc(x, y - s * 0.35, s * 0.5, Math.PI, 0);
  ctx.stroke();
  ctx.fillStyle = UI.bone;
  ctx.beginPath();
  ctx.roundRect(x - s * 0.8, y - s * 0.35, s * 1.6, s * 1.25, s * 0.2);
  ctx.fill();
  ctx.fillStyle = UI.ink;
  ctx.beginPath();
  ctx.arc(x, y + s * 0.15, s * 0.2, 0, TAU);
  ctx.fill();
  ctx.fillRect(x - s * 0.08, y + s * 0.15, s * 0.16, s * 0.42);
}

// -------------------------------------------------------------------- HUD

interface Btn {
  id: string;
  x: number;
  y: number;
  w: number;
  h: number;
  tap: () => void;
}
/** Rebuilt every frame while drawing; taps test against the last frame's. */
let btns: Btn[] = [];
let focusI = 0;
let showFocus = false;

/** The size of a HUD element in world units: readable on the smallest frame. */
function hudSize(): number {
  return Math.max(clamp(Math.min(view.w, view.h) * 0.075, 44, 64), 17 / unit);
}

function heartPos(i: number): { x: number; y: number; s: number } {
  const b = hudSize();
  const s = b * 0.36;
  return { x: b * 0.62 + i * s * 2.5, y: b * 0.75, s };
}

type Icon = 'pause' | 'play' | 'retry' | 'levels' | 'sound2' | 'sound1' | 'sound0' | 'nosound';

function soundIcon(): Icon {
  if (!soundAlive()) return 'nosound';
  return progress.sound === 2 ? 'sound2' : progress.sound === 1 ? 'sound1' : 'sound0';
}

function drawIcon(icon: Icon, x: number, y: number, s: number, color: string): void {
  ctx.fillStyle = color;
  ctx.strokeStyle = color;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  switch (icon) {
    case 'pause':
      ctx.beginPath();
      ctx.roundRect(x - s * 0.34, y - s * 0.4, s * 0.24, s * 0.8, s * 0.06);
      ctx.roundRect(x + s * 0.1, y - s * 0.4, s * 0.24, s * 0.8, s * 0.06);
      ctx.fill();
      break;
    case 'play':
      ctx.beginPath();
      ctx.moveTo(x - s * 0.26, y - s * 0.4);
      ctx.lineTo(x + s * 0.42, y);
      ctx.lineTo(x - s * 0.26, y + s * 0.4);
      ctx.closePath();
      ctx.fill();
      break;
    case 'retry':
      ctx.lineWidth = s * 0.16;
      ctx.beginPath();
      ctx.arc(x, y, s * 0.34, -0.9, Math.PI * 1.35);
      ctx.stroke();
      ctx.beginPath();
      ctx.moveTo(x + s * 0.02, y - s * 0.56);
      ctx.lineTo(x + s * 0.36, y - s * 0.36);
      ctx.lineTo(x + s * 0.04, y - s * 0.1);
      ctx.closePath();
      ctx.fill();
      break;
    case 'levels':
      for (let r = 0; r < 2; r++) {
        for (let c = 0; c < 2; c++) {
          ctx.beginPath();
          ctx.roundRect(x - s * 0.38 + c * s * 0.42, y - s * 0.38 + r * s * 0.42, s * 0.34, s * 0.34, s * 0.07);
          ctx.fill();
        }
      }
      break;
    default: {
      // A speaker; waves for sound, a note for music, a stroke for silence.
      ctx.beginPath();
      ctx.moveTo(x - s * 0.42, y - s * 0.14);
      ctx.lineTo(x - s * 0.22, y - s * 0.14);
      ctx.lineTo(x + s * 0.02, y - s * 0.36);
      ctx.lineTo(x + s * 0.02, y + s * 0.36);
      ctx.lineTo(x - s * 0.22, y + s * 0.14);
      ctx.lineTo(x - s * 0.42, y + s * 0.14);
      ctx.closePath();
      ctx.fill();
      ctx.lineWidth = s * 0.09;
      if (icon === 'sound2' || icon === 'sound1') {
        ctx.beginPath();
        ctx.arc(x + s * 0.04, y, s * 0.24, -0.8, 0.8);
        ctx.stroke();
      }
      if (icon === 'sound2') {
        ctx.beginPath();
        ctx.arc(x + s * 0.04, y, s * 0.42, -0.8, 0.8);
        ctx.stroke();
      }
      if (icon === 'sound0' || icon === 'nosound') {
        ctx.beginPath();
        ctx.moveTo(x + s * 0.16, y - s * 0.2);
        ctx.lineTo(x + s * 0.46, y + s * 0.2);
        ctx.moveTo(x + s * 0.46, y - s * 0.2);
        ctx.lineTo(x + s * 0.16, y + s * 0.2);
        ctx.stroke();
      }
    }
  }
}

function iconButton(id: string, x: number, y: number, s: number, icon: Icon, tap: () => void, focusIndex = -1): void {
  const dead = icon === 'nosound';
  ctx.fillStyle = 'rgba(18,10,36,0.72)';
  ctx.beginPath();
  ctx.roundRect(x, y, s, s, s * 0.28);
  ctx.fill();
  ctx.strokeStyle = showFocus && focusI === focusIndex ? UI.bone : UI.edge;
  ctx.lineWidth = Math.max(1.5, s * 0.05);
  ctx.stroke();
  drawIcon(icon, x + s / 2, y + s / 2, s * 0.86, dead ? UI.dim : UI.bone);
  // The touch target is at least 44 CSS pixels.
  const hit = Math.max(s, 44 / unit);
  btns.push({ id, x: x + s / 2 - hit / 2, y: Math.max(0, y + s / 2 - hit / 2), w: hit, h: hit, tap });
}

/** A little spider or butterfly for the switch. */
function creatureIcon(butterfly: boolean, x: number, y: number, s: number, color: string): void {
  ctx.fillStyle = color;
  ctx.strokeStyle = color;
  ctx.lineCap = 'round';
  if (butterfly) {
    for (const side of [-1, 1]) {
      ctx.beginPath();
      ctx.ellipse(x + side * s * 0.23, y - s * 0.12, s * 0.2, s * 0.26, side * 0.5, 0, TAU);
      ctx.ellipse(x + side * s * 0.17, y + s * 0.2, s * 0.14, s * 0.17, -side * 0.4, 0, TAU);
      ctx.fill();
    }
    ctx.lineWidth = s * 0.09;
    ctx.beginPath();
    ctx.moveTo(x, y - s * 0.26);
    ctx.lineTo(x, y + s * 0.3);
    ctx.stroke();
  } else {
    ctx.beginPath();
    ctx.arc(x, y, s * 0.2, 0, TAU);
    ctx.fill();
    ctx.lineWidth = s * 0.07;
    for (const side of [-1, 1]) {
      for (let i = 0; i < 4; i++) {
        const a = -0.9 + i * 0.6;
        ctx.beginPath();
        ctx.moveTo(x + side * s * 0.14, y + Math.sin(a) * s * 0.1);
        ctx.lineTo(x + side * s * 0.34, y + Math.sin(a) * s * 0.3 - s * 0.08);
        ctx.lineTo(x + side * s * 0.44, y + Math.sin(a) * s * 0.36 + s * 0.06);
        ctx.stroke();
      }
    }
  }
}

/** Two halves: spiders on the left, butterflies on the right; the lit one is on. */
function modeSwitch(x: number, y: number, h: number, focusIndex: number): void {
  const w = h * 2.2;
  const bf = butterflies();
  ctx.fillStyle = 'rgba(18,10,36,0.78)';
  ctx.beginPath();
  ctx.roundRect(x, y, w, h, h * 0.5);
  ctx.fill();
  ctx.strokeStyle = showFocus && focusI === focusIndex ? UI.bone : UI.edge;
  ctx.lineWidth = Math.max(1.5, h * 0.05);
  ctx.stroke();
  const kx = x + (bf ? w - h * 1.1 : 0) + h * 0.08;
  ctx.fillStyle = bf ? UI.pink : UI.slime;
  ctx.beginPath();
  ctx.roundRect(kx, y + h * 0.08, h * 1.02, h * 0.84, h * 0.42);
  ctx.fill();
  creatureIcon(false, x + h * 0.59, y + h / 2, h * 0.86, bf ? UI.dim : UI.ink);
  creatureIcon(true, x + w - h * 0.59, y + h / 2, h * 0.86, bf ? UI.ink : UI.dim);
  const hit = Math.max(h, 44 / unit);
  btns.push({ id: 'mode', x, y: Math.max(0, y + h / 2 - hit / 2), w, h: hit, tap: toggleMode });
}

function drawHud(g: Game): void {
  const b = hudSize();
  // Hearts.
  for (let i = 0; i < MAX_HEARTS; i++) {
    const p = heartPos(i);
    const full = i < g.hearts;
    const last = full && g.hearts === 1;
    const s = p.s * (last ? 1 + 0.12 * Math.sin(time * 9) : 1);
    heartPath(ctx, p.x, p.y, s);
    ctx.fillStyle = full ? UI.heart : 'rgba(18,10,36,0.6)';
    ctx.fill();
    ctx.strokeStyle = full ? UI.ink : 'rgba(255,255,255,0.3)';
    ctx.lineWidth = Math.max(1.5, s * 0.16);
    ctx.stroke();
    if (full) {
      ctx.fillStyle = 'rgba(255,255,255,0.55)';
      ctx.beginPath();
      ctx.ellipse(p.x - s * 0.42, p.y - s * 0.3, s * 0.2, s * 0.13, -0.6, 0, TAU);
      ctx.fill();
    }
  }
  // Progress: spiders beaten, then the queen's health.
  const bossPhase = g.phase === 'bossIntro' || g.phase === 'boss' || g.phase === 'outro';
  const right = view.w - b * 3.05;
  const left = heartPos(MAX_HEARTS - 1).x + b * 0.7;
  const bw = Math.min(right - left, 460);
  if (bw > b * 2) {
    const bx = left + (right - left - bw) / 2;
    const by = b * 0.75;
    const bh = b * 0.3;
    const f = bossPhase ? (g.boss ? g.boss.hp / g.boss.maxHp : g.phase === 'outro' ? 0 : 1) : g.progress;
    ctx.fillStyle = 'rgba(18,10,36,0.72)';
    ctx.beginPath();
    ctx.roundRect(bx - 4, by - bh / 2 - 4, bw + 8, bh + 8, bh);
    ctx.fill();
    ctx.fillStyle = bossPhase ? UI.pink : UI.slime;
    if (f > 0.01) {
      ctx.beginPath();
      ctx.roundRect(bx, by - bh / 2, Math.max(bh, bw * f), bh, bh / 2);
      ctx.fill();
      ctx.fillStyle = 'rgba(255,255,255,0.3)';
      ctx.beginPath();
      ctx.roundRect(bx + bh * 0.3, by - bh * 0.32, Math.max(0, bw * f - bh * 0.6), bh * 0.22, bh * 0.1);
      ctx.fill();
    }
    // The crown at the end of the bar.
    const cx = bossPhase ? bx - b * 0.1 : bx + bw + b * 0.02;
    const cs = b * 0.3;
    ctx.fillStyle = UI.gold;
    ctx.strokeStyle = UI.ink;
    ctx.lineWidth = Math.max(1.2, cs * 0.14);
    ctx.lineJoin = 'round';
    ctx.beginPath();
    ctx.moveTo(cx - cs, by + cs * 0.7);
    ctx.lineTo(cx - cs * 1.1, by - cs * 0.6);
    ctx.lineTo(cx - cs * 0.5, by);
    ctx.lineTo(cx, by - cs * 0.9);
    ctx.lineTo(cx + cs * 0.5, by);
    ctx.lineTo(cx + cs * 1.1, by - cs * 0.6);
    ctx.lineTo(cx + cs, by + cs * 0.7);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
  }
  iconButton('sound', view.w - b * 2.5, b * 0.25, b, soundIcon(), cycleSound);
  iconButton('pause', view.w - b * 1.25, b * 0.25, b, 'pause', () => {
    A.sfx.click();
    openOverlay('pause');
  });
}

/** The name of the place as the level opens, and the queen's entrance. */
function drawBanner(g: Game): void {
  let text = '';
  let sub = '';
  let k = 0;
  let color = UI.slime;
  if (g.phase === 'intro') {
    k = g.phaseT / 1.9;
    text = g.def.name;
    sub = `Nivel ${level + 1}`;
  } else if (g.phase === 'bossIntro') {
    k = g.phaseT / 2.6;
    text = butterflies() ? '¡LA REINA MARIPOSA!' : '¡LA REINA ARAÑA!';
    color = UI.pink;
  } else {
    return;
  }
  const a = k < 0.15 ? k / 0.15 : k > 0.8 ? (1 - k) / 0.2 : 1;
  const slide = (1 - smooth(Math.min(1, k / 0.2))) * view.w * 0.4;
  const size = Math.min(view.w * 0.1, view.h * 0.16, 130);
  ctx.save();
  ctx.globalAlpha = clamp(a, 0, 1);
  ctx.fillStyle = 'rgba(10,5,22,0.6)';
  ctx.fillRect(0, view.h * 0.42 - size * 0.95, view.w, size * 1.9);
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.lineJoin = 'round';
  const jitter = g.phase === 'bossIntro' && !fx.calm ? Math.sin(time * 40) * 4 : 0;
  ctx.font = `${size}px ${FONT}`;
  ctx.strokeStyle = UI.ink;
  ctx.lineWidth = size * 0.16;
  ctx.strokeText(text, view.w / 2 - slide + jitter, view.h * 0.42 + (sub ? size * 0.16 : 0), view.w * 0.92);
  ctx.fillStyle = color;
  ctx.fillText(text, view.w / 2 - slide + jitter, view.h * 0.42 + (sub ? size * 0.16 : 0), view.w * 0.92);
  if (sub) {
    ctx.font = `${size * 0.4}px ${FONT}`;
    ctx.fillStyle = UI.bone;
    ctx.fillText(sub, view.w / 2 + slide, view.h * 0.42 - size * 0.58);
  }
  ctx.restore();
}

/** Before the very first kill: show what to do. */
function drawHint(g: Game): void {
  if (level !== 0 || progress.stars[0] > 0 || g.kills > 0 || g.phase !== 'waves') return;
  const s = g.spiders.find((x) => x.state === 'lurk' || x.state === 'aim');
  if (!s) return;
  const pulse = (time * 1.4) % 1;
  ctx.strokeStyle = `rgba(255,255,255,${1 - pulse})`;
  ctx.lineWidth = 6;
  ctx.beginPath();
  ctx.arc(s.x, s.y, 70 + pulse * 70, 0, TAU);
  ctx.stroke();
  // A pointing hand that taps.
  const tap = Math.abs(Math.sin(time * 4)) * 22;
  const hx = s.x + 104 * s.scale + tap * 0.5;
  const hy = s.y + 132 * s.scale + tap * 0.5;
  ctx.save();
  ctx.translate(hx, hy);
  ctx.rotate(-0.6);
  ctx.fillStyle = UI.bone;
  ctx.strokeStyle = UI.ink;
  ctx.lineWidth = 5;
  ctx.lineJoin = 'round';
  ctx.beginPath();
  ctx.roundRect(-13, -62, 26, 70, 13);
  ctx.roundRect(-34, -6, 68, 60, 20);
  ctx.stroke();
  ctx.fill();
  ctx.restore();
  const size = Math.max(46, 18 / unit);
  ctx.font = `${size}px ${FONT}`;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.lineJoin = 'round';
  ctx.strokeStyle = UI.ink;
  ctx.lineWidth = size * 0.2;
  const ty = s.y > view.h * 0.5 ? s.y - 150 : s.y + 190;
  ctx.strokeText('¡TÓCALA!', clamp(s.x, 150, view.w - 150), ty);
  ctx.fillStyle = UI.gold;
  ctx.fillText('¡TÓCALA!', clamp(s.x, 150, view.w - 150), ty);
}

// --------------------------------------------------------------- overlays

function textButton(id: string, x: number, y: number, w: number, h: number, label: string, icon: Icon, primary: boolean, index: number, tap: () => void): void {
  const focused = showFocus && focusI === index;
  ctx.fillStyle = 'rgba(0,0,0,0.35)';
  ctx.beginPath();
  ctx.roundRect(x, y + h * 0.1, w, h, h * 0.32);
  ctx.fill();
  ctx.fillStyle = primary ? UI.slime : '#4a3272';
  ctx.beginPath();
  ctx.roundRect(x, y, w, h, h * 0.32);
  ctx.fill();
  ctx.strokeStyle = focused ? UI.bone : primary ? UI.slimeDark : UI.edge;
  ctx.lineWidth = Math.max(2, h * (focused ? 0.09 : 0.05));
  ctx.stroke();
  const color = primary ? UI.ink : UI.bone;
  const fs = Math.min(h * 0.5, (w - h) / (label.length * 0.5));
  ctx.font = `${fs}px ${FONT}`;
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'left';
  const iw = h * 0.6;
  if (fs < h * 0.24) {
    // Too narrow for the word: the icon says it.
    drawIcon(icon, x + w / 2, y + h / 2, iw, color);
  } else {
    const tw = ctx.measureText(label).width;
    const x0 = x + (w - (iw + tw + h * 0.12)) / 2;
    drawIcon(icon, x0 + iw / 2, y + h / 2, iw, color);
    ctx.fillStyle = color;
    ctx.fillText(label, x0 + iw + h * 0.12, y + h * 0.53);
  }
  btns.push({ id, x, y, w, h, tap });
}

function drawOverlay(g: Game, dt: number): void {
  overlayT += dt;
  const a = Math.min(1, overlayT / 0.25);
  ctx.fillStyle = `rgba(8,4,18,${0.66 * a})`;
  ctx.fillRect(0, 0, view.w, view.h);
  // Only the panel's own buttons take taps now.
  btns = [];

  const lastLevel = level === LEVELS.length - 1;
  const bf = butterflies();
  const title = overlay === 'pause' ? 'PAUSA' : overlay === 'won' ? (lastLevel ? (bf ? '¡ATRAPASTE A LA REINA!' : '¡VENCISTE A LA REINA!') : '¡GANASTE!') : '¡OH, NO!';
  const lostText = bf ? 'Las mariposas se escaparon…' : 'Las arañas ganaron esta vez…';
  const bestText = bf ? '¡Eres la mejor cazadora de mariposas!' : '¡Eres la mejor cazadora de arañas!';
  const sub = overlay === 'lost' ? lostText : overlay === 'won' ? (lastLevel ? bestText : g.def.name) : g.def.name;
  type Item = { id: string; label: string; icon: Icon; tap: () => void };
  const items: Item[] = [];
  const hasNext = overlay === 'won' && !lastLevel;
  if (overlay === 'pause') items.push({ id: 'resume', label: 'Seguir', icon: 'play', tap: () => (overlay = null) });
  if (hasNext) items.push({ id: 'next', label: 'Siguiente', icon: 'play', tap: () => startLevel(level + 1) });
  items.push({ id: 'retry', label: 'Otra vez', icon: 'retry', tap: () => startLevel(level) });
  items.push({ id: 'levels', label: 'Niveles', icon: 'levels', tap: toMenu });

  const narrow = view.w < 900;
  const pw = Math.min(view.w * 0.92, 760);
  const bh = Math.max(clamp(view.h * 0.105, 64, 92), 30 / unit);
  const gap = bh * 0.22;
  const titleSize = Math.min(pw / (title.length * 0.5), view.h * 0.15, 120);
  const starR = overlay === 'won' ? Math.min(pw * 0.085, view.h * 0.07) : 0;
  const subSize = Math.max(titleSize * 0.3, Math.min(34, 13 / unit));
  const rows = narrow ? items.length : 1;
  const ph = titleSize * 1.15 + subSize * 1.5 + (starR ? starR * 2.9 : 0) + rows * (bh + gap) + bh * 0.6;
  const pop = 0.9 + 0.1 * smooth(a);
  ctx.save();
  ctx.translate(view.w / 2, view.h / 2);
  ctx.scale(pop, pop);
  ctx.globalAlpha = a;
  const x = -pw / 2;
  let y = -ph / 2;
  ctx.fillStyle = UI.panel;
  ctx.beginPath();
  ctx.roundRect(x, y, pw, ph, 30);
  ctx.fill();
  ctx.strokeStyle = overlay === 'lost' ? '#8a3b5a' : UI.edge;
  ctx.lineWidth = 5;
  ctx.stroke();
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.lineJoin = 'round';
  y += bh * 0.3 + titleSize * 0.55;
  ctx.font = `${titleSize}px ${FONT}`;
  ctx.strokeStyle = UI.ink;
  ctx.lineWidth = titleSize * 0.14;
  ctx.strokeText(title, 0, y, pw * 0.92);
  ctx.fillStyle = overlay === 'lost' ? '#ff7a8a' : overlay === 'won' ? UI.gold : UI.bone;
  ctx.fillText(title, 0, y, pw * 0.92);
  y += titleSize * 0.6 + subSize * 0.7;
  ctx.font = `${subSize}px ${FONT}`;
  ctx.fillStyle = UI.dim;
  ctx.fillText(sub, 0, y, pw * 0.9);
  y += subSize * 0.8;
  if (starR) {
    y += starR * 1.35;
    for (let i = 0; i < 3; i++) {
      const at = 0.5 + i * 0.4;
      const won = i < g.stars;
      const k = clamp((overlayT - at) / 0.25, 0, 1);
      const sx = (i - 1) * starR * 2.5;
      star(ctx, sx, y + (i === 1 ? -starR * 0.2 : 0), starR, 'rgba(0,0,0,0.4)');
      if (won && k > 0) {
        const s = starR * (1.6 - 0.6 * smooth(k));
        star(ctx, sx, y + (i === 1 ? -starR * 0.2 : 0), s, UI.gold, UI.ink);
        if (starsShown <= i) {
          starsShown = i + 1;
          A.sfx.star(i);
          fx.sparkle(view.w / 2 + sx * pop, view.h / 2 + (y + (i === 1 ? -starR * 0.2 : 0)) * pop, UI.gold, 14);
        }
      }
    }
    y += starR * 1.55;
  }
  y += gap;
  ctx.restore();
  // Buttons are laid out in world units, without the pop, so taps line up.
  const by0 = view.h / 2 + y;
  if (narrow) {
    const bw = pw * 0.8;
    items.forEach((it, i) => textButton(it.id, view.w / 2 - bw / 2, by0 + i * (bh + gap), bw, bh, it.label, it.icon, i === 0, i, it.tap));
  } else {
    const bw = (pw * 0.92 - (items.length - 1) * gap) / items.length;
    items.forEach((it, i) => textButton(it.id, view.w / 2 - pw * 0.46 + i * (bw + gap), by0, bw, bh, it.label, it.icon, i === 0, i, it.tap));
  }
  ctx.globalAlpha = 1;
  if (overlay === 'pause') {
    const b = hudSize();
    // Over the dimmed one in the HUD, so there is only one to see.
    iconButton('sound', view.w - b * 2.5, b * 0.25, b, soundIcon(), cycleSound, items.length);
  }
  fx.draw(ctx);
  ctx.globalCompositeOperation = 'lighter';
  fx.drawGlow(ctx, glowSprite);
  ctx.globalCompositeOperation = 'source-over';
}

// ------------------------------------------------------------------- play

function drawDarkness(sc: Scene): void {
  const d = sc.darkness(playTime);
  // Butterflies like it brighter.
  if (butterflies()) d.level *= 0.5;
  if (d.level < 0.02) return;
  const c = dark.getContext('2d') as Ctx;
  const sx = dark.width / view.w;
  const sy = dark.height / view.h;
  c.setTransform(1, 0, 0, 1, 0, 0);
  c.globalCompositeOperation = 'source-over';
  c.clearRect(0, 0, dark.width, dark.height);
  c.fillStyle = `rgba(5,6,20,${d.level})`;
  c.fillRect(0, 0, dark.width, dark.height);
  c.globalCompositeOperation = 'destination-out';
  c.setTransform(sx, 0, 0, sy, 0, 0);
  for (const l of d.lights) {
    if (l.power <= 0.01) continue;
    const g = c.createRadialGradient(l.x, l.y, 0, l.x, l.y, l.r);
    g.addColorStop(0, `rgba(0,0,0,${l.power})`);
    g.addColorStop(0.5, `rgba(0,0,0,${l.power * 0.55})`);
    g.addColorStop(1, 'rgba(0,0,0,0)');
    c.fillStyle = g;
    c.fillRect(l.x - l.r, l.y - l.r, l.r * 2, l.r * 2);
  }
  ctx.drawImage(dark, 0, 0, view.w, view.h);
}

/** Peeking spiders are cut off at the edge they hide behind. */
function clipFor(s: Spider): boolean {
  if (s.mode !== 'peek' || !scene) return false;
  const spot = scene.spots[s.spot];
  if (!spot || spot.edge === undefined) return false;
  ctx.save();
  ctx.beginPath();
  if (spot.dir === 'left') ctx.rect(-50, -50, spot.edge + 50, view.h + 100);
  else if (spot.dir === 'right') ctx.rect(spot.edge, -50, view.w - spot.edge + 50, view.h + 100);
  else ctx.rect(-50, -50, view.w + 100, spot.edge + 50);
  ctx.clip();
  return true;
}

const ORDER = { peek: 0, drop: 1, crawl: 2 };

function drawPlay(dt: number): void {
  const g = game as Game;
  const sc = scene as Scene;
  const off = fx.offset(time);
  // Night behind the picture, so a shake shows no bright edge.
  ctx.fillStyle = UI.night;
  ctx.fillRect(0, 0, view.w, view.h);
  ctx.save();
  ctx.translate(off.x, off.y);
  ctx.drawImage(bg, 0, 0, view.w, view.h);
  sc.paintLive(ctx, playTime);
  fx.drawBack(ctx);

  const sorted = g.spiders.slice().sort((a, b) => ORDER[a.mode] - ORDER[b.mode] || (a.kind === 'boss' ? -1 : 0) - (b.kind === 'boss' ? -1 : 0) || a.y - b.y);
  const poses = sorted.map(poseOf);
  sorted.forEach((s, i) => {
    const clipped = clipFor(s);
    drawCreature(poses[i]);
    if (clipped) ctx.restore();
    // The queen sees stars when she is dizzy.
    if (s.state === 'stun') {
      for (let k = 0; k < 3; k++) {
        const a = s.age * 5 + (k * TAU) / 3;
        star(ctx, s.x + Math.cos(a) * 62 * s.scale, s.y - 96 * s.scale + Math.sin(a) * 16 * s.scale, 13 * s.scale, UI.gold, UI.ink);
      }
    }
  });

  for (const p of g.pickups) {
    const fade = p.life - p.t < 2 ? (Math.sin(p.t * 16) > 0 ? 1 : 0.35) : 1;
    const s = 30 * (1 + 0.1 * Math.sin(p.t * 6));
    const x = p.x + Math.sin(p.t * 2.2 + p.seed * 6) * 16;
    ctx.globalAlpha = fade * Math.min(1, p.t * 4);
    heartPath(ctx, x, p.y, s);
    ctx.fillStyle = UI.heart;
    ctx.fill();
    ctx.strokeStyle = '#ffffff';
    ctx.lineWidth = 4;
    ctx.stroke();
    ctx.globalAlpha = 1;
  }

  fx.draw(ctx);
  sc.paintFront(ctx, playTime);
  drawDarkness(sc);

  ctx.globalCompositeOperation = 'lighter';
  sorted.forEach((s, i) => {
    const clipped = clipFor(s);
    drawCreatureGlow(poses[i]);
    if (clipped) ctx.restore();
  });
  for (const p of g.pickups) {
    ctx.globalAlpha = 0.6;
    glow(ctx, glowSprite, p.x + Math.sin(p.t * 2.2 + p.seed * 6) * 16, p.y, 80, UI.heart);
  }
  ctx.globalAlpha = 1;
  fx.drawGlow(ctx, glowSprite);
  ctx.globalCompositeOperation = 'source-over';
  fx.drawWords(ctx, FONT);
  ctx.restore();

  fx.drawScreen(ctx, view);
  drawBanner(g);
  drawHud(g);
  drawHint(g);
  if (overlay) drawOverlay(g, dt);
}

/** One fixed step of the rules, with everything that follows from it. */
const STEP = 1 / 60;
let carry = 0;

function advance(dt: number): void {
  const g = game as Game;
  const sc = scene as Scene;
  carry += dt;
  let n = 0;
  while (carry >= STEP && n++ < 5) {
    carry -= STEP;
    g.update(STEP);
    for (const ev of g.events.splice(0)) handle(ev);
  }
  if (n >= 5) carry = 0;
  playTime += dt;
  sc.step(dt, playTime, playScene);
  // The last warning before each shot.
  let tension = 0;
  for (const s of g.spiders) {
    if (s.state !== 'aim') continue;
    const heat = s.t / s.dur;
    tension = Math.max(tension, heat);
    if (heat > 0.72 && !warned.has(s.id)) {
      warned.add(s.id);
      if (butterflies()) A.bsfx.warn(panAt(s.x));
      else A.sfx.warn(panAt(s.x));
    }
  }
  musicTension = tension;
  if (lostIn >= 0) {
    lostIn -= dt;
    if (lostIn < 0) {
      openOverlay('lost');
      if (butterflies()) A.bsfx.lose();
      else A.sfx.lose();
    }
  }
}
let musicTension = 0;

// ------------------------------------------------------------------- loop

let last = 0;
function frame(ms: number): void {
  requestAnimationFrame(frame);
  resize();
  if (cssW < 2) return;
  const dt = Math.min(0.05, last ? (ms - last) / 1000 : 0.016);
  last = ms;
  time += dt;
  btns = [];
  ctx.setTransform(px, 0, 0, px, 0, 0);
  if (screen === 'play' && game && scene) {
    if (overlay === null) advance(dt);
    fx.update(dt);
    drawPlay(dt);
  } else {
    fx.update(dt);
    drawMenu(dt);
  }
  const bossHere = !!game && (game.phase === 'bossIntro' || game.phase === 'boss');
  A.music({
    mode: overlay === 'won' || overlay === 'lost' || lostIn >= 0 || game?.phase === 'outro' ? 'off' : 'on',
    tune: screen === 'menu' ? -1 : level,
    boss: bossHere,
    tension: screen === 'play' ? musicTension : 0,
    paused: overlay === 'pause',
  });
}

// ------------------------------------------------------------------ input

function worldPoint(e: PointerEvent): { x: number; y: number } {
  const r = canvas.getBoundingClientRect();
  return { x: (e.clientX - r.left) / unit, y: (e.clientY - r.top) / unit };
}

canvas.addEventListener('pointermove', (e) => {
  pointer = worldPoint(e);
});

canvas.addEventListener('pointerdown', (e) => {
  e.preventDefault();
  ensureAudio();
  showFocus = false;
  const p = worldPoint(e);
  pointer = p;
  for (let i = btns.length - 1; i >= 0; i--) {
    const b = btns[i];
    if (p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h) {
      if (b.id !== 'sound' && b.id !== 'mode' && !b.id.startsWith('level')) A.sfx.click();
      b.tap();
      return;
    }
  }
  if (screen === 'menu') {
    tapMenu(p);
    return;
  }
  if (overlay === null && game) game.click(p.x, p.y);
});

function tapMenu(p: { x: number; y: number }): void {
  const L = menuLayout();
  const pose = menuSpiderPose(L);
  if (pose && menuSpider && Math.hypot(p.x - pose.x, p.y - pose.y) < 100 * pose.scale + 30) {
    const big = menuSpider.kind === 'boss';
    fx.impact(p.x, p.y, true);
    if (butterflies()) {
      fx.collect(pose.x, pose.y, pose.scale, menuSpider.kind, WINGS[menuSpider.kind].glow, view.w / 2, -40, big);
      fx.word(pose.x, pose.y - 120 * pose.scale, 56, CAUGHT_WORDS[menuKills % CAUGHT_WORDS.length]);
      A.bsfx.caught(panAt(pose.x), menuKills % 5, pose.scale);
    } else {
      fx.burst(pose.x, pose.y, pose.scale, PALETTES[menuSpider.kind], view.h - 60, { hat: big ? 9 : pose.hat, pistols: big ? 4 : 2, big });
      fx.word(pose.x, pose.y - 110 * pose.scale, 60);
      A.sfx.hit(panAt(pose.x), big);
      A.sfx.pop(panAt(pose.x), menuKills % 6, pose.scale);
      A.sfx.squeal(panAt(pose.x), menuSpider.kind);
    }
    menuSpider = null;
    menuSpiderIn = 1.1;
    menuKills++;
    return;
  }
  fx.impact(p.x, p.y, false);
  A.sfx.miss(panAt(p.x));
}

window.addEventListener('keydown', (e) => {
  if (e.metaKey || e.ctrlKey || e.altKey) return;
  ensureAudio();
  const k = e.key;
  if (k === 'm' || k === 'M') {
    cycleSound();
    return;
  }
  if (screen === 'play' && overlay === null) {
    if (k === 'Escape' || k === 'p' || k === 'P' || k === ' ') {
      openOverlay('pause');
      e.preventDefault();
    }
    return;
  }
  if (overlay === 'pause' && (k === 'Escape' || k === 'p' || k === 'P')) {
    overlay = null;
    return;
  }
  // Menus and panels: arrows or Tab move, Enter or Space choose.
  const list = btns.filter((b) => b.id !== 'pause');
  if (!list.length) return;
  const cols = screen === 'menu' && overlay === null && view.w < view.h * 1.12 ? 2 : 1;
  if (k === 'ArrowRight' || k === 'ArrowDown' || (k === 'Tab' && !e.shiftKey)) {
    focusI = (focusI + (k === 'ArrowDown' ? cols : 1)) % list.length;
    showFocus = true;
    e.preventDefault();
  } else if (k === 'ArrowLeft' || k === 'ArrowUp' || (k === 'Tab' && e.shiftKey)) {
    focusI = (focusI - (k === 'ArrowUp' ? cols : 1) + list.length * 2) % list.length;
    showFocus = true;
    e.preventDefault();
  } else if (k === 'Enter' || k === ' ') {
    const b = list[Math.min(focusI, list.length - 1)];
    if (b.id !== 'sound' && !b.id.startsWith('level')) A.sfx.click();
    b.tap();
    showFocus = true;
    e.preventDefault();
  }
});

canvas.addEventListener('contextmenu', (e) => e.preventDefault());

// ------------------------------------------------------------------ start

async function loadFont(): Promise<void> {
  let face: FontFace;
  try {
    // From bytes, which needs no font source in the host's content policy.
    face = new FontFace('Creepster', await (await assetBlob('creepster')).arrayBuffer());
    await face.load();
  } catch {
    try {
      // The dev server serves the font as a file instead of embedding it.
      face = new FontFace('Creepster', `url(${await assetUrl('creepster')})`);
      await face.load();
    } catch {
      return; // The fallback font stays.
    }
  }
  document.fonts.add(face);
  FONT = `"Creepster", ${FONT}`;
}

const calm = window.matchMedia?.('(prefers-reduced-motion: reduce)');
fx.calm = !!calm?.matches;
calm?.addEventListener?.('change', (e) => (fx.calm = e.matches));

void loadFont();
void loadProgress();
requestAnimationFrame(frame);

if (import.meta.env.DEV) {
  // For scripted checks against the dev server; not part of the built napplet.
  (window as unknown as Record<string, unknown>).__ap = {
    game: () => game,
    scene: () => scene,
    view: () => view,
    unit: () => unit,
    start: startLevel,
    menu: toMenu,
    progress,
    setMode,
    fx,
    overlay: () => overlay,
    btns: () => btns,
    audio: A,
    open: (i: number) => testOpen.add(i),
  };
}