Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/starsnake

Starsnake: steer a snake-like ship Asteroids style, grow a crystal tail, and spend crystals on towers to defend your core. Mobile friendly.

FollowForkOpen app

Files

game.js

1052 lines · 46.4 KB · JavaScript
// Starsnake client. Plain browser JS, inlined into the page by app/page.ts (see scripts/build.mjs).
;(() => {
	'use strict'
	const $ = (id) => document.getElementById(id)
	const canvas = $('c')
	const ctx = canvas.getContext('2d', { alpha: false })
	const KEYS = { hi: 'starsnake-hi', mute: 'starsnake-mute', seen: 'starsnake-seen' }
	const store = {
		get(k) { try { return localStorage.getItem(k) } catch { return null } },
		set(k, v) { try { localStorage.setItem(k, v) } catch {} },
	}
	const TAU = Math.PI * 2
	const clamp = (v, a, b) => (v < a ? a : v > b ? b : v)

	// ---------- seeded random (use ?seed=N for reproducible runs) ----------
	const params = new URLSearchParams(location.search)
	let seed = Number(params.get('seed')) || (Math.random() * 4294967296) >>> 0
	function rand() {
		seed = (seed + 0x6d2b79f5) | 0
		let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
		t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
		return ((t ^ (t >>> 14)) >>> 0) / 4294967296
	}
	const rr = (a, b) => a + (b - a) * rand()

	// ---------- tuning ----------
	const SHORT_SIDE = 600 // world units along the shorter screen edge
	const SPACING = 14
	const SEG_R = 6
	const HEAD_R = 8
	const MAX_TAIL = 30
	const GEMS_PER_SEG = 3
const TAIL_DMG = 2 // damage per tail hit
const TAIL_WHIP_SPEED = 180 // ship speed above this adds +1 damage (boosting whips harder)
const TAIL_BEAD_CD = 0.4 // seconds before the same bead can hit again
const TAIL_ROCK_CD = 0.15 // seconds before the same rock can be hit by the tail again
	const TOWER = {
		pulse: { name: 'PULSE', color: '#5ef2ff', cost: 8, up: [10, 18], range: [125, 142, 160], rate: [2.2, 3.2, 4.2], dmg: [1, 1, 2] },
		cannon: { name: 'CANNON', color: '#ffb347', cost: 18, up: [20, 34], range: [165, 185, 205], rate: [0.55, 0.7, 0.9], dmg: [3, 4, 6], splash: [44, 52, 60] },
		frost: { name: 'FROST', color: '#9bd1ff', cost: 12, up: [14, 24], range: [95, 115, 135], slow: [0.4, 0.55, 0.7] },
	}
	const GUN_COSTS = [20, 40, 70]
	const REPAIR_COST = 10
	const REPAIR_HP = 20
	const MAX_TOWERS = 14
	const ROCK = { 1: { r: 12, hp: 1 }, 2: { r: 21, hp: 2 }, 3: { r: 34, hp: 3 } }

	// ---------- world / canvas ----------
	let W = 600, H = 900, scale = 1, dpr = 1, vw = 0, vh = 0
	let stars = null
	const pointerCoarse = matchMedia('(pointer: coarse)').matches
	document.documentElement.classList.add(pointerCoarse ? 'touch' : 'mouse')

	function buildStars() {
		stars = document.createElement('canvas')
		stars.width = Math.max(1, Math.round(vw * dpr))
		stars.height = Math.max(1, Math.round(vh * dpr))
		const s = stars.getContext('2d')
		s.fillStyle = '#060913'
		s.fillRect(0, 0, stars.width, stars.height)
		const g = s.createRadialGradient(stars.width / 2, stars.height / 2, 0, stars.width / 2, stars.height / 2, Math.max(stars.width, stars.height) * 0.6)
		g.addColorStop(0, '#13204a')
		g.addColorStop(1, '#060913')
		s.fillStyle = g
		s.fillRect(0, 0, stars.width, stars.height)
		let sd = 12345
		const r = () => ((sd = (sd * 1664525 + 1013904223) >>> 0) / 4294967296)
		const n = Math.round((vw * vh) / 2600)
		for (let i = 0; i < n; i++) {
			const x = r() * stars.width, y = r() * stars.height, b = r()
			s.fillStyle = `rgba(200,220,255,${0.15 + b * 0.55})`
			const z = (b > 0.93 ? 2 : 1) * dpr
			s.fillRect(x, y, z, z)
		}
	}

	function resize() {
		vw = Math.max(1, window.innerWidth)
		vh = Math.max(1, window.innerHeight)
		dpr = Math.min(window.devicePixelRatio || 1, 2.5)
		canvas.width = Math.round(vw * dpr)
		canvas.height = Math.round(vh * dpr)
		canvas.style.width = vw + 'px'
		canvas.style.height = vh + 'px'
		const sc = Math.min(vw, vh) / SHORT_SIDE
		const nw = vw / sc, nh = vh / sc
		if (G) {
			const fx = nw / W, fy = nh / H
			const mv = (o) => { o.x *= fx; o.y *= fy }
			;[G.ship, G.core, ...G.rocks, ...G.gems, ...G.towers, ...G.trail, ...G.ambient].forEach(mv)
		}
		W = nw; H = nh; scale = sc
		buildStars()
	}

	// ---------- game state ----------
	let G = null
	function newGame() {
		const g = {
			state: 'title', t: 0, score: 0, wave: 0, crystals: 10, gemCount: 0, tailLen: 3, gunLvl: 1,
			core: { x: W / 2, y: H / 2, r: 26, hp: 100, max: 100, cd: 0, flash: 0 },
			ship: { x: W / 2, y: H / 2 + 140, vx: 0, vy: 0, a: Math.PI, inv: 0, cd: 0, thrust: 0 },
			trail: [], segs: [], segCd: [], segHit: [], segFlash: [], bullets: [], rocks: [], gems: [], towers: [], parts: [], rings: [], ambient: [],
			queue: [], spawnT: 0, waveState: 'break', breakT: 1.2, shake: 0, over: '', dyingT: 0, banner: { t: 0, text: '' },
			toast: { t: 0, text: '', bad: false }, kills: 0, tailKills: 0, playT: 0, hintT: 0, tailBit: null,
		}
		for (let i = 0; i < 160; i++) g.trail.push({ x: g.ship.x + i * 2.2, y: g.ship.y })
		return g
	}
	G = null

	// ---------- input ----------
	const input = { left: false, right: false, up: false, stick: null }
	const pointers = new Map()

	// ---------- audio ----------
	let ac = null
	let muted = store.get(KEYS.mute) === '1'
	function audio() {
		if (!ac) { try { ac = new (window.AudioContext || window.webkitAudioContext)() } catch {} }
		if (ac && ac.state === 'suspended') ac.resume().catch(() => {})
		return ac
	}
	function tone(f0, f1, dur, type, vol) {
		if (muted || !ac) return
		const t = ac.currentTime
		const o = ac.createOscillator(), g = ac.createGain()
		o.type = type || 'square'
		o.frequency.setValueAtTime(f0, t)
		o.frequency.exponentialRampToValueAtTime(Math.max(20, f1), t + dur)
		g.gain.setValueAtTime(vol || 0.05, t)
		g.gain.exponentialRampToValueAtTime(0.0001, t + dur)
		o.connect(g).connect(ac.destination)
		o.start(t); o.stop(t + dur + 0.02)
	}
	let noiseBuf = null
	function noise(dur, vol, hp) {
		if (muted || !ac) return
		if (!noiseBuf) {
			noiseBuf = ac.createBuffer(1, ac.sampleRate, ac.sampleRate)
			const d = noiseBuf.getChannelData(0)
			for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1
		}
		const t = ac.currentTime
		const s = ac.createBufferSource(), g = ac.createGain(), f = ac.createBiquadFilter()
		s.buffer = noiseBuf; f.type = 'lowpass'; f.frequency.value = hp || 900
		g.gain.setValueAtTime(vol, t); g.gain.exponentialRampToValueAtTime(0.0001, t + dur)
		s.connect(f).connect(g).connect(ac.destination)
		s.start(t, Math.random() * 0.5, dur)
	}
	const SFX = {
		shoot: () => tone(880, 440, 0.07, 'square', 0.02),
		tower: () => tone(1200, 700, 0.05, 'triangle', 0.025),
		boom: (s) => noise(0.12 + s * 0.08, 0.1 + s * 0.04, 500 + s * 300),
		gem: () => tone(660 + Math.random() * 80, 1320, 0.09, 'sine', 0.05),
		build: () => { tone(300, 600, 0.12, 'square', 0.05); setTimeout(() => tone(600, 900, 0.1, 'square', 0.04), 90) },
		up: () => { tone(500, 1000, 0.14, 'triangle', 0.06); setTimeout(() => tone(900, 1500, 0.12, 'triangle', 0.05), 100) },
		whip: () => { tone(220, 90, 0.08, 'sawtooth', 0.05); noise(0.06, 0.08, 1400) },
		bad: () => tone(160, 110, 0.18, 'sawtooth', 0.05),
		hurt: () => { noise(0.25, 0.2, 400); tone(140, 50, 0.3, 'sawtooth', 0.07) },
		wave: () => { tone(440, 440, 0.1, 'square', 0.04); setTimeout(() => tone(660, 660, 0.14, 'square', 0.04), 120) },
		over: () => { tone(400, 60, 0.9, 'sawtooth', 0.08); noise(0.8, 0.2, 700) },
	}
	function updateMuteBtn() {
		const b = $('muteBtn')
		b.textContent = muted ? 'MUTE' : 'SND'
		b.setAttribute('aria-pressed', String(!muted))
		b.setAttribute('aria-label', muted ? 'Sound is off. Turn on' : 'Sound is on. Turn off')
	}
	function toggleMute() {
		muted = !muted
		store.set(KEYS.mute, muted ? '1' : '0')
		if (!muted) audio()
		updateMuteBtn()
	}

	// ---------- helpers ----------
	const wrapX = (x) => (x < 0 ? x + W : x >= W ? x - W : x)
	const wrapY = (y) => (y < 0 ? y + H : y >= H ? y - H : y)
	const dW = (a, b, L) => { let d = b - a; if (d > L / 2) d -= L; else if (d < -L / 2) d += L; return d }
	const angDiff = (a, b) => { let d = (b - a) % TAU; if (d > Math.PI) d -= TAU; if (d < -Math.PI) d += TAU; return d }

	function burst(x, y, color, n, speed, life, size) {
		if (G.parts.length > 500) return
		for (let i = 0; i < n; i++) {
			const a = rand() * TAU, s = speed * (0.3 + rand() * 0.7)
			G.parts.push({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, life: life * (0.5 + rand() * 0.5), max: life, color, size: size || 2 })
		}
	}
	function ring(x, y, r0, r1, color, life) { G.rings.push({ x, y, r0, r1, color, life, max: life }) }
	function say(text, bad) { G.toast = { t: 1.8, text, bad: !!bad } }
	function banner(text) { G.banner = { t: 2.2, text } }

	// ---------- rocks ----------
	function makeShape(r) {
		const n = 8 + Math.floor(rand() * 4), pts = []
		for (let i = 0; i < n; i++) pts.push([Math.cos((i / n) * TAU) * r * rr(0.78, 1.12), Math.sin((i / n) * TAU) * r * rr(0.78, 1.12)])
		return pts
	}
	function addRock(x, y, vx, vy, size, boss) {
		const def = ROCK[size]
		const r = boss ? 58 : def.r
		const hp = boss ? 14 + G.wave * 2 : def.hp + (G.wave >= 8 && size === 3 ? 1 : 0)
		G.rocks.push({ x, y, vx, vy, r, hp, max: hp, size, boss: !!boss, rot: rand() * TAU, vr: rr(-1.2, 1.2), shape: makeShape(r), slow: 0, hit: 0, safe: 0, tailCd: 0 })
	}
	function rockSpeed(size) { return Math.min(26 + G.wave * 2.4, 72) * (size === 1 ? 1.35 : size === 2 ? 1.15 : 1) }
	function spawnRock(size, boss) {
		const def = ROCK[size], r = boss ? 58 : def.r
		const side = Math.floor(rand() * 4)
		let x, y
		if (side === 0) { x = rr(0, W); y = -r - 8 }
		else if (side === 1) { x = W + r + 8; y = rr(0, H) }
		else if (side === 2) { x = rr(0, W); y = H + r + 8 }
		else { x = -r - 8; y = rr(0, H) }
		const a = Math.atan2(G.core.y - y, G.core.x - x) + rr(-0.5, 0.5)
		const sp = rockSpeed(size) * (boss ? 0.6 : 1) * rr(0.85, 1.15)
		addRock(x, y, Math.cos(a) * sp, Math.sin(a) * sp, size, boss)
	}
	function startWave() {
		G.wave++
		const n = G.wave
		const big = 3 + Math.floor(n * 1.3), med = Math.floor(n * 0.9), small = n > 3 ? Math.floor(n * 0.6) : 0
		const q = []
		for (let i = 0; i < big; i++) q.push(3)
		for (let i = 0; i < med; i++) q.push(2)
		for (let i = 0; i < small; i++) q.push(1)
		for (let i = q.length - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)); [q[i], q[j]] = [q[j], q[i]] }
		if (n % 5 === 0) q.push('boss')
		G.queue = q
		G.spawnT = 0.5
		G.waveState = 'fight'
		banner(n % 5 === 0 ? `WAVE ${n}: BIG ROCK` : `WAVE ${n}`)
		SFX.wave()
	}
	function destroyRock(rk, byPlayer, byTail) {
		if (rk.dead) return
		rk.dead = true
		if (byTail) G.tailKills++
		G.score += (rk.boss ? 300 : rk.size * 10) * (1 + Math.floor(G.wave / 4) * 0.25) | 0
		G.kills++
		burst(rk.x, rk.y, '#c8d6f5', 8 + rk.size * 4, 90 + rk.size * 30, 0.7, 2)
		ring(rk.x, rk.y, rk.r * 0.5, rk.r * 1.6, '#8fb2ff', 0.3)
		G.shake = Math.max(G.shake, rk.boss ? 10 : rk.size * 1.2)
		SFX.boom(rk.boss ? 3 : rk.size)
		if (byPlayer !== false) {
			const gems = rk.boss ? 10 : rk.size === 1 ? (rand() < 0.6 ? 1 : 0) : 1
			for (let i = 0; i < gems; i++) G.gems.push({ x: rk.x + rr(-6, 6), y: rk.y + rr(-6, 6), vx: rk.vx * 0.3 + rr(-30, 30), vy: rk.vy * 0.3 + rr(-30, 30), life: 14, rot: rand() * TAU })
		}
		if (rk.boss) {
			for (let i = 0; i < 4; i++) { const a = (i / 4) * TAU + rand(); addRock(rk.x, rk.y, rk.vx * 0.5 + Math.cos(a) * 55, rk.vy * 0.5 + Math.sin(a) * 55, 3); G.rocks[G.rocks.length - 1].safe = 0.6 }
		} else if (rk.size > 1) {
			for (let i = 0; i < 2; i++) {
				const a = rand() * TAU, sp = 40 + rand() * 40
				addRock(rk.x, rk.y, rk.vx * 0.6 + Math.cos(a) * sp, rk.vy * 0.6 + Math.sin(a) * sp, rk.size - 1)
				G.rocks[G.rocks.length - 1].safe = 0.6
			}
		}
	}
	function hitRock(rk, dmg, byTail) {
		if (rk.dead) return
		rk.hp -= dmg
		rk.hit = 0.08
		if (rk.hp <= 0) destroyRock(rk, true, byTail)
	}

	// ---------- bullets ----------
	function fire(x, y, ang, speed, life, dmg, color, extra) {
		G.bullets.push(Object.assign({ x, y, vx: Math.cos(ang) * speed, vy: Math.sin(ang) * speed, life, dmg, color, wrap: false }, extra))
	}
	function nearestRock(x, y, range, wrapAware) {
		let best = null, bd = Infinity
		for (const rk of G.rocks) {
			if (rk.dead) continue
			const dx = wrapAware ? dW(x, rk.x, W) : rk.x - x, dy = wrapAware ? dW(y, rk.y, H) : rk.y - y
			const d = Math.hypot(dx, dy) - rk.r
			if (d < range && d < bd) { bd = d; best = rk }
		}
		return best
	}
	function aim(x, y, rk, speed) {
		const dx = rk.x - x, dy = rk.y - y, t = Math.hypot(dx, dy) / speed
		return Math.atan2(dy + rk.vy * t, dx + rk.vx * t)
	}

	// ---------- towers ----------
	function towerStat(t, key) { return TOWER[t.type][key][t.lvl - 1] }
	function upgradeCost(t) { return t.lvl >= 3 ? null : TOWER[t.type].up[t.lvl - 1] }
	function nearTower(x, y, d) {
		let best = null, bd = d
		for (const t of G.towers) { const k = Math.hypot(t.x - x, t.y - y); if (k < bd) { bd = k; best = t } }
		return best
	}
	function tryUpgrade(t) {
		const c = upgradeCost(t)
		if (c == null) return say('TOWER MAXED', true), SFX.bad(), false
		if (G.crystals < c) return say(`NEED ${c} CRYSTALS`, true), SFX.bad(), false
		G.crystals -= c; t.lvl++; t.maxhp = 60 + (t.lvl - 1) * 30; t.hp = t.maxhp
		ring(t.x, t.y, 10, 50, TOWER[t.type].color, 0.5); burst(t.x, t.y, TOWER[t.type].color, 14, 120, 0.6, 2)
		say(`${TOWER[t.type].name} LEVEL ${t.lvl}`); SFX.up()
		return true
	}
	function build(type) {
		if (G.state !== 'play') return
		const def = TOWER[type], s = G.ship
		const under = nearTower(s.x, s.y, 30)
		if (under && under.type === type) return tryUpgrade(under)
		if (G.crystals < def.cost) return say(`NEED ${def.cost} CRYSTALS`, true), SFX.bad()
		if (G.towers.length >= MAX_TOWERS) return say('TOWER LIMIT', true), SFX.bad()
		if (Math.hypot(s.x - G.core.x, s.y - G.core.y) < G.core.r + 26) return say('TOO CLOSE TO CORE', true), SFX.bad()
		if (nearTower(s.x, s.y, 30)) return say('TOO CLOSE TO A TOWER', true), SFX.bad()
		G.crystals -= def.cost
		G.towers.push({ x: s.x, y: s.y, type, lvl: 1, cd: 0.4, hp: 60, maxhp: 60, ang: -Math.PI / 2, hit: 0, born: 0 })
		ring(s.x, s.y, 8, 46, def.color, 0.45); burst(s.x, s.y, def.color, 12, 100, 0.5, 2)
		SFX.build()
	}
	function repair() {
		if (G.state !== 'play') return
		if (G.core.hp >= G.core.max) return say('CORE IS FULL', true), SFX.bad()
		if (G.crystals < REPAIR_COST) return say(`NEED ${REPAIR_COST} CRYSTALS`, true), SFX.bad()
		G.crystals -= REPAIR_COST
		G.core.hp = Math.min(G.core.max, G.core.hp + REPAIR_HP)
		ring(G.core.x, G.core.y, 20, 80, '#7dff9a', 0.6); say('CORE REPAIRED'); SFX.up()
	}
	function gunUp() {
		if (G.state !== 'play') return
		if (G.gunLvl >= 4) return say('GUN MAXED', true), SFX.bad()
		const c = GUN_COSTS[G.gunLvl - 1]
		if (G.crystals < c) return say(`NEED ${c} CRYSTALS`, true), SFX.bad()
		G.crystals -= c; G.gunLvl++
		ring(G.ship.x, G.ship.y, 10, 60, '#ffffff', 0.5); say(`GUN LEVEL ${G.gunLvl}`); SFX.up()
	}
	function upgradeNearest() {
		if (G.state !== 'play') return
		const t = nearTower(G.ship.x, G.ship.y, 70)
		if (!t) return say('FLY NEAR A TOWER', true), SFX.bad()
		tryUpgrade(t)
	}

	// ---------- simulation ----------
	function updateSegs() {
		const n = G.tailLen, segs = G.segs
		segs.length = 0
		let need = SPACING, acc = 0, px = G.ship.x, py = G.ship.y
		for (let k = 0; k < G.trail.length && segs.length < n; k++) {
			const t = G.trail[k], dx = dW(px, t.x, W), dy = dW(py, t.y, H), d = Math.hypot(dx, dy)
			if (d > 0) {
				while (acc + d >= need && segs.length < n) {
					const f = (need - acc) / d
					segs.push({ x: wrapX(px + dx * f), y: wrapY(py + dy * f) })
					need += SPACING
				}
			}
			acc += d; px = t.x; py = t.y
		}
		while (segs.length < n) segs.push({ x: px, y: py })
	}

	function endGame(reason) {
		if (G.state !== 'play') return
		G.state = 'dying'; G.dyingT = 1.1; G.over = reason
		SFX.over()
		G.shake = 14
		const s = G.ship
		burst(s.x, s.y, '#7dff9a', 40, 220, 1, 3)
		for (const sg of G.segs) burst(sg.x, sg.y, '#7dff9a', 3, 120, 0.8, 2)
		if (reason === 'core') { burst(G.core.x, G.core.y, '#ff5f7a', 60, 260, 1.2, 3); ring(G.core.x, G.core.y, 20, 260, '#ff5f7a', 0.9) }
	}

	function stepPlay(dt) {
		const s = G.ship, core = G.core
		G.playT += dt
		// steering
		let thrust = 0
		const st = input.stick
		if (st) {
			const dx = st.x - st.ox, dy = st.y - st.oy, m = Math.min(1, Math.hypot(dx, dy) / 50)
			if (m > 0.18) {
				const target = Math.atan2(dy, dx)
				const d = angDiff(s.a, target), rate = 5.4 * dt
				s.a += clamp(d, -rate, rate)
				thrust = clamp((m - 0.5) * 2, 0, 1)
			}
		}
		if (input.left) s.a -= 3.8 * dt
		if (input.right) s.a += 3.8 * dt
		if (input.up) thrust = 1
		s.thrust = thrust
		const hx = Math.cos(s.a), hy = Math.sin(s.a)
		s.vx += hx * thrust * 430 * dt
		s.vy += hy * thrust * 430 * dt
		const drag = Math.exp(-0.9 * dt)
		s.vx *= drag; s.vy *= drag
		let fwd = s.vx * hx + s.vy * hy
		let sx = s.vx - hx * fwd, sy = s.vy - hy * fwd
		const side = Math.exp(-3.2 * dt)
		sx *= side; sy *= side
		if (fwd < 72) fwd += (72 - fwd) * Math.min(1, 3 * dt)
		s.vx = hx * fwd + sx; s.vy = hy * fwd + sy
		const sp = Math.hypot(s.vx, s.vy)
		if (sp > 300) { s.vx *= 300 / sp; s.vy *= 300 / sp }
		const ox = s.x, oy = s.y
		s.x = wrapX(s.x + s.vx * dt); s.y = wrapY(s.y + s.vy * dt)
		s.inv = Math.max(0, s.inv - dt)
		// trail
		const last = G.trail[0]
		if (Math.hypot(dW(last.x, s.x, W), dW(last.y, s.y, H)) >= 2) G.trail.unshift({ x: s.x, y: s.y })
		const maxPts = Math.ceil(((G.tailLen + 3) * SPACING) / 1.5) + 20
		if (G.trail.length > maxPts) G.trail.length = maxPts
		updateSegs()
		for (let i = 0; i < G.segs.length; i++) { if (G.segHit[i] > 0) G.segHit[i] -= dt; if (G.segFlash[i] > 0) G.segFlash[i] -= dt }
		void ox; void oy

		// ship autofire
		s.cd -= dt
		if (s.cd <= 0) {
			const lvl = G.gunLvl
			s.cd = lvl >= 3 ? 0.17 : 0.24
			const muzzle = [s.x + hx * 11, s.y + hy * 11]
			const lanes = lvl >= 4 ? [-0.2, 0, 0.2] : lvl >= 2 ? [-0.09, 0.09] : [0]
			for (const l of lanes) fire(muzzle[0], muzzle[1], s.a + l, 540, 0.85, 1, '#ffffff', { wrap: true })
			if (G.playT % 0.5 < 0.25) SFX.shoot()
		}
		// tail guns
		G.segs.forEach((sg, i) => {
			if (i % 3 !== 2) return
			G.segCd[i] = (G.segCd[i] ?? rand() * 1.2) - dt
			if (G.segCd[i] > 0) return
			const rk = nearestRock(sg.x, sg.y, 150, false)
			G.segCd[i] = 1.3
			if (rk) fire(sg.x, sg.y, aim(sg.x, sg.y, rk, 420), 420, 0.7, 1, '#7dff9a', {})
		})
		// core turret
		core.cd -= dt
		core.flash = Math.max(0, core.flash - dt)
		if (core.cd <= 0) {
			const rk = nearestRock(core.x, core.y, 150, false)
			if (rk) { core.cd = 0.9; fire(core.x, core.y, aim(core.x, core.y, rk, 380), 380, 0.7, 1, '#ff9ad5', {}) } else core.cd = 0.2
		}
		// towers
		for (const t of G.towers) {
			t.hit = Math.max(0, t.hit - dt); t.born += dt
			const def = TOWER[t.type]
			const range = towerStat(t, 'range')
			if (t.type === 'frost') continue
			t.cd -= dt
			const rk = nearestRock(t.x, t.y, range, false)
			if (rk) {
				const speed = t.type === 'pulse' ? 440 : 300
				t.ang = aim(t.x, t.y, rk, speed)
				if (t.cd <= 0) {
					t.cd = 1 / towerStat(t, 'rate')
					if (t.type === 'pulse') fire(t.x, t.y, t.ang, speed, 0.8, towerStat(t, 'dmg'), def.color, {})
					else fire(t.x, t.y, t.ang, speed, 1.1, towerStat(t, 'dmg'), def.color, { splash: towerStat(t, 'splash'), big: true })
					SFX.tower()
				}
			}
		}
		// rocks
		for (const rk of G.rocks) {
			if (rk.dead) continue
			let slow = 0
			for (const t of G.towers) if (t.type === 'frost' && Math.hypot(t.x - rk.x, t.y - rk.y) < towerStat(t, 'range') + rk.r) slow = Math.max(slow, towerStat(t, 'slow'))
			rk.slow = slow
			const k = 1 - slow
			const dx = core.x - rk.x, dy = core.y - rk.y, d = Math.hypot(dx, dy) || 1
			rk.vx += (dx / d) * 12 * dt; rk.vy += (dy / d) * 12 * dt
			const cap = rockSpeed(rk.size) * 1.8
			const v = Math.hypot(rk.vx, rk.vy)
			if (v > cap) { rk.vx *= cap / v; rk.vy *= cap / v }
			rk.x += rk.vx * k * dt; rk.y += rk.vy * k * dt
			rk.rot += rk.vr * dt * k
			rk.hit = Math.max(0, rk.hit - dt); rk.safe = Math.max(0, rk.safe - dt)
			// core
			if (d < core.r + rk.r * 0.8) {
				core.hp -= rk.boss ? 30 : rk.size * 5
				core.flash = 0.25
				G.shake = Math.max(G.shake, 9)
				SFX.hurt()
				burst(rk.x, rk.y, '#ff5f7a', 16, 160, 0.6, 2)
				destroyRock(rk, false)
				G.score -= 0
				continue
			}
			// towers
			for (const t of G.towers) {
				if (t.dead) continue
				if (Math.hypot(t.x - rk.x, t.y - rk.y) < rk.r + 11) {
					t.hp -= rk.boss ? 60 : rk.size * 15; t.hit = 0.2
					burst(t.x, t.y, '#ff9a5f', 10, 120, 0.5, 2)
					if (t.hp <= 0) { t.dead = true; burst(t.x, t.y, TOWER[t.type].color, 24, 200, 0.8, 2); ring(t.x, t.y, 10, 60, '#ff5f7a', 0.4); SFX.hurt() }
					destroyRock(rk, false)
					break
				}
			}
			if (rk.dead || rk.safe > 0) continue
			// tail is a weapon: beads hurt rocks (per-bead and per-rock cooldowns keep it from grinding)
			rk.tailCd = Math.max(0, rk.tailCd - dt)
			if (rk.safe <= 0.3 && rk.tailCd <= 0) {
				const whip = Math.hypot(s.vx, s.vy) > TAIL_WHIP_SPEED ? 1 : 0
				for (let i = 0; i < G.segs.length; i++) {
					const sg = G.segs[i]
					if ((G.segHit[i] || 0) > 0) continue
					const dx = dW(sg.x, rk.x, W), dy = dW(sg.y, rk.y, H), dd = Math.hypot(dx, dy)
					if (dd >= rk.r + SEG_R) continue
					G.segHit[i] = TAIL_BEAD_CD; G.segFlash[i] = 0.15; rk.tailCd = TAIL_ROCK_CD
					const nx = dx / (dd || 1), ny = dy / (dd || 1)
					burst(sg.x, sg.y, '#b6ff7a', 8, 150, 0.4, 2)
					ring(sg.x, sg.y, 4, 22, '#b6ff7a', 0.2)
					SFX.whip()
					G.shake = Math.max(G.shake, 2.5)
					if (rk.boss) {
						// Big rocks fight back: a boss hit chips it for 1 and knocks the bead off.
						hitRock(rk, 1, true)
						G.tailLen = Math.max(0, G.tailLen - 1); G.segs.splice(i, 1); G.segHit.splice(i, 1); G.segFlash.splice(i, 1)
					} else {
						rk.vx += nx * 110; rk.vy += ny * 110
						hitRock(rk, TAIL_DMG + whip, true)
					}
					break
				}
			}
			if (rk.dead) continue
			// ship
			if (s.inv <= 0 && Math.hypot(dW(s.x, rk.x, W), dW(s.y, rk.y, H)) < rk.r + HEAD_R) {
				s.inv = 1.4
				if (G.tailLen > 0) G.tailLen = Math.max(0, G.tailLen - 2)
				else { core.hp -= 6; core.flash = 0.2 }
				G.shake = Math.max(G.shake, 8)
				burst(s.x, s.y, '#ffffff', 16, 180, 0.6, 2)
				SFX.hurt()
				destroyRock(rk, true)
				say('SHIP HIT', true)
			}
		}
		G.towers = G.towers.filter((t) => !t.dead)
		// bullets
		for (const b of G.bullets) {
			b.x += b.vx * dt; b.y += b.vy * dt; b.life -= dt
			if (b.wrap) { b.x = wrapX(b.x); b.y = wrapY(b.y) }
			let hit = false
			if (b.life > 0) {
				for (const rk of G.rocks) {
					if (rk.dead) continue
					const dx = b.wrap ? dW(b.x, rk.x, W) : rk.x - b.x, dy = b.wrap ? dW(b.y, rk.y, H) : rk.y - b.y
					if (Math.hypot(dx, dy) < rk.r + (b.big ? 4 : 2.5)) {
						hit = true
						if (b.splash) {
							for (const o of G.rocks) if (!o.dead && Math.hypot(o.x - b.x, o.y - b.y) < b.splash + o.r) hitRock(o, b.dmg)
						} else hitRock(rk, b.dmg)
						burst(b.x, b.y, b.color, 4, 80, 0.3, 1.5)
						break
					}
				}
			}
			if (hit) b.life = 0
			else if (b.life <= 0 && b.splash) {
				for (const o of G.rocks) if (!o.dead && Math.hypot(o.x - b.x, o.y - b.y) < b.splash + o.r) hitRock(o, b.dmg)
			}
			if (b.life <= 0 && b.splash) { ring(b.x, b.y, 4, b.splash, b.color, 0.3); burst(b.x, b.y, b.color, 10, 120, 0.4, 2) }
		}
		G.bullets = G.bullets.filter((b) => b.life > 0)
		G.rocks = G.rocks.filter((r) => !r.dead && r.x > -220 && r.x < W + 220 && r.y > -220 && r.y < H + 220)
		// gems
		for (const g of G.gems) {
			g.life -= dt; g.rot += dt * 3
			const dx = dW(g.x, s.x, W), dy = dW(g.y, s.y, H), d = Math.hypot(dx, dy)
			const mag = 60 + G.tailLen * 1.2
			if (d < mag) { const pull = (1 - d / mag) * 520 + 120; g.vx += (dx / d) * pull * dt; g.vy += (dy / d) * pull * dt }
			g.vx *= Math.exp(-1.6 * dt); g.vy *= Math.exp(-1.6 * dt)
			g.x = wrapX(g.x + g.vx * dt); g.y = wrapY(g.y + g.vy * dt)
			if (d < HEAD_R + 8) {
				g.life = 0
				G.crystals++; G.gemCount++; G.score += 5
				if (G.gemCount % GEMS_PER_SEG === 0 && G.tailLen < MAX_TAIL) G.tailLen++
				SFX.gem()
				burst(g.x, g.y, '#ff7ad9', 4, 70, 0.3, 1.5)
			}
		}
		G.gems = G.gems.filter((g) => g.life > 0)
		// own tail
		for (let i = 6; i < G.segs.length; i++) {
			const sg = G.segs[i]
			if (Math.hypot(dW(s.x, sg.x, W), dW(s.y, sg.y, H)) < HEAD_R + SEG_R - 1) { G.tailBit = sg; endGame('tail'); break }
		}
		// waves
		if (G.waveState === 'break') {
			G.breakT -= dt
			if (G.breakT <= 0) startWave()
		} else {
			G.spawnT -= dt
			if (G.queue.length && G.spawnT <= 0) {
				const k = G.queue.pop()
				if (k === 'boss') spawnRock(3, true); else spawnRock(k)
				G.spawnT = Math.max(0.55, 2.2 - G.wave * 0.1) * rr(0.7, 1.2)
			}
			if (!G.queue.length && !G.rocks.some((r) => !r.dead)) {
				G.waveState = 'break'; G.breakT = 4
				const bonus = 3 + G.wave
				G.crystals += bonus; G.score += 100 * G.wave
				core.hp = Math.min(core.max, core.hp + 8)
				for (const t of G.towers) t.hp = t.maxhp
				banner(`WAVE ${G.wave} CLEARED`)
				say(`+${bonus} CRYSTALS, TOWERS REPAIRED`)
				SFX.up()
			}
		}
		if (core.hp <= 0) { core.hp = 0; endGame('core') }
		if (G.state === 'play') {
			if (G.hintT > 0) G.hintT -= dt
		}
	}

	function stepFx(dt) {
		for (const p of G.parts) { p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= Math.exp(-2 * dt); p.vy *= Math.exp(-2 * dt); p.life -= dt }
		G.parts = G.parts.filter((p) => p.life > 0)
		for (const r of G.rings) r.life -= dt
		G.rings = G.rings.filter((r) => r.life > 0)
		G.shake = Math.max(0, G.shake - dt * 30)
		G.banner.t = Math.max(0, G.banner.t - dt)
		G.toast.t = Math.max(0, G.toast.t - dt)
	}

	function stepAmbient(dt) {
		for (const a of G.ambient) {
			a.x = wrapX(a.x + a.vx * dt); a.y = wrapY(a.y + a.vy * dt); a.rot += a.vr * dt
		}
	}

	// ---------- rendering ----------
	function strokeGlow(color, w, fn) {
		ctx.lineJoin = 'round'; ctx.lineCap = 'round'
		ctx.globalAlpha = 0.22; ctx.lineWidth = w + 5; ctx.strokeStyle = color; fn(); ctx.stroke()
		ctx.globalAlpha = 1; ctx.lineWidth = w; fn(); ctx.stroke()
	}
	function wrapDraw(x, y, r, fn) {
		const xs = [0], ys = [0]
		if (x < r) xs.push(W); else if (x > W - r) xs.push(-W)
		if (y < r) ys.push(H); else if (y > H - r) ys.push(-H)
		for (const ox of xs) for (const oy of ys) fn(x + ox, y + oy)
	}
	function drawRock(rk) {
		ctx.save()
		ctx.translate(rk.x, rk.y); ctx.rotate(rk.rot)
		const color = rk.hit > 0 ? '#ffffff' : rk.slow > 0 ? '#9bd1ff' : rk.boss ? '#ff8a5f' : '#aab8d6'
		const path = () => { ctx.beginPath(); rk.shape.forEach((p, i) => (i ? ctx.lineTo(p[0], p[1]) : ctx.moveTo(p[0], p[1]))); ctx.closePath() }
		path(); ctx.fillStyle = rk.boss ? '#2a1620' : '#0f1630'; ctx.fill()
		strokeGlow(color, rk.boss ? 3 : 2, path)
		if (rk.max > 1 && rk.hp < rk.max) {
			ctx.globalAlpha = 0.7; ctx.strokeStyle = color; ctx.lineWidth = 1.2
			ctx.beginPath(); ctx.moveTo(-rk.r * 0.3, -rk.r * 0.1); ctx.lineTo(rk.r * 0.1, rk.r * 0.2); ctx.lineTo(rk.r * 0.35, rk.r * 0.1); ctx.stroke(); ctx.globalAlpha = 1
		}
		ctx.restore()
	}
	function drawGem(g) {
		const a = g.life < 3 ? (Math.sin(G.t * 18) > 0 ? 1 : 0.3) : 1
		ctx.save(); ctx.translate(g.x, g.y); ctx.rotate(g.rot); ctx.globalAlpha = a
		const path = () => { ctx.beginPath(); ctx.moveTo(0, -7); ctx.lineTo(5, 0); ctx.lineTo(0, 7); ctx.lineTo(-5, 0); ctx.closePath() }
		path(); ctx.fillStyle = '#ff7ad9'; ctx.fill(); strokeGlow('#ffc2f0', 1.4, path)
		ctx.restore()
	}
	function drawTower(t) {
		const def = TOWER[t.type], c = t.hit > 0 ? '#ffffff' : def.color
		ctx.save(); ctx.translate(t.x, t.y)
		const pop = Math.min(1, t.born * 5), sc = 0.6 + 0.4 * pop
		ctx.scale(sc, sc)
		ctx.globalAlpha = 0.13; ctx.fillStyle = def.color; ctx.beginPath(); ctx.arc(0, 0, 15, 0, TAU); ctx.fill(); ctx.globalAlpha = 1
		let path
		if (t.type === 'pulse') path = () => { ctx.beginPath(); for (let i = 0; i < 6; i++) { const a = (i / 6) * TAU; i ? ctx.lineTo(Math.cos(a) * 11, Math.sin(a) * 11) : ctx.moveTo(Math.cos(a) * 11, Math.sin(a) * 11) } ctx.closePath() }
		else if (t.type === 'cannon') path = () => { ctx.beginPath(); ctx.rect(-10, -10, 20, 20) }
		else path = () => { ctx.beginPath(); ctx.moveTo(0, -13); ctx.lineTo(10, 0); ctx.lineTo(0, 13); ctx.lineTo(-10, 0); ctx.closePath() }
		path(); ctx.fillStyle = '#0b1328'; ctx.fill(); strokeGlow(c, 2.2, path)
		if (t.type !== 'frost') {
			ctx.rotate(t.ang)
			ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(t.type === 'cannon' ? 17 : 15, 0)
			ctx.strokeStyle = c; ctx.lineWidth = t.type === 'cannon' ? 5 : 3; ctx.lineCap = 'round'; ctx.stroke()
			ctx.rotate(-t.ang)
		} else {
			ctx.beginPath(); ctx.arc(0, 0, 3, 0, TAU); ctx.fillStyle = c; ctx.fill()
		}
		for (let i = 0; i < t.lvl; i++) { ctx.beginPath(); ctx.arc(-6 + i * 6, 17, 2, 0, TAU); ctx.fillStyle = c; ctx.fill() }
		ctx.restore()
		if (t.hp < t.maxhp) {
			ctx.fillStyle = '#00000088'; ctx.fillRect(t.x - 12, t.y - 21, 24, 3)
			ctx.fillStyle = t.hp / t.maxhp > 0.4 ? '#7dff9a' : '#ff5f7a'; ctx.fillRect(t.x - 12, t.y - 21, 24 * (t.hp / t.maxhp), 3)
		}
	}
	function drawCore() {
		const c = G.core, hpf = c.hp / c.max, pulse = 1 + Math.sin(G.t * 3) * 0.05
		ctx.save(); ctx.translate(c.x, c.y)
		for (const rad of [70, 110]) { ctx.beginPath(); ctx.arc(0, 0, rad, 0, TAU); ctx.strokeStyle = 'rgba(94,242,255,0.07)'; ctx.lineWidth = 1; ctx.stroke() }
		const col = c.flash > 0 ? '#ffffff' : '#ff9ad5'
		ctx.globalAlpha = 0.16; ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, c.r * 1.6 * pulse, 0, TAU); ctx.fill(); ctx.globalAlpha = 1
		const path = () => { ctx.beginPath(); ctx.moveTo(0, -c.r * pulse); ctx.lineTo(c.r * 0.85 * pulse, 0); ctx.lineTo(0, c.r * pulse); ctx.lineTo(-c.r * 0.85 * pulse, 0); ctx.closePath() }
		path(); ctx.fillStyle = '#2a0f2e'; ctx.fill(); strokeGlow(col, 3, path)
		ctx.beginPath(); ctx.arc(0, 0, 6, 0, TAU); ctx.fillStyle = col; ctx.fill()
		ctx.beginPath(); ctx.arc(0, 0, c.r + 9, -Math.PI / 2, -Math.PI / 2 + TAU * hpf)
		ctx.strokeStyle = hpf > 0.5 ? '#7dff9a' : hpf > 0.25 ? '#ffd24d' : '#ff5f7a'; ctx.lineWidth = 4; ctx.lineCap = 'round'; ctx.stroke()
		ctx.restore()
	}
	function drawShip(dim) {
		const s = G.ship
		if (s.inv > 0 && Math.floor(G.t * 16) % 2 === 0) return
		wrapDraw(s.x, s.y, 24, (x, y) => {
			ctx.save(); ctx.translate(x, y); ctx.rotate(s.a)
			if (s.thrust > 0.05 || dim === 0) {
				const f = 8 + Math.random() * 7 * Math.max(s.thrust, 0.3)
				ctx.beginPath(); ctx.moveTo(-8, -4); ctx.lineTo(-8 - f, 0); ctx.lineTo(-8, 4)
				ctx.fillStyle = '#ffb347'; ctx.fill()
			}
			const path = () => { ctx.beginPath(); ctx.moveTo(13, 0); ctx.lineTo(-9, -9); ctx.lineTo(-4, 0); ctx.lineTo(-9, 9); ctx.closePath() }
			path(); ctx.fillStyle = '#0d2b2a'; ctx.fill(); strokeGlow('#c8fff0', 2.2, path)
			ctx.restore()
		})
	}
	function drawTail() {
		const segs = G.segs
		if (!segs.length) return
		// body line
		ctx.lineCap = 'round'; ctx.lineJoin = 'round'
		let prev = { x: G.ship.x, y: G.ship.y }
		for (let i = 0; i < segs.length; i++) {
			const sg = segs[i], d = Math.hypot(dW(prev.x, sg.x, W), dW(prev.y, sg.y, H))
			if (d < SPACING * 2) {
				ctx.beginPath(); ctx.moveTo(prev.x, prev.y); ctx.lineTo(prev.x + dW(prev.x, sg.x, W), prev.y + dW(prev.y, sg.y, H))
				ctx.strokeStyle = 'rgba(46,230,200,0.35)'; ctx.lineWidth = 6; ctx.stroke()
			}
			prev = sg
		}
		for (let i = segs.length - 1; i >= 0; i--) {
			const sg = segs[i], f = i / Math.max(1, segs.length - 1)
			const gunner = i % 3 === 2
			const col = (G.segFlash[i] || 0) > 0 ? '#ffffff' : gunner ? '#b6ff7a' : `hsl(${160 - f * 25},85%,${62 - f * 14}%)`
			wrapDraw(sg.x, sg.y, 10, (x, y) => {
				ctx.beginPath(); ctx.arc(x, y, SEG_R * (1 - f * 0.18) * ((G.segFlash[i] || 0) > 0 ? 1.35 : 1), 0, TAU)
				ctx.fillStyle = col; ctx.fill()
				ctx.lineWidth = 1.5; ctx.strokeStyle = '#06241f'; ctx.stroke()
				if (gunner) { ctx.beginPath(); ctx.arc(x, y, 2, 0, TAU); ctx.fillStyle = '#ff7a3d'; ctx.fill() }
			})
		}
		if (G.tailBit && G.state !== 'play') {
			ctx.beginPath(); ctx.arc(G.tailBit.x, G.tailBit.y, 12 + Math.sin(G.t * 20) * 3, 0, TAU); ctx.strokeStyle = '#ff5f7a'; ctx.lineWidth = 3; ctx.stroke()
		}
	}
	function drawWorld() {
		ctx.drawImage(stars, 0, 0)
		const sh = G.shake
		ctx.setTransform(dpr * scale, 0, 0, dpr * scale, (rand() - 0.5) * sh * dpr, (rand() - 0.5) * sh * dpr)
		// ambient rocks on title
		for (const a of G.ambient) { const rk = { x: a.x, y: a.y, rot: a.rot, shape: a.shape, r: a.r, hit: 0, slow: 0, boss: false, max: 1, hp: 1 }; drawRock(rk) }
		if (G.state !== 'title') drawCore()
		// frost / range rings for nearby towers
		for (const t of G.towers) {
			if (t.type === 'frost') {
				ctx.beginPath(); ctx.arc(t.x, t.y, towerStat(t, 'range'), 0, TAU)
				ctx.fillStyle = 'rgba(155,209,255,0.06)'; ctx.fill(); ctx.strokeStyle = 'rgba(155,209,255,0.25)'; ctx.lineWidth = 1; ctx.stroke()
			}
		}
		if (G.state === 'play') {
			const t = nearTower(G.ship.x, G.ship.y, 30)
			if (t) {
				ctx.beginPath(); ctx.arc(t.x, t.y, towerStat(t, 'range'), 0, TAU); ctx.setLineDash([4, 6]); ctx.strokeStyle = TOWER[t.type].color + '66'; ctx.lineWidth = 1; ctx.stroke(); ctx.setLineDash([])
			}
		}
		for (const t of G.towers) drawTower(t)
		for (const g of G.gems) drawGem(g)
		for (const rk of G.rocks) drawRock(rk)
		for (const b of G.bullets) {
			ctx.beginPath(); ctx.arc(b.x, b.y, b.big ? 3.6 : 2.2, 0, TAU); ctx.fillStyle = b.color; ctx.fill()
			ctx.globalAlpha = 0.3; ctx.beginPath(); ctx.arc(b.x, b.y, b.big ? 7 : 4.5, 0, TAU); ctx.fill(); ctx.globalAlpha = 1
		}
		if (G.state === 'play' || G.state === 'dying' && G.dyingT > 0.8 || G.state === 'paused') { drawTail(); drawShip() }
		for (const r of G.rings) {
			const k = 1 - r.life / r.max
			ctx.globalAlpha = (1 - k) * 0.8; ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU); ctx.strokeStyle = r.color; ctx.lineWidth = 2; ctx.stroke()
		}
		for (const p of G.parts) { ctx.globalAlpha = clamp(p.life / p.max, 0, 1); ctx.fillStyle = p.color; ctx.fillRect(p.x - p.size / 2, p.y - p.size / 2, p.size, p.size) }
		ctx.globalAlpha = 1
		// screen-space overlays
		ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
		const st = input.stick
		if (st && G.state === 'play') {
			const dx = st.x - st.ox, dy = st.y - st.oy, d = Math.hypot(dx, dy), k = d > 50 ? 50 / d : 1
			ctx.beginPath(); ctx.arc(st.ox, st.oy, 50, 0, TAU); ctx.strokeStyle = 'rgba(200,230,255,0.35)'; ctx.lineWidth = 2; ctx.stroke()
			ctx.beginPath(); ctx.arc(st.ox, st.oy, 50, 0, TAU); ctx.fillStyle = 'rgba(200,230,255,0.05)'; ctx.fill()
			ctx.beginPath(); ctx.arc(st.ox + dx * k, st.oy + dy * k, 20, 0, TAU); ctx.fillStyle = 'rgba(200,230,255,0.35)'; ctx.fill()
		}
		// banner and toast
		if (G.banner.t > 0 && (G.state === 'play')) {
			const a = Math.min(1, G.banner.t * 2, (2.2 - G.banner.t) * 4)
			ctx.globalAlpha = clamp(a, 0, 1); ctx.fillStyle = '#e8f4ff'; ctx.textAlign = 'center'
			ctx.font = `800 ${Math.min(34, vw / 12)}px ui-monospace, Menlo, monospace`
			ctx.fillText(G.banner.text, vw / 2, vh * 0.3); ctx.globalAlpha = 1
		}
		if (G.toast.t > 0 && G.state === 'play') {
			ctx.globalAlpha = clamp(G.toast.t * 3, 0, 1); ctx.textAlign = 'center'
			ctx.font = `700 13px ui-monospace, Menlo, monospace`
			ctx.fillStyle = G.toast.bad ? '#ff8a9a' : '#9dffd0'
			ctx.fillText(G.toast.text, vw / 2, vh - 112 - (document.documentElement.classList.contains('touch') ? 0 : 0)); ctx.globalAlpha = 1
		}
		if (G.state === 'play' && G.hintT > 0) {
			ctx.globalAlpha = clamp(G.hintT, 0, 1); ctx.textAlign = 'center'; ctx.fillStyle = '#c9dcff'
			ctx.font = `600 13px ui-monospace, Menlo, monospace`
			const lines = pointerCoarse
				? ['Drag anywhere to steer', 'Push far to boost', 'Collect pink crystals', 'Tap a button to drop a tower', 'Whip your tail into rocks', 'Never touch it with your head']
				: ['Arrows or A/D turn, Up or W boost', 'Collect pink crystals', 'Press 1, 2, 3 to drop towers', 'Whip your tail into rocks', 'Never touch it with your head']
			lines.forEach((l, i) => ctx.fillText(l, vw / 2, vh * 0.6 + i * 20)); ctx.globalAlpha = 1
		}
	}

	// ---------- HUD ----------
	const el = { coreBar: $('coreBar'), wave: $('wave'), score: $('score'), gems: $('gems'), hi: $('hiTitle'), bar: $('buildBar') }
	const hudCache = {}
	function setText(id, v) { if (hudCache[id] !== v) { hudCache[id] = v; $(id).textContent = v } }
	function updateHud() {
		const c = G.core
		const f = Math.max(0, c.hp / c.max)
		const w = Math.round(f * 100) + '%'
		if (hudCache.cb !== w) { hudCache.cb = w; el.coreBar.style.width = w; el.coreBar.className = f > 0.5 ? '' : f > 0.25 ? 'mid' : 'low' }
		setText('wave', String(Math.max(1, G.wave)))
		setText('score', String(G.score))
		setText('gems', String(G.crystals))
		const s = G.ship
		const under = G.state === 'play' ? nearTower(s.x, s.y, 30) : null
		for (const b of el.bar.querySelectorAll('button')) {
			const a = b.dataset.act
			let cost, lab = ''
			if (TOWER[a]) {
				if (under && under.type === a) { const u = upgradeCost(under); cost = u == null ? 0 : u; lab = u == null ? 'MAX' : 'UP ' + u } else cost = TOWER[a].cost
			} else if (a === 'repair') cost = REPAIR_COST
			else cost = G.gunLvl >= 4 ? 0 : GUN_COSTS[G.gunLvl - 1]
			const text = lab || (a === 'gun' && G.gunLvl >= 4 ? 'MAX' : a === 'gun' ? 'L' + (G.gunLvl + 1) + ' ' + cost : String(cost))
			const cEl = b.querySelector('.c')
			if (cEl.textContent !== text) cEl.textContent = text
			const poor = cost > 0 && G.crystals < cost
			b.classList.toggle('poor', poor)
			b.classList.toggle('hot', !!lab && lab !== 'MAX' && !poor)
		}
	}

	// ---------- screens ----------
	const screens = { title: $('title'), how: $('how'), pause: $('pause'), over: $('over') }
	function show(name) {
		for (const k in screens) screens[k].hidden = k !== name
		document.body.dataset.screen = name || ''
	}
	function toTitle() {
		document.body.classList.remove('playing')
		G = newGame(); G.state = 'title'
		G.ambient = []
		for (let i = 0; i < 7; i++) { const r = rr(14, 34); G.ambient.push({ x: rand() * W, y: rand() * H, vx: rr(-18, 18), vy: rr(-18, 18), rot: rand(), vr: rr(-0.6, 0.6), r, shape: makeShape(r) }) }
		el.hi.textContent = String(Number(store.get(KEYS.hi) || 0))
		show('title')
	}
	function startGame() {
		audio()
		const keepAmbient = []
		G = newGame(); G.state = 'play'; G.ambient = keepAmbient
		G.hintT = store.get(KEYS.seen) ? 0 : 7
		store.set(KEYS.seen, '1')
		hudCache.wave = null
		show('')
		document.body.classList.add('playing')
		SFX.build()
	}
	function pauseGame(auto) {
		if (!G || G.state !== 'play') return
		G.state = 'paused'
		input.stick = null; pointers.clear(); input.left = input.right = input.up = false
		show('pause')
		void auto
	}
	function resumeGame() {
		if (!G || G.state !== 'paused') return
		G.state = 'play'; show(''); audio()
	}
	function finishOver() {
		G.state = 'over'
		const hi = Number(store.get(KEYS.hi) || 0)
		const best = Math.max(hi, G.score)
		if (G.score > hi) store.set(KEYS.hi, String(G.score))
		$('overReason').textContent = G.over === 'tail' ? 'You bit your own tail.' : 'Your core was destroyed.'
		$('overScore').textContent = String(G.score)
		$('overWave').textContent = String(Math.max(1, G.wave))
		$('overTail').textContent = String(G.tailKills)
		$('overBest').textContent = String(best)
		$('overNew').hidden = !(G.score > hi && G.score > 0)
		document.body.classList.remove('playing')
		show('over')
	}

	// ---------- events ----------
	function screenToWorld(x, y) { return { x: x / scale, y: y / scale } }
	canvas.addEventListener('pointerdown', (e) => {
		audio()
		if (!G || G.state !== 'play') return
		e.preventDefault()
		try { canvas.setPointerCapture(e.pointerId) } catch {}
		pointers.set(e.pointerId, { x: e.clientX, y: e.clientY, t: performance.now(), moved: 0 })
		if (!input.stick) input.stick = { id: e.pointerId, ox: e.clientX, oy: e.clientY, x: e.clientX, y: e.clientY }
	})
	canvas.addEventListener('pointermove', (e) => {
		const p = pointers.get(e.pointerId)
		if (!p) return
		e.preventDefault()
		p.moved = Math.max(p.moved, Math.hypot(e.clientX - p.x, e.clientY - p.y))
		const st = input.stick
		if (st && st.id === e.pointerId) {
			st.x = e.clientX; st.y = e.clientY
			const dx = st.x - st.ox, dy = st.y - st.oy, d = Math.hypot(dx, dy)
			if (d > 70) { st.ox += (dx / d) * (d - 70); st.oy += (dy / d) * (d - 70) }
		}
	})
	function endPointer(e) {
		const p = pointers.get(e.pointerId)
		pointers.delete(e.pointerId)
		if (input.stick && input.stick.id === e.pointerId) input.stick = null
		if (p && G && G.state === 'play' && performance.now() - p.t < 280 && p.moved < 12) {
			const w = screenToWorld(e.clientX, e.clientY)
			const t = nearTower(w.x, w.y, 26)
			if (t) tryUpgrade(t)
		}
	}
	canvas.addEventListener('pointerup', endPointer)
	canvas.addEventListener('pointercancel', endPointer)
	canvas.addEventListener('contextmenu', (e) => e.preventDefault())
	// no zoom or scroll gestures
	for (const ev of ['gesturestart', 'gesturechange', 'gestureend']) document.addEventListener(ev, (e) => e.preventDefault())
	document.addEventListener('touchmove', (e) => { if (!e.target.closest('.scroll')) e.preventDefault() }, { passive: false })
	// Double-tap zoom is blocked by touch-action (none on the page, manipulation on buttons) plus the viewport meta.
	document.addEventListener('dblclick', (e) => e.preventDefault())
	document.addEventListener('wheel', (e) => { if (e.ctrlKey) e.preventDefault() }, { passive: false })

	const KEYMAP = { ArrowLeft: 'left', KeyA: 'left', ArrowRight: 'right', KeyD: 'right', ArrowUp: 'up', KeyW: 'up' }
	addEventListener('keydown', (e) => {
		if (e.ctrlKey || e.metaKey || e.altKey) return
		audio()
		const st = G && G.state
		if (KEYMAP[e.code]) { input[KEYMAP[e.code]] = true; if (st === 'play') e.preventDefault(); return }
		if (e.code === 'Space' || e.code === 'Enter') {
			if (st === 'title' && document.activeElement === document.body) { e.preventDefault(); startGame() }
			else if (st === 'over' && document.activeElement === document.body) { e.preventDefault(); startGame() }
			else if (st === 'paused' && document.activeElement === document.body) { e.preventDefault(); resumeGame() }
			return
		}
		if (e.code === 'Escape' || e.code === 'KeyP') { if (st === 'play') pauseGame(); else if (st === 'paused') resumeGame(); else if (st === 'title' && !screens.how.hidden) show('title'); return }
		if (e.code === 'KeyM') { toggleMute(); return }
		if (st !== 'play') return
		if (e.code === 'Digit1') build('pulse')
		else if (e.code === 'Digit2') build('cannon')
		else if (e.code === 'Digit3') build('frost')
		else if (e.code === 'Digit4' || e.code === 'KeyR') repair()
		else if (e.code === 'Digit5' || e.code === 'KeyG') gunUp()
		else if (e.code === 'KeyE' || e.code === 'KeyU') upgradeNearest()
	})
	addEventListener('keyup', (e) => { if (KEYMAP[e.code]) input[KEYMAP[e.code]] = false })
	addEventListener('blur', () => { input.left = input.right = input.up = false; pauseGame(true) })
	document.addEventListener('visibilitychange', () => { if (document.hidden) pauseGame(true) })
	addEventListener('pagehide', () => pauseGame(true))
	addEventListener('resize', () => { resize() })
	addEventListener('orientationchange', () => setTimeout(resize, 150))
	if (window.visualViewport) window.visualViewport.addEventListener('resize', resize)

	$('playBtn').addEventListener('click', startGame)
	$('howBtn').addEventListener('click', () => show('how'))
	$('howBack').addEventListener('click', () => show(G && G.state === 'paused' ? 'pause' : 'title'))
	$('howBtn2').addEventListener('click', () => show('how'))
	$('resumeBtn').addEventListener('click', resumeGame)
	$('quitBtn').addEventListener('click', toTitle)
	$('againBtn').addEventListener('click', startGame)
	$('menuBtn').addEventListener('click', toTitle)
	$('pauseBtn').addEventListener('click', () => pauseGame())
	$('muteBtn').addEventListener('click', toggleMute)
	// Build buttons: act on pointerdown so a tap while steering with the other thumb is instant.
	for (const b of el.bar.querySelectorAll('button')) {
		b.addEventListener('pointerdown', (e) => {
			e.preventDefault(); audio()
			const a = b.dataset.act
			if (TOWER[a]) build(a); else if (a === 'repair') repair(); else if (a === 'gun') gunUp()
		})
		b.addEventListener('click', (e) => e.preventDefault())
	}

	// ---------- loop ----------
	let last = performance.now()
	function frame(now) {
		const dt = Math.min(0.033, (now - last) / 1000)
		last = now
		G.t += dt
		if (G.state === 'play') stepPlay(dt)
		else if (G.state === 'dying') {
			G.dyingT -= dt
			stepPlay_dying(dt)
			if (G.dyingT <= 0) finishOver()
		} else if (G.state === 'title') stepAmbient(dt)
		if (G.state !== 'paused') stepFx(dt)
		drawWorld()
		updateHud()
		requestAnimationFrame(frame)
	}
	function stepPlay_dying(dt) {
		for (const rk of G.rocks) { rk.x += rk.vx * dt * 0.3; rk.y += rk.vy * dt * 0.3; rk.rot += rk.vr * dt }
	}

	// ---------- debug / test hooks (read-mostly, no secrets) ----------
	window.__starsnake = {
		get state() { return G.state },
		get snap() {
			return { state: G.state, score: G.score, wave: G.wave, crystals: G.crystals, tail: G.tailLen, towers: G.towers.length, rocks: G.rocks.length, tailKills: G.tailKills, rockHp: G.rocks[0] ? G.rocks[0].hp : 0,
				core: G.core.hp, gun: G.gunLvl, ship: { x: Math.round(G.ship.x), y: Math.round(G.ship.y), a: +G.ship.a.toFixed(2) }, over: G.over, world: [Math.round(W), Math.round(H)] }
		},
		start: startGame,
		give(n) { G.crystals += n },
		setTail(n) { G.tailLen = n },
		build, repair, gunUp,
		scene() { // staged scene used for the social preview art
			startGame()
			G.hintT = 0; G.crystals = 40; G.wave = 6; G.score = 2840; G.tailLen = 22; G.gunLvl = 3; G.core.hp = 78; G.waveState = 'fight'; G.queue = [3, 3, 2]
			G.banner.t = 0
			const cx = G.core.x, cy = G.core.y
			const T = (dx, dy, type, lvl) => G.towers.push({ x: cx + dx, y: cy + dy, type, lvl, cd: rand(), hp: 60, maxhp: 60, ang: rand() * TAU, hit: 0, born: 9 })
			T(-95, -60, 'pulse', 2); T(100, -40, 'cannon', 2); T(-70, 90, 'frost', 2); T(85, 100, 'pulse', 3); T(0, -130, 'cannon', 1); T(-150, 20, 'pulse', 1)
			const s = G.ship; s.x = cx + 120; s.y = cy + 200; s.a = -0.9; s.vx = 0; s.vy = 0
			G.trail = []; for (let i = 0; i < 360; i++) { const a = i * 0.02; G.trail.push({ x: s.x - 150 * Math.sin(a * 3) * 0.5 - i * 0.2 + 40 * Math.cos(a * 5), y: s.y + i * 1.1 }) }
			const mk = (dx, dy, size, vx, vy) => { addRock(cx + dx, cy + dy, vx, vy, size) }
			mk(-210, -250, 3, 20, 30); mk(190, -300, 3, -15, 25); mk(-60, -330, 2, 5, 30); mk(240, 20, 2, -30, 5); mk(-250, 110, 1, 28, -4); mk(30, -230, 1, 4, 28)
			for (let i = 0; i < 7; i++) G.gems.push({ x: cx + rr(-180, 180), y: cy + rr(-160, 200), vx: 0, vy: 0, life: 20, rot: rand() * TAU })
			G.spawnT = 99
			for (let i = 0; i < 6; i++) { stepFx(0.05) }
			G.state = 'play'
		},
		tailTest(size) { // test hook: park a rock on the tail so the tail has to deal with it
			G.rocks = []; G.towers = []; G.queue = []; G.waveState = 'break'; G.breakT = 99
			G.core.cd = 99
			const sg = G.segs[Math.min(8, G.segs.length - 1)]
			addRock(sg.x, sg.y, 0, 0, size)
			G.rocks[0].safe = 0
			return { rock: { hp: G.rocks[0].hp, size }, tail: G.tailLen }
		},
		rockToTail() { // test hook: move surviving rocks back onto a tail bead
			const sg = G.segs[Math.min(8, G.segs.length - 1)]
			for (const r of G.rocks) { r.x = sg.x; r.y = sg.y; r.vx = 0; r.vy = 0 }
		},
		freeze() { G.state = 'paused'; show('') },
	}

	// ---------- boot ----------
	updateMuteBtn()
	resize()
	toTitle()
	if (params.has('autostart')) startGame()
	requestAnimationFrame((t) => { last = t; requestAnimationFrame(frame) })
})()