CUT THE CORD

by Betaaj Baadshah in Design > Software

858 Views, 2 Favorites, 0 Comments

CUT THE CORD

This contest celebrates "the freedom that comes with cutting the cord". So I built exactly that, literally.

CUT THE CORD is a neon top-down escape game where you play as a desk power bank that snips its own charging cable at midnight and fights its way out of an office building to reach the sun. The whole contest theme is the plot: beyond the wall outlet and into the world.

The twist that makes it unique: your battery charge is ONE resource that is simultaneously your health, your ammo, your stamina, your light radius, and your money. Everything you do spends your own body. Every mechanic in the game is real battery physics: self-discharge, thermal runaway, short circuits, induction charging, solar power. Each of the 7 levels opens with a true battery fact, so you finish the game slightly smarter about batteries than when you started.

There is no game engine, no downloaded art, no sound files. Every pixel is drawn by code on an HTML canvas and every sound is synthesized live with the Web Audio API. The entire game is two files you can read, and it runs in any browser, even offline.

You may skip to Step 10 to play the game, then come back and build it from scratch.

Supplies

SUPPLIES:

  1. Any modern browser (Chrome, Edge, Firefox) or a phone in landscape; it has full touch controls
  2. Any plain text editor (Notepad or VS Code)
  3. That's genuinely it. No installs, no accounts, no libraries.

Turn the Theme Into a Character

Every game needs a hook. Mine came straight from the contest description: "batteries help your project move beyond the wall outlet and into the world."

So the hero IS a battery. Not a robot powered by one. The battery itself: a little power bank with LED eyes whose first act in the game is cutting its own charging cord (that's the title screen: press ENTER and scissors do the rest).

The design rule I committed to before writing any code: the battery's charge must be the ONLY resource in the game. No separate health bar, no ammo pickups, no stamina wheel. If the player wants to do anything: shoot, dash, see in the dark, open a door (they pay for it in charge).

That one decision creates all the tension: a battery that does nothing still dies slowly, and a battery that does everything dies fast.


One Resource to Rule Them All

Here is how one number (0–100%) becomes five game systems:

  1. HEALTH — enemy hits drain charge. At 0% you flatline.
  2. AMMO — every spark bolt you fire costs 1.2%.
  3. STAMINA — every dash costs 2.5%.
  4. LIGHT — your glow radius is literally (70 + charge × 2) pixels. Full battery = lighthouse. Dying battery = candle.
  5. CURRENCY — wall sockets open locked doors, but they charge YOU 12–16% per door.

And you get charge back the same way real devices do: you eat loose AA cells (+15%), stand on induction pads, and you stun hostile office machines (robo-vacuums, hover-zappers, security turrets) and vampire-drain their packs while they're stunned. In the screenshot you can see the "[HOLD E] DRAIN" prompt next to a stunned robo-vacuum, and the yellow wall socket that opens door A.

The core cost code is tiny: this is the entire "everything drains you" economy:

// self-discharge: even standing still costs charge
P.charge -= (0.45 + (moving ? 0.18 : 0)) * dt;

// shooting costs body
P.shootCD = 0.19; P.charge -= 1.2; addHeat(8);

// dashing costs body
P.charge -= 2.5; addHeat(16);

// your light IS your charge
function lightRadius() { return 70 + P.charge * 2.0; }

Real Battery Physics As Game Mechanics

I wanted the game to be honest about how batteries actually behave, so every hazard is borrowed from a datasheet:

  1. SELF-DISCHARGE — you lose ~0.45%/second doing nothing, because real cells do the same on a shelf.
  2. THERMAL RUNAWAY — shooting and dashing generate HEAT. Hit 100% and you go into a 2.6-second
  3. THERMAL LOCKOUT — no weapons, no dash, half speed, smoke particles, exactly like a li-ion pack tripping its thermal cutoff. In the server-farm level the ambient is 41°C, so heat barely dissipates and you must fire in bursts. In the screenshot I've overheated at 47% charge with turret bolts incoming, which is the worst moment of my life.
  4. SHORT CIRCUITS — water puddles drain 10%/second on contact. Stay dry.
  5. INDUCTION — glowing Qi pads trickle-charge you if you stand still on them (and standing still is exactly when the vacuums find you).
  6. SOLAR — the final level's sunlit ground feeds you 10%/second, because sunlight really does deliver ~1000 W/m² for free.

The whole thermal system is ~10 lines:

function addHeat(h) {
P.heat += h; P.lastHeat = 0;
if (P.heat >= 100 && P.locked <= 0) {
P.locked = 2.6; // thermal cutoff tripped
P.heat = 100;
sfx.lock();
}
}
// heat only dissipates after 0.4s without firing/dashing,
// multiplied by the level's ambient (0.42 in the server farm)
P.heat = Math.max(0, P.heat - 14 * L.heatMul * dt);

Levels Are Just Text (And Each One Teaches a Fact)

All 7 levels THE DESK, OPEN OFFICE, THE SERVER FARM, MAINTENANCE, SECURITY, THE LOBBY, DAYLIGHT are drawn as plain ASCII text right inside the code. Every character is one floor tile:

'########################', # wall . floor
'#......#...............#', P you X exit
'#..P...#...*...........#', * AA cell W water
'#......#.......######..#', I induction S solar ground
'#...........*..#....#..#', A-D doors a-d matching sockets
'#..####........#.*..#..#', r vacuum z zapper t turret

This means anyone can design a new level in VS Code in five minutes.

Want a door? Type "A" in a wall and put an "a" socket somewhere reachable. I even wrote a little validator script that flood-fills each map from P to prove the exit is reachable through the correct door-unlock order (it caught one of my own rooms being sealed shut. Computers are humbling, right?).

Each level begins with a card like the one in the screenshot: a real battery fact tied to the mechanic you're about to face self-discharge, Volta's 1800 pile, energy density of an AA cell (~10 kJ, enough to lift a car a metre!), Qi induction, thermal runaway, and solar flux.

It's a game that smuggles in a science lesson.

Light and Sound From Nothing

Two tricks give the game its atmosphere, and neither uses a single asset file:

DARKNESS THAT OBEYS YOUR CHARGE. Every frame, a black overlay covers the level, then radial-gradient "holes" get punched out of it, one around you (sized by your charge), plus small ones around sockets, induction pads and the exit. In the basement level (see the screenshot. I'm at 38% and nearly blind) this turns your battery percentage into pure fear. The renderer is ~15 lines using canvas' destination-out composite mode.

SOUND FROM MATH. There are no .mp3 files. Every sound is an oscillator synthesized at the moment it plays:

function tone(f0, f1, dur, type, vol) {
const o = audioCtx.createOscillator(), g = audioCtx.createGain();
o.type = type; // square, sine, sawtooth
o.frequency.setValueAtTime(f0, t); // start pitch
o.frequency.exponentialRampToValueAtTime(f1, t + dur); // slide
g.gain.exponentialRampToValueAtTime(0.0001, t + dur); // fade
o.connect(g); g.connect(audioCtx.destination);
o.start(t); o.stop(t + dur);
}

shoot() { tone(950, 240, 0.08, 'square', 0.05); } // pew
socket() { tone(200, 900, 0.35, 'sine', 0.12); } // power surge
dead() { tone(400, 40, 1.1, 'sawtooth', 0.15); } // flatline

A pitch that slides down = impact. A pitch that slides up = power. That one function makes the entire soundtrack, plus a slow procedural bass pulse for music.

The Complete Code (Two Files)

The whole game is two files. Create a folder, then create each file in VS Code, paste, and save. That's the entire installation.

FILE 1 — save as: index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CUT THE CORD — you are the battery</title>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<style>
html,body{margin:0;padding:0;height:100%;background:#04050a;overflow:hidden;touch-action:none;-webkit-user-select:none;user-select:none}
#wrap{height:100%;display:flex;align-items:center;justify-content:center}
canvas{display:block;background:#04050a;cursor:crosshair;width:min(100vw,160vh);height:auto}
</style>
</head>
<body>
<div id="wrap"><canvas id="cv" width="960" height="600"></canvas></div>
<script src="game.js"></script>
</body>
</html>


FILE 2 — save as: game.js (create it inside the same/parent folder)

Since this file is worth more than 1400 lines of code, so I have turned it into three smaller sections.

Section 1 (game.js)

'use strict';

const cv = document.getElementById('cv'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height, TS = 40, TAU = Math.PI * 2;

// ---------- utils ----------
const clamp = (v, a, b) => v < a ? a : v > b ? b : v;
const lerp = (a, b, t) => a + (b - a) * t;
const dist = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);
const rnd = (a, b) => a + Math.random() * (b - a);

// ---------- audio (all synthesized) ----------
let AC = null, muted = false;
function ac() {
if (!AC) AC = new (window.AudioContext || window.webkitAudioContext)();
if (AC.state === 'suspended') AC.resume();
return AC;
}
function tone(f0, f1, dur, type, vol, delay) {
if (muted) return;
try {
const a = ac(), t = a.currentTime + (delay || 0);
const o = a.createOscillator(), g = a.createGain();
o.type = type;
o.frequency.setValueAtTime(Math.max(f0, 1), t);
o.frequency.exponentialRampToValueAtTime(Math.max(f1, 1), t + dur);
g.gain.setValueAtTime(vol, t);
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
o.connect(g); g.connect(a.destination);
o.start(t); o.stop(t + dur + 0.03);
} catch (e) {}
}
const sfx = {
shoot() { tone(950, 240, 0.08, 'square', 0.05); },
ehit() { tone(300, 90, 0.12, 'sawtooth', 0.08); },
stun() { tone(600, 80, 0.35, 'sawtooth', 0.09); tone(1200, 160, 0.3, 'square', 0.05, 0.05); },
boom() { tone(140, 30, 0.5, 'sawtooth', 0.16); tone(90, 25, 0.6, 'square', 0.12, 0.03); },
hurt() { tone(200, 60, 0.2, 'sawtooth', 0.13); },
cell() { tone(660, 660, 0.07, 'sine', 0.12); tone(990, 990, 0.1, 'sine', 0.12, 0.07); },
drainTick(p) { tone(300 + 400 * p, 340 + 430 * p, 0.05, 'sine', 0.07); },
socket() { tone(200, 900, 0.35, 'sine', 0.12); tone(60, 55, 0.25, 'square', 0.12, 0.3); },
dash() { tone(400, 900, 0.1, 'sine', 0.05); },
lock() { tone(880, 440, 0.18, 'square', 0.1); tone(880, 440, 0.18, 'square', 0.1, 0.22); },
dead() { tone(400, 40, 1.1, 'sawtooth', 0.15); },
snip() { tone(1400, 200, 0.12, 'square', 0.12); tone(900, 80, 0.2, 'sawtooth', 0.1, 0.06); },
zap() { tone(1600, 300, 0.14, 'sawtooth', 0.06); },
win() { [523, 659, 784, 1047, 1319].forEach((f, i) => tone(f, f, 0.22, 'square', 0.09, i * 0.13)); }
};
// minimal procedural music: slow bass pulse + sparse pings
let musT = 0, beat = 0;
const bassNotes = [55, 55, 65.4, 49];
function music(dt) {
if (muted || ST !== 'play') return;
musT -= dt;
if (musT <= 0) {
musT = 0.32; beat++;
const bar = (beat >> 3) % 4;
if (beat % 2 === 0) tone(bassNotes[bar], bassNotes[bar], 0.3, 'sine', 0.05);
if (beat % 8 === 3) tone(bassNotes[bar] * 4, bassNotes[bar] * 4, 0.14, 'triangle', 0.028);
if (beat % 16 === 10) tone(bassNotes[bar] * 6, bassNotes[bar] * 6, 0.14, 'triangle', 0.022);
}
}

// ---------- input ----------
const keys = {};
const mouse = { x: W / 2, y: H / 2, down: false };
addEventListener('keydown', e => {
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].includes(e.code)) e.preventDefault();
if (e.code === 'KeyM' && !e.repeat) { muted = !muted; toast(muted ? 'MUTED' : 'SOUND ON'); }
if (e.repeat) return;
keys[e.code] = true;
onKey(e.code);
});
addEventListener('keyup', e => { keys[e.code] = false; });
cv.addEventListener('mousemove', e => {
const r = cv.getBoundingClientRect();
mouse.x = (e.clientX - r.left) * (W / r.width);
mouse.y = (e.clientY - r.top) * (H / r.height);
});
cv.addEventListener('mousedown', () => { mouse.down = true; ac(); onKey('Mouse'); });
addEventListener('mouseup', () => { mouse.down = false; });

// ---------- touch (mobile, landscape) ----------
let TOUCH = false;
const joy = { active: false, ox: 0, oy: 0, dx: 0, dy: 0 };
const BTN = {
dash: { x: W - 76, y: H - 172, r: 40, label: 'DASH', col: '#29f5ff' },
act: { x: W - 172, y: H - 76, r: 40, label: 'USE', col: '#5dff6e' },
pause: { x: W - 28, y: 84, r: 20 }
};
const touchRoles = {};
function cvPos(t) {
const r = cv.getBoundingClientRect();
return { x: (t.clientX - r.left) * (W / r.width), y: (t.clientY - r.top) * (H / r.height) };
}
function tryImmersive() {
try {
if (!document.fullscreenElement && document.documentElement.requestFullscreen)
document.documentElement.requestFullscreen().catch(() => {});
if (screen.orientation && screen.orientation.lock)
screen.orientation.lock('landscape').catch(() => {});
} catch (e) {}
}
cv.addEventListener('touchstart', e => {
e.preventDefault(); TOUCH = true; ac();
for (const t of e.changedTouches) {
const p = cvPos(t);
if (ST !== 'play') {
touchRoles[t.identifier] = 'ui';
if (ST === 'title') {
tryImmersive();
if (savedMax() > 0 && p.y > 458 && p.y < 494) { P.charge = 100; showCard(savedMax()); }
else onKey('Enter');
} else if (ST === 'dead') { if (deadT > 0.8) onKey('KeyR'); }
else if (ST === 'pause') ST = 'play';
else onKey('Mouse');
continue;
}
if (dist(p.x, p.y, BTN.pause.x, BTN.pause.y) < BTN.pause.r + 10) { touchRoles[t.identifier] = 'ui'; ST = 'pause'; }
else if (dist(p.x, p.y, BTN.dash.x, BTN.dash.y) < BTN.dash.r + 12) { touchRoles[t.identifier] = 'dash'; keys.ShiftLeft = true; }
else if (dist(p.x, p.y, BTN.act.x, BTN.act.y) < BTN.act.r + 12) { touchRoles[t.identifier] = 'act'; keys.KeyE = true; }
else if (p.x < W * 0.42) { touchRoles[t.identifier] = 'joy'; joy.active = true; joy.ox = p.x; joy.oy = p.y; joy.dx = joy.dy = 0; }
else { touchRoles[t.identifier] = 'aim'; mouse.x = p.x; mouse.y = p.y; mouse.down = true; }
}
}, { passive: false });
cv.addEventListener('touchmove', e => {
e.preventDefault();
for (const t of e.changedTouches) {
const role = touchRoles[t.identifier], p = cvPos(t);
if (role === 'joy') {
let dx = (p.x - joy.ox) / 48, dy = (p.y - joy.oy) / 48;
const l = Math.hypot(dx, dy);
if (l > 1) { dx /= l; dy /= l; }
joy.dx = dx; joy.dy = dy;
} else if (role === 'aim') { mouse.x = p.x; mouse.y = p.y; }
}
}, { passive: false });
function endTouch(e) {
e.preventDefault();
for (const t of e.changedTouches) {
const role = touchRoles[t.identifier];
delete touchRoles[t.identifier];
if (role === 'joy') { joy.active = false; joy.dx = joy.dy = 0; }
else if (role === 'aim') mouse.down = false;
else if (role === 'dash') keys.ShiftLeft = false;
else if (role === 'act') keys.KeyE = false;
}
}
cv.addEventListener('touchend', endTouch, { passive: false });
cv.addEventListener('touchcancel', endTouch, { passive: false });

// ---------- level data ----------
// # wall . floor P start X exit * AA cell W water I induction pad S solar
// A-D doors, a-d matching wall sockets r roomba z zapper t turret
const LEVELS = [
{
name: 'THE DESK', sub: 'floor 4 · your desk · 11:58 PM',
fact: 'BATTERY FACT — SELF-DISCHARGE: every battery slowly drains itself, even doing nothing. A li-ion pack loses charge each month just sitting on a shelf. So will you. Standing still is not safe.',
hint: 'grab loose AA cells to top up · standing still drains you too · reach the EXIT ring',
dark: 0.55, heatMul: 1, socketCost: 12,
map: [
'########################',
'#......#...............#',
'#..P...#...*...........#',
'#......#.......######..#',
'#...........*..#....#..#',
'#..####........#.*..#..#',
'#..#..#........#....#..#',
'#..####..*.....##.###..#',
'#......................#',
'#...............#......#',
'#.......#########......#',
'#...*...#..............#',
'#.......#.........X....#',
'#.......#..............#',
'########################']
},
{
name: 'OPEN OFFICE', sub: 'floor 4 · cubicle farm',
fact: 'BATTERY FACT — THE PRICE OF FREEDOM: a wall outlet delivers effectively unlimited energy. You are leaving that behind. Jack into a SOCKET and spend your own charge to power doors open. Your body is the currency now.',
hint: 'Stun robo-vacuums with sparks, then HOLD E to vampire-drain their charge · sockets open matching doors',
dark: 0.6, heatMul: 1, socketCost: 12,
map: [
'##############################',
'#P.......#..........#.......X#',
'#........#....r.....#........#',
'#........#......*...#........#',
'#...*....#..........A........#',
'#........#..........#........#',
'####.#####..........#........#',
'#..........r........#........#',
'#....##########.....#........#',
'#....#........#..a..#........#',
'#....#...*....#.....#........#',
'#....#........#.....#........#',
'#....#####.####.....#........#',
'#...................#....*...#',
'#......r............#........#',
'#...................#........#',
'##############################']
},
{
name: 'THE SERVER FARM', sub: 'floor 3 · 41°C ambient',
fact: 'BATTERY FACT — THERMAL RUNAWAY: push a lithium cell too hard and it overheats; past a point the reaction feeds itself. Real packs have thermal cutoffs — so do you. In this hot room your HEAT bar barely cools. Fire in bursts. And coolant puddles SHORT-CIRCUIT you — stay dry.',
hint: 'Watch the HEAT bar — overheat means total lockout · water drains you fast',
dark: 0.65, heatMul: 0.42, socketCost: 14,
map: [
'################################',
'#P............#................#',
'#.....W.......#....z...........#',
'#.....W.......#................#',
'#..##########.#..##########....#',
'#..............................#',
'#..##########....##########..*.#',
'#...........W..................#',
'#..##########....##########....#',
'#......*................b......#',
'#..##########....##########....#',
'#..........................z...#',
'#########B######################',
'#....W..........z..............#',
'#...............#####..........#',
'#...............#...#....X.....#',
'#....W......................z..#',
'################################']
},
{
name: 'MAINTENANCE', sub: 'basement · lights out',
fact: 'BATTERY FACT — INDUCTION: wireless Qi chargers push power across an air gap with magnetic fields switching ~100,000 times a second. Stand on the glowing pads to sip charge. One more thing: down here, YOU are the only light source — and your light shrinks as you drain.',
hint: 'Your glow radius = your charge · low charge means near-blindness · pads recharge you slowly',
dark: 0.93, heatMul: 1, socketCost: 14,
map: [
'############################',
'#P...........#..........#.X#',
'#....*.......#..........C..#',
'#............#..........####',
'#..######....#....z........#',
'#..#....#....#.............#',
'#..#.I..#....#.....######..#',
'#..#....#....#.....#....#..#',
'#..######....#.....#.I..#..#',
'#............#.....#....#..#',
'#.....r......#.....##.###..#',
'#............#.............#',
'#....####....#......*......#',
'#....#..#..................#',
'#..z.#..#.......c......r...#',
'############################']
},
{
name: 'SECURITY', sub: 'floor 1 · you were noticed',
fact: 'BATTERY FACT — 1800: Alessandro Volta stacked zinc and copper discs soaked in brine and made the first battery. 226 years later, one of his descendants is shooting its way past the security turrets. Turrets reboot unless you drain them EMPTY.',
hint: 'Turrets have long range but need line of sight · break contact behind cover · drain them dry to kill',
dark: 0.75, heatMul: 1, socketCost: 15,
map: [
'################################',
'#P.......#............#.......X#',
'#........#.....t......#........#',
'#..*.....A............B........#',
'#........#............#........#',
'#..a.....#....######..#........#',
'#........#....#....#..#.....t..#',
'##########....#.b..#..#........#',
'#.........*...#....#..#........#',
'#.............#.##.#..#........#',
'#....t................#........#',
'#.....................#........#',
'#.....######..######..#....t...#',
'#.....#..........*.#..#........#',
'#..z..#............#..#........#',
'#.....##############..#...*....#',
'#.....................#........#',
'################################']
},
{
name: 'THE LOBBY', sub: 'ground floor · so close',
fact: 'BATTERY FACT — ENERGY DENSITY: one AA alkaline cell holds about 10,000 joules — enough to lift a small car a metre off the ground. The loose cells you have been eating are not snacks. They are car-lifters. Now cross the lobby.',
hint: 'Everything is here · the fountain short-circuits · pads are safe harbours · two doors between you and daylight',
dark: 0.7, heatMul: 0.8, socketCost: 16,
map: [
'####################################',
'#P...........#...............#....X#',
'#............#.....t.........#.....#',
'#....*.......#...............#.....#',
'#............#....WWWW.......#.....#',
'#..######....#....WWWW.......#..t..#',
'#..#....#....#...............#.....#',
'#..#.I..#....#...I.......z...#.....#',
'#..#....#....#...............#.....#',
'#..######....A...............B.....#',
'#............#.....b.........#..*..#',
'#.....r......#...............#.....#',
'#............#.....######....#.....#',
'#............#.....#....#....#..I..#',
'#....r.......#.....#.*..#....#.....#',
'#............#.....##.###....#.....#',
'#............#..z............#..t..#',
'#.....*..a...#...............#.....#',
'#............#...............#.....#',
'####################################']
},
{
name: 'DAYLIGHT', sub: 'parking level · the sun is out there',
fact: 'BATTERY FACT — THE SUN: sunlight delivers about 1,000 watts per square metre, for free, forever. Beyond the wall outlet and into the world. The alarm is ringing and everything is hunting you. RUN. The sunlit ground will feed you. Reach the light.',
hint: 'ALARM — every machine knows where you are · sunlit ground recharges you fast · GO',
dark: 0.5, heatMul: 1, socketCost: 15, alarm: true,
map: [
'#######################################',
'#P......#..........#.....SSSSSSSSSSSS.#',
'#.......#....r.....#.....SSSSSSSSSSSS.#',
'#..*....#..........#.....SSSSSSSSSSSS.#',
'#.......#.....##...#.....SSSSSSSSSSSS.#',
'#..............#...#.....SSSSSSSSSSSS.#',
'#...z.....................SSSSSSSSSSS.#',
'#.....................SSSSSSSSSSSSSSX.#',
'#..r......................SSSSSSSSSSS.#',
'#...............#..#..t..SSSSSSSSSSSS.#',
'#..*............#..#.....SSSSSSSSSSSS.#',
'#...............#..#.....SSSSSSSSSSSS.#',
'#....r.....z....#..#.....SSSSSSSSSSSS.#',
'#...............#..#..................#',
'#######################################']
}];

// ---------- game state ----------
let ST = 'title'; // title | snip | card | play | dead | pause | win
let levelIdx = 0, cardT = 0, snipT = 0, deadT = 0, winT = 0, titleT = 0;
let grid = [], gw = 0, gh = 0;
let doors = {}, sockets = [], cells = [], enemies = [], bullets = [], parts = [], floats = [];
let exitPos = null, solarBox = null, padList = [];
let camX = 0, camY = 0, shake = 0, flashA = 0, flashCol = '255,255,255';
let toastMsg = '', toastT = 0, hintT = 0;
const stats = { time: 0, cells: 0, drained: 0, deaths: 0 };
let levelStartCharge = 100;

const P = {
x: 0, y: 0, r: 13, vx: 0, vy: 0,
charge: 100, heat: 0, locked: 0, lastHeat: 0,
dashT: 0, dashCD: 0, ifr: 0, shootCD: 0,
aim: 0, hitCD: 0, drainSnd: 0, blink: 0
};

function toast(m) { toastMsg = m; toastT = 2.2; }
function save() { try { localStorage.setItem('ctc_max', String(Math.max(levelIdx, Number(localStorage.getItem('ctc_max') || 0)))); } catch (e) {} }
function savedMax() { try { return clamp(Number(localStorage.getItem('ctc_max') || 0), 0, LEVELS.length - 1); } catch (e) { return 0; } }

// ---------- level loading ----------
function mkRoomba(x, y) { return { type: 'roomba', x, y, r: 14, hp: 3, maxhp: 3, pool: 22, stun: 0, aggro: 0, dir: rnd(0, TAU), t: rnd(0, 2), spin: 0, hitFlash: 0 }; }
function mkZapper(x, y) { return { type: 'zapper', x, y, r: 12, hp: 2, maxhp: 2, pool: 16, stun: 0, aggro: 0, dir: rnd(0, TAU), t: rnd(0, 2), fireCD: rnd(1, 2), bob: rnd(0, TAU), hitFlash: 0 }; }
function mkTurret(x, y) { return { type: 'turret', x, y, r: 15, hp: 4, maxhp: 4, pool: 30, stun: 0, aggro: 0, aimA: 0, fireCD: 1.5, burst: 0, hitFlash: 0 }; }

function loadLevel(idx) {
const L = LEVELS[idx];
const rows = L.map, h = rows.length;
let w = 0; rows.forEach(r => w = Math.max(w, r.length));
grid = []; doors = {}; sockets = []; cells = []; enemies = []; bullets = []; parts = []; floats = [];
exitPos = null; padList = [];
let sMinX = 1e9, sMinY = 1e9, sMaxX = -1e9, sMaxY = -1e9, hasSolar = false;
for (let y = 0; y < h; y++) {
grid[y] = [];
const row = rows[y];
for (let x = 0; x < w; x++) {
const c = x < row.length ? row[x] : '#';
let t = 'floor';
if (c === '#') t = 'wall';
else if (c === 'W') t = 'water';
else if (c === 'I') t = 'pad';
else if (c === 'S') t = 'solar';
if (c >= 'A' && c <= 'D') {
t = 'door';
if (!doors[c]) doors[c] = { tiles: [], open: false, anim: 0 };
doors[c].tiles.push({ x, y });
}
grid[y][x] = t;
const cx = x * TS + TS / 2, cy = y * TS + TS / 2;
if (t === 'pad') padList.push({ x: cx, y: cy });
if (t === 'solar') { hasSolar = true; sMinX = Math.min(sMinX, cx); sMinY = Math.min(sMinY, cy); sMaxX = Math.max(sMaxX, cx); sMaxY = Math.max(sMaxY, cy); }
if (c === 'P') { P.x = cx; P.y = cy; }
if (c === 'X') exitPos = { x: cx, y: cy };
if (c >= 'a' && c <= 'd') sockets.push({ x: cx, y: cy, door: c.toUpperCase(), used: false, prog: 0 });
if (c === '*') cells.push({ x: cx, y: cy, taken: false, bob: rnd(0, TAU) });
if (c === 'r') enemies.push(mkRoomba(cx, cy));
if (c === 'z') enemies.push(mkZapper(cx, cy));
if (c === 't') enemies.push(mkTurret(cx, cy));
}
}
gw = w; gh = h;
solarBox = hasSolar ? { x: (sMinX + sMaxX) / 2, y: (sMinY + sMaxY) / 2, r: Math.max(sMaxX - sMinX, sMaxY - sMinY) / 2 + 90 } : null;
P.vx = P.vy = 0; P.heat = 0; P.locked = 0; P.dashT = 0; P.dashCD = 0; P.ifr = 0; P.hitCD = 0;
hintT = 7;
}

function startLevel(idx, retry) {
levelIdx = idx;
if (retry) P.charge = levelStartCharge;
else { P.charge = clamp(Math.max(P.charge, 75), 0, 100); levelStartCharge = P.charge; }
loadLevel(idx);
save();
ST = 'play';
}

// ---------- tiles / physics ----------
function tileAt(tx, ty) {
if (ty < 0 || ty >= gh || tx < 0 || tx >= gw) return 'wall';
return grid[ty][tx];
}
function tileOpen(tx, ty) {
const t = tileAt(tx, ty);
if (t === 'wall') return false;
if (t === 'door') {
for (const k in doors) if (doors[k].tiles.some(d => d.x === tx && d.y === ty)) return doors[k].open;
return false;
}
return true;
}
function solidAt(px, py) { return !tileOpen(Math.floor(px / TS), Math.floor(py / TS)); }

function moveEnt(o, dx, dy) {
// axis-separated square-vs-tile pushout
o.x += dx;
let tx0 = Math.floor((o.x - o.r) / TS), tx1 = Math.floor((o.x + o.r) / TS);
let ty0 = Math.floor((o.y - o.r) / TS), ty1 = Math.floor((o.y + o.r) / TS);
for (let ty = ty0; ty <= ty1; ty++) for (let tx = tx0; tx <= tx1; tx++) {
if (!tileOpen(tx, ty)) {
if (dx > 0) o.x = Math.min(o.x, tx * TS - o.r - 0.01);
else if (dx < 0) o.x = Math.max(o.x, tx * TS + TS + o.r + 0.01);
}
}
o.y += dy;
tx0 = Math.floor((o.x - o.r) / TS); tx1 = Math.floor((o.x + o.r) / TS);
ty0 = Math.floor((o.y - o.r) / TS); ty1 = Math.floor((o.y + o.r) / TS);
for (let ty = ty0; ty <= ty1; ty++) for (let tx = tx0; tx <= tx1; tx++) {
if (!tileOpen(tx, ty)) {
if (dy > 0) o.y = Math.min(o.y, ty * TS - o.r - 0.01);
else if (dy < 0) o.y = Math.max(o.y, ty * TS + TS + o.r + 0.01);
}
}
}

function los(x1, y1, x2, y2) {
const d = dist(x1, y1, x2, y2), n = Math.ceil(d / 9);
for (let i = 1; i < n; i++) {
const t = i / n;
if (solidAt(lerp(x1, x2, t), lerp(y1, y2, t))) return false;
}
return true;
}

// ---------- particles / juice ----------
function spark(x, y, n, col, spd, life) {
for (let i = 0; i < n; i++) {
const a = rnd(0, TAU), s = rnd(spd * 0.3, spd);
parts.push({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, life: rnd(life * 0.5, life), max: life, col, sz: rnd(1.5, 3.5) });
}
}
function floatText(x, y, txt, col) { floats.push({ x, y, txt, col, life: 1.1 }); }
function addHeat(h) {
P.heat += h; P.lastHeat = 0;
if (P.heat >= 100 && P.locked <= 0) {
P.locked = 2.6; P.heat = 100; sfx.lock();
floatText(P.x, P.y - 24, 'THERMAL LOCKOUT', '#ff4055');
shake = Math.max(shake, 6);
}
}
function damagePlayer(amt, kx, ky) {
if (P.ifr > 0 || P.hitCD > 0) return;
P.charge -= amt; P.hitCD = 0.35;
P.vx += (kx || 0); P.vy += (ky || 0);
shake = Math.max(shake, 7); flashA = 0.25; flashCol = '255,40,60';
spark(P.x, P.y, 10, '#ff4055', 180, 0.5);
floatText(P.x, P.y - 22, '-' + Math.round(amt) + '%', '#ff4055');
sfx.hurt();
}
function gainCharge(amt) {
P.charge = clamp(P.charge + amt, 0, 100);
}

// ---------- player update ----------
function lightRadius() { return 70 + P.charge * 2.0; }

function updatePlayer(dt) {
const L = LEVELS[levelIdx];
P.aim = Math.atan2(mouse.y + camY - P.y, mouse.x + camX - P.x);
P.ifr = Math.max(0, P.ifr - dt); P.hitCD = Math.max(0, P.hitCD - dt);
P.shootCD = Math.max(0, P.shootCD - dt); P.dashCD = Math.max(0, P.dashCD - dt);
P.blink -= dt; if (P.blink < -3) P.blink = rnd(2, 5);

// heat
P.lastHeat += dt;
if (P.locked > 0) {
P.locked -= dt;
if (Math.random() < dt * 22) parts.push({ x: P.x + rnd(-8, 8), y: P.y + rnd(-10, 4), vx: rnd(-10, 10), vy: rnd(-45, -20), life: rnd(0.4, 0.9), max: 0.9, col: '#8a8f9a', sz: rnd(2, 4) });
if (P.locked <= 0) { P.heat = 30; toast('SYSTEMS BACK ONLINE'); }
} else if (P.lastHeat > 0.4) {
P.heat = Math.max(0, P.heat - 14 * L.heatMul * dt);
}

Section 2 (game.js)

// movement
let mx = 0, my = 0;
if (keys.KeyW || keys.ArrowUp) my -= 1;
if (keys.KeyS || keys.ArrowDown) my += 1;
if (keys.KeyA || keys.ArrowLeft) mx -= 1;
if (keys.KeyD || keys.ArrowRight) mx += 1;
if (joy.active) { mx = joy.dx; my = joy.dy; } // analog stick overrides keys
let mlen = Math.hypot(mx, my);
if (mlen > 1) { mx /= mlen; my /= mlen; mlen = 1; }
let spd = 165 * (P.locked > 0 ? 0.55 : 1);

// tile underfoot
const ut = tileAt(Math.floor(P.x / TS), Math.floor(P.y / TS));
if (ut === 'water') {
spd *= 0.7;
P.charge -= 10 * dt;
if (Math.random() < dt * 14) { spark(P.x, P.y + 8, 2, '#4db6ff', 90, 0.4); if (Math.random() < 0.25) sfx.zap(); }
}
if (ut === 'pad') { gainCharge(7 * dt); if (Math.random() < dt * 5) spark(P.x, P.y, 2, '#29f
5ff', 60, 0.5); }
if (ut === 'solar') { gainCharge(10 * dt); if (Math.random() < dt * 6) spark(P.x, P.y, 2, '#ffe94a', 50, 0.6); }

// dash
if ((keys.ShiftLeft || keys.ShiftRight || keys.Space) && P.dashCD <= 0 && P.locked <= 0 && P.charge > 4) {
P.dashT = 0.16; P.dashCD = 0.55; P.ifr = 0.28;
P.charge -= 2.5; addHeat(16); sfx.dash();
const a = mlen > 0 ? Math.atan2(my, mx) : P.aim;
P.dvx = Math.cos(a); P.dvy = Math.sin(a);
spark(P.x, P.y, 8, '#29f5ff', 140, 0.4);
}
if (P.dashT > 0) {
P.dashT -= dt;
moveEnt(P, P.dvx * 480 * dt, P.dvy * 480 * dt);
if (Math.random() < dt * 40) parts.push({ x: P.x, y: P.y, vx: 0, vy: 0, life: 0.3, max: 0.3, col: '#29f5ff', sz: 6 });
} else {
P.vx = lerp(P.vx, mx * spd, 1 - Math.pow(0.0001, dt));
P.vy = lerp(P.vy, my * spd, 1 - Math.pow(0.0001, dt));
moveEnt(P, P.vx * dt, P.vy * dt);
}

// shoot
if (mouse.down && P.shootCD <= 0 && P.locked <= 0 && P.charge > 3) {
P.shootCD = 0.19; P.charge -= 1.2; addHeat(8); sfx.shoot();
const a = P.aim + rnd(-0.03, 0.03);
bullets.push({ x: P.x + Math.cos(a) * 16, y: P.y + Math.sin(a) * 16, vx: Math.cos(a) * 540, vy: Math.sin(a) * 540, life: 0.85, from: 'p' });
P.vx -= Math.cos(a) * 18; P.vy -= Math.sin(a) * 18;
}

// self-discharge (moving costs a touch more)
P.charge -= (0.45 + (mlen > 0 ? 0.18 : 0)) * dt;

// interact: sockets & stunned enemies
let target = null, tKind = '';
for (const s of sockets) {
if (!s.used && dist(P.x, P.y, s.x, s.y) < 52) { target = s; tKind = 'socket'; break; }
}
if (!target) {
for (const e of enemies) {
if (e.stun > 0 && e.pool > 0 && dist(P.x, P.y, e.x, e.y) < 54) { target = e; tKind = 'drain'; break; }
}
}
P.interact = target ? { t: target, kind: tKind } : null;
if (target && keys.KeyE) {
if (tKind === 'socket') {
const cost = L.socketCost;
if (P.charge < cost + 4) {
if (Math.random() < dt * 2) floatText(target.x, target.y - 26, 'NEED ' + cost + '% CHARGE', '#ff4055');
} else {
target.prog += dt;
spark(target.x, target.y, 1, '#ffe94a', 70, 0.3);
if (target.prog >= 1) {
target.used = true; P.charge -= cost;
const d = doors[target.door];
if (d) { d.open = true; d.anim = 1; }
sfx.socket(); shake = Math.max(shake, 5);
floatText(target.x, target.y - 26, '-' + cost + '% DOOR ' + target.door + ' OPEN', '#ffe94a');
spark(target.x, target.y, 20, '#ffe94a', 200, 0.7);
}
}
} else {
const take = Math.min(26 * dt, target.pool);
target.pool -= take; gainCharge(take * 0.95);
P.drainSnd -= dt;
if (P.drainSnd <= 0) { P.drainSnd = 0.09; sfx.drainTick(1 - target.pool / 30); }
spark(lerp(P.x, target.x, 0.5), lerp(P.y, target.y, 0.5), 1, '#5dff6e', 70, 0.3);
if (target.pool <= 0) {
target.dead = true; stats.drained++;
sfx.boom(); shake = Math.max(shake, 6);
spark(target.x, target.y, 26, '#5dff6e', 240, 0.8);
floatText(target.x, target.y - 20, 'DRAINED DRY', '#5dff6e');
}
}
} else if (target && tKind === 'socket') {
target.prog = Math.max(0, target.prog - dt * 2);
}

// cells
for (const c of cells) {
if (!c.taken && dist(P.x, P.y, c.x, c.y) < 24) {
c.taken = true; gainCharge(15); stats.cells++;
sfx.cell(); floatText(c.x, c.y - 18, '+15%', '#5dff6e');
spark(c.x, c.y, 12, '#5dff6e', 150, 0.5);
}
}

// exit
if (exitPos && dist(P.x, P.y, exitPos.x, exitPos.y) < 30) {
if (levelIdx >= LEVELS.length - 1) { ST = 'win'; winT = 0; sfx.win(); save(); }
else { levelIdx++; save(); showCard(levelIdx); sfx.win(); }
return;
}

// death
if (P.charge <= 0) {
P.charge = 0; stats.deaths++;
ST = 'dead'; deadT = 0; sfx.dead();
spark(P.x, P.y, 30, '#ff4055', 220, 1);
}
}

// ---------- enemies ----------
function detectRange() { return lightRadius() * 0.85 + 55; }

function updateEnemies(dt) {
const L = LEVELS[levelIdx];
for (const e of enemies) {
e.hitFlash = Math.max(0, e.hitFlash - dt);
if (e.stun > 0) {
e.stun -= dt;
if (e.stun <= 0 && e.pool > 0) { e.hp = e.maxhp; e.aggro = 2; spark(e.x, e.y, 8, '#ffb54a', 120, 0.4); }
continue;
}
const dP = dist(e.x, e.y, P.x, P.y);
const sees = (L.alarm || dP < detectRange()) && los(e.x, e.y, P.x, P.y);
if (sees) e.aggro = 2.5; else e.aggro = Math.max(0, e.aggro - dt);

if (e.type === 'roomba') {
e.spin += dt * 6;
if (e.aggro > 0) {
const a = Math.atan2(P.y - e.y, P.x - e.x);
e.dir = a;
moveEnt(e, Math.cos(a) * 92 * dt, Math.sin(a) * 92 * dt);
} else {
e.t -= dt;
if (e.t <= 0) { e.t = rnd(1, 3); e.dir = rnd(0, TAU); }
const ox = e.x, oy = e.y;
moveEnt(e, Math.cos(e.dir) * 45 * dt, Math.sin(e.dir) * 45 * dt);
if (Math.abs(e.x - ox) + Math.abs(e.y - oy) < 44 * dt * 0.5) e.dir = rnd(0, TAU);
}
if (dP < e.r + P.r + 2 && P.hitCD <= 0 && P.ifr <= 0) {
const a = Math.atan2(P.y - e.y, P.x - e.x);
damagePlayer(11, Math.cos(a) * 260, Math.sin(a) * 260);
}
} else if (e.type === 'zapper') {
e.bob += dt * 4;
if (e.aggro > 0) {
const a = Math.atan2(P.y - e.y, P.x - e.x);
const want = dP > 230 ? 1 : (dP < 160 ? -1 : 0);
const strafe = Math.sin(performance.now() / 700 + e.bob) > 0 ? 1 : -1;
const ma = a + strafe * Math.PI / 2 * 0.6;
moveEnt(e, (Math.cos(a) * want * 70 + Math.cos(ma) * 40) * dt, (Math.sin(a) * want * 70 + Math.sin(ma) * 40) * dt);
e.fireCD -= dt;
if (e.fireCD <= 0 && los(e.x, e.y, P.x, P.y)) {
e.fireCD = 2.1; sfx.zap();
bullets.push({ x: e.x, y: e.y, vx: Math.cos(a) * 250, vy: Math.sin(a) * 250, life: 2.4, from: 'e', dmg: 8 });
}
}
} else if (e.type === 'turret') {
const a = Math.atan2(P.y - e.y, P.x - e.x);
if (e.aggro > 0 && dP < 340) {
e.aimA = e.aimA + (((a - e.aimA + Math.PI * 3) % TAU) - Math.PI) * dt * 3;
e.fireCD -= dt;
if (e.fireCD <= 0) { e.fireCD = 2.4; e.burst = 3; }
if (e.burst > 0) {
e.bT = (e.bT || 0) - dt;
if (e.bT <= 0) {
e.bT = 0.14; e.burst--;
if (los(e.x, e.y, P.x, P.y)) {
sfx.zap();
bullets.push({ x: e.x + Math.cos(e.aimA) * 18, y: e.y + Math.sin(e.aimA) * 18, vx: Math.cos(e.aimA) * 300, vy: Math.sin(e.aimA) * 300, life: 2, from: 'e', dmg: 9 });
}
}
}
} else { e.aimA += dt * 0.7; }
}
}
enemies = enemies.filter(e => !e.dead);
}

// ---------- bullets ----------
function updateBullets(dt) {
for (const b of bullets) {
b.x += b.vx * dt; b.y += b.vy * dt; b.life -= dt;
if (solidAt(b.x, b.y)) { b.life = 0; spark(b.x, b.y, 4, b.from === 'p' ? '#29f5ff' : '#ff8a3d', 100, 0.3); continue; }
if (b.from === 'p') {
for (const e of enemies) {
if (dist(b.x, b.y, e.x, e.y) < e.r + 4) {
b.life = 0; e.hitFlash = 0.12;
spark(b.x, b.y, 6, '#29f5ff', 130, 0.35);
if (e.stun <= 0) {
e.hp--;
sfx.ehit();
if (e.hp <= 0) {
e.stun = e.type === 'turret' ? 8 : 6;
sfx.stun();
floatText(e.x, e.y - 20, 'STUNNED — HOLD E TO DRAIN', '#5dff6e');
spark(e.x, e.y, 14, '#ffe94a', 160, 0.5);
}
}
break;
}
}
} else {
if (dist(b.x, b.y, P.x, P.y) < P.r + 4 && P.ifr <= 0) {
b.life = 0;
damagePlayer(b.dmg || 8, b.vx * 0.3, b.vy * 0.3);
}
}
}
bullets = bullets.filter(b => b.life > 0);
}

function updateParts(dt) {
for (const p of parts) { p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.94; p.vy *= 0.94; p.life -= dt; }
parts = parts.filter(p => p.life > 0);
for (const f of floats) { f.y -= 26 * dt; f.life -= dt; }
floats = floats.filter(f => f.life > 0);
}

// ---------- flow ----------
function showCard(idx) { levelIdx = idx; ST = 'card'; cardT = 0; }

function onKey(code) {
if (ST === 'title') {
if (code === 'Enter' || code === 'Mouse') {
ac();
stats.time = 0; stats.cells = 0; stats.drained = 0; stats.deaths = 0;
P.charge = 100;
ST = 'snip'; snipT = 0; sfx.snip();
} else if (code === 'KeyC' && savedMax() > 0) {
ac();
P.charge = 100;
showCard(savedMax());
}
} else if (ST === 'card') {
if (cardT > 0.5) startLevel(levelIdx, false);
} else if (ST === 'dead') {
if (code === 'KeyR' || (deadT > 1 && code === 'Mouse')) { startLevel(levelIdx, true); }
} else if (ST === 'win') {
if (code === 'Enter' || code === 'Mouse') { ST = 'title'; titleT = 0; }
} else if (ST === 'play') {
if (code === 'KeyP' || code === 'Escape') ST = 'pause';
} else if (ST === 'pause') {
if (code === 'KeyP' || code === 'Escape' || code === 'Enter') ST = 'play';
}
}

// ---------- rendering ----------
const dk = document.createElement('canvas'); dk.width = W; dk.height = H;
const dctx = dk.getContext('2d');

function neonText(c, txt, x, y, size, col, blur, align) {
c.save();
c.font = 'bold ' + size + 'px "Courier New",monospace';
c.textAlign = align || 'center';
c.shadowColor = col; c.shadowBlur = blur || 14;
c.fillStyle = col;
c.fillText(txt, x, y);
c.restore();
}
function wrapText(c, txt, x, y, maxW, lh, size, col, align) {
c.save();
c.font = size + 'px "Courier New",monospace';
c.textAlign = align || 'center';
c.fillStyle = col;
const words = txt.split(' ');
let line = '', yy = y;
for (const w2 of words) {
const test = line ? line + ' ' + w2 : w2;
if (c.measureText(test).width > maxW && line) { c.fillText(line, x, yy); yy += lh; line = w2; }
else line = test;
}
if (line) c.fillText(line, x, yy);
c.restore();
return yy;
}

function chargeColor(pct) {
if (pct > 55) return '#5dff6e';
if (pct > 25) return '#ffe94a';
return '#ff4055';
}

function drawBatteryChar(c, x, y, chg, aim, opts) {
opts = opts || {};
const s = opts.scale || 1;
c.save();
c.translate(x, y);
c.scale(s, s);
const locked = opts.locked;
const col = locked ? '#ff4055' : '#29f5ff';
// body
c.shadowColor = col; c.shadowBlur = 16;
c.strokeStyle = col; c.lineWidth = 2.4;
c.fillStyle = '#0a0f1e';
const bw = 24, bh = 32;
c.beginPath();
if (c.roundRect) c.roundRect(-bw / 2, -bh / 2, bw, bh, 5); else c.rect(-bw / 2, -bh / 2, bw, bh);
c.fill(); c.stroke();
// cap
c.fillStyle = col;
c.fillRect(-6, -bh / 2 - 5, 12, 5);
// charge fill
c.shadowBlur = 8;
const fc = chargeColor(chg);
c.fillStyle = fc; c.globalAlpha = 0.85;
const fh = (bh - 8) * clamp(chg / 100, 0, 1);
c.fillRect(-bw / 2 + 4, bh / 2 - 4 - fh, bw - 8, fh);
c.globalAlpha = 1;
// eyes
c.shadowBlur = 0;
const ex = Math.cos(aim) * 2.5, ey = Math.sin(aim) * 2.5;
const blink = opts.blink;
c.fillStyle = '#ffffff';
if (blink) { c.fillRect(-8, -7, 6, 1.6); c.fillRect(2, -7, 6, 1.6); }
else {
c.beginPath(); c.arc(-5, -6, 3.4, 0, TAU); c.arc(5, -6, 3.4, 0, TAU); c.fill();
c.fillStyle = '#0a0f1e';
c.beginPath(); c.arc(-5 + ex, -6 + ey, 1.7, 0, TAU); c.arc(5 + ex, -6 + ey, 1.7, 0, TAU); c.fill();
}
c.restore();
}

function renderWorld(dt) {
const lvW = gw * TS, lvH = gh * TS;
camX = lvW <= W ? (lvW - W) / 2 : clamp(P.x - W / 2, 0, lvW - W);
camY = lvH <= H ? (lvH - H) / 2 : clamp(P.y - H / 2, 0, lvH - H);
const sx = shake > 0 ? rnd(-shake, shake) : 0, sy = shake > 0 ? rnd(-shake, shake) : 0;

ctx.fillStyle = '#04050a';
ctx.fillRect(0, 0, W, H);
ctx.save();
ctx.translate(-camX + sx, -camY + sy);

const x0 = Math.max(0, Math.floor(camX / TS)), x1 = Math.min(gw - 1, Math.floor((camX + W) / TS));
const y0 = Math.max(0, Math.floor(camY / TS)), y1 = Math.min(gh - 1, Math.floor((camY + H) / TS));
const now = performance.now() / 1000;

// floor + tiles
for (let ty = y0; ty <= y1; ty++) for (let tx = x0; tx <= x1; tx++) {
const t = grid[ty][tx], px = tx * TS, py = ty * TS;
if (t === 'wall') continue;
ctx.fillStyle = '#0a0d18';
ctx.fillRect(px, py, TS, TS);
ctx.strokeStyle = 'rgba(41,245,255,0.05)';
ctx.strokeRect(px + 0.5, py + 0.5, TS, TS);
if (t === 'water') {
ctx.fillStyle = 'rgba(40,110,255,0.28)';
ctx.fillRect(px, py, TS, TS);
ctx.strokeStyle = 'rgba(120,190,255,0.4)';
ctx.beginPath();
const wy = py + TS / 2 + Math.sin(now * 2 + tx + ty) * 4;
ctx.moveTo(px + 6, wy); ctx.quadraticCurveTo(px + TS / 2, wy - 5, px + TS - 6, wy);
ctx.stroke();
} else if (t === 'pad') {
const pu = (Math.sin(now * 3 + tx) + 1) / 2;
ctx.strokeStyle = 'rgba(41,245,255,' + (0.35 + pu * 0.45) + ')';
ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(px + TS / 2, py + TS / 2, 8 + pu * 6, 0, TAU); ctx.stroke();
ctx.beginPath(); ctx.arc(px + TS / 2, py + TS / 2, 14, 0, TAU); ctx.stroke();
ctx.lineWidth = 1;
} else if (t === 'solar') {
ctx.fillStyle = 'rgba(255,220,80,0.14)';
ctx.fillRect(px, py, TS, TS);
ctx.strokeStyle = 'rgba(255,230,110,0.25)';
ctx.strokeRect(px + 3.5, py + 3.5, TS - 7, TS - 7);
if (Math.random() < 0.002) spark(px + rnd(5, 35), py + rnd(5, 35), 1, '#ffe94a', 20, 0.8);
}
}
// walls (drawn after floor, neon top edge)
for (let ty = y0; ty <= y1; ty++) for (let tx = x0; tx <= x1; tx++) {
const t = grid[ty][tx], px = tx * TS, py = ty * TS;
if (t === 'wall') {
ctx.fillStyle = '#101528';
ctx.fillRect(px, py, TS, TS);
ctx.strokeStyle = 'rgba(90,120,255,0.35)';
ctx.strokeRect(px + 0.5, py + 0.5, TS - 1, TS - 1);
} else if (t === 'door') {
let d = null;
for (const k in doors) if (doors[k].tiles.some(q => q.x === tx && q.y === ty)) { d = doors[k]; d.letter = k; }
if (d && !d.open) {
ctx.save();
ctx.shadowColor = '#ff3df0'; ctx.shadowBlur = 12;
ctx.fillStyle = '#2a0f2a';
ctx.fillRect(px + 2, py + 2, TS - 4, TS - 4);
ctx.strokeStyle = '#ff3df0'; ctx.lineWidth = 2;
ctx.strokeRect(px + 3, py + 3, TS - 6, TS - 6);
ctx.shadowBlur = 0;
ctx.fillStyle = '#ff3df0';
ctx.font = 'bold 18px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText(d.letter, px + TS / 2, py + TS / 2 + 6);
ctx.restore();
} else if (d && d.anim > 0) {
d.anim -= dt * 1.5;
ctx.globalAlpha = clamp(d.anim, 0, 1);
ctx.fillStyle = '#ff3df0';
ctx.fillRect(px + 2, py + 2, TS - 4, TS - 4);
ctx.globalAlpha = 1;
}
}
}

// exit
if (exitPos) {
const pu = (Math.sin(now * 4) + 1) / 2;
ctx.save();
ctx.shadowColor = '#5dff6e'; ctx.shadowBlur = 20 + pu * 14;
ctx.strokeStyle = '#5dff6e'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.arc(exitPos.x, exitPos.y, 15 + pu * 3, 0, TAU); ctx.stroke();
ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.arc(exitPos.x, exitPos.y, 7, 0, TAU); ctx.stroke();
ctx.shadowBlur = 6;
ctx.fillStyle = '#5dff6e';
ctx.font = 'bold 11px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText(levelIdx >= LEVELS.length - 1 ? 'THE SUN' : 'EXIT', exitPos.x, exitPos.y - 24);
ctx.restore();
}

// sockets
for (const s of sockets) {
ctx.save();
const col = s.used ? '#3a4155' : '#ffe94a';
ctx.shadowColor = col; ctx.shadowBlur = s.used ? 0 : 12;
ctx.fillStyle = '#171a26';
ctx.strokeStyle = col; ctx.lineWidth = 2;
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(s.x - 11, s.y - 13, 22, 26, 4); else ctx.rect(s.x - 11, s.y - 13, 22, 26);
ctx.fill(); ctx.stroke();
ctx.shadowBlur = 0;
ctx.fillStyle = col;
ctx.fillRect(s.x - 5, s.y - 6, 3, 7); ctx.fillRect(s.x + 2, s.y - 6, 3, 7);
ctx.font = 'bold 10px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText(s.door, s.x, s.y + 9);
if (!s.used && s.prog > 0) {
ctx.strokeStyle = '#ffe94a'; ctx.lineWidth = 3;
ctx.beginPath(); ctx.arc(s.x, s.y, 20, -Math.PI / 2, -Math.PI / 2 + TAU * clamp(s.prog, 0, 1)); ctx.stroke();
}
ctx.restore();
}

// cells
for (const c of cells) {
if (c.taken) continue;
const bob = Math.sin(now * 3 + c.bob) * 3;
ctx.save();
ctx.translate(c.x, c.y + bob);
ctx.rotate(Math.sin(now * 1.5 + c.bob) * 0.2);
ctx.shadowColor = '#5dff6e'; ctx.shadowBlur = 10;
ctx.fillStyle = '#0d2413'; ctx.strokeStyle = '#5dff6e'; ctx.lineWidth = 1.6;
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(-5, -9, 10, 18, 3); else ctx.rect(-5, -9, 10, 18);
ctx.fill(); ctx.stroke();
ctx.fillStyle = '#5dff6e';
ctx.fillRect(-2.5, -11.5, 5, 3);
ctx.shadowBlur = 0;
ctx.font = 'bold 8px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText('AA', 0, 3);
ctx.restore();
}

// enemies
for (const e of enemies) {
ctx.save();
ctx.translate(e.x, e.y);
const stunned = e.stun > 0;
const flash = e.hitFlash > 0;
if (e.type === 'roomba') {
const col = stunned ? '#8a8f9a' : (e.aggro > 0 ? '#ff4055' : '#ff8a3d');
ctx.shadowColor = col; ctx.shadowBlur = stunned ? 4 : 12;
ctx.fillStyle = flash ? '#ffffff' : '#191420';
ctx.strokeStyle = col; ctx.lineWidth = 2.2;
ctx.beginPath(); ctx.arc(0, 0, e.r, 0, TAU); ctx.fill(); ctx.stroke();
ctx.shadowBlur = 0;
if (!stunned) {
ctx.rotate(e.spin);
ctx.strokeStyle = 'rgba(255,138,61,0.5)';
ctx.beginPath(); ctx.moveTo(-e.r + 3, 0); ctx.lineTo(e.r - 3, 0); ctx.moveTo(0, -e.r + 3); ctx.lineTo(0, e.r - 3); ctx.stroke();
ctx.rotate(-e.spin);
ctx.fillStyle = col;
ctx.beginPath(); ctx.arc(0, 0, 3, 0, TAU); ctx.fill();
}
} else if (e.type === 'zapper') {
const bobY = stunned ? 6 : Math.sin(now * 4 + e.bob) * 4;
ctx.translate(0, bobY);
const col = stunned ? '#8a8f9a' : '#c26bff';
ctx.shadowColor = col; ctx.shadowBlur = stunned ? 4 : 14;
ctx.fillStyle = flash ? '#ffffff' : '#1a1226';
ctx.strokeStyle = col; ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(0, -e.r); ctx.lineTo(e.r, 0); ctx.lineTo(0, e.r); ctx.lineTo(-e.r, 0); ctx.closePath();
ctx.fill(); ctx.stroke();
ctx.shadowBlur = 0;
if (!stunned) { ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, 3.4, 0, TAU); ctx.fill(); }
} else {
const col = stunned ? '#8a8f9a' : '#ff4055';
ctx.shadowColor = col; ctx.shadowBlur = stunned ? 4 : 12;
ctx.fillStyle = flash ? '#ffffff' : '#1c1218';
ctx.strokeStyle = col; ctx.lineWidth = 2.4;
ctx.fillRect(-e.r, -e.r, e.r * 2, e.r * 2);
ctx.strokeRect(-e.r, -e.r, e.r * 2, e.r * 2);
ctx.shadowBlur = 0;
if (!stunned) {
ctx.strokeStyle = col; ctx.lineWidth = 5;
ctx.beginPath(); ctx.moveTo(0, 0);
ctx.lineTo(Math.cos(e.aimA) * (e.r + 8), Math.sin(e.aimA) * (e.r + 8)); ctx.stroke();
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, 4, 0, TAU); ctx.fill();
}
}
if (stunned && e.pool > 0) {
ctx.fillStyle = '#5dff6e';
ctx.font = 'bold 9px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText('⚡' + Math.ceil(e.pool) + '%', 0, -e.r - 8);
// stun sparks
if (Math.random() < 0.15) spark(e.x + rnd(-10, 10), e.y + rnd(-10, 10), 1, '#ffe94a', 40, 0.3);
}
ctx.restore();
}

Section 3 (game.js)

// bullets
for (const b of bullets) {
ctx.save();
if (b.from === 'p') {
ctx.shadowColor = '#29f5ff'; ctx.shadowBlur = 10;
ctx.strokeStyle = '#9df7ff'; ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(b.x - b.vx * 0.02, b.y - b.vy * 0.02);
ctx.lineTo(b.x, b.y); ctx.stroke();
} else {
ctx.shadowColor = '#ff8a3d'; ctx.shadowBlur = 12;
ctx.fillStyle = '#ffb54a';
ctx.beginPath(); ctx.arc(b.x, b.y, 4.5, 0, TAU); ctx.fill();
}
ctx.restore();
}

// player
drawBatteryChar(ctx, P.x, P.y, P.charge, P.aim, { locked: P.locked > 0, blink: P.blink < 0 });

// interact prompt
if (P.interact) {
const t = P.interact.t;
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 11px "Courier New",monospace'; ctx.textAlign = 'center';
const pu = (Math.sin(now * 6) + 1) / 2;
ctx.globalAlpha = 0.6 + pu * 0.4;
ctx.fillText(P.interact.kind === 'socket' ? '[HOLD E] POWER DOOR — ' + LEVELS[levelIdx].socketCost + '%' : '[HOLD E] DRAIN', t.x, t.y - 30);
ctx.globalAlpha = 1;
}

// particles
for (const p of parts) {
ctx.globalAlpha = clamp(p.life / p.max, 0, 1);
ctx.fillStyle = p.col;
ctx.fillRect(p.x - p.sz / 2, p.y - p.sz / 2, p.sz, p.sz);
}
ctx.globalAlpha = 1;

// float texts
for (const f of floats) {
ctx.globalAlpha = clamp(f.life, 0, 1);
ctx.fillStyle = f.col;
ctx.font = 'bold 12px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText(f.txt, f.x, f.y);
}
ctx.globalAlpha = 1;
ctx.restore();

// ---- darkness ----
const L2 = LEVELS[levelIdx];
dctx.clearRect(0, 0, W, H);
dctx.fillStyle = 'rgba(2,3,12,' + L2.dark + ')';
dctx.fillRect(0, 0, W, H);
dctx.globalCompositeOperation = 'destination-out';
const holes = [{ x: P.x, y: P.y, r: lightRadius() }];
if (exitPos) holes.push({ x: exitPos.x, y: exitPos.y, r: 70 });
for (const s of sockets) if (!s.used) holes.push({ x: s.x, y: s.y, r: 55 });
for (const p of padList) holes.push({ x: p.x, y: p.y, r: 65 });
if (solarBox) holes.push({ x: solarBox.x, y: solarBox.y, r: solarBox.r });
for (const h2 of holes) {
const hx = h2.x - camX, hy = h2.y - camY;
if (hx < -h2.r || hx > W + h2.r || hy < -h2.r || hy > H + h2.r) continue;
const g = dctx.createRadialGradient(hx, hy, h2.r * 0.15, hx, hy, h2.r);
g.addColorStop(0, 'rgba(0,0,0,1)');
g.addColorStop(1, 'rgba(0,0,0,0)');
dctx.fillStyle = g;
dctx.beginPath(); dctx.arc(hx, hy, h2.r, 0, TAU); dctx.fill();
}
dctx.globalCompositeOperation = 'source-over';
ctx.drawImage(dk, 0, 0);
}

function renderHUD() {
const L = LEVELS[levelIdx];
// battery bar
ctx.save();
const bx = 16, by = 14, bw = 150, bh = 22;
const col = chargeColor(P.charge);
ctx.shadowColor = col; ctx.shadowBlur = 8;
ctx.strokeStyle = col; ctx.lineWidth = 2;
ctx.strokeRect(bx, by, bw, bh);
ctx.fillStyle = col;
ctx.fillRect(bx + bw + 2, by + 6, 5, bh - 12);
ctx.shadowBlur = 0;
ctx.globalAlpha = 0.85;
const fw = (bw - 6) * clamp(P.charge / 100, 0, 1);
ctx.fillRect(bx + 3, by + 3, fw, bh - 6);
ctx.globalAlpha = 1;
// segment ticks
ctx.fillStyle = '#04050a';
for (let i = 1; i < 5; i++) ctx.fillRect(bx + (bw / 5) * i - 1, by + 3, 2, bh - 6);
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 12px "Courier New",monospace'; ctx.textAlign = 'left';
ctx.fillText(Math.max(0, Math.ceil(P.charge)) + '%', bx + bw + 14, by + 16);
// low charge warning
if (P.charge < 20 && ST === 'play' && Math.sin(performance.now() / 130) > 0) {
neonText(ctx, 'LOW BATTERY', bx + bw / 2, by + 58, 13, '#ff4055', 10);
}
// heat
const hy = by + bh + 6;
ctx.strokeStyle = P.locked > 0 ? '#ff4055' : 'rgba(255,138,61,0.8)';
ctx.strokeRect(bx, hy, bw, 8);
ctx.fillStyle = P.locked > 0 ? '#ff4055' : '#ff8a3d';
ctx.fillRect(bx + 1, hy + 1, (bw - 2) * clamp(P.heat / 100, 0, 1), 6);
ctx.fillStyle = 'rgba(255,255,255,0.6)';
ctx.font = '9px "Courier New",monospace';
ctx.fillText('HEAT', bx + bw + 14, hy + 8);
if (P.locked > 0 && Math.sin(performance.now() / 100) > 0) {
neonText(ctx, '!! THERMAL LOCKOUT !!', W / 2, 40, 20, '#ff4055', 16);
}
// level name / timer
ctx.textAlign = 'right';
ctx.fillStyle = 'rgba(255,255,255,0.75)';
ctx.font = 'bold 13px "Courier New",monospace';
ctx.fillText((levelIdx + 1) + '/' + LEVELS.length + ' — ' + L.name, W - 16, 26);
ctx.fillStyle = 'rgba(255,255,255,0.4)';
ctx.font = '11px "Courier New",monospace';
const m = Math.floor(stats.time / 60), s = Math.floor(stats.time % 60);
ctx.fillText(m + ':' + (s < 10 ? '0' : '') + s + ' [P]ause [M]ute', W - 16, 42);
// hint
if (hintT > 0) {
ctx.globalAlpha = clamp(hintT, 0, 1);
ctx.fillStyle = 'rgba(4,5,10,0.7)';
const tw = Math.min(W - 60, 760);
ctx.fillRect(W / 2 - tw / 2, H - 46, tw, 30);
ctx.fillStyle = '#9df7ff';
ctx.font = '11px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText(L.hint, W / 2, H - 27);
ctx.globalAlpha = 1;
}
if (L.alarm && Math.sin(performance.now() / 300) > 0.4) {
neonText(ctx, '⚠ ALARM ⚠', W / 2, 26, 15, '#ff4055', 12);
}
// toast
if (toastT > 0) {
ctx.globalAlpha = clamp(toastT, 0, 1);
neonText(ctx, toastMsg, W / 2, 70, 14, '#ffe94a', 10);
ctx.globalAlpha = 1;
}
// touch controls
if (TOUCH) {
for (const b of [BTN.dash, BTN.act]) {
const held = (b === BTN.dash && keys.ShiftLeft) || (b === BTN.act && keys.KeyE);
ctx.globalAlpha = held ? 0.75 : 0.35;
ctx.strokeStyle = b.col; ctx.lineWidth = 2.5;
ctx.beginPath(); ctx.arc(b.x, b.y, b.r, 0, TAU); ctx.stroke();
ctx.fillStyle = b.col;
ctx.font = 'bold 14px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText(b.label, b.x, b.y + 5);
}
ctx.globalAlpha = 0.35;
ctx.strokeStyle = 'rgba(255,255,255,0.9)'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(BTN.pause.x, BTN.pause.y, BTN.pause.r, 0, TAU); ctx.stroke();
ctx.fillStyle = '#fff';
ctx.fillRect(BTN.pause.x - 6, BTN.pause.y - 7, 4, 14);
ctx.fillRect(BTN.pause.x + 2, BTN.pause.y - 7, 4, 14);
ctx.globalAlpha = 1;
if (joy.active) {
ctx.globalAlpha = 0.28;
ctx.strokeStyle = '#9df7ff'; ctx.lineWidth = 2;
ctx.beginPath(); ctx.arc(joy.ox, joy.oy, 48, 0, TAU); ctx.stroke();
ctx.globalAlpha = 0.5; ctx.fillStyle = '#9df7ff';
ctx.beginPath(); ctx.arc(joy.ox + joy.dx * 48, joy.oy + joy.dy * 48, 18, 0, TAU); ctx.fill();
ctx.globalAlpha = 1;
}
}
ctx.restore();
}

function overlayScreen(alpha) {
ctx.fillStyle = 'rgba(2,3,10,' + alpha + ')';
ctx.fillRect(0, 0, W, H);
}

function renderTitle(dt) {
titleT += dt;
ctx.fillStyle = '#04050a'; ctx.fillRect(0, 0, W, H);
const now = performance.now() / 1000;
// grid floor
ctx.strokeStyle = 'rgba(41,245,255,0.06)';
for (let x = 0; x < W; x += 40) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H); ctx.stroke(); }
for (let y = 0; y < H; y += 40) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(W, y); ctx.stroke(); }

const flick = Math.random() < 0.02 ? 0.5 : 1;
ctx.globalAlpha = flick;
neonText(ctx, 'CUT THE CORD', W / 2, 150, 62, '#29f5ff', 30);
ctx.globalAlpha = 1;
neonText(ctx, 'YOU ARE THE BATTERY', W / 2, 192, 17, '#ff3df0', 12);

// scene: battery on left, outlet on right, cord between
const bx = W / 2 - 160, by2 = 330 + Math.sin(now * 2) * 4;
const ox = W / 2 + 200, oy = 322;
// cord
ctx.save();
ctx.strokeStyle = '#ffe94a'; ctx.lineWidth = 3;
ctx.shadowColor = '#ffe94a'; ctx.shadowBlur = 8;
ctx.beginPath();
ctx.moveTo(bx + 14, by2 + 2);
ctx.quadraticCurveTo(W / 2 + 20, by2 + 70 + Math.sin(now * 1.3) * 8, ox - 12, oy);
ctx.stroke();
ctx.restore();
// outlet
ctx.save();
ctx.strokeStyle = '#ffe94a'; ctx.lineWidth = 2; ctx.shadowColor = '#ffe94a'; ctx.shadowBlur = 10;
ctx.fillStyle = '#171a26';
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(ox - 14, oy - 18, 30, 38, 5); else ctx.rect(ox - 14, oy - 18, 30, 38);
ctx.fill(); ctx.stroke();
ctx.shadowBlur = 0; ctx.fillStyle = '#ffe94a';
ctx.fillRect(ox - 6, oy - 9, 4, 9); ctx.fillRect(ox + 4, oy - 9, 4, 9);
ctx.restore();
// dashed cut line + scissors marker
const cutX = W / 2 + 20, cutY = by2 + 52 + Math.sin(now * 1.3) * 6;
ctx.save();
ctx.strokeStyle = 'rgba(255,64,85,' + (0.4 + 0.4 * Math.sin(now * 5)) + ')';
ctx.setLineDash([5, 5]); ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(cutX, cutY - 26); ctx.lineTo(cutX, cutY + 26); ctx.stroke();
ctx.setLineDash([]);
neonText(ctx, '✂', cutX, cutY - 32, 20, '#ff4055', 8);
ctx.restore();
// battery character
drawBatteryChar(ctx, bx, by2, 100, Math.atan2(mouse.y - by2, mouse.x - bx), { scale: 2.2, blink: Math.sin(now * 0.7) > 0.97 });

const pu = (Math.sin(now * 3) + 1) / 2;
ctx.globalAlpha = 0.55 + pu * 0.45;
neonText(ctx, TOUCH ? '[ TAP ] CUT THE CORD' : '[ ENTER ] CUT THE CORD', W / 2, 445, 20, '#5dff6e', 14);
ctx.globalAlpha = 1;
if (savedMax() > 0) {
neonText(ctx, (TOUCH ? 'tap here to continue' : '[ C ] continue') + ' — level ' + (savedMax() + 1) + ': ' + LEVELS[savedMax()].name, W / 2, 476, 12, '#9df7ff', 6);
}
ctx.fillStyle = 'rgba(255,255,255,0.45)';
ctx.font = '11px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText(TOUCH
? 'left thumb: move · right thumb: aim & fire · DASH / USE buttons · charge = health + ammo + stamina + light'
: 'WASD move · mouse aim · LMB spark · SHIFT dash · E interact · charge = health + ammo + stamina + light', W / 2, 530);
ctx.fillText('a battery-powered escape · made for the Instructables Battery-Powered Contest', W / 2, 550);
ctx.fillStyle = 'rgba(255,255,255,0.25)';
ctx.fillText('audio starts on first input · M to mute', W / 2, 575);
}

function renderSnip(dt) {
snipT += dt;
renderTitle(0);
overlayScreen(clamp(snipT * 1.2, 0, 1) * 0.85);
const cutX = W / 2 + 20, cutY = 385;
if (snipT < 0.5) {
spark(0, 0, 0, '', 0, 0); // noop keep parts array warm
for (let i = 0; i < 3; i++) {
ctx.fillStyle = ['#ffe94a', '#ff4055', '#29f5ff'][i % 3];
const a = rnd(0, TAU), r = rnd(2, 40 * snipT * 4);
ctx.fillRect(cutX + Math.cos(a) * r, cutY + Math.sin(a) * r, 3, 3);
}
neonText(ctx, '✂', cutX, cutY, 34, '#ff4055', 16);
}
if (snipT > 0.4) {
neonText(ctx, 'FREE.', W / 2, H / 2, 44, '#5dff6e', 26);
}
if (snipT > 1.1) showCard(0);
}

function renderCard(dt) {
cardT += dt;
const L = LEVELS[levelIdx];
ctx.fillStyle = '#04050a'; ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = 'rgba(41,245,255,0.05)';
for (let x = 0; x < W; x += 40) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, H); ctx.stroke(); }
const a = clamp(cardT * 2, 0, 1);
ctx.globalAlpha = a;
neonText(ctx, 'LEVEL ' + (levelIdx + 1) + ' / ' + LEVELS.length, W / 2, 130, 15, '#ff3df0', 8);
neonText(ctx, L.name, W / 2, 185, 44, '#29f5ff', 24);
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.font = '13px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText(L.sub, W / 2, 214);
ctx.fillStyle = '#ffe94a';
wrapText(ctx, L.fact, W / 2, 280, 640, 20, 13, '#ffe94a');
ctx.fillStyle = '#9df7ff';
wrapText(ctx, '» ' + L.hint, W / 2, 420, 640, 18, 12, '#9df7ff');
if (cardT > 0.5) {
const pu = (Math.sin(performance.now() / 250) + 1) / 2;
ctx.globalAlpha = a * (0.5 + pu * 0.5);
neonText(ctx, '— press any key —', W / 2, 510, 14, '#5dff6e', 8);
}
ctx.globalAlpha = 1;
}

function renderDead(dt) {
deadT += dt;
renderWorld(0);
overlayScreen(clamp(deadT, 0, 0.82));
if (deadT > 0.4) {
neonText(ctx, 'FLATLINED', W / 2, H / 2 - 40, 52, '#ff4055', 26);
ctx.fillStyle = 'rgba(255,255,255,0.7)';
ctx.font = '14px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText('0% — every joule spent. the office keeps you.', W / 2, H / 2 + 4);
const pu = (Math.sin(performance.now() / 250) + 1) / 2;
ctx.globalAlpha = 0.5 + pu * 0.5;
neonText(ctx, '[ R ] reboot level ' + (levelIdx + 1), W / 2, H / 2 + 56, 17, '#5dff6e', 10);
ctx.globalAlpha = 1;
}
}

function renderWin(dt) {
winT += dt;
ctx.fillStyle = '#04050a'; ctx.fillRect(0, 0, W, H);
// sun
const g = ctx.createRadialGradient(W / 2, 180, 10, W / 2, 180, 300);
g.addColorStop(0, 'rgba(255,235,120,0.9)');
g.addColorStop(0.3, 'rgba(255,200,60,0.35)');
g.addColorStop(1, 'rgba(255,200,60,0)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
drawBatteryChar(ctx, W / 2, 300 + Math.sin(performance.now() / 400) * 6, 100, -Math.PI / 2, { scale: 2.6, blink: false });
neonText(ctx, 'YOU CUT THE CORD', W / 2, 90, 40, '#ffe94a', 26);
ctx.fillStyle = 'rgba(255,255,255,0.85)';
ctx.font = '14px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText('beyond the wall outlet and into the world.', W / 2, 122);
const m = Math.floor(stats.time / 60), s = Math.floor(stats.time % 60);
const lines = [
'ESCAPE TIME ' + m + ':' + (s < 10 ? '0' : '') + s,
'AA CELLS EATEN ' + stats.cells,
'MACHINES DRAINED ' + stats.drained,
'FLATLINES ' + stats.deaths
];
ctx.font = 'bold 15px "Courier New",monospace';
ctx.fillStyle = '#9df7ff';
lines.forEach((l, i) => ctx.fillText(l, W / 2, 400 + i * 26));
const pu = (Math.sin(performance.now() / 300) + 1) / 2;
ctx.globalAlpha = 0.5 + pu * 0.5;
neonText(ctx, '[ ENTER ] title', W / 2, 540, 14, '#5dff6e', 8);
ctx.globalAlpha = 1;
ctx.fillStyle = 'rgba(255,255,255,0.3)';
ctx.font = '11px "Courier New",monospace';
ctx.fillText('made for the Instructables Battery-Powered Contest 2026', W / 2, 575);
}

function renderPause() {
renderWorld(0);
renderHUD();
overlayScreen(0.6);
neonText(ctx, 'PAUSED', W / 2, H / 2 - 20, 40, '#29f5ff', 20);
ctx.fillStyle = 'rgba(255,255,255,0.7)';
ctx.font = '13px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText('P / ESC to resume · M mute', W / 2, H / 2 + 20);
ctx.fillText('charge drains even while you think. (not really. but it would.)', W / 2, H / 2 + 44);
}

// scanlines + vignette, applied over everything
function postFX() {
ctx.save();
ctx.globalAlpha = 0.05;
ctx.fillStyle = '#000';
for (let y = 0; y < H; y += 4) ctx.fillRect(0, y, W, 2);
ctx.restore();
const g = ctx.createRadialGradient(W / 2, H / 2, H / 2.2, W / 2, H / 2, H);
g.addColorStop(0, 'rgba(0,0,0,0)');
g.addColorStop(1, 'rgba(0,0,0,0.55)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
if (flashA > 0) {
ctx.fillStyle = 'rgba(' + flashCol + ',' + flashA + ')';
ctx.fillRect(0, 0, W, H);
}
}

// ---------- main loop ----------
let last = performance.now();
function frame(now) {
requestAnimationFrame(frame);
let dt = Math.min((now - last) / 1000, 0.05);
last = now;
shake = Math.max(0, shake - dt * 30);
flashA = Math.max(0, flashA - dt * 1.6);
toastT = Math.max(0, toastT - dt);
hintT = Math.max(0, hintT - dt);

// mobile portrait guard: the HUD layout needs landscape
if (TOUCH && innerHeight > innerWidth) {
ctx.fillStyle = '#04050a'; ctx.fillRect(0, 0, W, H);
neonText(ctx, 'ROTATE YOUR DEVICE', W / 2, H / 2 - 10, 30, '#ffe94a', 16);
ctx.fillStyle = 'rgba(255,255,255,0.6)';
ctx.font = '14px "Courier New",monospace'; ctx.textAlign = 'center';
ctx.fillText('this battery escapes in landscape', W / 2, H / 2 + 28);
return;
}

if (ST === 'play') {
stats.time += dt;
updatePlayer(dt);
if (ST === 'play') {
updateEnemies(dt);
updateBullets(dt);
}
updateParts(dt);
music(dt);
renderWorld(dt);
renderHUD();
} else if (ST === 'title') renderTitle(dt);
else if (ST === 'snip') { updateParts(dt); renderSnip(dt); }
else if (ST === 'card') renderCard(dt);
else if (ST === 'dead') { updateParts(dt); renderDead(dt); }
else if (ST === 'win') renderWin(dt);
else if (ST === 'pause') renderPause();
postFX();
}
requestAnimationFrame(frame);

That's it. No npm, no build step, no server.

I have duly labeled all the sections (audio / input / level data / physics / enemies / rendering) so you can find anything in seconds.

Play It, Tweak It, Escape

A battery's whole life is spent tethered to a wall, waiting. This game is about the other option. Cut the cord. Want to play it right now? Here you go!

TO PLAY: double-click index.html. It opens in your browser and runs offline. Progress auto-saves.

CONTROLS (keyboard): WASD move · mouse aim · left-click fire · SHIFT dash · hold E to drain machines / power doors · P pause · M mute · R reboot after flatlining.

CONTROLS (touch. see the second screenshot for your reference): it also plays on phones in landscape. Left thumb is a virtual joystick, right thumb aims and fires, and there are on-screen DASH and USE buttons. The canvas scales itself to any screen, and portrait mode politely asks you to rotate.

You know, everything is a constant you can edit in VS Code:

  1. Too hard? Lower the self-discharge (search for 0.45).
  2. Want chaos? Raise dash speed (480) or drop the socket costs.
  3. Add a level: copy any map block, draw your own rooms with # and dots, add it to the LEVELS list. The game picks it up automatically.


If you remix it: new levels, new machines, a boss photocopier, I'd love to see it in the comments.