// Wispmarch: a lantern wisp survives the night marsh. Canvas 2D, fixed 60 Hz sim with render interpolation,
// typed-array pools and a spatial hash so hundreds of gloom stay at 60 fps. (c) 2026 CyberMax. All rights reserved.
import { today, rng, count, store, toast, share, intents, download, pwa, canvasBlob, themeToggle } from './cmx.js';
import * as pass from './funpass.js';
import './looks.js'; // Skin Pack + Collector Pack wisp skins (owned ones join C.SKINS), $5 Store lane 30 Oct 2026
import * as C from './core.js';
import * as L from './levels.js';
const GAME = C.GAME, PATH = '/games/wispmarch/';
const $ = (id) => document.getElementById(id);
const cv = $('c'), ctx = cv.getContext('2d'); // alpha: the 3D marsh shows through behind the HUD when it is on
// 3D marsh (scene3d.js + three.js, lazy-loaded after the first frame). The 2D drawing stays as the fallback when WebGL2
// is missing, the GPU is a software one, the device is too slow, or ?2d=1. ?cap=1 = frame-stepped capture (window.__cap).
let R3 = null;
const QS = location.search;
const CAP = /[?&]cap=1/.test(QS);
let clock = null;
const fx3 = (k) => { if (R3) R3.fx(k); };
const stageEl = $('stage');
const STEP = 1 / 60, TAU = Math.PI * 2;
const REDUCED = matchMedia('(prefers-reduced-motion: reduce)').matches;
const TOUCH = matchMedia('(pointer: coarse)').matches || 'ontouchstart' in window;
pass.init({ game: GAME, name: 'Wispmarch', perks: [`Nights ${L.FREE_NIGHTS + 1}-${L.NIGHTS.length}: ${L.NIGHTS.length - L.FREE_NIGHTS} bonus hand-made nights`, `Trials: replay any cleared night at Danger 1-3 for ${L.MAX_CROWNS} crowns and more Embers (one free trial a day)`, '3 wisp skins: Aurora, Ember Rose, Frostlight', 'Endless Night mode: no dawn, scaling forever'] });
themeToggle($('theme'));
const install = pwa(GAME, $('install'));
let save = C.loadSave(store(C.SAVE_KEY));
const persist = () => store(C.SAVE_KEY, save);
// Trials: one free trial a day; unlimited with the full game or the Fun Pass.
const trialFree = () => pass.isPro() || save.trialDay !== today();
const TODAY = today(), DAILY = C.daily(TODAY);
if (save.daily.iso !== TODAY) save.daily = { iso: TODAY, best: 0, tries: 0 };
$('num').textContent = `#${DAILY.num}`;
// "Beat my score" link (?seed=&score=&lvl=); garbage is ignored by parseLink.
let LINK = L.parseLink(location.search);
if (LINK) { save.mode = LINK.lvl ? 'nights' : 'daily'; if (LINK.lvl) save.night = LINK.lvl; count(GAME, 'link', LINK.lvl ? 'night' : 'seed'); }
// ------------------------------------------------------------------ audio (procedural WebAudio)
let AC = null, master = null, musicGain = null, muted = !!store('wispmarch:mute');
const lastSfx = {};
function audio() {
if (AC) { if (AC.state === 'suspended') AC.resume(); return; }
try {
AC = new (window.AudioContext || window.webkitAudioContext)();
master = AC.createGain(); master.gain.value = muted ? 0 : 0.5; master.connect(AC.destination);
musicGain = AC.createGain(); musicGain.gain.value = 0.16; musicGain.connect(master);
} catch { AC = null; }
}
function tone(f, d, type = 'sine', vol = 0.2, slide = 0, delay = 0, dest = master) {
if (!AC || muted) return;
const t = AC.currentTime + delay, o = AC.createOscillator(), g = AC.createGain();
o.type = type; o.frequency.setValueAtTime(f, t);
if (slide) o.frequency.exponentialRampToValueAtTime(Math.max(30, f + slide), t + d);
g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(vol, t + 0.008); g.gain.exponentialRampToValueAtTime(0.0001, t + d);
o.connect(g); g.connect(dest); o.start(t); o.stop(t + d + 0.02);
}
let noiseBuf = null;
function noise(d, vol = 0.2, hp = 800, delay = 0, dest = master) {
if (!AC || muted) return;
if (!noiseBuf) { noiseBuf = AC.createBuffer(1, AC.sampleRate * 0.5, AC.sampleRate); const ch = noiseBuf.getChannelData(0); for (let i = 0; i < ch.length; i++) ch[i] = Math.random() * 2 - 1; }
const t = AC.currentTime + delay, s = AC.createBufferSource(), f = AC.createBiquadFilter(), g = AC.createGain();
s.buffer = noiseBuf; f.type = 'highpass'; f.frequency.value = hp;
g.gain.setValueAtTime(vol, t); g.gain.exponentialRampToValueAtTime(0.0001, t + d);
s.connect(f); f.connect(g); g.connect(dest); s.start(t); s.stop(t + d + 0.02);
}
let shardCombo = 0, shardComboT = 0;
function sfx(name) {
if (!AC || muted) return;
const now = AC.currentTime, gap = { shoot: 0.07, hit: 0.045, shard: 0.035, kill: 0.05, zap: 0.08, nova: 0.15, hurt: 0.2 }[name] || 0;
if (gap && now - (lastSfx[name] || 0) < gap) return;
lastSfx[name] = now;
switch (name) {
case 'shoot': tone(880, 0.07, 'triangle', 0.05, 500); break;
case 'hit': tone(220 + Math.random() * 60, 0.05, 'square', 0.03, -80); break;
case 'kill': tone(520, 0.08, 'triangle', 0.05, -260); noise(0.05, 0.04, 2500); break;
case 'shard': { shardCombo = Math.min(shardCombo + 1, 24); shardComboT = now; tone(660 * Math.pow(2, (shardCombo % 12) / 12), 0.06, 'sine', 0.07); break; }
case 'zap': noise(0.12, 0.08, 3000); tone(1400, 0.1, 'sawtooth', 0.03, -900); break;
case 'nova': tone(140, 0.35, 'sine', 0.2, 220); noise(0.25, 0.06, 400); break;
case 'moon': tone(1046, 0.4, 'sine', 0.06, -300); tone(1568, 0.3, 'sine', 0.04, 0, 0.05); break;
case 'hurt': tone(160, 0.2, 'sawtooth', 0.12, -90); noise(0.12, 0.1, 300); break;
case 'level': [523, 659, 784, 1046, 1318].forEach((f, i) => tone(f, 0.35, 'triangle', 0.12, 0, i * 0.065)); tone(2093, 0.6, 'sine', 0.05, 0, 0.33); break;
case 'pick': tone(784, 0.1, 'triangle', 0.1); tone(1175, 0.18, 'triangle', 0.1, 0, 0.06); break;
case 'chest': for (let i = 0; i < 8; i++) tone(500 + i * 90, 0.07, 'square', 0.04, 0, i * 0.11); break;
case 'reward': [784, 988, 1175, 1568].forEach((f, i) => tone(f, 0.4, 'triangle', 0.12, 0, i * 0.08)); break;
case 'elite': tone(90, 0.5, 'sawtooth', 0.12, -40); noise(0.4, 0.12, 200); break;
case 'boss': tone(55, 1.4, 'sawtooth', 0.18, 20); tone(82, 1.4, 'sawtooth', 0.12, 0, 0.2); break;
case 'heal': tone(660, 0.25, 'sine', 0.1, 330); break;
case 'die': tone(330, 0.9, 'triangle', 0.18, -280); noise(0.6, 0.1, 300); break;
case 'dawn': [392, 523, 659, 784, 1046].forEach((f, i) => tone(f, 1.0, 'sine', 0.1, 0, i * 0.15)); break;
case 'ui': tone(600, 0.05, 'triangle', 0.06); break;
case 'star': tone(1046, 0.25, 'triangle', 0.14); tone(1568, 0.35, 'sine', 0.08, 0, 0.05); noise(0.12, 0.05, 5000); break;
case 'nostar': tone(196, 0.18, 'triangle', 0.08, -40); break;
}
}
// Music: a minor-pentatonic arpeggio over a drone, a beat scheduler with lookahead; hats join as the night deepens.
const SCALE = [0, 3, 5, 7, 10, 12, 15, 17];
let musicT = 0, beat = 0, musicOn = false;
function musicTick() {
if (!AC || muted || !musicOn) return;
const spb = 60 / 100 / 2;
if (musicT < AC.currentTime) musicT = AC.currentTime + 0.05;
while (musicT < AC.currentTime + 0.2) {
const d = musicT - AC.currentTime, b = beat % 32, root = [0, 0, -4, -2][(beat >> 5) & 3];
if (b % 8 === 0) tone(55 * Math.pow(2, root / 12), spb * 8, 'triangle', 0.22, 0, d, musicGain);
const n = SCALE[(b * 5 + (b >> 3) * 3) % SCALE.length];
if (b % 2 === 0 || run.time > 3600) tone(220 * Math.pow(2, (n + root) / 12), spb * 1.6, 'sine', 0.09, 0, d, musicGain);
if (run.time > 7200 && b % 2 === 1) noise(0.03, 0.04, 6000, d, musicGain);
if (run.time > 14400 && b % 8 === 4) noise(0.08, 0.08, 150, d, musicGain);
musicT += spb; beat++;
}
}
setInterval(musicTick, 80);
function setMute(m) {
muted = m; store('wispmarch:mute', m); $('mute').textContent = m ? '๐' : '๐';
if (master) master.gain.value = m ? 0 : 0.5;
}
$('mute').onclick = () => { audio(); setMute(!muted); };
setMute(muted);
// ------------------------------------------------------------------ pools (struct of arrays)
const MAXE = 1100;
const ex = new Float32Array(MAXE), ey = new Float32Array(MAXE), epx = new Float32Array(MAXE), epy = new Float32Array(MAXE);
const ekx = new Float32Array(MAXE), eky = new Float32Array(MAXE), ehp = new Float32Array(MAXE), emax = new Float32Array(MAXE);
const espd = new Float32Array(MAXE), edmg = new Float32Array(MAXE), er = new Float32Array(MAXE), exp_ = new Float32Array(MAXE);
const etype = new Uint8Array(MAXE), eflash = new Uint8Array(MAXE), eorb = new Uint8Array(MAXE), edead = new Uint8Array(MAXE);
const eid = new Int32Array(MAXE), ephase = new Float32Array(MAXE);
let nE = 0, nextId = 1;
const ET = [ // type table
{ name: 'moth', hp: 6, spd: 66, dmg: 5, r: 9, xp: 1 },
{ name: 'crawler', hp: 24, spd: 40, dmg: 10, r: 13, xp: 2 },
{ name: 'wraith', hp: 42, spd: 60, dmg: 14, r: 14, xp: 4 },
{ name: 'brute', hp: 420, spd: 46, dmg: 22, r: 26, xp: 25 },
{ name: 'warden', hp: 9000, spd: 54, dmg: 34, r: 46, xp: 120 },
];
// spatial hash over a window around the player
const CS = 48, GW = 72, GH = 72, heads = new Int32Array(GW * GH), nextE = new Int32Array(MAXE);
let gox = 0, goy = 0;
const QB = new Int32Array(MAXE);
function buildHash() {
heads.fill(-1);
gox = run.px - (GW * CS) / 2; goy = run.py - (GH * CS) / 2;
for (let i = 0; i < nE; i++) {
const cx = ((ex[i] - gox) / CS) | 0, cy = ((ey[i] - goy) / CS) | 0;
if (cx < 0 || cy < 0 || cx >= GW || cy >= GH) { nextE[i] = -2; continue; }
const c = cy * GW + cx; nextE[i] = heads[c]; heads[c] = i;
}
}
function query(x, y, r) {
let n = 0;
const x0 = Math.max(0, ((x - r - gox) / CS) | 0), x1 = Math.min(GW - 1, ((x + r - gox) / CS) | 0);
const y0 = Math.max(0, ((y - r - goy) / CS) | 0), y1 = Math.min(GH - 1, ((y + r - goy) / CS) | 0);
for (let cy = y0; cy <= y1; cy++) for (let cx = x0; cx <= x1; cx++) {
for (let i = heads[cy * GW + cx]; i >= 0; i = nextE[i]) {
if (edead[i]) continue;
const dx = ex[i] - x, dy = ey[i] - y, rr = r + er[i];
if (dx * dx + dy * dy <= rr * rr) QB[n++] = i;
}
}
return n;
}
function nearest(x, y, maxR, skipId = 0) {
let best = -1, bd = maxR * maxR;
const n = query(x, y, maxR);
for (let k = 0; k < n; k++) { const i = QB[k]; if (eid[i] === skipId) continue; const dx = ex[i] - x, dy = ey[i] - y, d = dx * dx + dy * dy; if (d < bd) { bd = d; best = i; } }
return best;
}
// bolts
const MAXB = 500;
const bx = new Float32Array(MAXB), by = new Float32Array(MAXB), bpx = new Float32Array(MAXB), bpy = new Float32Array(MAXB), bvx = new Float32Array(MAXB), bvy = new Float32Array(MAXB);
const blife = new Float32Array(MAXB), bdmg = new Float32Array(MAXB), bpierce = new Int8Array(MAXB), blast = new Int32Array(MAXB), bbig = new Uint8Array(MAXB);
let nB = 0;
// gems (light shards)
const MAXG = 1400;
const gx = new Float32Array(MAXG), gy = new Float32Array(MAXG), gv = new Float32Array(MAXG), gpull = new Uint8Array(MAXG), gsp = new Float32Array(MAXG);
let nG = 0;
// pickups: 0 heart, 1 magnet, 2 chest
const MAXP = 40;
const kx = new Float32Array(MAXP), ky = new Float32Array(MAXP), kt = new Uint8Array(MAXP);
let nP = 0;
// ember patches
const MAXM = 240;
const mx = new Float32Array(MAXM), my = new Float32Array(MAXM), mlife = new Float32Array(MAXM), mr = new Float32Array(MAXM);
let nM = 0;
// moon strikes
const MAXS = 40;
const sx = new Float32Array(MAXS), sy = new Float32Array(MAXS), st = new Float32Array(MAXS), sr = new Float32Array(MAXS), sd = new Float32Array(MAXS);
let nS = 0;
// fx: rings and arcs
const MAXR = 40;
const rx = new Float32Array(MAXR), ry = new Float32Array(MAXR), rmax = new Float32Array(MAXR), rlife = new Float32Array(MAXR), rcol = new Uint8Array(MAXR);
let nR = 0;
const MAXA = 120;
const ax1 = new Float32Array(MAXA), ay1 = new Float32Array(MAXA), ax2 = new Float32Array(MAXA), ay2 = new Float32Array(MAXA), alife = new Float32Array(MAXA);
let nA = 0;
// particles
const MAXQ = 1600;
const qx = new Float32Array(MAXQ), qy = new Float32Array(MAXQ), qvx = new Float32Array(MAXQ), qvy = new Float32Array(MAXQ), ql = new Float32Array(MAXQ), qm = new Float32Array(MAXQ), qs = new Float32Array(MAXQ), qc = new Uint8Array(MAXQ);
let nQ = 0;
const PCOL = ['#FFE9A8', '#FFC857', '#9B8CFF', '#6FE3C1', '#FF6A8A', '#FFFFFF', '#7DA8FF', '#FF8A3D', '#B9F27C'];
// damage numbers (ring buffer)
const MAXN = 90;
const nx = new Float32Array(MAXN), ny = new Float32Array(MAXN), nv = new Float32Array(MAXN), nl = new Float32Array(MAXN), ncrit = new Uint8Array(MAXN);
let nHead = 0;
function particle(x, y, c, n, spd = 120, life = 0.5, size = 3) {
for (let k = 0; k < n && nQ < MAXQ; k++) {
const a = Math.random() * TAU, s = spd * (0.3 + Math.random() * 0.7), i = nQ++;
qx[i] = x; qy[i] = y; qvx[i] = Math.cos(a) * s; qvy[i] = Math.sin(a) * s; ql[i] = qm[i] = life * (0.6 + Math.random() * 0.6); qs[i] = size * (0.6 + Math.random() * 0.8); qc[i] = c;
}
}
function ring(x, y, r, c = 0) { if (nR >= MAXR) return; const i = nR++; rx[i] = x; ry[i] = y; rmax[i] = r; rlife[i] = 1; rcol[i] = c; }
function arc(x1, y1, x2, y2) { if (nA >= MAXA) return; const i = nA++; ax1[i] = x1; ay1[i] = y1; ax2[i] = x2; ay2[i] = y2; alife[i] = 1; }
function dmgNum(x, y, v, crit) { const i = nHead; nHead = (nHead + 1) % MAXN; nx[i] = x + (Math.random() - 0.5) * 10; ny[i] = y - 10; nv[i] = v; nl[i] = 1; ncrit[i] = crit ? 1 : 0; }
// ------------------------------------------------------------------ run state
const run = {
mode: 'standard', seed: 0, R: Math.random, time: 0, px: 0, py: 0, ppx: 0, ppy: 0, vx: 0, vy: 0, face: 1,
hp: 100, maxhp: 100, iframes: 0, level: 1, xp: 0, kills: 0, shards: 0, weapons: [], passives: {}, rerolls: 1, revives: 0,
dmgMul: 1, cdMul: 1, areaMul: 1, speed: 150, magnet: 70, regen: 0, xpMul: 1, light: 320, pending: 0,
spawnAcc: 0, nextElite: 90, boss: false, bossIdx: -1, bossDone: false, nextBossAt: C.BOSS_AT, swarms: [200, 360, 540],
hitstop: 0, shake: 0, hurtFlash: 0, levelFlash: 0, dawnT: 0, dieT: 0, won: false, god: false, auto: false, emberT: 0,
orbitA: 0, mod: null, mods: new Set(), night: null, dcfg: null, target: null, moved: 0, tut: false, wisp: C.WISPS[0], promptT: 0, banner: '', bannerT: 0, chest: null,
};
let state = 'menu';
let acc = 0, alpha = 1;
function weaponOf(id) { for (const w of run.weapons) if (w.id === id) return w; return null; }
function addWeapon(id) { const w = { id, lv: 1, evo: false, cd: 0.4, st: C.weaponStats(id, 1) }; run.weapons.push(w); return w; }
function levelWeapon(w) { if (w.lv < C.MAX_LV) w.lv++; w.st = C.weaponStats(w.id, w.lv, w.evo); }
function recalc() {
const meta = C.metaBonus(save.up), P = run.passives, ws = run.wisp, has = (id) => run.mods.has(id);
run.dmgMul = meta.dmg * (1 + 0.12 * (P.kindle || 0)) * (has('glass') ? 1.5 : 1);
run.cdMul = Math.pow(0.92, P.haste || 0) * (ws.id === 'volt' ? 0.9 : 1);
run.areaMul = (1 + 0.12 * (P.glow || 0)) * (ws.id === 'vesper' ? 1.15 : 1);
run.speed = 150 * meta.speed * (1 + 0.08 * (P.drift || 0)) * (ws.id === 'cinder' ? 1.1 : 1);
run.magnet = 90 * meta.magnet * (1 + 0.3 * (P.lure || 0));
const old = run.maxhp;
run.maxhp = Math.round((100 + meta.hp + 20 * (P.ward || 0)) * (ws.id === 'moss' ? 1.1 : 1) * (has('glass') ? 0.5 : 1));
if (run.maxhp > old) run.hp += run.maxhp - old;
run.hp = Math.min(run.hp, run.maxhp);
run.regen = 0.25 * (P.ward || 0);
run.xpMul = (has('doubleshards') ? 2 : 1) * (run.night ? L.NIGHT_XP : 1);
run.light = 330 * Math.sqrt(run.areaMul) * (has('fog') ? 0.7 : 1);
}
function resetPools() { nE = nB = nG = nP = nM = nS = nR = nA = nQ = 0; nl.fill(0); }
let lastStart = { mode: 'nights', n: 1, seed: null, target: null, link: false };
/** mode: 'nights' | 'daily' | 'standard' | 'endless'. o: { n (night), seed, target (score to beat), link }. */
function startRun(mode, o = {}) {
audio();
if (mode === 'endless' && !pass.isPro()) { pass.open('endless'); return; }
let N = null;
if (mode === 'trials') {
const n = o.n || L.nextTrial(save.nights, save.trials), d = o.danger || L.nextDanger(save.nights, save.trials, n);
if (!n || !d) { toast('Clear a night first: Trials replay nights you have cleared, at Danger 1-3.', 3500); return; }
if (!trialFree()) { pass.open('trial'); toast("Today's free trial is used. The full game makes Trials unlimited.", 3500); return; }
if (!pass.isPro()) save.trialDay = today();
N = L.trialNight(L.NIGHTS[n - 1], d);
}
if (mode === 'nights') {
const n = o.n || save.night || 1, a = L.access(n, save.nights, pass.isPro());
if (a === 'pass') { pass.open(`night-${n}`); return; }
if (a === 'locked' && !(o.link && n <= L.FREE_NIGHTS)) { toast(`๐ Clear night ${n - 1} first`); return; } // a friend's link may skip ahead in the free nights
N = L.NIGHTS[n - 1]; save.night = n;
if (a === 'open') L.markPlayed(save.nights, n);
}
lastStart = { mode, n: N ? N.n : 0, danger: N && N.danger ? N.danger : 0, seed: o.seed ?? null, target: o.target ?? null, link: !!o.link };
resetPools();
const meta = C.metaBonus(save.up);
Object.assign(run, {
mode: N ? 'night' : mode, time: 0, px: 0, py: 0, ppx: 0, ppy: 0, vx: 0, vy: 0, face: 1, iframes: 60, level: 1, xp: 0, kills: 0, shards: 0, weapons: [], passives: {},
rerolls: meta.rerolls, revives: meta.revives, spawnAcc: 0, boss: false, bossIdx: -1, bossDone: false, nextBossAt: C.BOSS_AT,
swarms: N ? N.swarms.slice() : mode === 'daily' ? [120, 220] : [200, 360, 540], hitstop: 0, shake: 0, hurtFlash: 0, levelFlash: 0, dawnT: 0, dieT: 0, won: false,
god: false, auto: false, emberT: 0, orbitA: 0, pending: 0, promptT: 5, banner: '', bannerT: 0, chest: null, maxhp: 100, hp: 100,
night: N, target: o.target ?? null, moved: 0, tut: !!(N && N.n === 1 && !save.nights.stars[1]),
});
run.dcfg = mode === 'daily' ? (o.seed != null && o.seed !== DAILY.seed ? { ...C.seeded(o.seed), num: 0 } : DAILY) : null;
run.mod = run.dcfg ? run.dcfg.mod : null;
run.mods = new Set(N ? N.mods : run.mod ? [run.mod.id] : []);
run.seed = N ? (o.seed ?? L.nightSeed(N.n)) : run.dcfg ? run.dcfg.seed : (Math.random() * 4294967296) >>> 0;
run.R = rng(run.seed);
run.wisp = C.WISPS.find((w) => w.id === save.wisp) || C.WISPS[0];
if (!C.wispUnlocked(save, run.wisp)) run.wisp = C.WISPS[0];
run.nextElite = N ? (N.elite || Infinity) : mode === 'daily' ? 60 : 90;
let start = run.wisp.weapon;
if (run.dcfg) start = run.dcfg.weapon;
else if (C.metaBonus(save.up).choice && save.weapon && startWeapons().includes(save.weapon)) start = save.weapon;
addWeapon(start);
if (run.mods.has('embers') && start !== 'ember') addWeapon('ember');
recalc(); run.hp = run.maxhp;
if (run.dcfg === DAILY) { save.daily.tries++; }
persist();
hideAll(); $('pause').hidden = false;
state = 'play'; acc = 0; musicOn = true;
cam.x = 0; cam.y = 0;
count(GAME, 'play', N ? (N.danger ? `trial-${N.danger}` : 'night') : mode);
cv.focus({ preventScroll: true });
if (N && N.danger) banner(`Trial ยท Night ${N.n} at ${N.dangerName}: ${N.name}`);
else if (N) banner(L.isTwist(N.n) && N.n > 1 ? `Night ${N.n} ยท New: ${L.groupOf(N.n).twist}` : N.challenge ? `Challenge night ${N.n}: ${N.name}` : `Night ${N.n}: ${N.name}`);
else if (mode === 'daily') banner(run.dcfg.num ? `Daily #${run.dcfg.num}: ${run.mod.name}` : `Seed ${run.seed}: ${run.mod.name}`);
}
function banner(t) { run.banner = t; run.bannerT = 2.6; }
function startWeapons() { const s = new Set(); for (const w of C.WISPS) if (C.wispUnlocked(save, w)) s.add(w.weapon); return [...s]; }
// ------------------------------------------------------------------ spawning
function spawn(type, x, y, hpMul = 1) {
if (nE >= MAXE) return -1;
const T = ET[type], i = nE++;
ex[i] = epx[i] = x; ey[i] = epy[i] = y; ekx[i] = eky[i] = 0;
ehp[i] = emax[i] = T.hp * hpMul; espd[i] = T.spd * (0.9 + run.R() * 0.2) * (type === 0 && run.mods.has('swiftmoths') ? 1.45 : 1);
edmg[i] = T.dmg * (1 + run.time / 60 / 900); er[i] = T.r; exp_[i] = T.xp; etype[i] = type; eflash[i] = 0; eorb[i] = 0; edead[i] = 0; eid[i] = nextId++;
ephase[i] = run.R() * TAU;
return i;
}
function viewRadius() { return Math.hypot(view.w, view.h) / 2 + 50; }
function spawnRing(type, hpMul, d = viewRadius()) {
const a = run.R() * TAU;
// bias spawns ahead of movement so running away isn't free
const mvx = run.vx, mvy = run.vy, sp = Math.hypot(mvx, mvy);
let ang = a;
if (sp > 10 && run.R() < 0.5) ang = Math.atan2(mvy, mvx) + (run.R() - 0.5) * 1.6;
return spawn(type, run.px + Math.cos(ang) * d, run.py + Math.sin(ang) * d, hpMul);
}
function hpScale(t) {
let s = 1 + t / 110;
if (t > 600) s *= Math.pow(1.6, (t - 600) / 120);
return s;
}
function nightDirector(N, t) {
const f = Math.min(1, t / N.dur), lerp = (a) => a[0] + (a[1] - a[0]) * f, hs = lerp(N.hp), target = lerp(N.spawn);
if (nE < target) {
run.spawnAcc += lerp(N.rate) / 60 * (nE < target * 0.5 ? 2 : 1);
const [a, b, c] = N.mix, tot = a + b + c;
while (run.spawnAcc >= 1) { run.spawnAcc -= 1; const r = run.R() * tot; spawnRing(r < a ? 0 : r < a + b ? 1 : 2, hs); }
}
if (t >= run.nextElite) { run.nextElite += N.elite; spawnRing(3, hs * 0.55); sfx('elite'); banner('An elite stirs in the reeds'); }
if (run.swarms.length && t >= run.swarms[0]) {
run.swarms.shift();
const n = Math.round(24 + N.n * 0.8), d = viewRadius() * 0.9;
for (let k = 0; k < n; k++) { const ang = (k / n) * TAU; spawn(0, run.px + Math.cos(ang) * d, run.py + Math.sin(ang) * d, hs); }
banner('A moth swarm closes in!');
}
if (N.boss && !run.boss && !run.bossDone && t >= N.boss.at) {
run.boss = true;
const w = N.boss.kind === 'warden';
run.bossIdx = spawnRing(w ? 4 : 3, w ? N.boss.hp : N.boss.hp * hs, viewRadius() * 0.8);
if (run.bossIdx >= 0) eid[run.bossIdx] = -1;
sfx('boss'); banner(w ? 'The Gloam Warden rises' : 'The Warden\'s Herald arrives'); run.shake = 14;
}
}
function director() {
const t = run.time / 60, daily = run.mode === 'daily';
if (run.night) { nightDirector(run.night, t); return; }
const target = Math.min(daily ? 18 + t * 0.9 + t * t / 900 : 12 + t * 0.6 + t * t / 1500 + (t > 600 ? (t - 600) * 0.8 : 0), 950);
if (nE < target) {
run.spawnAcc += (1 + t / 25) / 60 * (nE < target * 0.5 ? 2 : 1);
const hs = hpScale(t);
while (run.spawnAcc >= 1) {
run.spawnAcc -= 1;
const wm = Math.max(0.25, 1 - t / 420), wc = t > 40 ? Math.min(0.65, (t - 40) / 180) : 0, ww = t > 150 ? Math.min(0.5, (t - 150) / 240) : 0;
const r = run.R() * (wm + wc + ww);
spawnRing(r < wm ? 0 : r < wm + wc ? 1 : 2, hs);
}
}
if (t >= run.nextElite) {
run.nextElite += run.mods.has('elites') ? 40 : daily ? 60 : 75;
spawnRing(3, hpScale(t) * 0.9); sfx('elite'); banner('An elite stirs in the reeds');
}
if (run.swarms.length && t >= run.swarms[0]) {
run.swarms.shift();
const n = 54, d = viewRadius() * 0.9, hs = hpScale(t);
for (let k = 0; k < n; k++) { const a = (k / n) * TAU; spawn(0, run.px + Math.cos(a) * d, run.py + Math.sin(a) * d, hs); }
banner('A moth swarm closes in!');
}
if (run.mode !== 'daily' && !run.boss && t >= run.nextBossAt) {
run.boss = true; run.nextBossAt += C.BOSS_AT;
run.bossIdx = spawnRing(4, t > 600 ? hpScale(t) / 4 : 1, viewRadius() * 0.8);
if (run.bossIdx >= 0) { const b = run.bossIdx; eid[b] = -1; }
sfx('boss'); banner('The Gloam Warden rises'); run.shake = 14;
}
if (daily && !run.boss && !run.bossDone && t >= 240) { run.boss = true; const i = spawnRing(3, hpScale(t) * 3); if (i >= 0) eid[i] = -1; sfx('boss'); banner('The Warden\'s Herald arrives'); }
}
// ------------------------------------------------------------------ combat
function hurt(i, d, fromX, fromY, knock) {
if (edead[i]) return;
let dmg = d * run.dmgMul;
const crit = run.R() < 0.08; if (crit) dmg *= 2;
ehp[i] -= dmg; eflash[i] = 5;
if (knock && etype[i] < 3) { const dx = ex[i] - fromX, dy = ey[i] - fromY, l = Math.hypot(dx, dy) || 1; ekx[i] += (dx / l) * knock; eky[i] += (dy / l) * knock; }
else if (knock) { const dx = ex[i] - fromX, dy = ey[i] - fromY, l = Math.hypot(dx, dy) || 1; ekx[i] += (dx / l) * knock * 0.15; eky[i] += (dy / l) * knock * 0.15; }
dmgNum(ex[i], ey[i] - er[i], Math.round(dmg), crit);
sfx('hit');
if (ehp[i] <= 0) kill(i);
}
function kill(i) {
edead[i] = 1; run.kills++;
const t = etype[i], x = ex[i], y = ey[i];
particle(x, y, t === 0 ? 2 : t === 1 ? 8 : t === 2 ? 2 : 4, t >= 3 ? 40 : 7, t >= 3 ? 260 : 120, 0.5, t >= 3 ? 5 : 3);
dropGem(x, y, exp_[i]);
if (t >= 3) {
run.hitstop = t === 4 ? 26 : 9; run.shake = t === 4 ? 22 : 10;
ring(x, y, t === 4 ? 260 : 120, 1);
addPickup(x, y, 2);
if (t === 4 || eid[i] === -1) { run.bossDone = true; run.boss = false; banner(t === 4 ? 'Warden banished!' : 'Herald banished!'); for (let k = 0; k < 12; k++) dropGem(x + (Math.random() - 0.5) * 120, y + (Math.random() - 0.5) * 120, 10); }
sfx('elite');
} else {
sfx('kill');
const r = run.R();
if (t > 0 && r < 0.015) addPickup(x, y, 0); else if (r > 0.9975) addPickup(x, y, 1);
}
}
function dropGem(x, y, v) {
v *= run.xpMul;
if (nG >= MAXG) { const j = (Math.random() * nG) | 0; gv[j] += v; return; }
const i = nG++; gx[i] = x; gy[i] = y; gv[i] = v; gpull[i] = 0; gsp[i] = 0;
}
function addPickup(x, y, t) { if (nP >= MAXP) return; const i = nP++; kx[i] = x; ky[i] = y; kt[i] = t; }
function fireWeapons() {
const am = run.areaMul;
for (const w of run.weapons) {
const s = w.st;
switch (w.id) {
case 'spark': {
w.cd -= STEP; if (w.cd > 0) break; w.cd = s.cd * run.cdMul;
let tgt = nearest(run.px, run.py, 520);
for (let k = 0; k < s.count; k++) {
let ang;
if (tgt >= 0) ang = Math.atan2(ey[tgt] - run.py, ex[tgt] - run.px) + (k - (s.count - 1) / 2) * 0.16;
else ang = run.R() * TAU;
if (w.evo) ang += (run.R() - 0.5) * 0.4;
shootBolt(ang, s.speed, s.dmg, s.pierce, w.evo);
}
sfx('shoot'); break;
}
case 'firefly': {
const n = s.count, R = s.radius * am;
for (let k = 0; k < n; k++) {
const a = run.orbitA * s.spin + (k / n) * TAU, fx = run.px + Math.cos(a) * R, fy = run.py + Math.sin(a) * R;
const m = query(fx, fy, 12 * Math.sqrt(am));
for (let j = 0; j < m; j++) { const i = QB[j]; if (eorb[i] === 0) { eorb[i] = 18; hurt(i, s.dmg, run.px, run.py, 90); } }
}
break;
}
case 'nova': {
w.cd -= STEP; if (w.cd > 0) break; w.cd = s.cd * run.cdMul;
const R = s.radius * am, m = query(run.px, run.py, R);
for (let j = 0; j < m; j++) hurt(QB[j], s.dmg, run.px, run.py, s.knock);
ring(run.px, run.py, R, w.evo ? 1 : 0); sfx('nova'); run.shake = Math.max(run.shake, 3);
break;
}
case 'chain': {
w.cd -= STEP; if (w.cd > 0) break;
let cur = nearest(run.px, run.py, 360); if (cur < 0) { w.cd = 0.2; break; }
w.cd = s.cd * run.cdMul;
let lx = run.px, ly = run.py;
for (let k = 0; k < s.jumps && cur >= 0; k++) {
arc(lx, ly, ex[cur], ey[cur]); lx = ex[cur]; ly = ey[cur];
const id = eid[cur]; hurt(cur, s.dmg, lx, ly, 0);
cur = nearest(lx, ly, s.range * am, id);
if (cur >= 0 && edead[cur]) cur = -1;
}
sfx('zap'); break;
}
case 'ember': {
w.cd -= STEP;
if (w.cd <= 0 && nM < MAXM) {
w.cd = s.drop; const i = nM++; mx[i] = run.px + (run.R() - 0.5) * 8; my[i] = run.py + (run.R() - 0.5) * 8; mlife[i] = s.life; mr[i] = s.radius * am;
}
break;
}
case 'moon': {
w.cd -= STEP; if (w.cd > 0) break; w.cd = s.cd * run.cdMul;
for (let k = 0; k < s.count && nS < MAXS; k++) {
const m = query(run.px, run.py, Math.min(view.w, view.h) * 0.6);
let x, y;
if (m) { const i = QB[(run.R() * m) | 0]; x = ex[i]; y = ey[i]; } else { x = run.px + (run.R() - 0.5) * 300; y = run.py + (run.R() - 0.5) * 300; }
const i = nS++; sx[i] = x; sy[i] = y; st[i] = 0.35 + k * 0.08; sr[i] = s.radius * am; sd[i] = s.dmg;
}
break;
}
}
}
// ember damage ticks
const ew = weaponOf('ember');
if (ew && run.time % 12 === 0) for (let k = 0; k < nM; k++) { const m = query(mx[k], my[k], mr[k]); for (let j = 0; j < m; j++) hurt(QB[j], ew.st.dmg, mx[k], my[k], 0); }
}
function shootBolt(ang, spd, dmg, pierce, big) {
if (nB >= MAXB) return;
const i = nB++; bx[i] = bpx[i] = run.px; by[i] = bpy[i] = run.py; bvx[i] = Math.cos(ang) * spd; bvy[i] = Math.sin(ang) * spd;
blife[i] = 1.4; bdmg[i] = dmg; bpierce[i] = pierce; blast[i] = 0; bbig[i] = big ? 1 : 0;
}
// ------------------------------------------------------------------ input
const keys = new Set();
const joy = { on: false, id: -1, ox: 0, oy: 0, x: 0, y: 0 };
const mouse = { in: false, x: 0, y: 0 };
function inputDir(out) {
let dx = 0, dy = 0;
if (keys.has('ArrowLeft') || keys.has('KeyA')) dx -= 1;
if (keys.has('ArrowRight') || keys.has('KeyD')) dx += 1;
if (keys.has('ArrowUp') || keys.has('KeyW')) dy -= 1;
if (keys.has('ArrowDown') || keys.has('KeyS')) dy += 1;
if (dx || dy) { const l = Math.hypot(dx, dy); out.x = dx / l; out.y = dy / l; return; }
if (joy.on) {
const jx = joy.x - joy.ox, jy = joy.y - joy.oy, l = Math.hypot(jx, jy);
if (l > 6) { const m = Math.min(1, l / 48); out.x = (jx / l) * m; out.y = (jy / l) * m; return; }
}
if (save.mouse && mouse.in) {
const sxp = (run.px - cam.x) * view.k + view.cw / 2, syp = (run.py - cam.y) * view.k + view.ch / 2;
const jx = mouse.x - sxp, jy = mouse.y - syp, l = Math.hypot(jx, jy);
if (l > 18) { const m = Math.min(1, (l - 18) / 90); out.x = (jx / l) * m; out.y = (jy / l) * m; return; }
}
if (run.auto) { autopilot(out); return; }
out.x = 0; out.y = 0;
}
function autopilot(out) {
const t = run.time / 60;
let dx = Math.cos(t * 0.55) * 0.8, dy = Math.sin(t * 0.8) * 0.8;
const m = query(run.px, run.py, 110);
for (let j = 0; j < m; j++) { const i = QB[j], ox = run.px - ex[i], oy = run.py - ey[i], l = Math.hypot(ox, oy) || 1; dx += (ox / l) * 0.6; dy += (oy / l) * 0.6; }
// drift toward nearby shards
for (let g = 0; g < nG; g += 7) { const ox = gx[g] - run.px, oy = gy[g] - run.py, d = ox * ox + oy * oy; if (d < 200 * 200) { dx += ox / 400; dy += oy / 400; break; } }
const l = Math.hypot(dx, dy) || 1; out.x = dx / l; out.y = dy / l;
}
const rel = (e) => { const b = cv.getBoundingClientRect(); return [e.clientX - b.left, e.clientY - b.top]; };
cv.addEventListener('pointerdown', (e) => {
audio();
if (state === 'chest') { if (run.chest && run.chest.t > 0.5) run.chest.t = Math.max(run.chest.t, run.chest.dur); return; }
if (state !== 'play') return;
if (e.pointerType === 'mouse' && save.mouse) return;
const [x, y] = rel(e); joy.on = true; joy.id = e.pointerId; joy.ox = joy.x = x; joy.oy = joy.y = y;
try { cv.setPointerCapture(e.pointerId); } catch { /* ok */ }
e.preventDefault();
});
cv.addEventListener('pointermove', (e) => {
const [x, y] = rel(e);
if (e.pointerType === 'mouse') { mouse.in = true; mouse.x = x; mouse.y = y; }
if (joy.on && e.pointerId === joy.id) {
joy.x = x; joy.y = y;
const dx = x - joy.ox, dy = y - joy.oy, l = Math.hypot(dx, dy);
if (l > 70) { joy.ox = x - (dx / l) * 70; joy.oy = y - (dy / l) * 70; } // floating joystick follows the thumb
}
});
const endJoy = (e) => { if (e.pointerId === joy.id) joy.on = false; };
cv.addEventListener('pointerup', endJoy); cv.addEventListener('pointercancel', endJoy);
cv.addEventListener('pointerleave', (e) => { if (e.pointerType === 'mouse') mouse.in = false; });
const GAMEKEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Space']);
addEventListener('keydown', (e) => {
if (e.target && /INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) return;
if (document.querySelector('dialog[open]')) return;
const c = e.code;
if (state !== 'menu' || document.activeElement === cv) if (GAMEKEYS.has(c) && inStageView()) e.preventDefault();
keys.add(c);
if (state === 'play' && (c === 'Escape' || c === 'KeyP')) { pauseGame(); return; }
if (state === 'paused' && (c === 'Escape' || c === 'KeyP')) { resume(); return; }
if (c === 'KeyR' && (state === 'over' || state === 'paused' || state === 'play')) { retry(); return; }
if (c === 'KeyN' && state === 'over' && !$('next').hidden) { $('next').click(); return; }
if (c === 'KeyM') { audio(); setMute(!muted); }
if (state === 'menu' && (c === 'Space' || c === 'Enter') && !$('menu').hidden && document.activeElement?.tagName !== 'BUTTON') { e.preventDefault(); playFromMenu(); return; }
if (state === 'menu' && c === 'Escape' && !$('map').hidden) { showMenu(); return; }
if (state === 'levelup' && /^Digit[1-3]$/.test(c)) { const b = $('cardlist').children[+c.slice(5) - 1]; if (b) b.click(); }
if (state === 'levelup' && c === 'KeyX' && !$('reroll').disabled) $('reroll').click();
if (state === 'chest' && (c === 'Space' || c === 'Enter') && run.chest && run.chest.t > 0.5) run.chest.t = Math.max(run.chest.t, run.chest.dur);
if (state === 'over' && c === 'Space' && document.activeElement?.tagName !== 'BUTTON' && document.activeElement?.tagName !== 'A') { e.preventDefault(); retry(); }
});
addEventListener('keyup', (e) => keys.delete(e.code));
addEventListener('blur', () => keys.clear());
function inStageView() { const b = stageEl.getBoundingClientRect(); return b.bottom > 0 && b.top < innerHeight; }
document.addEventListener('visibilitychange', () => { if (document.hidden && state === 'play') pauseGame(); });
// ------------------------------------------------------------------ simulation tick
const dir = { x: 0, y: 0 };
function tick() {
if (run.hitstop > 0) { run.hitstop--; return; }
if (run.dieT > 0) { run.dieT--; updateFx(); if (run.dieT === 0) endRun(false); return; }
if (run.dawnT > 0) { run.dawnT--; updateFx(); if (run.dawnT === 0) endRun(true); return; }
run.time++;
const t = run.time / 60;
buildHash();
inputDir(dir);
run.ppx = run.px; run.ppy = run.py;
const tvx = dir.x * run.speed, tvy = dir.y * run.speed;
run.vx += (tvx - run.vx) * 0.25; run.vy += (tvy - run.vy) * 0.25;
run.px += run.vx * STEP; run.py += run.vy * STEP;
run.moved += Math.hypot(run.vx, run.vy) * STEP;
if (Math.abs(run.vx) > 5) run.face = run.vx > 0 ? 1 : -1;
run.orbitA += STEP;
if (run.iframes > 0) run.iframes--;
if (run.regen && run.hp < run.maxhp) run.hp = Math.min(run.maxhp, run.hp + run.regen * STEP);
director();
buildHash();
// enemies
const vr = viewRadius() * 1.7;
for (let i = 0; i < nE; i++) {
epx[i] = ex[i]; epy[i] = ey[i];
if (edead[i]) continue;
let dx = run.px - ex[i], dy = run.py - ey[i];
const d = Math.hypot(dx, dy) || 1;
if (d > vr && etype[i] < 3) { // recycle stragglers in front of the player
const a = Math.atan2(run.vy || dy, run.vx || dx) + (run.R() - 0.5) * 2, rr = viewRadius();
ex[i] = epx[i] = run.px + Math.cos(a) * rr; ey[i] = epy[i] = run.py + Math.sin(a) * rr; continue;
}
let sp = espd[i];
if (etype[i] === 2) sp *= 0.7 + 0.5 * Math.max(0, Math.sin(t * 2 + ephase[i])); // wraiths surge
let vx = (dx / d) * sp, vy = (dy / d) * sp;
if (etype[i] === 0) { vx += Math.cos(t * 6 + ephase[i]) * 30; vy += Math.sin(t * 5 + ephase[i]) * 30; } // moths flutter
// separation within the cell
const cx = ((ex[i] - gox) / CS) | 0, cy = ((ey[i] - goy) / CS) | 0;
if (cx >= 0 && cy >= 0 && cx < GW && cy < GH) {
let k = 0;
for (let j = heads[cy * GW + cx]; j >= 0 && k < 8; j = nextE[j], k++) {
if (j === i) continue;
const ox = ex[i] - ex[j], oy = ey[i] - ey[j], rr = er[i] + er[j], dd = ox * ox + oy * oy;
if (dd < rr * rr && dd > 0.01) { const l = Math.sqrt(dd), push = (rr - l) / rr * 90; vx += (ox / l) * push; vy += (oy / l) * push; }
}
}
ex[i] += (vx + ekx[i]) * STEP; ey[i] += (vy + eky[i]) * STEP;
ekx[i] *= 0.86; eky[i] *= 0.86;
if (eflash[i]) eflash[i]--;
if (eorb[i]) eorb[i]--;
// contact
const pr = 11 + er[i];
if (d < pr && run.iframes === 0 && !run.god) {
run.hp -= edmg[i]; run.iframes = 28; run.hurtFlash = 1; fx3('hurt'); run.shake = Math.max(run.shake, 7); sfx('hurt');
particle(run.px, run.py, 4, 10, 160, 0.4);
if (run.hp <= 0) { onDeath(); return; }
}
}
if (run.boss && run.mode !== 'daily' && nE && t % 6 < STEP && run.bossIdx >= 0) { // the warden calls moths
for (let i = 0; i < nE; i++) if (etype[i] === 4 && !edead[i]) { for (let k = 0; k < 10; k++) { const a = (k / 10) * TAU; spawn(0, ex[i] + Math.cos(a) * 60, ey[i] + Math.sin(a) * 60, hpScale(t)); } break; }
}
fireWeapons();
// bolts
for (let i = 0; i < nB; i++) {
bpx[i] = bx[i]; bpy[i] = by[i];
bx[i] += bvx[i] * STEP; by[i] += bvy[i] * STEP; blife[i] -= STEP;
if (blife[i] <= 0) continue;
const m = query(bx[i], by[i], bbig[i] ? 10 : 6);
for (let j = 0; j < m; j++) {
const e = QB[j]; if (eid[e] === blast[i]) continue;
blast[i] = eid[e]; hurt(e, bdmg[i], bx[i] - bvx[i], by[i] - bvy[i], 60);
particle(bx[i], by[i], 1, 3, 90, 0.25, 2);
if (bpierce[i]-- <= 0) { blife[i] = 0; break; }
}
}
// moon strikes
for (let i = 0; i < nS; i++) {
const was = st[i]; st[i] -= STEP;
if (was > 0 && st[i] <= 0) { const m = query(sx[i], sy[i], sr[i]); for (let j = 0; j < m; j++) hurt(QB[j], sd[i], sx[i], sy[i], 120); ring(sx[i], sy[i], sr[i], 2); particle(sx[i], sy[i], 6, 14, 200, 0.5); sfx('moon'); }
}
// embers
for (let i = 0; i < nM; i++) mlife[i] -= STEP;
// gems
const mg = run.magnet, mg2 = mg * mg;
for (let i = 0; i < nG; i++) {
const dx = run.px - gx[i], dy = run.py - gy[i], d2 = dx * dx + dy * dy;
if (!gpull[i] && d2 < mg2) gpull[i] = 1;
if (gpull[i]) {
gsp[i] = Math.min(900, gsp[i] + 30); const d = Math.sqrt(d2) || 1;
gx[i] += (dx / d) * gsp[i] * STEP; gy[i] += (dy / d) * gsp[i] * STEP;
if (d < 16) { run.xp += gv[i]; run.shards += gv[i]; gv[i] = 0; sfx('shard'); }
}
}
// pickups
for (let i = 0; i < nP; i++) {
const dx = run.px - kx[i], dy = run.py - ky[i];
if (dx * dx + dy * dy < 26 * 26) {
const t2 = kt[i];
if (t2 === 0) { run.hp = Math.min(run.maxhp, run.hp + run.maxhp * 0.25); sfx('heal'); particle(run.px, run.py, 4, 14, 140, 0.6); }
else if (t2 === 1) { for (let g = 0; g < nG; g++) gpull[g] = 1; sfx('pick'); banner('All shards drawn in!'); }
else if (t2 === 2) openChest();
kt[i] = 255;
}
}
updateFx();
compact();
if (run.hurtFlash > 0) run.hurtFlash = Math.max(0, run.hurtFlash - 0.05);
if (run.levelFlash > 0) run.levelFlash = Math.max(0, run.levelFlash - 0.03);
// level up
let need = C.xpNeed(run.level);
while (run.xp >= need) { run.xp -= need; run.level++; run.pending++; need = C.xpNeed(run.level); }
if (run.pending > 0 && state === 'play') { showLevelUp(); return; }
// dawn
if (t >= goalTime()) dawn();
}
function goalTime() { return run.night ? run.night.dur : run.mode === 'daily' ? C.DAILY_LEN : run.mode === 'standard' ? C.DAWN : Infinity; }
function updateFx() {
for (let i = 0; i < nQ; i++) { qx[i] += qvx[i] * STEP; qy[i] += qvy[i] * STEP; qvx[i] *= 0.93; qvy[i] *= 0.93; ql[i] -= STEP; }
for (let i = 0; i < nR; i++) rlife[i] -= STEP * 2.2;
for (let i = 0; i < nA; i++) alife[i] -= STEP * 4;
for (let i = 0; i < MAXN; i++) if (nl[i] > 0) { nl[i] -= STEP * 1.4; ny[i] -= 30 * STEP; }
if (run.dawnT || run.dieT) {
for (let i = 0; i < nQ; i++) if (ql[i] <= 0) { qx[i] = qx[--nQ]; qy[i] = qy[nQ]; qvx[i] = qvx[nQ]; qvy[i] = qvy[nQ]; ql[i] = ql[nQ]; qm[i] = qm[nQ]; qs[i] = qs[nQ]; qc[i] = qc[nQ]; i--; }
}
}
function compact() {
let w = 0;
for (let i = 0; i < nE; i++) {
if (edead[i]) continue;
if (w !== i) {
ex[w] = ex[i]; ey[w] = ey[i]; epx[w] = epx[i]; epy[w] = epy[i]; ekx[w] = ekx[i]; eky[w] = eky[i]; ehp[w] = ehp[i]; emax[w] = emax[i];
espd[w] = espd[i]; edmg[w] = edmg[i]; er[w] = er[i]; exp_[w] = exp_[i]; etype[w] = etype[i]; eflash[w] = eflash[i]; eorb[w] = eorb[i]; edead[w] = 0; eid[w] = eid[i]; ephase[w] = ephase[i];
}
w++;
}
nE = w;
w = 0;
for (let i = 0; i < nB; i++) { if (blife[i] <= 0) continue; if (w !== i) { bx[w] = bx[i]; by[w] = by[i]; bpx[w] = bpx[i]; bpy[w] = bpy[i]; bvx[w] = bvx[i]; bvy[w] = bvy[i]; blife[w] = blife[i]; bdmg[w] = bdmg[i]; bpierce[w] = bpierce[i]; blast[w] = blast[i]; bbig[w] = bbig[i]; } w++; }
nB = w; w = 0;
for (let i = 0; i < nG; i++) { if (gv[i] <= 0) continue; if (w !== i) { gx[w] = gx[i]; gy[w] = gy[i]; gv[w] = gv[i]; gpull[w] = gpull[i]; gsp[w] = gsp[i]; } w++; }
nG = w; w = 0;
for (let i = 0; i < nP; i++) { if (kt[i] === 255) continue; if (w !== i) { kx[w] = kx[i]; ky[w] = ky[i]; kt[w] = kt[i]; } w++; }
nP = w; w = 0;
for (let i = 0; i < nM; i++) { if (mlife[i] <= 0) continue; if (w !== i) { mx[w] = mx[i]; my[w] = my[i]; mlife[w] = mlife[i]; mr[w] = mr[i]; } w++; }
nM = w; w = 0;
for (let i = 0; i < nS; i++) { if (st[i] <= -0.3) continue; if (w !== i) { sx[w] = sx[i]; sy[w] = sy[i]; st[w] = st[i]; sr[w] = sr[i]; sd[w] = sd[i]; } w++; }
nS = w; w = 0;
for (let i = 0; i < nR; i++) { if (rlife[i] <= 0) continue; if (w !== i) { rx[w] = rx[i]; ry[w] = ry[i]; rmax[w] = rmax[i]; rlife[w] = rlife[i]; rcol[w] = rcol[i]; } w++; }
nR = w; w = 0;
for (let i = 0; i < nA; i++) { if (alife[i] <= 0) continue; if (w !== i) { ax1[w] = ax1[i]; ay1[w] = ay1[i]; ax2[w] = ax2[i]; ay2[w] = ay2[i]; alife[w] = alife[i]; } w++; }
nA = w; w = 0;
for (let i = 0; i < nQ; i++) { if (ql[i] <= 0) continue; if (w !== i) { qx[w] = qx[i]; qy[w] = qy[i]; qvx[w] = qvx[i]; qvy[w] = qvy[i]; ql[w] = ql[i]; qm[w] = qm[i]; qs[w] = qs[i]; qc[w] = qc[i]; } w++; }
nQ = w;
}
function onDeath() {
if (run.revives > 0) {
run.revives--; run.hp = run.maxhp * 0.5; run.iframes = 120;
const m = query(run.px, run.py, 260); for (let j = 0; j < m; j++) hurt(QB[j], 9999, run.px, run.py, 400);
ring(run.px, run.py, 260, 1); banner('Second Wick! Your light returns'); sfx('level'); return;
}
fx3('death'); run.hp = 0; run.dieT = 70; run.shake = 16; particle(run.px, run.py, 1, 60, 260, 1, 4); sfx('die');
}
function dawn() {
fx3('dawn'); run.won = true; run.dawnT = 110; sfx('dawn'); celebrate(); banner(run.mode === 'daily' ? 'You made it! Daily complete' : 'Dawn breaks over the marsh!');
for (let i = 0; i < nE; i++) if (!edead[i]) { particle(ex[i], ey[i], 0, 2, 80, 0.8); edead[i] = 1; }
compact();
}
// ------------------------------------------------------------------ level-up cards
let opts = [];
function candidates() {
const c = [];
for (const w of run.weapons) {
const W = C.WEAPONS[w.id];
if (!w.evo && w.lv >= C.MAX_LV && run.passives[W.evo.with]) c.push({ k: 'evo', id: w.id, w: 100 });
else if (!w.evo && w.lv < C.MAX_LV) c.push({ k: 'wup', id: w.id, w: 3 });
}
if (run.weapons.length < 6) for (const id in C.WEAPONS) if (!weaponOf(id)) c.push({ k: 'wnew', id, w: 2 });
const np = Object.keys(run.passives).length;
for (const id in C.PASSIVES) { const lv = run.passives[id] || 0; if (lv && lv < C.MAX_LV) c.push({ k: 'pup', id, w: 2 }); else if (!lv && np < 6) c.push({ k: 'pnew', id, w: 1.5 }); }
return c;
}
function rollOptions(n = 3) {
const c = candidates(), out = [];
const evo = c.filter((x) => x.k === 'evo'); if (evo.length) out.push(evo[0]);
const pool = c.filter((x) => x.k !== 'evo');
while (out.length < n && pool.length) {
let tot = 0; for (const x of pool) tot += x.w;
let r = run.R() * tot, k = 0;
for (; k < pool.length - 1; k++) { r -= pool[k].w; if (r <= 0) break; }
out.push(pool.splice(k, 1)[0]);
}
if (!out.length) out.push({ k: 'heal' }, { k: 'gold' });
return out;
}
function cardInfo(o) {
if (o.k === 'heal') return { icon: 'โค', name: 'Warm Glow', text: 'Restore 40% light' };
if (o.k === 'gold') return { icon: '๐ฅ', name: 'Ember Cache', text: '+25 Embers after the run' };
if (o.k === 'evo') { const W = C.WEAPONS[o.id]; return { icon: 'โ
', name: `Evolve: ${W.evo.name}`, text: `${W.name} + ${C.PASSIVES[W.evo.with].name} fuse into something brighter` }; }
if (o.k === 'wup' || o.k === 'wnew') { const W = C.WEAPONS[o.id], lv = o.k === 'wnew' ? 1 : weaponOf(o.id).lv + 1; return { icon: W.icon, name: `${W.name}${lv > 1 ? ` Lv ${lv}` : ''}`, text: W.desc[lv - 1] }; }
const P = C.PASSIVES[o.id], lv = (run.passives[o.id] || 0) + 1;
return { icon: P.icon, name: `${P.name}${lv > 1 ? ` Lv ${lv}` : ''}`, text: P.desc };
}
let bonusEmbers = 0;
function applyOption(o) {
if (o.k === 'evo') { const w = weaponOf(o.id); w.evo = true; w.st = C.weaponStats(w.id, w.lv, true); banner(`${C.WEAPONS[o.id].evo.name}!`); }
else if (o.k === 'wup') levelWeapon(weaponOf(o.id));
else if (o.k === 'wnew') addWeapon(o.id);
else if (o.k === 'pup' || o.k === 'pnew') run.passives[o.id] = (run.passives[o.id] || 0) + 1;
else if (o.k === 'heal') run.hp = Math.min(run.maxhp, run.hp + run.maxhp * 0.4);
else if (o.k === 'gold') bonusEmbers += 25;
recalc();
}
function showLevelUp() {
state = 'levelup'; joy.on = false; sfx('level'); run.levelFlash = 1; fx3('level');
ring(run.px, run.py, 140, 1); particle(run.px, run.py, 1, 24, 200, 0.6);
if (run.auto) { applyOption(rollOptions(1)[0]); run.pending--; state = 'play'; return; }
opts = rollOptions();
renderCards();
$('cards').hidden = false;
setTimeout(() => { const b = $('cardlist').firstElementChild; if (b && !TOUCH) b.focus({ preventScroll: true }); }, 30);
}
function renderCards() {
$('cards-title').textContent = `Level ${run.level - run.pending + 1}!`;
const list = $('cardlist'); list.innerHTML = '';
opts.forEach((o, i) => {
const info = cardInfo(o), b = document.createElement('button');
b.type = 'button'; b.className = `card${o.k === 'evo' ? ' evo' : ''}${o.k === 'wnew' || o.k === 'pnew' ? ' new' : ''}`;
b.innerHTML = `${i + 1}`;
b.querySelector('.ic').textContent = info.icon; b.querySelector('b').textContent = info.name; b.querySelector('small').textContent = info.text;
b.onclick = () => pickCard(o);
list.appendChild(b);
});
const rb = $('reroll'); rb.textContent = `โป Reroll (${run.rerolls})`; rb.disabled = run.rerolls <= 0; rb.hidden = run.rerolls <= 0;
}
function pickCard(o) {
if (state !== 'levelup') return;
applyOption(o); sfx('pick'); run.pending--;
if (run.pending > 0) { opts = rollOptions(); renderCards(); sfx('level'); return; }
$('cards').hidden = true; state = 'play'; acc = 0; cv.focus({ preventScroll: true });
}
$('reroll').onclick = () => { if (run.rerolls <= 0 || state !== 'levelup') return; run.rerolls--; opts = rollOptions(); renderCards(); sfx('ui'); };
// chest: a short roll through the upgrade icons, then 1-3 upgrades
function openChest() {
const n = run.R() < 0.15 ? 3 : run.R() < 0.4 ? 2 : 1, picks = [];
for (let k = 0; k < n; k++) { const o = rollOptions(1)[0]; picks.push(o); applyOption(o); }
if (run.auto) { banner(`Chest: ${picks.map((p) => cardInfo(p).name).join(', ')}`); return; }
run.chest = { t: 0, dur: 1.5, picks, icons: picks.map((p) => cardInfo(p)) };
state = 'chest'; sfx('chest'); joy.on = false;
}
// ------------------------------------------------------------------ screens
function hideAll() { for (const id of ['menu', 'map', 'shop', 'cards', 'pausem', 'over']) $(id).hidden = true; }
function pauseGame() {
if (state !== 'play') return;
state = 'paused'; joy.on = false; keys.clear();
$('build').innerHTML = '';
for (const w of run.weapons) { const s = document.createElement('span'); s.textContent = `${C.WEAPONS[w.id].icon} ${w.evo ? C.WEAPONS[w.id].evo.name : C.WEAPONS[w.id].name} ${w.evo ? 'โ
' : 'Lv ' + w.lv}`; $('build').appendChild(s); }
for (const id in run.passives) { const s = document.createElement('span'); s.textContent = `${C.PASSIVES[id].icon} ${C.PASSIVES[id].name} ${run.passives[id]}`; $('build').appendChild(s); }
$('pausem').hidden = false; $('resume').focus({ preventScroll: true });
}
function resume() { if (state !== 'paused') return; $('pausem').hidden = true; state = 'play'; acc = 0; cv.focus({ preventScroll: true }); }
$('pause').onclick = () => (state === 'play' ? pauseGame() : resume());
$('resume').onclick = resume;
$('endrun').onclick = () => { if (state === 'paused') { $('pausem').hidden = true; state = 'play'; endRun(false); } };
function retry() { const o = lastStart; startRun(o.mode === 'endless' && !pass.isPro() ? 'standard' : o.mode, { n: o.n, danger: o.danger, seed: o.seed, target: o.target, link: o.link }); }
$('retry').onclick = retry;
$('tomenu').onclick = () => showMenu();
function showMenu() {
hideAll(); state = 'menu'; musicOn = false; $('pause').hidden = true;
resetPools(); run.time = 0; run.hp = run.maxhp;
renderMenu(); $('menu').hidden = false;
}
function menuNight() { // the night the Play button starts
const pro = pass.isPro(), n = save.night;
return L.access(n, save.nights, pro) === 'open' || (LINK && LINK.lvl === n) ? n : L.nextNight(save.nights, pro);
}
function renderMenu() {
const modes = $('modes'); modes.innerHTML = '';
const M = [['nights', '๐ Nights'], ['daily', `Daily #${DAILY.num}`], ['standard', '10-min run'], ['endless', 'Endless'], ['trials', `โ Trials ๐${L.crowns(save.trials)}`]];
for (const [id, label] of M) {
const b = document.createElement('button'); b.type = 'button'; b.className = 'chip'; b.setAttribute('aria-pressed', String(save.mode === id));
b.innerHTML = `${label}${id === 'endless' && !pass.isPro() ? ' ๐ Pass' : id === 'trials' && !trialFree() ? ' ๐' : ''}`;
b.onclick = () => { sfx('ui'); if (id === 'endless' && !pass.isPro()) { pass.open('endless'); return; } if (id !== save.mode) LINK = null; save.mode = id; persist(); renderMenu(); };
modes.appendChild(b);
}
const line = $('modline'), n = menuNight(), N = L.NIGHTS[n - 1];
if (save.mode === 'trials') {
const tn = L.nextTrial(save.nights, save.trials), d = tn ? L.nextDanger(save.nights, save.trials, tn) : 0, D = L.DANGER[d];
line.textContent = tn ? `Trial: night ${tn} (${L.NIGHTS[tn - 1].name}) at ${D.name}: gloom ร${D.hp} toughness, ร${D.rate} spawns${D.mods.length ? `, ${D.mods.map((m) => (m === 'fog' ? 'fog' : 'fast moths')).join(' + ')}` : ''}, ร${D.embers} Embers ยท ๐ ${L.crowns(save.trials)}/${L.MAX_CROWNS} crowns ยท pick any cleared night on the map${pass.isPro() ? '' : ' ยท 1 free trial a day'}`
: 'Trials replay nights you have cleared at Danger 1-3. Clear night 1 first.';
$('play').textContent = tn ? `โ Play trial: night ${tn}, ${D.name}` : 'โถ Play night 1';
} else if (save.mode === 'nights') {
const st = save.nights.stars[n] || 0, g = L.groupOf(n);
line.textContent = `Night ${n}${N.challenge ? ' (challenge)' : ''}: ${N.name} ยท ${C.fmtTime(N.dur)} ยท ${g.icon} ${g.twist}${st ? ` ยท ${'โ
'.repeat(st)}${'โ'.repeat(3 - st)}` : ''}`;
$('play').textContent = `โถ Play night ${n}`;
} else {
$('play').textContent = 'โถ Play';
if (save.mode === 'daily') line.textContent = LINK && LINK.seed != null && LINK.seed !== DAILY.seed ? `Seed ${LINK.seed}: ${C.seeded(LINK.seed).mod.name} ยท 5:00` : `Today: ${DAILY.mod.name} (${DAILY.mod.desc}) ยท start with ${C.WEAPONS[DAILY.weapon].name} ยท 5:00 ยท best ${save.daily.best}`;
else if (save.mode === 'endless') line.textContent = 'No dawn. The dark only grows stronger. How long can your light last?';
else line.textContent = 'Survive until dawn at 10:00. The Gloam Warden rises at 8:00.';
}
const lc = $('linkcard');
lc.hidden = !LINK;
if (LINK) {
const a = LINK.lvl ? L.access(LINK.lvl, save.nights, pass.isPro()) : 'open', why = a === 'pass' ? ' ยท ๐ Fun Pass night' : a === 'locked' && LINK.lvl > L.FREE_NIGHTS ? ` ยท ๐ clear night ${LINK.lvl - 1} first` : '';
$('link-txt').textContent = `โ A friend's challenge: ${LINK.lvl ? `Night ${LINK.lvl}` : LINK.seed === DAILY.seed ? `Daily #${DAILY.num}` : `Seed ${LINK.seed}`}${LINK.score != null ? ` ยท Beat ${LINK.score.toLocaleString()}` : ''}${why}`;
}
$('starcount').textContent = `${L.totalStars(save.nights)}/${L.MAX_STARS}`;
const strk = L.liveStreak(save.streak, TODAY);
$('streak').textContent = strk ? `๐ฏ๏ธ ${strk}-day streak` : '';
const wl = $('wisps'); wl.innerHTML = '';
for (const w of C.WISPS) {
const ok = C.wispUnlocked(save, w), b = document.createElement('button');
b.type = 'button'; b.className = ok ? '' : 'locked'; b.setAttribute('aria-pressed', String(save.wisp === w.id));
b.innerHTML = `${C.WEAPONS[w.weapon].icon}${w.name}`; b.title = ok ? `${C.WEAPONS[w.weapon].name} ยท ${w.perk}` : `Locked: ${w.hint}`;
b.onclick = () => { sfx('ui'); if (!ok) { toast(`๐ ${w.name}: ${w.hint}`); return; } save.wisp = w.id; persist(); renderMenu(); toast(`${w.name}: ${C.WEAPONS[w.weapon].name} ยท ${w.perk}`, 1600); };
wl.appendChild(b);
}
const choice = C.metaBonus(save.up).choice;
$('wpnrow').hidden = !choice;
if (choice) {
const el = $('weapons'); el.innerHTML = '';
for (const id of ['', ...startWeapons()]) {
const b = document.createElement('button'); b.type = 'button'; b.setAttribute('aria-pressed', String(save.weapon === id));
b.innerHTML = id ? `${C.WEAPONS[id].icon}${C.WEAPONS[id].name.split(' ')[0]}` : 'โงWisp\'s own';
b.onclick = () => { save.weapon = id; persist(); renderMenu(); };
el.appendChild(b);
}
}
const sk = $('skins'); sk.innerHTML = '';
for (const s of C.SKINS) {
const lock = s.pass && !pass.isPro(), b = document.createElement('button');
b.type = 'button'; b.className = lock ? 'passlock' : ''; b.setAttribute('aria-pressed', String(save.skin === s.id));
b.innerHTML = `${s.name}`;
b.onclick = () => { sfx('ui'); if (lock) { pass.open('skin'); return; } save.skin = s.id; persist(); renderMenu(); makeWispSprite(); };
sk.appendChild(b);
}
$('embers').textContent = save.embers; $('embers2').textContent = save.embers;
$('mouse-btn').textContent = `Mouse steer: ${save.mouse ? 'on' : 'off'}`; $('mouse-btn').hidden = TOUCH;
const S = save.stats;
$('stats').textContent = S.runs ? `Runs ${S.runs} ยท best ${C.fmtTime(S.bestTime)} ยท best level ${S.bestLevel} ยท gloom banished ${S.kills.toLocaleString()}${S.wins ? ` ยท dawns ${S.wins}` : ''}` : '';
$('pass-btn').hidden = pass.isPro();
}
function playFromMenu() {
if (LINK && (save.mode === 'nights' ? LINK.lvl === menuNight() : save.mode === 'daily' && !LINK.lvl)) startRun(save.mode, { n: LINK.lvl || 0, seed: LINK.seed, target: LINK.score, link: true });
else if (save.mode === 'trials' && !L.nextTrial(save.nights, save.trials)) startRun('nights', { n: 1 });
else startRun(save.mode, { n: save.mode === 'nights' ? menuNight() : 0 });
}
$('play').onclick = playFromMenu;
$('link-x').onclick = () => { LINK = null; renderMenu(); };
$('map-btn').onclick = () => { sfx('ui'); showMap(); };
$('map-back').onclick = () => showMenu();
function showMap() {
hideAll(); state = 'menu'; musicOn = false; $('pause').hidden = true;
renderMap(); $('map').hidden = false;
const cur = $('maplist').querySelector('.cur'); if (cur) cur.scrollIntoView({ block: 'center' });
}
function renderMap() {
const pro = pass.isPro(), P = save.nights, list = $('maplist'), cur = menuNight();
$('map-sum').textContent = `โ
${L.totalStars(P)} of ${L.MAX_STARS} ยท nights 1-${L.FREE_NIGHTS} free ยท ${L.FREE_NIGHTS + 1}-${L.NIGHTS.length} with the Fun Pass ยท every 10th night is a challenge`;
list.innerHTML = '';
L.GROUPS.forEach((g, gi) => {
const to = (L.GROUPS[gi + 1] ? L.GROUPS[gi + 1].from : L.NIGHTS.length + 1) - 1;
const box = document.createElement('div'); box.className = 'mgroup';
const h = document.createElement('h3'); h.textContent = `${g.icon} ${g.name}`; const sm = document.createElement('small'); sm.textContent = `${g.from}-${to} ยท ${g.twist}`; h.appendChild(sm); box.appendChild(h);
const row = document.createElement('div'); row.className = 'mrowN';
for (let n = g.from; n <= to; n++) {
const N = L.NIGHTS[n - 1], a = L.access(n, P, pro), st = P.stars[n] || 0, b = document.createElement('button');
b.type = 'button'; b.className = `node${N.challenge ? ' ch' : ''}${a !== 'open' ? ` ${a}` : ''}${n === cur ? ' cur' : ''}`;
b.dataset.n = n;
b.setAttribute('aria-label', `Night ${n}: ${N.name}${N.challenge ? ', challenge' : ''}, ${a === 'open' ? `${st} of 3 stars` : a === 'pass' ? 'needs the Fun Pass' : 'locked'}`);
const cr = save.trials[n] || 0;
b.innerHTML = `${N.challenge ? 'โ' : ''}${n}${a === 'pass' ? '๐ Fun Pass' : a === 'locked' ? '๐' : `${'โ
'.repeat(st)}${'โ
'.repeat(3 - st)}`}${cr ? `${'๐'.repeat(cr)}` : ''}`;
b.onclick = () => {
sfx('ui');
if (a === 'pass') { pass.open(`map-night-${n}`); return; }
if (a === 'locked') { toast(`๐ Clear night ${n - 1} first`); return; }
if (save.mode === 'trials' && st) { startRun('trials', { n }); return; }
if (LINK && LINK.lvl !== n) LINK = null;
save.mode = 'nights'; save.night = n; persist(); startRun('nights', { n, ...(LINK && LINK.lvl === n ? { seed: LINK.seed, target: LINK.score, link: true } : {}) });
};
row.appendChild(b);
}
box.appendChild(row); list.appendChild(box);
});
}
$('mouse-btn').onclick = () => { save.mouse = !save.mouse; persist(); renderMenu(); };
$('pass-btn').onclick = () => pass.open('menu');
$('shop-btn').onclick = () => { sfx('ui'); renderShop(); $('menu').hidden = true; $('shop').hidden = false; };
$('shop-back').onclick = () => { $('shop').hidden = true; renderMenu(); $('menu').hidden = false; };
function renderShop() {
$('embers2').textContent = save.embers;
const l = $('shoplist'); l.innerHTML = '';
for (const s of C.SHOP) {
const lv = save.up[s.id] || 0, cost = C.shopCost(s.id, lv), row = document.createElement('div');
row.className = 'srow';
row.innerHTML = ` `;
row.querySelector('.ic').textContent = s.icon; row.querySelector('b').textContent = s.name; row.querySelector('.tx span').textContent = s.desc;
row.querySelector('.pips').textContent = 'โ'.repeat(lv) + 'โ'.repeat(s.max - lv);
const b = document.createElement('button'); b.type = 'button'; b.className = 'btn sm';
b.textContent = cost === Infinity ? 'Max' : `๐ฅ ${cost}`; b.disabled = cost === Infinity || save.embers < cost;
if (b.disabled) b.style.opacity = '.5';
b.onclick = () => { if (C.buy(save, s.id)) { persist(); sfx('reward'); renderShop(); count(GAME, 'shop', s.id); } };
row.appendChild(b); l.appendChild(row);
}
}
// ------------------------------------------------------------------ end of run + share
let last = null;
function endRun(won) {
if (state === 'over') return;
const t = run.time / 60, N = run.night;
const r = { mode: run.mode, time: t, kills: run.kills, shards: Math.round(run.shards), level: run.level, won, boss: run.bossDone, wisp: run.wisp.name, skin: save.skin, score: C.dailyScore(t, run.kills, Math.round(run.shards)),
n: N ? N.n : 0, dur: N ? N.dur : goalTime(), hpFrac: won ? run.hp / run.maxhp : 0, stars: 0, seed: run.seed, target: run.target, daily: run.dcfg === DAILY, dnum: run.dcfg ? run.dcfg.num : 0, mod: run.mod ? run.mod.name : '' };
if (N) r.stars = L.starsFor(N, r);
r.danger = N && N.danger ? N.danger : 0;
r.embers = Math.floor(C.embersFor(r) * (r.danger ? L.DANGER[r.danger].embers : 1)) + bonusEmbers; bonusEmbers = 0;
let crown = false;
if (r.danger && won && !run.god && (save.trials[N.n] || 0) < r.danger) { save.trials[N.n] = r.danger; crown = true; count(GAME, 'level_clear', `trial-${N.n}-${r.danger}`); }
last = r;
let rec = null;
if (!run.god) {
save.embers += r.embers;
const S = save.stats; S.runs++; S.kills += r.kills; S.bestTime = Math.max(S.bestTime, Math.floor(t)); S.bestLevel = Math.max(S.bestLevel, r.level); if (won && r.mode === 'standard') S.wins++;
if (r.daily) save.daily.best = Math.max(save.daily.best, r.score);
if (N) {
rec = L.recordNight(save.nights, N.n, r.stars);
if (won) { count(GAME, 'level_clear', `night-${N.n}`); if (N.n < L.NIGHTS.length && L.access(N.n + 1, save.nights, pass.isPro()) === 'open') save.night = N.n + 1; }
}
L.bumpStreak(save.streak, TODAY);
}
const got = run.god ? [] : C.checkUnlocks(save, r);
persist();
state = 'over'; musicOn = false; joy.on = false; $('pause').hidden = true;
$('over-title').textContent = r.danger ? (won ? `${crown ? '๐ Crown! ' : ''}Night ${N.n} cleared at ${N.dangerName}!` : `Trial lost: night ${N.n} at ${N.dangerName}`) : N ? (won ? `Night ${N.n} cleared!` : `Night ${N.n}: your lantern went out`) : won ? (r.mode === 'daily' ? (r.dnum ? `Daily #${r.dnum} complete!` : 'Seed night survived!') : 'Dawn reached!') : 'Your lantern went out';
$('over-line').textContent = `${C.fmtTime(t)} survived ยท ${r.kills.toLocaleString()} gloom banished ยท level ${r.level} ยท score ${r.score.toLocaleString()}`;
// stars (nights only): pop in one by one with a sound each
const se = $('over-stars');
se.hidden = !N; se.innerHTML = '';
if (N) {
const goals = L.starGoals(N);
for (let k = 0; k < 3; k++) { const b = document.createElement('span'); b.className = `star${k < r.stars ? ' on' : ''}`; b.style.animationDelay = `${0.15 + k * 0.28}s`; b.textContent = 'โ
'; b.title = goals[k]; se.appendChild(b); }
for (let k = 0; k < 3; k++) setTimeout(() => sfx(k < r.stars ? 'star' : 'nostar'), 150 + k * 280);
const sg = document.createElement('small'); sg.textContent = goals.map((g, k) => `${k < r.stars ? 'โ
' : 'โ'} ${g}`).join(' ยท '); se.appendChild(sg);
}
const tl = $('over-target');
tl.hidden = r.target == null;
if (r.target != null) tl.textContent = r.score > r.target ? `You beat ${r.target.toLocaleString()}! ๐ Send it back.` : `${(r.target - r.score + 1).toLocaleString()} more to beat ${r.target.toLocaleString()}. Again?`;
$('over-grid').textContent = grid(r);
const unlockTxt = got.map((u) => C.WISPS.find((w) => w.unlock === u)).filter(Boolean).map((w) => ` ยท New wisp: ${w.name}!`).join('');
$('over-embers').textContent = `+${r.embers} Embers ๐ฅ (total ${save.embers})${rec && rec.gained ? ` ยท +${rec.gained}โ
new` : ''}${unlockTxt}`;
const sk = L.liveStreak(save.streak, TODAY);
$('over-streak').textContent = sk ? `๐ฏ๏ธ ${sk}-day streak${save.streak.best > sk ? ` ยท best ${save.streak.best}` : ''}` : '';
// next night / map buttons
const nb = $('next'), mb = $('tomap');
nb.hidden = !(N && won && N.n < L.NIGHTS.length) || !!r.danger; mb.hidden = !N;
if (!nb.hidden) {
const a = L.access(N.n + 1, save.nights, pass.isPro());
nb.textContent = a === 'pass' ? `Night ${N.n + 1} ๐ Fun Pass` : `โถ Night ${N.n + 1}`;
nb.className = a === 'pass' ? 'btn pass sm' : 'btn big';
}
$('retry').className = N && won ? 'btn ghost sm' : 'btn big';
const txt = shareText(r), I = intents(GAME, txt, sharePath(r));
$('sx').href = I.x; $('sb').href = I.bsky; $('sw').href = I.whatsapp;
$('over').hidden = false;
pass.afterWin($('over').querySelector('.menu-in'), won ? 'win' : 'over');
install.offer();
count(GAME, won ? 'win' : 'over', r.mode);
setTimeout(() => (nb.hidden ? $('retry') : nb).focus({ preventScroll: true }), 40);
}
$('next').onclick = () => { if (!last || !last.n) return; const n = last.n + 1; if (L.access(n, save.nights, pass.isPro()) === 'pass') { pass.open(`next-night-${n}`); return; } startRun('nights', { n }); };
$('tomap').onclick = () => showMap();
function celebrate() { // a burst of light from the wisp and a small shake (shake is skipped for reduced motion)
for (let k = 0; k < 5; k++) particle(run.px + (Math.random() - 0.5) * 160, run.py + (Math.random() - 0.5) * 120, [0, 1, 3, 5, 8][k], 22, 260, 1.1, 4);
ring(run.px, run.py, 220, 1); run.shake = Math.max(run.shake, 8);
}
/** Path (with ?seed=&score=&lvl=) that reopens the same night or seed with "Beat ". */
function sharePath(r) {
if (r.n) return PATH + L.linkQuery({ lvl: r.n, seed: r.seed === L.nightSeed(r.n) ? null : r.seed, score: r.score });
if (r.mode === 'daily') return PATH + L.linkQuery({ seed: r.seed, score: r.score });
return PATH;
}
function grid(r) {
const cells = r.mode === 'daily' ? 5 : r.mode === 'endless' ? Math.min(15, Math.max(10, Math.ceil(r.time / 60))) : 10;
const seg = r.mode === 'endless' ? 60 : r.dur / cells, bossCell = r.mode === 'standard' ? 7 : r.n && L.NIGHTS[r.n - 1].boss ? Math.floor(L.NIGHTS[r.n - 1].boss.at / seg) : -1;
let s = '';
for (let m = 0; m < cells; m++) s += r.time >= (m + 1) * seg ? (m === bossCell ? '๐ฅ' : '๐จ') : r.time > m * seg ? '๐ง' : 'โฌ';
return s + (r.won ? '๐
' : '๐ฏ๏ธ');
}
function shareText(r) {
const stars = r.n ? ` ${'โ
'.repeat(r.stars)}${'โ'.repeat(3 - r.stars)}` : '';
const head = r.danger ? `Wispmarch Trial ยท Night ${r.n} at Danger ${r.danger}${r.won ? ' ๐' : ''} ๐ฎ` : r.n ? `Wispmarch Night ${r.n}${stars} ๐ฎ` : r.mode === 'daily' ? (r.dnum ? `Wispmarch Daily #${r.dnum} ๐ฎ` : `Wispmarch Seed ${r.seed} ๐ฎ`) : r.mode === 'endless' ? `Wispmarch Endless Night ๐ ${C.fmtTime(r.time)}` : `Wispmarch ๐ฎ ${r.won ? 'Reached dawn!' : `Lasted ${C.fmtTime(r.time)}`}`;
const mod = r.mode === 'daily' ? `${r.mod} ยท ` : r.n ? `${L.NIGHTS[r.n - 1].name} ยท ` : '';
const sk = L.liveStreak(save.streak, TODAY);
const beat = r.n || r.mode === 'daily' ? `\nBeat my ${r.score.toLocaleString()}:` : '';
return `${head}\n${mod}โฑ ${C.fmtTime(r.time)} ยท ๐ ${r.kills.toLocaleString()} ยท โจ Lv ${r.level} ยท Score ${r.score.toLocaleString()}\n${grid(r)}${sk > 1 ? `\n๐ฏ๏ธ ${sk}-day streak` : ''}${beat}`;
}
function cardCanvas(r) {
const c = document.createElement('canvas'); c.width = c.height = 1080; const g = c.getContext('2d');
const bgG = g.createRadialGradient(540, 470, 40, 540, 470, 700); bgG.addColorStop(0, '#3A2F6E'); bgG.addColorStop(1, '#120F24');
g.fillStyle = bgG; g.fillRect(0, 0, 1080, 1080);
const S = C.SKINS.find((s) => s.id === r.skin) || C.SKINS[0];
const glow = g.createRadialGradient(540, 420, 10, 540, 420, 220); glow.addColorStop(0, S.core); glow.addColorStop(0.25, S.glow); glow.addColorStop(1, 'rgba(0,0,0,0)');
g.fillStyle = glow; g.fillRect(0, 0, 1080, 1080);
g.fillStyle = '#fff'; g.beginPath(); g.arc(540, 420, 42, 0, TAU); g.fill();
g.textAlign = 'center'; g.fillStyle = '#FFE9A8'; g.font = '900 96px system-ui,sans-serif'; g.fillText('Wispmarch', 540, 160);
g.fillStyle = '#BDB4D9'; g.font = '700 38px system-ui,sans-serif';
g.fillText(r.n ? `Night ${r.n} ยท ${L.NIGHTS[r.n - 1].name}` : r.mode === 'daily' ? (r.dnum ? `Daily #${r.dnum} ยท ${r.mod}` : `Seed ${r.seed} ยท ${r.mod}`) : r.mode === 'endless' ? 'Endless Night' : 'Standard run', 540, 222);
if (r.n) { g.font = '900 110px system-ui,sans-serif'; for (let k = 0; k < 3; k++) { g.fillStyle = k < r.stars ? '#FFC857' : 'rgba(255,255,255,.18)'; g.fillText('โ
', 540 + (k - 1) * 120, 330); } }
g.fillStyle = '#fff'; g.font = '900 84px system-ui,sans-serif';
g.fillText(r.won ? (r.n ? 'Night cleared!' : r.mode === 'daily' ? 'Night survived!' : 'Dawn reached!') : `Lasted ${C.fmtTime(r.time)}`, 540, 650);
g.font = '700 46px system-ui,sans-serif'; g.fillStyle = '#FFC857';
g.fillText(`โฑ ${C.fmtTime(r.time)} ๐ ${r.kills.toLocaleString()} โจ Lv ${r.level}`, 540, 740);
g.fillStyle = '#fff'; g.font = '800 54px system-ui,sans-serif'; g.fillText(`Score ${r.score.toLocaleString()}`, 540, 820);
g.font = '60px system-ui,sans-serif'; g.fillText(grid(r), 540, 915);
g.fillStyle = '#8F86B3'; g.font = '700 32px system-ui,sans-serif'; g.fillText('cybermaxtools.com/games/wispmarch ยท CyberMax', 540, 1030);
return c;
}
$('share').onclick = async () => { if (!last) return; const blob = await canvasBlob(cardCanvas(last)); await share(GAME, shareText(last), sharePath(last), blob, `wispmarch-${last.n ? `night-${last.n}` : last.mode}.png`); };
$('card').onclick = async () => { if (!last) return; download(await canvasBlob(cardCanvas(last)), `wispmarch-${last.mode}.png`); count(GAME, 'share', 'card'); };
for (const id of ['sx', 'sb', 'sw']) $(id).addEventListener('click', () => count(GAME, 'share', id));
// ------------------------------------------------------------------ rendering
let darkGrad = null;
const view = { cw: 800, ch: 600, dpr: 1, k: 1, w: 800, h: 600 };
const cam = { x: 0, y: 0 };
function resize() {
const b = stageEl.getBoundingClientRect();
view.dpr = Math.min(2, devicePixelRatio || 1);
view.cw = Math.max(200, b.width); view.ch = Math.max(200, b.height);
cv.width = Math.round(view.cw * view.dpr); cv.height = Math.round(view.ch * view.dpr);
const s = Math.sqrt(view.cw * view.ch) / 820;
view.k = Math.max(0.55, Math.min(1.25, s));
view.w = view.cw / view.k; view.h = view.ch / view.k;
darkGrad = null;
}
new ResizeObserver(resize).observe(stageEl);
resize();
function sprite(size, draw) { const c = document.createElement('canvas'); c.width = c.height = size; const g = c.getContext('2d'); g.translate(size / 2, size / 2); draw(g, size / 2); return c; }
function flashOf(src) { const c = document.createElement('canvas'); c.width = src.width; c.height = src.height; const g = c.getContext('2d'); g.drawImage(src, 0, 0); g.globalCompositeOperation = 'source-in'; g.fillStyle = '#fff'; g.fillRect(0, 0, c.width, c.height); return c; }
const SPR = [], SPRW = [], EYES = [];
function blob(g, r, col, wob = 0) { g.fillStyle = col; g.beginPath(); for (let k = 0; k <= 16; k++) { const a = (k / 16) * TAU, rr = r * (1 + Math.sin(a * 5) * wob); g.lineTo(Math.cos(a) * rr, Math.sin(a) * rr); } g.fill(); }
SPR[0] = sprite(48, (g) => { g.fillStyle = '#6B5FA8'; for (const s of [-1, 1]) { g.beginPath(); g.ellipse(s * 10, -2, 11, 8, s * 0.5, 0, TAU); g.fill(); } g.fillStyle = '#4A3F7E'; g.beginPath(); g.ellipse(0, 2, 5, 9, 0, 0, TAU); g.fill(); g.fillStyle = '#8D80C9'; for (const s of [-1, 1]) { g.beginPath(); g.ellipse(s * 7, 6, 6, 4, s * -0.4, 0, TAU); g.fill(); } });
SPR[1] = sprite(64, (g) => { g.strokeStyle = '#1F3B2C'; g.lineWidth = 3; for (let k = 0; k < 6; k++) { const a = (k / 6) * TAU + 0.3; g.beginPath(); g.moveTo(0, 0); g.lineTo(Math.cos(a) * 19, Math.sin(a) * 19); g.stroke(); } blob(g, 14, '#2F5A43', 0.08); blob(g, 10, '#3D7357', 0.05); });
SPR[2] = sprite(64, (g) => { g.fillStyle = '#4B2E78'; g.beginPath(); g.moveTo(0, -18); g.quadraticCurveTo(16, -14, 14, 6); g.lineTo(16, 18); g.lineTo(8, 12); g.lineTo(0, 19); g.lineTo(-8, 12); g.lineTo(-16, 18); g.lineTo(-14, 6); g.quadraticCurveTo(-16, -14, 0, -18); g.fill(); g.fillStyle = '#1A0F33'; g.beginPath(); g.ellipse(0, -4, 9, 8, 0, 0, TAU); g.fill(); });
SPR[3] = sprite(96, (g) => { g.fillStyle = '#5A1E2E'; for (const s of [-1, 1]) { g.beginPath(); g.moveTo(s * 14, -20); g.lineTo(s * 26, -38); g.lineTo(s * 22, -16); g.fill(); } blob(g, 28, '#3A1626', 0.07); blob(g, 22, '#5A2338', 0.05); });
SPR[4] = sprite(160, (g) => { const gr = g.createRadialGradient(0, 0, 10, 0, 0, 60); gr.addColorStop(0, '#2A1B4F'); gr.addColorStop(1, '#0B0718'); blob(g, 50, '#0B0718', 0.09); g.fillStyle = gr; g.beginPath(); g.arc(0, 0, 44, 0, TAU); g.fill(); g.fillStyle = '#3D2A6E'; for (let k = 0; k < 7; k++) { const a = -Math.PI / 2 + (k - 3) * 0.32; g.beginPath(); g.moveTo(Math.cos(a) * 40, Math.sin(a) * 40); g.lineTo(Math.cos(a) * 66, Math.sin(a) * 66); g.lineTo(Math.cos(a + 0.12) * 42, Math.sin(a + 0.12) * 42); g.fill(); } });
for (let t = 0; t < 5; t++) SPRW[t] = flashOf(SPR[t]);
const EYECOL = ['#E8DFFF', '#C6FF7A', '#B98CFF', '#FF4B4B', '#FF3D7F'];
for (let t = 0; t < 5; t++) {
const r = ET[t].r, s = r * 4;
EYES[t] = sprite(Math.ceil(s), (g) => {
const e = Math.max(1.6, r * 0.16), off = r * 0.36;
for (const sgn of [-1, 1]) { const x = sgn * off, y = t === 1 ? -r * 0.1 : -r * 0.25; const gl = g.createRadialGradient(x, y, 0, x, y, e * 3.2); gl.addColorStop(0, EYECOL[t]); gl.addColorStop(0.35, EYECOL[t] + '88'); gl.addColorStop(1, EYECOL[t] + '00'); g.fillStyle = gl; g.fillRect(x - e * 4, y - e * 4, e * 8, e * 8); }
if (t === 4) for (let k = 0; k < 3; k++) { const x = (k - 1) * r * 0.3, y = r * 0.15; g.fillStyle = EYECOL[t]; g.beginPath(); g.arc(x, y, e * 0.6, 0, TAU); g.fill(); }
});
}
const glowSpr = (col, r) => sprite(r * 2, (g) => { const gr = g.createRadialGradient(0, 0, 0, 0, 0, r); gr.addColorStop(0, '#FFFFFF'); gr.addColorStop(0.18, col); gr.addColorStop(1, col + '00'); g.fillStyle = gr; g.fillRect(-r, -r, 2 * r, 2 * r); });
const BOLT = glowSpr('#FFD86B', 16), BOLTB = glowSpr('#FF9A3D', 24), FLY = glowSpr('#C8FF6B', 18), EMBER = glowSpr('#FF7A2E', 32);
const GEM = [glowSpr('#8FD3FF', 10), glowSpr('#6FE3C1', 12), glowSpr('#FFC857', 14), glowSpr('#FF6AD5', 16)];
const HEART = sprite(40, (g) => { g.fillStyle = '#FF5E7A'; g.beginPath(); g.moveTo(0, 10); g.bezierCurveTo(-16, -2, -8, -14, 0, -6); g.bezierCurveTo(8, -14, 16, -2, 0, 10); g.fill(); });
const MAGNET = sprite(40, (g) => { g.strokeStyle = '#7DA8FF'; g.lineWidth = 6; g.beginPath(); g.arc(0, 0, 9, Math.PI, 0); g.lineTo(9, 9); g.moveTo(-9, 0); g.lineTo(-9, 9); g.stroke(); });
const CHEST = sprite(56, (g) => { g.fillStyle = '#7A4A1E'; g.fillRect(-16, -10, 32, 22); g.fillStyle = '#A8682A'; g.fillRect(-16, -14, 32, 9); g.fillStyle = '#FFC857'; g.fillRect(-3, -8, 6, 8); });
let WISP = null, WISPGLOW = null, skinCol = C.SKINS[0];
function makeWispSprite() {
skinCol = C.SKINS.find((s) => s.id === save.skin) || C.SKINS[0];
if (skinCol.pass && !pass.isPro()) skinCol = C.SKINS[0];
WISPGLOW = glowSpr(skinCol.glow, 60);
WISP = sprite(40, (g) => { const gr = g.createRadialGradient(-3, -4, 1, 0, 0, 13); gr.addColorStop(0, '#FFFFFF'); gr.addColorStop(0.5, skinCol.core); gr.addColorStop(1, skinCol.glow); g.fillStyle = gr; g.beginPath(); g.moveTo(0, -17); g.quadraticCurveTo(12, -4, 11, 4); g.arc(0, 4, 11, 0, Math.PI); g.quadraticCurveTo(-12, -4, 0, -17); g.fill(); g.fillStyle = '#120F24'; g.beginPath(); g.ellipse(-4, 2, 1.8, 2.6, 0, 0, TAU); g.ellipse(4, 2, 1.8, 2.6, 0, 0, TAU); g.fill(); });
}
makeWispSprite();
// marsh ground tile (seeded so it looks the same every load)
const TILE = 512;
const ground = (() => {
const c = document.createElement('canvas'); c.width = c.height = TILE; const g = c.getContext('2d'), R = rng(7);
g.fillStyle = '#1B2236'; g.fillRect(0, 0, TILE, TILE);
const wrap = (fn) => { for (const ox of [-TILE, 0, TILE]) for (const oy of [-TILE, 0, TILE]) { g.save(); g.translate(ox, oy); fn(); g.restore(); } };
for (let k = 0; k < 9; k++) { const x = R() * TILE, y = R() * TILE, rx = 30 + R() * 70, ry = 18 + R() * 40; wrap(() => { g.fillStyle = '#16304A'; g.beginPath(); g.ellipse(x, y, rx, ry, R() * 3, 0, TAU); g.fill(); g.strokeStyle = 'rgba(140,190,255,.12)'; g.lineWidth = 2; g.beginPath(); g.ellipse(x, y, rx * 0.7, ry * 0.5, 0.2, 0, TAU); g.stroke(); }); }
for (let k = 0; k < 30; k++) { const x = R() * TILE, y = R() * TILE, r = 10 + R() * 26; wrap(() => { g.fillStyle = R() < 0.5 ? '#223A2E' : '#26283F'; g.beginPath(); g.arc(x, y, r, 0, TAU); g.fill(); }); }
for (let k = 0; k < 14; k++) { const x = R() * TILE, y = R() * TILE; wrap(() => { g.fillStyle = '#2C5A3E'; g.beginPath(); g.arc(x, y, 7, 0.4, TAU - 0.2); g.lineTo(x, y); g.fill(); }); }
g.lineCap = 'round';
for (let k = 0; k < 60; k++) { const x = R() * TILE, y = R() * TILE, h = 10 + R() * 18, lean = (R() - 0.5) * 8; wrap(() => { g.strokeStyle = R() < 0.5 ? '#3B6B4A' : '#4E7E50'; g.lineWidth = 2; g.beginPath(); g.moveTo(x, y); g.quadraticCurveTo(x + lean * 0.3, y - h * 0.5, x + lean, y - h); g.stroke(); }); }
for (let k = 0; k < 40; k++) { const x = R() * TILE, y = R() * TILE; g.fillStyle = 'rgba(200,220,255,.08)'; g.fillRect(x, y, 2, 2); }
return c;
})();
const DR = 500;
function getDark() {
if (darkGrad) return darkGrad;
darkGrad = ctx.createRadialGradient(0, 0, DR * 0.32, 0, 0, DR);
darkGrad.addColorStop(0, 'rgba(9,6,22,0)'); darkGrad.addColorStop(0.45, 'rgba(9,6,22,0.38)'); darkGrad.addColorStop(1, 'rgba(9,6,22,0.9)');
return darkGrad;
}
let lastNow = performance.now(), fpsN = 0, fpsT = 0, fps = 60;
function frame(now) {
if (!CAP) requestAnimationFrame(frame);
let dt = (now - lastNow) / 1000; lastNow = now;
if (dt > 0.25) dt = 0.25;
fpsN++; fpsT += dt; if (fpsT >= 1) { fps = fpsN / fpsT; fpsN = 0; fpsT = 0; }
if (state === 'play') {
acc += dt;
let n = 0;
while (acc >= STEP && n < 5) { tick(); acc -= STEP; n++; if (state !== 'play') break; }
if (n === 5) acc = 0;
alpha = state === 'play' ? acc / STEP : 1;
} else alpha = 1;
if (state === 'chest' && run.chest) {
run.chest.t += dt;
if (run.chest.t >= run.chest.dur + 1.1) { banner(run.chest.icons.map((i) => i.name).join(' ยท ')); run.chest = null; state = 'play'; acc = 0; sfx('reward'); }
}
if (run.bannerT > 0) run.bannerT -= dt;
if (run.promptT > 0 && state === 'play' && (run.time > 30 || run.weapons.length)) run.promptT -= dt;
render(dt);
}
function render(dt) {
const { dpr, k, cw, ch } = view, W = cv.width, H = cv.height;
const a = alpha;
const pxI = run.ppx + (run.px - run.ppx) * a, pyI = run.ppy + (run.py - run.ppy) * a;
const f = 1 - Math.exp(-dt * 9);
cam.x += (pxI - cam.x) * f; cam.y += (pyI - cam.y) * f;
if (state === 'menu') { cam.x += dt * 14; run.px = run.ppx = cam.x; run.py = run.ppy = cam.y; }
run.shake *= Math.exp(-dt * 9);
const sh = REDUCED ? 0 : run.shake;
const shx = (Math.random() - 0.5) * sh * 2, shy = (Math.random() - 0.5) * sh * 2;
const K = dpr * k, ox = W / 2 - cam.x * K + shx * dpr, oy = H / 2 - cam.y * K + shy * dpr;
if (R3) { render3d(dt, a, pxI, pyI); return; }
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.globalCompositeOperation = 'source-over'; ctx.globalAlpha = 1;
ctx.fillStyle = '#120F24'; ctx.fillRect(0, 0, W, H);
ctx.setTransform(K, 0, 0, K, ox, oy);
// ground
const vw = view.w / 2 + 40, vh = view.h / 2 + 40;
const x0 = Math.floor((cam.x - vw) / TILE) * TILE, y0 = Math.floor((cam.y - vh) / TILE) * TILE;
for (let y = y0; y < cam.y + vh; y += TILE) for (let x = x0; x < cam.x + vw; x += TILE) ctx.drawImage(ground, x, y, TILE + 0.5, TILE + 0.5);
// pickups on the ground
for (let i = 0; i < nP; i++) { const s = kt[i] === 2 ? CHEST : kt[i] === 0 ? HEART : MAGNET, bob = Math.sin(run.time / 10 + i) * 3; ctx.drawImage(s, kx[i] - s.width / 2, ky[i] - s.height / 2 + bob); }
// enemies
const tt = run.time / 60;
for (let i = 0; i < nE; i++) {
const t = etype[i], x = epx[i] + (ex[i] - epx[i]) * a, y = epy[i] + (ey[i] - epy[i]) * a, s = (eflash[i] ? SPRW : SPR)[t], r = er[i];
const sz = r * (t === 4 ? 3.4 : t === 3 ? 3.6 : t === 0 ? 2.6 : 2.4);
if (t === 2) ctx.globalAlpha = 0.65 + 0.35 * Math.sin(tt * 3 + ephase[i]);
if (t === 0) { const fl = 0.75 + 0.25 * Math.abs(Math.sin(tt * 18 + ephase[i])); ctx.drawImage(s, x - sz / 2 * fl, y - sz / 2, sz * fl, sz); }
else { const sq = 1 + Math.sin(tt * 8 + ephase[i]) * 0.06; ctx.drawImage(s, x - sz / 2 * sq, y - sz / 2 / sq, sz * sq, sz / sq); }
if (t === 2) ctx.globalAlpha = 1;
}
// darkness: the lantern's light
const lr = run.light * (1 + 0.025 * Math.sin(performance.now() / 90)) * (state === 'menu' ? 1.1 : 1);
const psx = (pxI - cam.x) * K + W / 2 + shx * dpr, psy = (pyI - cam.y) * K + H / 2 + shy * dpr, sc = (lr * K) / DR;
ctx.setTransform(sc, 0, 0, sc, psx, psy);
ctx.globalAlpha = run.dawnT ? Math.max(0, run.dawnT / 110) : 1;
ctx.fillStyle = getDark(); ctx.fillRect(-psx / sc, -psy / sc, W / sc, H / sc);
ctx.globalAlpha = 1;
// lights (additive)
ctx.setTransform(K, 0, 0, K, ox, oy);
ctx.globalCompositeOperation = 'lighter';
for (let i = 0; i < nM; i++) { const r = mr[i] * 1.5 * Math.min(1, mlife[i] * 2); ctx.globalAlpha = 0.7; ctx.drawImage(EMBER, mx[i] - r, my[i] - r, r * 2, r * 2); }
ctx.globalAlpha = 1;
for (let i = 0; i < nE; i++) { const t = etype[i], e = EYES[t], x = epx[i] + (ex[i] - epx[i]) * a, y = epy[i] + (ey[i] - epy[i]) * a; ctx.drawImage(e, x - e.width / 2, y - e.height / 2); }
for (let i = 0; i < nG; i++) { const v = gv[i], s = GEM[v >= 25 ? 3 : v >= 10 ? 2 : v >= 3 ? 1 : 0]; ctx.drawImage(s, gx[i] - s.width / 2, gy[i] - s.height / 2); }
for (let i = 0; i < nB; i++) { const s = bbig[i] ? BOLTB : BOLT, x = bpx[i] + (bx[i] - bpx[i]) * a, y = bpy[i] + (by[i] - bpy[i]) * a; ctx.drawImage(s, x - s.width / 2, y - s.height / 2); }
const fw = weaponOf('firefly');
if (fw && state !== 'menu') { const s = fw.st, R = s.radius * run.areaMul, oa = run.orbitA - (1 - a) * STEP; for (let j = 0; j < s.count; j++) { const an = oa * s.spin + (j / s.count) * TAU, x = pxI + Math.cos(an) * R, y = pyI + Math.sin(an) * R; ctx.drawImage(FLY, x - 18, y - 18); } }
// moon strikes
for (let i = 0; i < nS; i++) {
const tl = st[i];
if (tl > 0) { ctx.globalAlpha = 0.35; ctx.strokeStyle = '#BFD4FF'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(sx[i], sy[i], sr[i] * (1 - tl), 0, TAU); ctx.stroke(); }
else { const al = 1 + tl / 0.3; ctx.globalAlpha = al * 0.8; ctx.fillStyle = '#9DB8FF'; ctx.fillRect(sx[i] - sr[i] * 0.35, sy[i] - 900, sr[i] * 0.7, 900); ctx.drawImage(GEM[0], sx[i] - sr[i], sy[i] - sr[i], sr[i] * 2, sr[i] * 2); }
}
ctx.globalAlpha = 1;
// chain arcs
if (nA) {
ctx.strokeStyle = '#B6E3FF'; ctx.lineWidth = 2.5; ctx.beginPath();
for (let i = 0; i < nA; i++) { const dx = ax2[i] - ax1[i], dy = ay2[i] - ay1[i]; ctx.moveTo(ax1[i], ay1[i]); for (let s = 1; s < 4; s++) ctx.lineTo(ax1[i] + dx * s / 4 + (Math.random() - 0.5) * 16, ay1[i] + dy * s / 4 + (Math.random() - 0.5) * 16); ctx.lineTo(ax2[i], ay2[i]); }
ctx.stroke();
}
// rings
for (let i = 0; i < nR; i++) { const l = rlife[i]; if (l <= 0) continue; const r = rmax[i] * (1 - l * l * 0.6); ctx.globalAlpha = Math.max(0, l) * 0.8; ctx.strokeStyle = ['#FFE9A8', '#FFC857', '#BFD4FF'][rcol[i]]; ctx.lineWidth = 6 * l + 1; ctx.beginPath(); ctx.arc(rx[i], ry[i], r, 0, TAU); ctx.stroke(); }
// particles
for (let i = 0; i < nQ; i++) { const l = ql[i] / qm[i]; if (l <= 0) continue; ctx.globalAlpha = l; ctx.fillStyle = PCOL[qc[i]]; const s = qs[i] * (0.5 + l * 0.5); ctx.fillRect(qx[i] - s / 2, qy[i] - s / 2, s, s); }
ctx.globalAlpha = 1;
// the wisp
if (run.dieT === 0 || run.dieT > 50) {
const sp = Math.hypot(run.vx, run.vy) / 150, st2 = 1 + Math.min(0.25, sp * 0.18), bob = Math.sin(performance.now() / 220) * 2;
ctx.globalAlpha = 0.85; ctx.drawImage(WISPGLOW, pxI - 60, pyI - 60 + bob); ctx.globalAlpha = 1;
ctx.globalCompositeOperation = 'source-over';
if (!(run.iframes > 0 && run.iframes % 6 < 3 && !run.god && state === 'play')) {
ctx.save(); ctx.translate(pxI, pyI + bob); ctx.rotate(Math.max(-0.35, Math.min(0.35, run.vx / 500))); ctx.scale(run.face / st2, st2);
ctx.drawImage(WISP, -20, -20); ctx.restore();
}
}
ctx.globalCompositeOperation = 'source-over';
// damage numbers
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
for (let i = 0; i < MAXN; i++) {
if (nl[i] <= 0) continue;
const l = nl[i], pop = l > 0.85 ? 1 + (l - 0.85) * 3 : 1;
ctx.globalAlpha = Math.min(1, l * 2);
ctx.font = `800 ${Math.round((ncrit[i] ? 17 : 12) * pop)}px system-ui,sans-serif`;
ctx.fillStyle = '#120F24'; ctx.fillText(nv[i], nx[i] + 1, ny[i] + 1);
ctx.fillStyle = ncrit[i] ? '#FFC857' : '#FFFFFF'; ctx.fillText(nv[i], nx[i], ny[i]);
}
ctx.globalAlpha = 1;
// player HP bar under the wisp
if (state !== 'menu') { ctx.fillStyle = 'rgba(0,0,0,.5)'; ctx.fillRect(pxI - 18, pyI + 22, 36, 5); ctx.fillStyle = run.hp / run.maxhp < 0.3 ? '#FF5E7A' : '#FFC857'; ctx.fillRect(pxI - 18, pyI + 22, 36 * Math.max(0, run.hp / run.maxhp), 5); }
hud(dt);
}
const POOLS = { get nE() { return nE; }, ex, ey, epx, epy, etype, er, eflash, ephase, get nB() { return nB; }, bx, by, bpx, bpy, bbig,
get nG() { return nG; }, gx, gy, gv, get nP() { return nP; }, kx, ky, kt, get nM() { return nM; }, mx, my, mr, mlife, get nS() { return nS; }, sx, sy, st, sr,
get nR() { return nR; }, rx, ry, rmax, rlife, rcol, get nA() { return nA; }, ax1, ay1, ax2, ay2, get nQ() { return nQ; }, qx, qy, ql, qm, qc, qs, fly: null };
function render3d(dt, a, pxI, pyI) {
const fw = weaponOf('firefly');
POOLS.fly = fw && state !== 'menu' ? { count: fw.st.count, R: fw.st.radius * run.areaMul, spin: fw.st.spin, oa: run.orbitA - (1 - a) * STEP } : null;
R3.frame({ W: POOLS, run, a, dt: CAP ? 1 / 30 : dt, state, skin: skinCol, camX: cam.x, camY: cam.y, viewW: view.w, viewH: view.h, shake: run.shake });
if (R3.st.tooSlow) { drop3d(); return; }
const { dpr, cw, ch } = view;
ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, cv.width, cv.height);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
// damage numbers and the HP bar, placed over the 3D view
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
for (let i = 0; i < MAXN; i++) {
if (nl[i] <= 0) continue;
const l = nl[i], pop = l > 0.85 ? 1 + (l - 0.85) * 3 : 1, [x, y, ok] = R3.project(nx[i], ny[i], 2.5, cw, ch);
if (!ok) continue;
ctx.globalAlpha = Math.min(1, l * 2); ctx.font = `800 ${Math.round((ncrit[i] ? 19 : 14) * pop)}px system-ui,sans-serif`;
ctx.fillStyle = '#120F24'; ctx.fillText(nv[i], x + 1, y + 1); ctx.fillStyle = ncrit[i] ? '#FFC857' : '#FFFFFF'; ctx.fillText(nv[i], x, y);
}
ctx.globalAlpha = 1;
if (state !== 'menu' && (run.dieT === 0 || run.dieT > 50)) { const [x, y] = R3.project(pxI, pyI, 0, cw, ch); ctx.fillStyle = 'rgba(0,0,0,.5)'; ctx.fillRect(x - 20, y + 12, 40, 5); ctx.fillStyle = run.hp / run.maxhp < 0.3 ? '#FF5E7A' : '#FFC857'; ctx.fillRect(x - 20, y + 12, 40 * Math.max(0, run.hp / run.maxhp), 5); }
hud(dt);
}
/** This device can't keep the 3D marsh smooth: carry on in 2D (same run, same rules) for the rest of this visit. */
function drop3d() {
const gc = R3 && R3.st.canvas; R3 = null;
if (gc) gc.remove();
document.documentElement.classList.remove('is3d');
try { sessionStorage.setItem('wispmarch:2d', '1'); } catch { /* private mode */ }
}
/** WebGL2 on a real GPU. Software renderers (SwiftShader, llvmpipe) get the 2D game: 3D there runs at a few frames a
* second. ?3d=1 (tests) or ?cap=1 (trailers) force 3D wherever WebGL2 exists. */
function gpuOk() {
try {
const gl = document.createElement('canvas').getContext('webgl2');
if (!gl) return false;
if (/[?&](3d|cap)=1/.test(QS)) return true;
const ext = gl.getExtension('WEBGL_debug_renderer_info');
const r = ext ? String(gl.getParameter(ext.UNMASKED_RENDERER_WEBGL)) : '';
const lose = gl.getExtension('WEBGL_lose_context'); if (lose) lose.loseContext();
return !/SwiftShader|llvmpipe|softpipe|Software|Basic Render/i.test(r);
} catch { return false; }
}
async function boot3d() {
try {
let slow = false; try { slow = !CAP && sessionStorage.getItem('wispmarch:2d') === '1'; } catch { /* */ }
if (slow || /[?&]2d=1/.test(QS) || !gpuOk()) return;
const [{ MarshScene }, { mountBehind }] = await Promise.all([import('./scene3d.js'), import('./stage3d.js')]);
const glc = mountBehind(cv);
const scene = new MarshScene(glc, { record: CAP, fixedQuality: /[?&](3d|fixedq)=1/.test(QS) });
const fit = () => { const r = cv.getBoundingClientRect(); if (r.width > 1) scene.resize(r.width, r.height); };
fit(); if (window.ResizeObserver) new ResizeObserver(fit).observe(cv);
R3 = scene;
document.documentElement.classList.add('is3d');
requestAnimationFrame(() => glc.classList.add('on'));
} catch (e) { R3 = null; document.documentElement.classList.remove('is3d'); }
}
function hud() {
const { dpr, cw, ch } = view;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
if (run.hurtFlash > 0) { ctx.fillStyle = `rgba(255,40,80,${run.hurtFlash * 0.25})`; ctx.fillRect(0, 0, cw, ch); }
if (run.levelFlash > 0) { ctx.fillStyle = `rgba(255,220,140,${run.levelFlash * 0.18})`; ctx.fillRect(0, 0, cw, ch); }
if (state === 'menu') return;
// xp bar
const need = C.xpNeed(run.level);
ctx.fillStyle = 'rgba(0,0,0,.45)'; ctx.fillRect(0, 0, cw, 8);
const xg = ctx.createLinearGradient(0, 0, cw, 0); xg.addColorStop(0, '#6FE3C1'); xg.addColorStop(1, '#8FD3FF');
ctx.fillStyle = xg; ctx.fillRect(0, 0, cw * Math.min(1, run.xp / need), 8);
ctx.textBaseline = 'top'; ctx.textAlign = 'left';
ctx.font = '800 14px system-ui,sans-serif'; ctx.fillStyle = '#FFE9A8'; ctx.fillText(`Lv ${run.level}`, 12, 16);
ctx.fillStyle = '#E8E2FF'; ctx.fillText(`๐ ${run.kills}`, 12, 36);
ctx.textAlign = 'center';
const t = run.time / 60, goal = goalTime(), N = run.night;
let gy = 42;
if (N) { // the goal line: night, countdown to dawn and the three star goals, lit while you are on track
ctx.font = '800 11px system-ui,sans-serif'; ctx.fillStyle = '#FFC857'; ctx.fillText(`NIGHT ${N.n}${N.challenge ? ' ยท CHALLENGE' : ''}`, cw / 2, 12);
ctx.font = '900 24px system-ui,sans-serif'; ctx.fillStyle = '#FFFFFF'; ctx.fillText(`๐
${C.fmtTime(Math.ceil(goal - t))}`, cw / 2, 26);
const ok = [run.dawnT > 0 || run.won, run.hp / run.maxhp >= 0.5, N.star3 === 'boss' ? run.bossDone : run.kills >= N.kills];
const parts = ['โ
dawn', 'โ
ยฝ light', N.star3 === 'boss' ? `โ
${N.boss.kind === 'warden' ? 'Warden' : 'Herald'}` : `โ
${Math.min(run.kills, N.kills)}/${N.kills}๐`];
ctx.font = '800 12px system-ui,sans-serif';
const ws = parts.map((p) => ctx.measureText(p).width + 14), tw = ws.reduce((a, b) => a + b, 0);
let x = cw / 2 - tw / 2;
for (let k = 0; k < 3; k++) { ctx.fillStyle = ok[k] ? '#FFC857' : 'rgba(232,226,255,.55)'; ctx.fillText(parts[k], x + ws[k] / 2, 54); x += ws[k]; }
gy = 70;
} else {
ctx.font = '900 24px system-ui,sans-serif'; ctx.fillStyle = '#FFFFFF'; ctx.fillText(C.fmtTime(t), cw / 2, 14);
ctx.font = '700 11px system-ui,sans-serif'; ctx.fillStyle = '#BDB4D9';
ctx.fillText(goal < Infinity ? `dawn in ${C.fmtTime(goal - t)}` : 'endless night', cw / 2, 42);
gy = 58;
}
if (run.target != null) { // a friend's "beat my score" target
const sc = C.dailyScore(t, run.kills, Math.round(run.shards)), beat = sc > run.target;
ctx.font = '800 13px system-ui,sans-serif'; ctx.fillStyle = beat ? '#6FE3C1' : '#FFD1DC';
ctx.fillText(beat ? `Beat ${run.target.toLocaleString()} โ ยท ${sc.toLocaleString()}` : `Beat ${run.target.toLocaleString()} ยท you ${sc.toLocaleString()}`, cw / 2, gy);
}
// weapon icons
ctx.textAlign = 'left'; ctx.font = '700 12px system-ui,sans-serif';
let wx = 10;
for (const w of run.weapons) { ctx.fillStyle = w.evo ? 'rgba(255,200,87,.35)' : 'rgba(255,255,255,.12)'; ctx.fillRect(wx, ch - 32, 28, 22); ctx.fillStyle = '#fff'; ctx.fillText(C.WEAPONS[w.id].icon, wx + 4, ch - 28); ctx.fillStyle = '#FFC857'; ctx.fillText(w.evo ? 'โ
' : String(w.lv), wx + 17, ch - 28); wx += 31; }
// boss bar
if (run.boss) {
for (let i = 0; i < nE; i++) if (etype[i] >= 3 && eid[i] === -1 || etype[i] === 4) {
const bw = Math.min(360, cw - 120), bxp = (cw - bw) / 2;
ctx.fillStyle = 'rgba(0,0,0,.6)'; const by0 = run.night || run.target != null ? 90 : 62;
ctx.fillRect(bxp, by0, bw, 10); ctx.fillStyle = '#FF3D7F'; ctx.fillRect(bxp, by0, bw * Math.max(0, ehp[i] / emax[i]), 10);
ctx.textAlign = 'center'; ctx.fillStyle = '#FFD1DC'; ctx.font = '800 11px system-ui,sans-serif'; ctx.fillText(etype[i] === 4 ? 'THE GLOAM WARDEN' : 'THE WARDEN\'S HERALD', cw / 2, by0 + 13);
break;
}
}
// banner
if (run.bannerT > 0) {
const al = Math.min(1, run.bannerT * 2, (2.6 - run.bannerT) * 4);
ctx.globalAlpha = al; ctx.textAlign = 'center'; ctx.font = '900 20px system-ui,sans-serif';
ctx.fillStyle = '#120F24'; ctx.fillText(run.banner, cw / 2 + 2, ch * 0.24 + 2); ctx.fillStyle = '#FFE9A8'; ctx.fillText(run.banner, cw / 2, ch * 0.24);
ctx.globalAlpha = 1;
}
// night 1 tutorial, no words: a hand drags a joystick (touch) or arrow keys light up (keyboard), then an arrow points at a shard
if (run.tut && state === 'play' && !run.auto) tutorial(cw, ch);
// onboarding prompt
else if (run.promptT > 0 && state === 'play' && !run.auto) {
ctx.globalAlpha = Math.min(1, run.promptT); ctx.textAlign = 'center'; ctx.font = '800 16px system-ui,sans-serif';
const msg = TOUCH ? 'Drag anywhere to move' : save.mouse ? 'Point the mouse to steer' : 'Move: WASD or arrow keys';
const msg2 = 'Your lantern fires by itself ยท grab light shards';
ctx.fillStyle = 'rgba(18,15,36,.7)'; ctx.fillRect(cw / 2 - 170, ch * 0.7 - 6, 340, 50);
ctx.fillStyle = '#FFFFFF'; ctx.fillText(msg, cw / 2, ch * 0.7); ctx.fillStyle = '#BDB4D9'; ctx.font = '600 13px system-ui,sans-serif'; ctx.fillText(msg2, cw / 2, ch * 0.7 + 22);
ctx.globalAlpha = 1;
}
// joystick
if (joy.on && state === 'play') {
ctx.globalAlpha = 0.35; ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(joy.ox, joy.oy, 48, 0, TAU); ctx.stroke();
ctx.globalAlpha = 0.6; ctx.fillStyle = '#FFE9A8'; ctx.beginPath(); ctx.arc(joy.x, joy.y, 18, 0, TAU); ctx.fill(); ctx.globalAlpha = 1;
}
// chest roll
if (state === 'chest' && run.chest) {
const c = run.chest, p = Math.min(1, c.t / c.dur);
ctx.fillStyle = 'rgba(10,8,24,.72)'; ctx.fillRect(0, 0, cw, ch);
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = '900 26px system-ui,sans-serif'; ctx.fillStyle = '#FFC857'; ctx.fillText('Lantern chest!', cw / 2, ch * 0.3);
const all = Object.values(C.WEAPONS).map((w) => w.icon).concat(Object.values(C.PASSIVES).map((x) => x.icon));
const n = c.icons.length, gap = 90;
for (let j = 0; j < n; j++) {
const x = cw / 2 + (j - (n - 1) / 2) * gap, done = p >= 1 || c.t > c.dur * (0.55 + 0.15 * j);
ctx.fillStyle = done ? 'rgba(255,200,87,.25)' : 'rgba(255,255,255,.1)'; ctx.fillRect(x - 36, ch / 2 - 36, 72, 72);
ctx.font = '40px system-ui,sans-serif'; ctx.fillStyle = '#fff';
ctx.fillText(done ? c.icons[j].icon : all[Math.floor(c.t * 22 + j * 3) % all.length], x, ch / 2);
if (done) { ctx.font = '700 12px system-ui,sans-serif'; ctx.fillStyle = '#FFE9A8'; ctx.fillText(c.icons[j].name.slice(0, 18), x, ch / 2 + 50); }
}
ctx.font = '600 12px system-ui,sans-serif'; ctx.fillStyle = '#BDB4D9'; ctx.fillText('tap to continue', cw / 2, ch * 0.72);
}
}
function tutorial(cw, ch) {
const T = performance.now() / 1000;
if (run.moved < 160) {
const cx = cw / 2, cy = ch * 0.72;
if (TOUCH || save.mouse) {
const a = T * 2.2, hx = cx + Math.cos(a) * 34, hy = cy + Math.sin(a) * 34;
ctx.globalAlpha = 0.4; ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(cx, cy, 48, 0, TAU); ctx.stroke();
ctx.globalAlpha = 0.7; ctx.fillStyle = '#FFE9A8'; ctx.beginPath(); ctx.arc(hx, hy, 16, 0, TAU); ctx.fill();
ctx.globalAlpha = 1; ctx.font = '40px system-ui,sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'top'; ctx.fillText('๐', hx + 6, hy - 2);
} else {
const lit = Math.floor(T * 2.5) % 4, K = [['โ', -46, 0], ['โ', 0, -42], ['โ', 46, 0], ['โ', 0, 0]];
ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.font = '900 20px system-ui,sans-serif';
K.forEach(([g, dx, dy], k) => { const on = k === [0, 1, 2, 3][lit]; ctx.fillStyle = on ? '#FFC857' : 'rgba(255,255,255,.14)'; ctx.fillRect(cx + dx - 19, cy + dy - 19, 38, 38); ctx.fillStyle = on ? '#120F24' : '#fff'; ctx.fillText(g, cx + dx, cy + dy); });
ctx.textBaseline = 'top';
}
return;
}
if (run.shards > 0 || !nG) { if (run.shards > 0) run.tut = false; return; }
// arrow from the wisp toward the nearest shard
let best = -1, bd = Infinity;
for (let g = 0; g < nG; g++) { const d = (gx[g] - run.px) ** 2 + (gy[g] - run.py) ** 2; if (d < bd) { bd = d; best = g; } }
if (best < 0) return;
const { k } = view, ang = Math.atan2(gy[best] - run.py, gx[best] - run.px), wx = (run.px - cam.x) * k + cw / 2, wy = (run.py - cam.y) * k + ch / 2;
const r = 44 + Math.sin(T * 6) * 6;
ctx.save(); ctx.translate(wx + Math.cos(ang) * r, wy + Math.sin(ang) * r); ctx.rotate(ang);
ctx.fillStyle = '#8FD3FF'; ctx.globalAlpha = 0.9; ctx.beginPath(); ctx.moveTo(14, 0); ctx.lineTo(-8, -10); ctx.lineTo(-3, 0); ctx.lineTo(-8, 10); ctx.closePath(); ctx.fill();
ctx.restore(); ctx.globalAlpha = 1;
}
// ------------------------------------------------------------------ boot, hooks
pass.onChange(() => { makeWispSprite(); if (state === 'menu') { if (!$('map').hidden) renderMap(); else renderMenu(); } });
$('hint').textContent = TOUCH ? 'Drag anywhere to move. Your lantern fires by itself.' : 'WASD / arrows to move ยท Esc pause ยท R restart. Your lantern fires by itself.';
showMenu();
if (!CAP) requestAnimationFrame(frame); else { clock = performance.now(); lastNow = clock; frame(clock); }
boot3d();
// Read-only state for scripts/games/upgrade_e2e.mjs (2026 upgrade checks: playable, restart, 3D on).
window.__cmxPlay = () => ({ state: state === 'play' || state === 'levelup' || state === 'chest' ? 'run' : state, t: Math.round((run.time || 0)), score: run.kills || 0, is3d: !!R3 });
if (CAP) window.__cap = {
ready: () => !!R3,
/** Step n frames of 1/30 s: the sim and the 3D view both advance by exactly that, then the page is drawn. Level-up
* cards are picked (first card) the moment they appear, so the bot keeps playing. */
advance(n = 1) { for (let i = 0; i < n; i++) { clock += 1000 / 30; frame(clock); if (state === 'levelup') { const b = $('cardlist').firstElementChild; if (b) b.click(); } } },
bot(on = true) { window.__capBot = on; if (run) run.auto = on; },
play(m) { hideAll(); startRun(m.kind === 'daily' ? 'daily' : 'standard'); if (window.__capBot) run.auto = true; },
state: () => ({ state: state === 'over' ? 'dead' : state === 'play' || state === 'levelup' || state === 'chest' ? 'run' : state, score: run.kills, kind: run.mode }),
};
function simulate(sec) { // run the sim fast (for screenshots and the demo)
const n = Math.round(sec * 60);
for (let i = 0; i < n; i++) { if (state !== 'play') break; tick(); }
}
function prep(weapons, passives) {
run.god = true; run.auto = true; run.promptT = 0;
for (const [id, lv] of weapons) { const w = weaponOf(id) || addWeapon(id); w.lv = lv; w.st = C.weaponStats(id, lv); }
Object.assign(run.passives, passives); recalc(); run.hp = run.maxhp;
}
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
window.__cmxShot = async (stage = 1) => {
hideAll(); startRun('standard'); run.R = rng(42);
prep([['spark', 3], ['firefly', 3], ['nova', 2], ['chain', 2]], { glow: 2, kindle: 1 });
simulate(stage === 2 ? 150 : 115);
run.kills += 0; run.bannerT = 0;
if (stage === 2) { run.god = false; endRun(false); return; }
run.hp = run.maxhp * 0.8;
await wait(300);
};
window.__cmxDemo = async () => {
hideAll(); startRun('standard'); run.R = rng(99);
prep([['spark', 4], ['firefly', 3], ['chain', 3], ['moon', 2]], { glow: 3, haste: 2 });
simulate(95);
await wait(2200);
run.auto = false; run.xp = C.xpNeed(run.level) + 1; // show a real level-up
await new Promise((ok) => { const h = setInterval(() => { if (state === 'levelup') { clearInterval(h); ok(); } }, 30); setTimeout(() => { clearInterval(h); ok(); }, 1500); });
await wait(1100);
const b = $('cardlist').firstElementChild; if (b && state === 'levelup') b.click();
run.auto = true;
await wait(900);
const e = spawn(3, run.px + 120, run.py - 40, 0.15); if (e >= 0) banner('An elite stirs in the reeds');
await wait(3800);
};
window.__wm = { state: () => state, fps: () => fps, run, counts: () => ({ enemies: nE, gems: nG, bolts: nB, particles: nQ }),
save: () => save, last: () => last, shareText: () => (last ? shareText(last) : ''), sharePath: () => (last ? sharePath(last) : ''), start: startRun, simulate, link: () => LINK };