changeset 17:fe680946164b

reorganised repo
author ark
date 2026-10-20 00:12 +0200
parents 30bd10284fd8
children 5dc69898a091
files .hgignore config/game.toml doc/architecture.md doc/art.md doc/roadmap.md doc/sound.md game/index.html game/js/assets.js game/js/audio.js game/js/game.js game/js/input.js game/js/main.js game/js/map.js game/js/monster.js game/js/projectile.js game/js/render.js game/js/storage.js game/js/tower.js game/js/ui.js game/js/util.js game/js/wave.js game/style.css tools/build.py
diffstat 23 files changed, 2085 insertions(+), 39 deletions(-) [+]
line wrap: on
line diff
--- a/.hgignore	Mon Oct 19 23:47:22 2026 +0200
+++ b/.hgignore	Tue Oct 20 00:12:36 2026 +0200
@@ -1,5 +1,4 @@
 .DS_Store
 temp/
-game/
 www/
 dist/
--- a/config/game.toml	Mon Oct 19 23:47:22 2026 +0200
+++ b/config/game.toml	Tue Oct 20 00:12:36 2026 +0200
@@ -1,4 +1,4 @@
-# game settings. tools/build.py checks this file and writes game/data/config.js.
+# game settings. tools/build.py checks this file and writes www/data/config.js.
 #
 # units: distances in map pixels (pixels of the map image as scanned), times
 # in seconds, speeds in map pixels per second.
--- a/doc/architecture.md	Mon Oct 19 23:47:22 2026 +0200
+++ b/doc/architecture.md	Tue Oct 20 00:12:36 2026 +0200
@@ -2,10 +2,11 @@
 ------------
 
 the game is a static html page with plain javascript, drawn on a 2d canvas. it
-uses no javascript libraries and needs no build step to run. a python build
-script prepares everything that can be calculated in advance: processed
-images, map data, route data and the config. its output is committed, so the
-game runs straight from the source tree.
+uses no javascript libraries. a python build script prepares everything that
+can be calculated in advance: processed images, map data, route data and the
+config. it writes them to www/, together with a copy of the hand-written game
+files from game/. www/ is the runnable game. it is not kept in the repository,
+so the game has to be built before it can be run.
 
 this is a plan; nothing is implemented yet.
 
@@ -22,14 +23,15 @@
         game.toml       numbers from balance.md, waves, debug switches
         routes.toml     manual corrections to the extracted routes
     tools/          python build scripts
-    game/           the runnable game, opened as game/index.html
+    game/           hand-written game files
         index.html
         style.css
-        js/             game code, hand-written
-        assets/         processed images (generated, committed)
-        data/           maps.js, sounds.js, config.js (generated, committed)
+        js/             game code
     doc/            design and technical notes
-    www/            copy of game/ prepared for publishing (ignored)
+    www/            the built game, opened as www/index.html (generated, ignored)
+        index.html      copied from game/, as are style.css and js/
+        assets/         processed images
+        data/           maps.js, sounds.js, config.js
     dist/           zip archives for distribution (ignored)
     temp/           scratch files, build previews (ignored)
 
@@ -40,11 +42,11 @@
 running the game
 ----------------
 
-- desktop: open game/index.html directly from disk, or serve the directory
+- desktop: open www/index.html directly from disk, or serve the directory
   with any static web server
 - tablet: tablets cannot easily open local html files, so the game is served
-  over http, from a computer on the home network or from a web host. www/ is
-  the copy meant for that
+  over http, from a computer on the home network or from a web host. the zip
+  in dist/ is meant for that
 - an optional later step makes it installable to the home screen (web app
   manifest, offline cache). that requires https
 
@@ -69,7 +71,7 @@
 page. the ff_screenshot script (in $PATH, ~/bin/ff_screenshot) drives
 headless firefox over marionette and waits before capturing:
 
-    ff_screenshot -w 1024,768 -s 2 file://$PWD/game/index.html temp/splash.png
+    ff_screenshot -w 1024,768 -s 2 file://$PWD/www/index.html temp/splash.png
 
 -w sets the viewport, -s the wait after loading. the game state is not
 reachable from outside, so other screens are reached by tapping: -J runs
@@ -80,7 +82,7 @@
     ff_screenshot -w 1024,768 -s 2 -S 3 -J 'document.getElementById("game")
         .dispatchEvent(new PointerEvent("pointerdown",
         {clientX: 497, clientY: 560, bubbles: true}))' \
-        file://$PWD/game/index.html temp/play.png
+        file://$PWD/www/index.html temp/play.png
 
 `ff_screenshot -h` lists the other options.
 
@@ -100,7 +102,7 @@
 
 steps:
 
-1. sprites: trim transparent edges, write to game/assets/. this covers the
+1. sprites: trim transparent edges, write to www/assets/. this covers the
    icons, buttons and screens, and the digits from art/digits/ as
    digit_NAME_N. make the hp bar variants: the empty part, and the blue bars
    for slowed monsters (art.md)
@@ -117,20 +119,23 @@
     - write a placement grid: cells where a tower footprint fits next to the
       road, within the limits in balance.md. the red path in the mask is the
       centre line of the road; the road's half width is set per map
-5. sounds: embed art/sounds/*.mp3 as base64 in game/data/sounds.js,
+5. sounds: embed art/sounds/*.mp3 as base64 in www/data/sounds.js,
    grouped by event
-6. config: read config/game.toml, check it, write game/data/config.js
+6. config: read config/game.toml, check it, write www/data/config.js
 7. checks: print a summary per map (routes with length and turning, monster
    counts, coins and hp per map against the target) and warn on problems
 8. previews: draw each map with its routes, entrances, exits and placement
    grid into temp/preview/, for checking without starting the game
+9. game files: copy the files in game/ to www/. a file is copied when its
+   time or size differs from the copy. files no longer in game/ are removed
+   from www/, apart from www/assets/ and www/data/
 
 a watch mode (`tools/build.py --watch`) reruns the build when a file in
-config/, art/ or art/sounds/ changes. tuning then means: edit the toml, save, reload the
-browser.
+config/, art/, art/sounds/ or game/ changes. tuning then means: edit the toml,
+save, reload the browser. the same goes for changes to the game code: they
+show in www/ only after the build has copied them.
 
-`tools/publish.py` copies game/ to www/ with debug switches off, and writes a
-zip into dist/.
+`tools/publish.py` writes a zip of www/ into dist/, with debug switches off.
 
 
 routes
@@ -169,7 +174,7 @@
 ------
 
 config/game.toml holds every number in balance.md, the wave lists, and debug
-switches. the build converts it into game/data/config.js. toml allows comments,
+switches. the build converts it into www/data/config.js. toml allows comments,
 so each value can carry its source note (guess, decided).
 
 wave format:
--- a/doc/art.md	Mon Oct 19 23:47:22 2026 +0200
+++ b/doc/art.md	Tue Oct 20 00:12:36 2026 +0200
@@ -53,7 +53,7 @@
 
 files in art/ stay as supplied, apart from the sprites cut from a sheet and
 the sounds cut from the recordings. the build (see architecture.md) writes
-processed copies to game/assets/.
+processed copies to www/assets/.
 
 attn: the source_sheet_* files have the towers t0 and t1 swapped. 
 
--- a/doc/roadmap.md	Mon Oct 19 23:47:22 2026 +0200
+++ b/doc/roadmap.md	Tue Oct 20 00:12:36 2026 +0200
@@ -39,7 +39,7 @@
     - icons, screens and digits as the drawings arrive (art.md)
     - voice recordings as they arrive (sound.md)
 10. publishing
-    - publish script, www/, dist/ zip, hosting for tablet play
+    - publish script, dist/ zip of www/, hosting for tablet play
 11. help page
     - a hint page made from game graphics, no text where a picture will do
     - the tower ranges side by side
--- a/doc/sound.md	Mon Oct 19 23:47:22 2026 +0200
+++ b/doc/sound.md	Tue Oct 20 00:12:36 2026 +0200
@@ -59,7 +59,7 @@
   trims silence, filters low rumble, fades the ends and brings every sound to
   the same peak level. the output is mono mp3, which desktop browsers and
   tablets (including safari) play
-- the build embeds art/sounds/ as base64 in game/data/sounds.js. see
+- the build embeds art/sounds/ as base64 in www/data/sounds.js. see
   architecture.md for why
 
 browsers only play sound after the first user interaction. the play button on
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/index.html	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,30 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
+<title>minor monsters</title>
+<link rel="stylesheet" href="style.css">
+</head>
+<body>
+<canvas id="game"></canvas>
+<!-- plain script tags in a fixed order, so the page runs from disk (architecture.md) -->
+<script src="data/config.js"></script>
+<script src="data/maps.js"></script>
+<script src="data/sounds.js"></script>
+<script src="js/util.js"></script>
+<script src="js/storage.js"></script>
+<script src="js/assets.js"></script>
+<script src="js/audio.js"></script>
+<script src="js/map.js"></script>
+<script src="js/monster.js"></script>
+<script src="js/tower.js"></script>
+<script src="js/projectile.js"></script>
+<script src="js/wave.js"></script>
+<script src="js/game.js"></script>
+<script src="js/render.js"></script>
+<script src="js/ui.js"></script>
+<script src="js/input.js"></script>
+<script src="js/main.js"></script>
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/assets.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,61 @@
+// image loading and the sprite table
+
+window.MM = window.MM || {};
+
+MM.assets = (function () {
+    "use strict";
+
+    var images = {};
+    var cfg = MM.config;
+
+    // load every sprite of the config's sprite table and every map image.
+    // calls done(failed names) once all have loaded or failed.
+    function load(done) {
+        var names = Object.keys(cfg.sprites);
+        var jobs = names.map(function (n) { return [n, "assets/" + n + ".png"]; });
+        MM.maps.forEach(function (m) { jobs.push([m.name, m.image]); });
+        var left = jobs.length, failed = [];
+        jobs.forEach(function (job) {
+            var img = new Image();
+            img.onload = finish;
+            img.onerror = function () { failed.push(job[1]); finish(); };
+            img.src = job[1];
+            images[job[0]] = img;
+        });
+        function finish() {
+            if (--left === 0) done(failed);
+        }
+    }
+
+    function img(name) {
+        return images[name];
+    }
+
+    // sprite size in map pixels at the given scale
+    function size(name, scale) {
+        var s = cfg.sprites[name];
+        return [s[0] * scale, s[1] * scale];
+    }
+
+    // draw a sprite with its pivot at x, y. angle is the direction to face
+    // in radians, ignored for sprites that do not turn. sx, sy stretch the
+    // sprite around its pivot.
+    function draw(ctx, name, x, y, scale, angle, sx, sy) {
+        var image = images[name];
+        if (!image || !image.complete) return;
+        var w = cfg.sprites[name][0] * scale;
+        var h = cfg.sprites[name][1] * scale;
+        var pivot = cfg.art.pivot[name] || [0.5, 0.5];
+        var drawn = cfg.art.angle[name];
+        ctx.save();
+        ctx.translate(x, y);
+        if (drawn !== undefined && angle !== undefined && angle !== null) {
+            ctx.rotate(angle - MM.util.deg(drawn));
+        }
+        if (sx !== undefined) ctx.scale(sx, sy);
+        ctx.drawImage(image, -pivot[0] * w, -pivot[1] * h, w, h);
+        ctx.restore();
+    }
+
+    return { load: load, img: img, size: size, draw: draw };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/audio.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,126 @@
+// sound: recorded sounds from data/sounds.js, placeholder beeps for events
+// without a recording. the player's sound on or off choice is stored with
+// MM.storage; the config's enabled setting applies until the first choice.
+
+window.MM = window.MM || {};
+
+MM.audio = (function () {
+    "use strict";
+
+    var cfg = MM.config.sound;
+    var ctx = null, master = null;
+    var buffers = {};   // event -> decoded recordings
+    var last = {};      // event -> audio clock time of its last play
+    var ends = {};      // event -> audio clock time when its sounds have ended
+    var started = false;
+    var on = MM.storage.get("sound", cfg.enabled);
+
+    // create the audio context and decode the recordings. the browser keeps
+    // the context suspended until unlock() runs in a user interaction.
+    function init() {
+        var AC = window.AudioContext || window.webkitAudioContext;
+        if (!AC) return;
+        ctx = new AC();
+        master = ctx.createGain();
+        master.gain.value = on ? cfg.volume : 0;
+        master.connect(ctx.destination);
+        var sounds = MM.sounds || {};
+        Object.keys(sounds).forEach(function (name) {
+            buffers[name] = [];
+            sounds[name].forEach(function (b64) { decode(name, b64); });
+        });
+    }
+
+    function decode(name, b64) {
+        var bin = atob(b64), bytes = new Uint8Array(bin.length);
+        for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+        // the callback form, as older safari has no promise form
+        ctx.decodeAudioData(bytes.buffer,
+            function (buf) { buffers[name].push(buf); },
+            function () { console.error("sound not decoded:", name); });
+    }
+
+    // call from the play button's handler. sound stays off until then.
+    function start() {
+        started = true;
+        unlock();
+    }
+
+    // call from a pointer or touch handler: browsers start sound only there.
+    // does nothing before start().
+    function unlock() {
+        if (!ctx || !started || ctx.state === "running") return;
+        ctx.resume();
+        // older safari also needs a sound started in the handler
+        var src = ctx.createBufferSource();
+        src.buffer = ctx.createBuffer(1, 1, 22050);
+        src.connect(ctx.destination);
+        src.start(0);
+    }
+
+    // notes of [frequency, seconds] from when on, into out. returns the
+    // total length.
+    function beep(notes, out, when) {
+        var t = when;
+        notes.forEach(function (n) {
+            var osc = ctx.createOscillator(), env = ctx.createGain();
+            osc.type = cfg.beep_wave;
+            osc.frequency.value = n[0];
+            env.gain.setValueAtTime(1, t);
+            env.gain.exponentialRampToValueAtTime(0.001, t + n[1]);
+            osc.connect(env);
+            env.connect(out);
+            osc.start(t);
+            osc.stop(t + n[1]);
+            t += n[1];
+        });
+        return t - when;
+    }
+
+    // play a random recording of the event, or its beep if it has none.
+    // after lists events whose sounds still playing are let finish first.
+    // variants are picked with Math.random, so sound does not change the
+    // game's seeded random numbers.
+    function play(name, after) {
+        if (!on || !ctx || ctx.state !== "running") return;
+        var ev = cfg.event[name];
+        if (!ev) return;
+        var now = ctx.currentTime;
+        if (ev.min_interval && now - last[name] < ev.min_interval) return;
+        last[name] = now;
+        var when = now;
+        (after || []).forEach(function (a) {
+            if (ends[a] > when) when = ends[a];
+        });
+        var gain = ctx.createGain();
+        gain.gain.value = ev.volume;
+        gain.connect(master);
+        var list = buffers[name], length;
+        if (list && list.length) {
+            var src = ctx.createBufferSource();
+            src.buffer = list[Math.floor(Math.random() * list.length)];
+            src.connect(gain);
+            src.start(when);
+            length = src.buffer.duration;
+        } else if (ev.beep) {
+            length = beep(ev.beep, gain, when);
+        } else {
+            return;
+        }
+        ends[name] = Math.max(ends[name] || 0, when + length);
+    }
+
+    function enabled() {
+        return on;
+    }
+
+    // switch sound on or off and store the choice. sounds already playing
+    // are muted at once.
+    function toggle() {
+        on = !on;
+        if (master) master.gain.value = on ? cfg.volume : 0;
+        MM.storage.set("sound", on);
+    }
+
+    return { init: init, start: start, unlock: unlock, play: play, enabled: enabled, toggle: toggle };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/game.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,242 @@
+// game state and rules: coins, hearts, building, upgrading, selling, win
+// and loss
+
+window.MM = window.MM || {};
+
+MM.Game = (function () {
+    "use strict";
+
+    var cfg = MM.config;
+    var dbg = cfg.debug;
+
+    // firstWave counts from 1
+    function Game(mapIndex, seed, firstWave) {
+        var mc = cfg.maps[mapIndex];
+        this.map = new MM.GameMap(mapIndex);
+        this.seed = seed;
+        this.random = MM.util.rng(seed);
+        this.coins = dbg.start_coins >= 0 ? dbg.start_coins : mc.starting_coins;
+        this.hearts = cfg.hearts.per_map;
+        this.monsters = [];
+        this.towers = [];
+        this.projectiles = [];
+        this.flights = [];      // coins flying to the counter
+        this.puffs = [];        // death puffs, {x, y, boss, t}
+        this.waves = new MM.Waves(mapIndex, MM.util.clamp(firstWave - 1, 0, mc.waves.length - 1),
+                                  this.random);
+        this.time = 0;
+        this.paused = false;
+        this.speeds = cfg.controls.speeds.concat(dbg.extra_speeds);
+        this.speedIndex = 0;
+        this.result = null;     // "won" or "lost"
+        this.splash = false;    // splash screen shown over the paused map
+        // player selection: shop tower type, its snapped preview, a built tower
+        this.shop = null;
+        this.preview = null;
+        this.selected = null;
+        this.sellArmed = false; // sell was tapped once and waits for the second tap
+    }
+
+    Game.prototype.speed = function () {
+        return this.speeds[this.speedIndex];
+    };
+
+    Game.prototype.lastMap = function () {
+        return this.map.index === MM.maps.length - 1;
+    };
+
+    // towers cannot be built, upgraded or sold while paused, so pausing
+    // drops the shop choice, its preview and the tower selection
+    Game.prototype.togglePause = function () {
+        this.paused = !this.paused;
+        if (this.paused) {
+            this.shop = null;
+            this.preview = null;
+            this.selected = null;
+            this.sellArmed = false;
+        }
+    };
+
+    Game.prototype.canAfford = function (cost) {
+        return dbg.unlimited_coins || this.coins >= cost;
+    };
+
+    Game.prototype.pay = function (cost) {
+        if (!dbg.unlimited_coins) this.coins -= cost;
+    };
+
+    // one simulation step of dt seconds
+    Game.prototype.step = function (dt) {
+        if (this.result) return;
+        var self = this;
+        this.time += dt;
+        this.waves.update(dt, this.monsters.length, function (kind) {
+            var m = MM.monster.create(self, kind);
+            self.monsters.push(m);
+            MM.audio.play(m.boss ? "boss_enter" : "monster_enter");
+        });
+        this.monsters.forEach(function (m) {
+            if (m.alive && MM.monster.update(m, dt)) self.escape(m);
+        });
+        this.towers.forEach(function (t) { MM.tower.update(t, self, dt); });
+        this.projectiles.forEach(function (p) { MM.projectile.update(p, self, dt); });
+        this.monsters = this.monsters.filter(function (m) { return m.alive; });
+        this.projectiles = this.projectiles.filter(function (p) { return !p.done; });
+        this.flights.forEach(function (f) { f.t += dt; });
+        this.puffs.forEach(function (p) { p.t += dt; });
+        this.puffs = this.puffs.filter(function (p) { return p.t < cfg.animation.death_puff; });
+        var flying = this.flights.length;
+        this.flights = this.flights.filter(function (f) { return f.t < cfg.coins.flight_time; });
+        if (this.flights.length < flying) MM.audio.play("coins_arrive");
+
+        // the end sound waits for the last exit or death sound
+        if (this.hearts <= 0) {
+            this.result = "lost";
+            MM.audio.play("map_lost", ["monster_exit", "boss_exit"]);
+        } else if (this.waves.phase === "done" && this.monsters.length === 0) {
+            this.result = "won";
+            MM.audio.play("map_won", ["monster_die", "boss_die"]);
+        }
+        // the simulation stops here; the coins in flight are counted already
+        if (this.result) {
+            this.flights = [];
+            this.puffs = [];
+        }
+    };
+
+    // a monster reached the exit
+    Game.prototype.escape = function (m) {
+        m.alive = false;
+        MM.audio.play(m.boss ? "boss_exit" : "monster_exit");
+        if (!dbg.no_heart_loss) {
+            this.hearts = Math.max(0, this.hearts - (m.boss ? cfg.hearts.boss : cfg.hearts.monster));
+        }
+    };
+
+    Game.prototype.damage = function (m, amount) {
+        if (!m.alive) return;
+        m.hp -= amount;
+        if (m.hp > 0) {
+            MM.audio.play("monster_hit");
+            return;
+        }
+        m.alive = false;
+        MM.audio.play(m.boss ? "boss_die" : "monster_die");
+        this.puffs.push({ x: m.x, y: m.y, boss: m.boss, t: 0 });
+        // coins count at once; the flying coins only show it (balance.md)
+        this.coins += m.coins;
+        var n = Math.min(m.coins, cfg.coins.max_sprites);
+        for (var i = 0; i < n; i++) {
+            this.flights.push({
+                x: m.x + (this.random() - 0.5) * m.w,
+                y: m.y - m.h / 2 + (this.random() - 0.5) * m.h / 2,
+                sprite: "c" + Math.floor(this.random() * 4),
+                // stagger the coins a little
+                t: -i * 0.05
+            });
+        }
+    };
+
+    Game.prototype.startEarly = function () {
+        var bonus = this.waves.startEarly();
+        this.coins += bonus;
+        if (bonus > 0) MM.audio.play("early_bonus");
+    };
+
+    Game.prototype.towerAt = function (x, y) {
+        var r = cfg.placement.footprint_radius;
+        for (var i = 0; i < this.towers.length; i++) {
+            var t = this.towers[i];
+            if (Math.hypot(t.x - x, t.y - y) <= r) return t;
+        }
+        return null;
+    };
+
+    Game.prototype.chooseShop = function (type) {
+        this.selected = null;
+        this.preview = null;
+        this.shop = this.shop === type ? null : type;
+    };
+
+    // a press on the map at map position x, y. hitRadius is how close the
+    // press must be to the preview to count as a press on it. returns
+    // "preview" for a press on the preview, "place" for any other press
+    // while a shop tower is chosen, and null when the press selected or
+    // deselected a built tower.
+    Game.prototype.pressMap = function (x, y, hitRadius) {
+        var onPreview = this.preview && Math.hypot(this.preview.x - x, this.preview.y - y) <= hitRadius;
+        var t = this.towerAt(x, y);
+        this.sellArmed = false;
+        if (t && !onPreview) {
+            this.shop = null;
+            this.preview = null;
+            this.selected = t === this.selected ? null : t;
+            return null;
+        }
+        this.selected = null;
+        if (!this.shop) return null;
+        return onPreview ? "preview" : "place";
+    };
+
+    // move the preview to the nearest legal position to map position x, y.
+    // where there is none, the preview stays where it was. returns false
+    // when no legal position was found.
+    Game.prototype.movePreview = function (x, y) {
+        if (!this.shop) return false;
+        var pv = this.map.snap(x, y, this.towers);
+        if (!pv) return false;
+        if (this.preview && this.preview.x === pv.x && this.preview.y === pv.y) return true;
+        // t0 draws spikes only towards the path, judged by its top level range
+        var def = cfg.tower[this.shop];
+        if (def.projectile_speed === 0) {
+            pv.sides = this.map.facingSides(pv.x, pv.y, def.range[def.range.length - 1]);
+        }
+        this.preview = pv;
+        return true;
+    };
+
+    // build the shop tower at the preview. returns false when there is no
+    // preview or the tower cannot be afforded.
+    Game.prototype.build = function () {
+        if (!this.shop || !this.preview) return false;
+        var cost = cfg.tower[this.shop].cost[0];
+        if (!this.canAfford(cost)) return false;
+        this.pay(cost);
+        var pv = this.preview;
+        var t = MM.tower.create(this.shop, pv.x, pv.y, pv.sides);
+        t.paid += cost;
+        this.towers.push(t);
+        MM.audio.play("tower_built");
+        this.shop = null;
+        this.preview = null;
+        return true;
+    };
+
+    // upgrade the selected tower by one level
+    Game.prototype.upgrade = function () {
+        var t = this.selected;
+        var cost = t && MM.tower.upgradeCost(t);
+        if (!cost || !this.canAfford(cost)) return;
+        this.pay(cost);
+        t.level++;
+        t.paid += cost;
+        MM.audio.play("tower_upgraded");
+    };
+
+    // the first tap arms selling, the second sells
+    Game.prototype.sell = function () {
+        var t = this.selected;
+        if (!t) return;
+        if (!this.sellArmed) {
+            this.sellArmed = true;
+            return;
+        }
+        this.sellArmed = false;
+        this.coins += MM.tower.refund(t);
+        this.towers.splice(this.towers.indexOf(t), 1);
+        this.selected = null;
+        MM.audio.play("tower_sold");
+    };
+
+    return Game;
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/input.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,168 @@
+// pointer events: mouse and touch alike. hover only highlights the screen
+// buttons and sets the cursor; nothing relies on it
+
+window.MM = window.MM || {};
+
+MM.input = (function () {
+    "use strict";
+
+    // how close a tap must be to the placement preview to build, css pixels
+    var PREVIEW_HIT = 28;
+    // how far a press on the preview may move and still count as a tap that
+    // builds, css pixels. a longer move drags the preview
+    var DRAG_SLOP = 10;
+    var REFUSED_TIME = 500;
+
+    // app: {canvas, view, game(), layout(), and the screen actions play(),
+    // next(), retry(), restart()}
+    function attach(app) {
+        var c = app.canvas;
+        // the press that moves the placement preview, followed until the
+        // pointer is released. other pointers are ignored meanwhile
+        var drag = null;
+
+        function pos(e) {
+            var r = c.getBoundingClientRect();
+            return { x: e.clientX - r.left, y: e.clientY - r.top };
+        }
+
+        c.addEventListener("pointerdown", function (e) {
+            e.preventDefault();
+            MM.audio.unlock();
+            if (drag) return;
+            var p = pos(e);
+            drag = press(app, p.x, p.y);
+            if (!drag) return;
+            drag.id = e.pointerId;
+            // keep receiving the pointer when it leaves the canvas
+            try { c.setPointerCapture(e.pointerId); } catch (err) { /* not supported */ }
+        });
+        c.addEventListener("pointermove", function (e) {
+            var p = pos(e);
+            if (drag && e.pointerId === drag.id) move(app, drag, p.x, p.y);
+            // mouse only: the position for the hover highlight, and the
+            // pointer cursor over buttons
+            if (e.pointerType !== "mouse" || !app.game()) return;
+            app.view.hover = p;
+            c.style.cursor = MM.ui.hit(app.game(), app.layout(), p.x, p.y) ? "pointer" : "";
+        });
+        c.addEventListener("pointerup", function (e) {
+            if (!drag || e.pointerId !== drag.id) return;
+            var p = pos(e);
+            release(app, drag, p.x, p.y);
+            drag = null;
+        });
+        // the browser took the pointer, for example for a system gesture:
+        // the preview stays where it is and nothing is built
+        c.addEventListener("pointercancel", function (e) {
+            if (drag && e.pointerId === drag.id) drag = null;
+        });
+        c.addEventListener("pointerleave", function () {
+            app.view.hover = null;
+            c.style.cursor = "";
+        });
+        // browsers count only some events as a user interaction that may
+        // start sound: pointerdown for the mouse, pointerup and touchend
+        // for touch
+        document.addEventListener("pointerup", MM.audio.unlock);
+        document.addEventListener("touchend", MM.audio.unlock);
+        // block the context menu, double tap zoom and pinch gestures
+        c.addEventListener("contextmenu", function (e) { e.preventDefault(); });
+        c.addEventListener("touchstart", function (e) { e.preventDefault(); }, { passive: false });
+        document.addEventListener("gesturestart", function (e) { e.preventDefault(); });
+        document.addEventListener("dblclick", function (e) { e.preventDefault(); });
+    }
+
+    // map position of css position x, y, or null outside the map
+    function mapPos(game, L, x, y) {
+        var mx = (x - L.ox) / L.scale, my = (y - L.oy) / L.scale;
+        if (mx < 0 || my < 0 || mx > game.map.width || my > game.map.height) return null;
+        return { x: mx, y: my };
+    }
+
+    // a press at css position x, y. buttons and tower selection act at once.
+    // a press on the map while a shop tower is chosen returns the drag that
+    // places the preview:
+    //   game      the game it belongs to
+    //   onPreview the press was on the preview; it builds on release unless
+    //             the pointer moved further than DRAG_SLOP
+    //   moved     the pointer moved further than DRAG_SLOP
+    //   found     a legal position was found during the drag
+    //   sx, sy    css position of the press
+    //   dx, dy    offset from the pointer to the preview in map pixels, so
+    //             a preview grabbed off centre does not jump
+    function press(app, x, y) {
+        var game = app.game(), L = app.layout();
+        var b = MM.ui.hit(game, L, x, y);
+        if (b) {
+            // the play button starts the sound. switching sound on or off
+            // comes first, so the tap is heard when it goes on
+            if (b.id === "play") MM.audio.start();
+            if (b.id === "sound") MM.audio.toggle();
+            MM.audio.play("button_tap");
+            // any other button cancels an armed sell, and any button outside
+            // the tower menu closes it
+            if (b.id !== "sell") game.sellArmed = false;
+            if (b.id !== "sell" && b.id !== "upgrade") game.selected = null;
+            if (b.id === "play") app.play();
+            else if (b.id === "next") app.next();
+            else if (b.id === "retry") app.retry();
+            else if (b.id === "restart") app.restart();
+            else if (b.id === "pause") game.togglePause();
+            else if (b.id === "speed") game.speedIndex = (game.speedIndex + 1) % game.speeds.length;
+            else if (b.id === "early") game.startEarly();
+            else if (b.id === "shop" && !game.paused && game.canAfford(MM.config.tower[b.tower].cost[0])) game.chooseShop(b.tower);
+            else if (b.id === "upgrade") game.upgrade();
+            else if (b.id === "sell") game.sell();
+            return null;
+        }
+        if (game.result || game.paused) return null;
+        var m = mapPos(game, L, x, y);
+        if (!m) {
+            game.sellArmed = false;
+            game.selected = null;
+            return null;
+        }
+        var hitR = Math.max(MM.config.placement.footprint_radius, PREVIEW_HIT / L.scale);
+        var kind = game.pressMap(m.x, m.y, hitR);
+        if (!kind) return null;
+        var d = { game: game, onPreview: kind === "preview", moved: false, found: false,
+                  sx: x, sy: y, dx: 0, dy: 0 };
+        if (d.onPreview) {
+            d.dx = game.preview.x - m.x;
+            d.dy = game.preview.y - m.y;
+            d.found = true;
+        } else {
+            d.found = game.movePreview(m.x, m.y);
+        }
+        return d;
+    }
+
+    // the pointer of a drag moved to css position x, y
+    function move(app, d, x, y) {
+        var game = app.game();
+        if (game !== d.game || game.result || !game.shop) return;
+        if (!d.moved && Math.hypot(x - d.sx, y - d.sy) <= DRAG_SLOP) {
+            // a press on the preview stays a tap until it moves far enough
+            if (d.onPreview) return;
+        } else {
+            d.moved = true;
+        }
+        var m = mapPos(game, app.layout(), x, y);
+        if (m && game.movePreview(m.x + d.dx, m.y + d.dy)) d.found = true;
+    }
+
+    // the pointer of a drag was released at css position x, y. a tap on the
+    // preview builds; a drag that never found a legal position is refused
+    function release(app, d, x, y) {
+        var game = app.game(), L = app.layout();
+        if (game !== d.game || game.result || game.paused) return;
+        var ok = d.onPreview && !d.moved ? game.build() : d.found;
+        if (ok) return;
+        MM.audio.play("placement_refused");
+        app.view.refused = { x: (x - L.ox) / L.scale, y: (y - L.oy) / L.scale,
+                             until: performance.now() + REFUSED_TIME };
+    }
+
+    return { attach: attach };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/main.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,101 @@
+// start-up and main loop
+
+window.MM = window.MM || {};
+
+(function () {
+    "use strict";
+
+    var cfg = MM.config;
+    var STEP = 1 / 60;
+    // most simulation steps per frame and game speed step; the rest of a
+    // long frame is dropped, so the game slows down instead of freezing
+    var MAX_STEPS = 4;
+
+    var canvas = document.getElementById("game");
+    var ctx = canvas.getContext("2d");
+    var game = null;
+    var L = null;
+    var view = { dpr: 1, now: 0, refused: null, hover: null, stats: { ms: 0 } };
+
+    // the first map is the debug start map; only it starts at the debug
+    // start wave
+    var FIRST = MM.util.clamp(cfg.debug.start_map, 0, MM.maps.length - 1);
+
+    function startMap(m) {
+        var seed = cfg.debug.seed || (Math.random() * 4294967296) >>> 0;
+        game = new MM.Game(m, seed, m === FIRST ? cfg.debug.start_wave : 1);
+        resize();
+    }
+
+    // the splash screen over the paused first map
+    function splash() {
+        startMap(FIRST);
+        game.splash = true;
+        game.paused = true;
+    }
+
+    function play() {
+        game.splash = false;
+        game.paused = false;
+    }
+
+    // canvas resolution follows the device pixel ratio
+    function resize() {
+        var w = canvas.clientWidth, h = canvas.clientHeight;
+        view.dpr = window.devicePixelRatio || 1;
+        canvas.width = Math.round(w * view.dpr);
+        canvas.height = Math.round(h * view.dpr);
+        if (game) L = MM.ui.layout(w, h, game.map);
+    }
+
+    var last = 0, acc = 0;
+
+    function frame(now) {
+        var dt = last ? (now - last) / 1000 : 0;
+        last = now;
+        view.now = now;
+        var t0 = performance.now();
+
+        if (!game.paused && !game.result) {
+            var speed = game.speed();
+            acc += dt * speed;
+            var n = 0;
+            while (acc >= STEP && n < MAX_STEPS * speed) {
+                game.step(STEP);
+                acc -= STEP;
+                n++;
+            }
+            if (n >= MAX_STEPS * speed) acc = 0;
+        } else {
+            acc = 0;
+        }
+
+        ctx.setTransform(1, 0, 0, 1, 0, 0);
+        ctx.fillStyle = "#e8e2d4";
+        ctx.fillRect(0, 0, canvas.width, canvas.height);
+        MM.render.draw(ctx, game, L, view);
+        MM.ui.draw(ctx, game, L, view);
+        MM.render.drawFlights(ctx, game, L, view);
+
+        view.stats.ms = view.stats.ms * 0.9 + (performance.now() - t0) * 0.1;
+        requestAnimationFrame(frame);
+    }
+
+    window.addEventListener("resize", resize);
+    MM.audio.init();
+    MM.input.attach({
+        canvas: canvas,
+        view: view,
+        game: function () { return game; },
+        layout: function () { return L; },
+        play: play,
+        next: function () { startMap(game.map.index + 1); },
+        retry: function () { startMap(FIRST); },
+        restart: splash
+    });
+    MM.assets.load(function (failed) {
+        if (failed.length) console.error("images not loaded:", failed);
+        splash();
+        requestAnimationFrame(frame);
+    });
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/map.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,232 @@
+// placement lookup, snapping, route sampling
+
+window.MM = window.MM || {};
+
+MM.Route = (function () {
+    "use strict";
+
+    // sideways offsets on the inside of a bend: share of the distance at
+    // which the offset point would stop moving forward, and how fast the
+    // limit may change per pixel along the route
+    var BEND_SHARE = 0.7;
+    var LIMIT_SLOPE = 0.5;
+
+    // a route from the build: a polyline with cumulative distances, so a
+    // point can be found by the distance walked. maxOffset is the largest
+    // sideways offset that shifted() will be asked for.
+    function Route(data, maxOffset) {
+        var p = data.points;
+        this.xs = [];
+        this.ys = [];
+        this.at = [];
+        var d = 0;
+        for (var i = 0; i < p.length; i += 2) {
+            if (i > 0) d += Math.hypot(p[i] - p[i - 2], p[i + 1] - p[i - 1]);
+            this.xs.push(p[i]);
+            this.ys.push(p[i + 1]);
+            this.at.push(d);
+        }
+        this.length = d;
+        this.value = data.value;
+        this.weight = data.weight;
+        this.sideways(maxOffset);
+    }
+
+    // set up the sideways direction at each point (nx, ny) and how far an
+    // offset may go to the left and right there (left, right)
+    Route.prototype.sideways = function (maxOffset) {
+        var xs = this.xs, ys = this.ys, at = this.at, n = xs.length, i;
+        // direction of travel of segment i, from point i - 1 to point i
+        var tx = [0], ty = [0];
+        for (i = 1; i < n; i++) {
+            var len = at[i] - at[i - 1];
+            tx.push((xs[i] - xs[i - 1]) / len);
+            ty.push((ys[i] - ys[i - 1]) / len);
+        }
+        // at each point, the left side as drawn, averaged over the two
+        // segments that meet there
+        this.nx = [];
+        this.ny = [];
+        for (i = 0; i < n; i++) {
+            var a = Math.max(i, 1), b = Math.min(i + 1, n - 1);
+            var sx = ty[a] + ty[b], sy = -tx[a] - tx[b], sl = Math.hypot(sx, sy);
+            if (sl < 1e-6) { sx = ty[a]; sy = -tx[a]; sl = 1; }
+            this.nx.push(sx / sl);
+            this.ny.push(sy / sl);
+        }
+        // along a segment the sideways direction turns. an offset on the
+        // inside of the turn moves forward at 1 + offset * k of the walking
+        // speed, k being negative on that side. limit the offset at both
+        // ends of the segment so this stays above 1 - BEND_SHARE
+        var left = [], right = [];
+        for (i = 0; i < n; i++) {
+            left.push(maxOffset);
+            right.push(maxOffset);
+        }
+        for (i = 1; i < n; i++) {
+            var k = ((this.nx[i] - this.nx[i - 1]) * tx[i]
+                     + (this.ny[i] - this.ny[i - 1]) * ty[i]) / (at[i] - at[i - 1]);
+            var lim = BEND_SHARE / Math.abs(k);
+            var side = k < 0 ? left : right;
+            side[i - 1] = Math.min(side[i - 1], lim);
+            side[i] = Math.min(side[i], lim);
+        }
+        // let the limits change gradually, so monsters drift towards the
+        // centre line before a tight bend rather than at it
+        [left, right].forEach(function (lim) {
+            for (i = 1; i < n; i++)
+                lim[i] = Math.min(lim[i], lim[i - 1] + LIMIT_SLOPE * (at[i] - at[i - 1]));
+            for (i = n - 2; i >= 0; i--)
+                lim[i] = Math.min(lim[i], lim[i + 1] + LIMIT_SLOPE * (at[i + 1] - at[i]));
+        });
+        this.left = left;
+        this.right = right;
+    };
+
+    // write the point at distance s along the route into out.x, out.y.
+    // out.seg remembers the segment, so the next search for a point
+    // further along starts there
+    Route.prototype.point = function (s, out) {
+        var at = this.at, n = at.length;
+        if (s <= 0) { out.x = this.xs[0]; out.y = this.ys[0]; return out; }
+        if (s >= this.length) { out.x = this.xs[n - 1]; out.y = this.ys[n - 1]; return out; }
+        var i = out.seg || 1;
+        if (i >= n || at[i - 1] > s) i = 1;
+        while (at[i] < s) i++;
+        out.seg = i;
+        var t = (s - at[i - 1]) / (at[i] - at[i - 1]);
+        out.x = this.xs[i - 1] + (this.xs[i] - this.xs[i - 1]) * t;
+        out.y = this.ys[i - 1] + (this.ys[i] - this.ys[i - 1]) * t;
+        return out;
+    };
+
+    // as point(), moved sideways by d: positive to the left of the direction
+    // of travel as drawn, negative to the right. on the inside of bends d is
+    // reduced, so the point keeps moving forward as s grows
+    Route.prototype.shifted = function (s, d, out) {
+        this.point(s, out);
+        var at = this.at, n = at.length, i, t;
+        if (s <= 0) { i = 1; t = 0; }
+        else if (s >= this.length) { i = n - 1; t = 1; }
+        else { i = out.seg; t = (s - at[i - 1]) / (at[i] - at[i - 1]); }
+        var lim = d > 0 ? this.left : this.right;
+        var m = lim[i - 1] + (lim[i] - lim[i - 1]) * t;
+        if (Math.abs(d) > m) d = d > 0 ? m : -m;
+        out.x += d * (this.nx[i - 1] + (this.nx[i] - this.nx[i - 1]) * t);
+        out.y += d * (this.ny[i - 1] + (this.ny[i] - this.ny[i - 1]) * t);
+        return out;
+    };
+
+    return Route;
+})();
+
+MM.GameMap = (function () {
+    "use strict";
+
+    var cfg = MM.config;
+    // spike sides: distance between route samples, and the share of the
+    // samples in reach a side needs to count as facing the path
+    var SIDE_STEP = 4;
+    var SIDE_SHARE = 0.2;
+
+    function GameMap(index) {
+        var d = MM.maps[index];
+        this.index = index;
+        this.data = d;
+        this.name = d.name;
+        this.width = d.width;
+        this.height = d.height;
+        // largest sideways offset of a monster from the centre line
+        this.maxOffset = cfg.movement.offset * cfg.maps[index].path_half_width;
+        var maxOffset = this.maxOffset;
+        this.routes = d.routes.map(function (r) { return new MM.Route(r, maxOffset); });
+    }
+
+    GameMap.prototype.legalCell = function (cx, cy) {
+        var d = this.data;
+        if (cx < 0 || cy < 0 || cx >= d.cols || cy >= d.rows) return false;
+        return d.grid.charCodeAt(cy * d.cols + cx) === 49;
+    };
+
+    // nearest legal tower position to x, y within the snap radius that keeps
+    // the minimum distance to the towers in the list. returns {x, y} or null.
+    GameMap.prototype.snap = function (x, y, towers) {
+        var p = cfg.placement, cell = this.data.cell;
+        var reach = Math.ceil(p.snap_radius / cell);
+        var cx0 = Math.floor(x / cell), cy0 = Math.floor(y / cell);
+        var best = null, bestD = p.snap_radius;
+        for (var cy = cy0 - reach; cy <= cy0 + reach; cy++) {
+            for (var cx = cx0 - reach; cx <= cx0 + reach; cx++) {
+                if (!this.legalCell(cx, cy)) continue;
+                var px = cx * cell + cell / 2, py = cy * cell + cell / 2;
+                var d = Math.hypot(px - x, py - y);
+                if (d > bestD) continue;
+                var free = true;
+                for (var i = 0; i < towers.length; i++) {
+                    if (Math.hypot(towers[i].x - px, towers[i].y - py) < p.min_tower_distance) {
+                        free = false;
+                        break;
+                    }
+                }
+                if (free) {
+                    best = { x: px, y: py };
+                    bestD = d;
+                }
+            }
+        }
+        return best;
+    };
+
+    // which sides of a tower at x, y face the path, as four booleans: up,
+    // right, down, left. each side covers a quarter of the directions. a side
+    // faces the path when it holds at least SIDE_SHARE of the route points
+    // within reach. with no route point in reach, only the side towards the
+    // nearest one does.
+    GameMap.prototype.facingSides = function (x, y, reach) {
+        var count = [0, 0, 0, 0], total = 0, nearest = Infinity, nearSide = 0;
+        var pt = {};
+        this.routes.forEach(function (r) {
+            pt.seg = 1;
+            for (var s = 0; s <= r.length; s += SIDE_STEP) {
+                r.point(s, pt);
+                var dx = pt.x - x, dy = pt.y - y, d = Math.hypot(dx, dy);
+                var side = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? 1 : 3) : (dy > 0 ? 2 : 0);
+                if (d < nearest) {
+                    nearest = d;
+                    nearSide = side;
+                }
+                if (d <= reach) {
+                    count[side]++;
+                    total++;
+                }
+            }
+        });
+        return count.map(function (c, i) {
+            return total ? c >= SIDE_SHARE * total : i === nearSide;
+        });
+    };
+
+    // route weights for a monster of the given speed (balance.md, route
+    // preference). fixed weights from routes.toml take precedence.
+    GameMap.prototype.routeWeights = function (speed) {
+        var rp = cfg.route_preference;
+        var f = MM.util.clamp((speed - rp.reference_speed) / rp.reference_speed, -1, 1);
+        return this.routes.map(function (r) {
+            if (r.weight !== null) return r.weight;
+            return Math.max(rp.min_weight, 1 + rp.bias * f * (2 * r.value - 1));
+        });
+    };
+
+    // index of the shortest route, leaving out routes with a fixed weight
+    // of 0 in routes.toml
+    GameMap.prototype.shortestRoute = function () {
+        var best = -1;
+        this.routes.forEach(function (r, i) {
+            if (r.weight === 0) return;
+            if (best < 0 || r.length < this.routes[best].length) best = i;
+        }, this);
+        return best;
+    };
+
+    return GameMap;
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/monster.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,123 @@
+// monsters: movement along a route, hops, slow, hp
+
+window.MM = window.MM || {};
+
+MM.monster = (function () {
+    "use strict";
+
+    var cfg = MM.config;
+    // share of the hop cycle spent in the air; the rest is the landing
+    var AIR = 0.8;
+
+    // a new monster of the given kind at the start of a route chosen by
+    // the map's route weights. a boss takes the shortest route
+    function create(game, kind) {
+        var def = cfg.monster[kind];
+        var mv = cfg.movement;
+        var map = game.map;
+        var speed = def.speed * (1 + mv.speed_variation * (2 * game.random() - 1));
+        var r = def.boss ? map.shortestRoute() : MM.util.pick(map.routeWeights(speed), game.random);
+        var route = map.routes[r];
+        // sideways offsets at every wander_step along the route: a fixed
+        // lean plus a wandering part, together within the map's largest offset
+        var lean = mv.lean * map.maxOffset * (2 * game.random() - 1);
+        var wander = (1 - mv.lean) * map.maxOffset;
+        var offsets = [];
+        for (var i = Math.ceil(route.length / mv.wander_step) + 2; i > 0; i--)
+            offsets.push(lean + wander * (2 * game.random() - 1));
+        var size = MM.assets.size(kind, cfg.scale.sprite);
+        var m = {
+            kind: kind,
+            boss: !!def.boss,
+            route: route,
+            routeIndex: r,
+            s: 0,
+            x: 0,
+            y: 0,
+            seg: 1,
+            offsets: offsets,
+            hp: def.hp,
+            maxHp: def.hp,
+            speed: speed,
+            coins: def.coins,
+            w: size[0],
+            h: size[1],
+            hitRadius: cfg.animation.hit_radius * Math.min(size[0], size[1]),
+            // start at a random point of the hop cycle, so a group does not hop in step
+            phase: game.random(),
+            slows: [],      // running slows, {factor, left}
+            alive: true
+        };
+        m.route.point(0, m);
+        return m;
+    }
+
+    // sideways offset at the distance walked: changes smoothly between the
+    // values at every wander_step, and grows from 0 over the first fade_in
+    function offset(m) {
+        var mv = cfg.movement, u = m.s / mv.wander_step;
+        var i = Math.floor(u), t = (1 - Math.cos(Math.PI * (u - i))) / 2;
+        var d = m.offsets[i] + (m.offsets[i + 1] - m.offsets[i]) * t;
+        var f = Math.min(m.s / mv.fade_in, 1);
+        return d * (1 - Math.cos(Math.PI * f)) / 2;
+    }
+
+    // share of its speed a monster keeps: the strongest running slow
+    // applies, slows do not add up. 1 when not slowed.
+    function slowFactor(m) {
+        var k = 1;
+        for (var i = 0; i < m.slows.length; i++) k = Math.min(k, m.slows[i].factor);
+        return k;
+    }
+
+    // slow to factor of the speed for time seconds. a new hit of the same
+    // strength restarts its time.
+    function slow(m, factor, time) {
+        for (var i = 0; i < m.slows.length; i++) {
+            if (m.slows[i].factor === factor) {
+                m.slows[i].left = time;
+                return;
+            }
+        }
+        m.slows.push({ factor: factor, left: time });
+    }
+
+    // advance by dt seconds. returns true when the monster reached the exit.
+    function update(m, dt) {
+        for (var i = m.slows.length - 1; i >= 0; i--) {
+            m.slows[i].left -= dt;
+            if (m.slows[i].left <= 0) m.slows.splice(i, 1);
+        }
+        // a slowed monster also hops slower
+        var k = slowFactor(m);
+        m.s += m.speed * k * dt;
+        m.phase = (m.phase + k * dt / cfg.animation.hop_time) % 1;
+        m.route.shifted(m.s, offset(m), m);
+        return m.s >= m.route.length;
+    }
+
+    function remaining(m) {
+        return m.route.length - m.s;
+    }
+
+    // hop height and stretch for drawing: {lift, sx, sy}
+    function pose(m, time) {
+        var a = cfg.animation, p = m.phase, lift = 0, sx = 1, sy = 1;
+        if (p < AIR) {
+            var k = Math.sin(Math.PI * p / AIR);
+            lift = a.hop_height * k;
+            sx = 1 - a.stretch * k;
+            sy = 1 + a.stretch * k;
+        } else {
+            var q = Math.sin(Math.PI * (p - AIR) / (1 - AIR));
+            sx = 1 + a.squash * q;
+            sy = 1 - a.squash * q;
+        }
+        // slow breathing on top of the hops
+        var bob = a.idle_bob * Math.sin(time * 2 * Math.PI / 1.3 + m.phase * 6.28);
+        return { lift: lift, sx: sx * (1 - bob / 2), sy: sy * (1 + bob) };
+    }
+
+    return { create: create, update: update, remaining: remaining, pose: pose,
+             slow: slow, slowFactor: slowFactor };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/projectile.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,55 @@
+// projectiles: fly towards their target and damage it on arrival, p2 also
+// slows it
+
+window.MM = window.MM || {};
+
+MM.projectile = (function () {
+    "use strict";
+
+    function create(tower, target, damage) {
+        var def = tower.def;
+        return {
+            kind: def.projectile,
+            speed: def.projectile_speed,
+            x: tower.x,
+            y: tower.y,
+            tx: target.x,
+            ty: target.y,
+            target: target,
+            damage: damage,
+            slow: def.slow ? def.slow[tower.level - 1] : 0,
+            slowTime: def.slow_time,
+            angle: Math.atan2(target.y - tower.y, target.x - tower.x),
+            done: false
+        };
+    }
+
+    // home in on the target. if it died first, fly on to its last position
+    // and disappear there without damage.
+    function update(p, game, dt) {
+        var t = p.target;
+        if (t && t.alive) {
+            p.tx = t.x;
+            p.ty = t.y;
+        } else {
+            t = null;
+        }
+        var dx = p.tx - p.x, dy = p.ty - p.y;
+        var d = Math.hypot(dx, dy);
+        var step = p.speed * dt;
+        var reach = t ? Math.max(step, t.hitRadius) : step;
+        if (d <= reach) {
+            if (t) {
+                if (p.slow) MM.monster.slow(t, p.slow, p.slowTime);
+                game.damage(t, p.damage);
+            }
+            p.done = true;
+            return;
+        }
+        p.angle = Math.atan2(dy, dx);
+        p.x += dx / d * step;
+        p.y += dy / d * step;
+    }
+
+    return { create: create, update: update };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/render.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,198 @@
+// drawing of the map and everything on it. reads the game state, never
+// changes it. the top bar, shop and screens are drawn by ui.js.
+
+window.MM = window.MM || {};
+
+MM.render = (function () {
+    "use strict";
+
+    var cfg = MM.config;
+    var dbg = cfg.debug;
+    var A = MM.assets;
+    // debug placement grid, drawn once per map into a canvas of its own
+    var gridCache = { map: null, canvas: null };
+
+    function gridCanvas(map) {
+        if (gridCache.map === map.index) return gridCache.canvas;
+        var d = map.data;
+        var c = document.createElement("canvas");
+        c.width = d.width;
+        c.height = d.height;
+        var g = c.getContext("2d");
+        g.fillStyle = "rgba(40, 160, 40, 0.55)";
+        for (var i = 0; i < d.grid.length; i++) {
+            if (d.grid.charCodeAt(i) !== 49) continue;
+            g.fillRect((i % d.cols) * d.cell, Math.floor(i / d.cols) * d.cell, d.cell - 1, d.cell - 1);
+        }
+        gridCache.map = map.index;
+        gridCache.canvas = c;
+        return c;
+    }
+
+    function circle(ctx, x, y, r, fill, stroke, width) {
+        ctx.beginPath();
+        ctx.arc(x, y, r, 0, Math.PI * 2);
+        if (fill) {
+            ctx.fillStyle = fill;
+            ctx.fill();
+        }
+        if (stroke) {
+            ctx.strokeStyle = stroke;
+            ctx.lineWidth = width;
+            ctx.stroke();
+        }
+    }
+
+    function drawRoutes(ctx, map) {
+        var colours = ["#d0009f", "#005aff", "#ff7800", "#00a03c", "#8c00ff", "#00b4c8", "#c82828", "#5a5a5a"];
+        map.routes.forEach(function (r, k) {
+            ctx.beginPath();
+            for (var i = 0; i < r.xs.length; i++) ctx.lineTo(r.xs[i], r.ys[i]);
+            ctx.strokeStyle = colours[k % colours.length];
+            ctx.lineWidth = 2;
+            ctx.stroke();
+        });
+    }
+
+    // t0 spikes: one p0 per side that faces the path. during an attack each
+    // spike stretches from its base under the tower until its tip reaches
+    // the range, and back
+    function drawSpikes(ctx, t, scale) {
+        var half = A.size(MM.tower.sprite(t), scale)[1] / 2;
+        var spike = A.size("p0", scale)[1];
+        var k = t.burst > 0 ? Math.sin(Math.PI * (1 - t.burst / MM.tower.BURST_TIME)) : 0;
+        // at rest a quarter of the spike shows beyond the tower's edge
+        var base = half - spike * 0.75;
+        var tip = MM.util.lerp(half + spike * 0.25, MM.tower.range(t), k);
+        var mid = (base + tip) / 2, stretch = (tip - base) / spike;
+        for (var side = 0; side < 4; side++) {
+            if (!t.sides[side]) continue;
+            var a = -Math.PI / 2 + side * Math.PI / 2;
+            A.draw(ctx, "p0", t.x + Math.cos(a) * mid, t.y + Math.sin(a) * mid, scale, a, 1, stretch);
+        }
+    }
+
+    // k scales the drawing, for the pulsing preview
+    function drawTower(ctx, t, alpha, k) {
+        var scale = cfg.scale.sprite * (k || 1);
+        ctx.globalAlpha = alpha;
+        if (t.def.projectile_speed === 0) drawSpikes(ctx, t, scale);
+        A.draw(ctx, MM.tower.sprite(t), t.x, t.y, scale, t.angle);
+        ctx.globalAlpha = 1;
+    }
+
+    function drawRange(ctx, x, y, r, mapScale) {
+        circle(ctx, x, y, r, "rgba(255, 255, 255, 0.25)", "rgba(40, 40, 40, 0.7)", 2 / mapScale);
+    }
+
+    function drawMonster(ctx, m, time) {
+        var pose = MM.monster.pose(m, time);
+        var img = A.img(m.kind);
+        ctx.save();
+        // feet on the ground point, so squash and stretch keep them down
+        ctx.translate(m.x, m.y + m.h / 2 - pose.lift);
+        ctx.scale(pose.sx, pose.sy);
+        ctx.drawImage(img, -m.w / 2, -m.h, m.w, m.h);
+        ctx.restore();
+
+        // hp bar, cut to the share of hp left over its darkened copy. the
+        // boss has its own bar; a slowed monster's bar is blue
+        var name = (m.boss ? "hpb" : "hpm") + (MM.monster.slowFactor(m) < 1 ? "_slow" : "");
+        var bar = A.size(name, cfg.scale.hp_bar);
+        var bx = m.x - bar[0] / 2, by = m.y - m.h / 2 - pose.lift - bar[1] - 2;
+        var share = Math.max(0, m.hp / m.maxHp);
+        var full = A.img(name), empty = A.img(name + "_empty");
+        ctx.drawImage(empty, bx, by, bar[0], bar[1]);
+        if (share > 0) {
+            ctx.drawImage(full, 0, 0, full.naturalWidth * share, full.naturalHeight,
+                          bx, by, bar[0] * share, bar[1]);
+        }
+    }
+
+    // death puff: grows from 60 % to full size, and fades out over the second
+    // half of its time
+    function drawPuff(ctx, p) {
+        var u = p.t / cfg.animation.death_puff;
+        var k = MM.util.lerp(0.6, 1, MM.util.easeOut(Math.min(1, u * 2)));
+        var name = p.boss ? "boss_death" : "monster_death";
+        ctx.globalAlpha = u < 0.5 ? 1 : 2 - 2 * u;
+        A.draw(ctx, name, p.x, p.y, cfg.scale.sprite, null, k, k);
+        ctx.globalAlpha = 1;
+    }
+
+    // draw the map area. L is the layout from ui.js, view holds the canvas
+    // pixel ratio, wall clock and tap feedback.
+    function draw(ctx, game, L, view) {
+        var map = game.map, s = L.scale, dpr = view.dpr;
+        ctx.setTransform(dpr * s, 0, 0, dpr * s, dpr * L.ox, dpr * L.oy);
+        ctx.drawImage(A.img(map.name), 0, 0, map.width, map.height);
+
+        if (dbg.show_grid) ctx.drawImage(gridCanvas(map), 0, 0);
+        if (dbg.show_routes) drawRoutes(ctx, map);
+
+        game.towers.slice().sort(function (a, b) { return a.y - b.y; })
+            .forEach(function (t) { drawTower(ctx, t, 1); });
+        if (dbg.show_ranges) {
+            game.towers.forEach(function (t) { drawRange(ctx, t.x, t.y, MM.tower.range(t), s); });
+        }
+        if (game.selected) {
+            var t = game.selected;
+            drawRange(ctx, t.x, t.y, MM.tower.range(t), s);
+            drawTower(ctx, t, 1);
+        }
+        if (game.preview) {
+            var pv = MM.tower.create(game.shop, game.preview.x, game.preview.y, game.preview.sides);
+            drawRange(ctx, pv.x, pv.y, MM.tower.range(pv), s);
+            // the preview pulses with the chosen shop item: it grows while
+            // the item shows one drawing and shrinks while it shows the other
+            var k = 0.5 - 0.5 * Math.cos(Math.PI * view.now / MM.ui.BUBBLE_FLIP);
+            drawTower(ctx, pv, MM.util.lerp(0.45, 0.8, k), MM.util.lerp(1, 1.08, k));
+        }
+
+        game.monsters.slice().sort(function (a, b) { return a.y - b.y; })
+            .forEach(function (m) { drawMonster(ctx, m, game.time); });
+        game.puffs.forEach(function (p) { drawPuff(ctx, p); });
+        if (dbg.show_hit_areas) {
+            game.monsters.forEach(function (m) {
+                circle(ctx, m.x, m.y, m.hitRadius, null, "rgba(255, 0, 0, 0.8)", 1 / s);
+            });
+        }
+
+        game.projectiles.forEach(function (p) {
+            A.draw(ctx, p.kind, p.x, p.y, cfg.scale.sprite, p.angle);
+        });
+
+        // refused placement: a red cross where the tap was
+        if (view.refused && view.now < view.refused.until) {
+            var f = view.refused, r = 10 / s;
+            ctx.strokeStyle = "#d02020";
+            ctx.lineWidth = 4 / s;
+            ctx.beginPath();
+            ctx.moveTo(f.x - r, f.y - r);
+            ctx.lineTo(f.x + r, f.y + r);
+            ctx.moveTo(f.x + r, f.y - r);
+            ctx.lineTo(f.x - r, f.y + r);
+            ctx.stroke();
+        }
+    }
+
+    // coins flying from the monster to the coin counter, in screen pixels
+    function drawFlights(ctx, game, L, view) {
+        var dpr = view.dpr, ft = cfg.coins.flight_time;
+        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+        game.flights.forEach(function (f) {
+            var u = MM.util.clamp(f.t / ft, 0, 1);
+            var e = MM.util.easeIn(u);
+            var sx = L.ox + f.x * L.scale, sy = L.oy + f.y * L.scale;
+            var x = MM.util.lerp(sx, L.coinIcon.x, e);
+            var y = MM.util.lerp(sy, L.coinIcon.y, e) - 40 * Math.sin(Math.PI * u);
+            var start = A.size(f.sprite, cfg.scale.coin)[0] * L.scale;
+            var size = MM.util.lerp(start, L.coinIcon.size, e);
+            var img = A.img(f.sprite);
+            var h = size * img.naturalHeight / img.naturalWidth;
+            ctx.drawImage(img, x - size / 2, y - h / 2, size, h);
+        });
+    }
+
+    return { draw: draw, drawFlights: drawFlights };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/storage.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,38 @@
+// settings kept in the browser (architecture.md, persistence). one
+// localStorage entry holds all of them, with a format version. every access
+// is wrapped, so the game still runs when storage is unavailable, for
+// example in private browsing; settings are then not kept.
+
+window.MM = window.MM || {};
+
+MM.storage = (function () {
+    "use strict";
+
+    var KEY = "minor_monsters";
+    var VERSION = 1;
+    var settings = {};
+
+    // an entry of another version is ignored and replaced on the next set()
+    try {
+        var entry = JSON.parse(window.localStorage.getItem(KEY));
+        if (entry && entry.version === VERSION && entry.settings) settings = entry.settings;
+    } catch (e) {
+        settings = {};
+    }
+
+    // the stored value of a setting, or fallback when it was never set
+    function get(name, fallback) {
+        return Object.prototype.hasOwnProperty.call(settings, name) ? settings[name] : fallback;
+    }
+
+    function set(name, value) {
+        settings[name] = value;
+        try {
+            window.localStorage.setItem(KEY, JSON.stringify({ version: VERSION, settings: settings }));
+        } catch (e) {
+            // storage unavailable or full: the setting holds until a reload
+        }
+    }
+
+    return { get: get, set: set };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/tower.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,97 @@
+// towers: targeting, attacks, upgrade, sell
+
+window.MM = window.MM || {};
+
+MM.tower = (function () {
+    "use strict";
+
+    var cfg = MM.config;
+    // how long a melee attack shows its spikes pushed out
+    var BURST_TIME = 0.3;
+
+    // sides: for t0, which sides draw spikes (map.facingSides); all four
+    // when left out
+    function create(type, x, y, sides) {
+        return {
+            type: type,
+            def: cfg.tower[type],
+            level: 1,
+            x: x,
+            y: y,
+            sides: sides || [true, true, true, true],
+            paid: 0,            // coins paid for building and upgrades
+            angle: -Math.PI / 2,
+            cooldown: 0,
+            burst: 0
+        };
+    }
+
+    // cost of the next level, null at the top level
+    function upgradeCost(t) {
+        return t.level < t.def.cost.length ? t.def.cost[t.level] : null;
+    }
+
+    // coins back for selling the tower: half of everything paid for it,
+    // rounded down
+    function refund(t) {
+        return Math.floor(t.paid * cfg.tower_rules.sell_refund);
+    }
+
+    function sprite(t) {
+        return t.level === 1 ? t.type : t.type + "_" + t.level;
+    }
+
+    function range(t) {
+        return t.def.range[t.level - 1];
+    }
+
+    function damage(t) {
+        return t.def.damage[t.level - 1];
+    }
+
+    function inRange(t, m) {
+        var r = range(t);
+        var dx = m.x - t.x, dy = m.y - t.y;
+        return dx * dx + dy * dy <= r * r;
+    }
+
+    // the monster in range that is furthest along, that is with the least
+    // distance left to its exit
+    function target(t, monsters) {
+        var best = null, left = Infinity;
+        for (var i = 0; i < monsters.length; i++) {
+            var m = monsters[i];
+            if (!m.alive || !inRange(t, m)) continue;
+            var l = MM.monster.remaining(m);
+            if (l < left) {
+                left = l;
+                best = m;
+            }
+        }
+        return best;
+    }
+
+    function update(t, game, dt) {
+        if (t.cooldown > 0) t.cooldown -= dt;
+        if (t.burst > 0) t.burst -= dt;
+        var melee = t.def.projectile_speed === 0;
+        var m = target(t, game.monsters);
+        if (!m) return;
+        if (!melee) t.angle = Math.atan2(m.y - t.y, m.x - t.x);
+        if (t.cooldown > 0) return;
+        t.cooldown += t.def.attack_time;
+        // sound events t0_attack for the melee tower, t1_shot and so on
+        MM.audio.play(t.type + (melee ? "_attack" : "_shot"));
+        if (melee) {
+            // every monster in range at once
+            var hit = game.monsters.filter(function (o) { return o.alive && inRange(t, o); });
+            hit.forEach(function (o) { game.damage(o, damage(t)); });
+            t.burst = BURST_TIME;
+        } else {
+            game.projectiles.push(MM.projectile.create(t, m, damage(t)));
+        }
+    }
+
+    return { create: create, update: update, sprite: sprite, range: range,
+             upgradeCost: upgradeCost, refund: refund, BURST_TIME: BURST_TIME };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/ui.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,352 @@
+// screen layout, top bar, tower shop, tower menu, splash and end screens,
+// drawn from the supplied icons and drawings (art.md). numbers use the
+// hand-drawn digits.
+
+window.MM = window.MM || {};
+
+MM.ui = (function () {
+    "use strict";
+
+    var cfg = MM.config;
+    var A = MM.assets;
+    var TOP = 60;           // top bar height, css pixels
+    var SHOP = 96;          // shop width (landscape) or height (portrait)
+    var BUTTON = 52;        // top bar buttons, at least 48 for touch
+    var SHOP_W = 84;        // shop items
+    var SHOP_H = 72;
+    var POPUP_W = 168;      // tower menu bubble; its height follows the drawing
+    var DIGIT = 28;         // digit height in the top bar
+    var PRICE = 18;         // digit height of prices
+    var DIGIT_GAP = 0.08;   // space between digits, a share of their height
+    var BUBBLE_FLIP = 400;  // ms between the two drawings of the chosen shop item
+    var PULSE = 1.2;        // seconds of one pulse of a screen button
+    var WARN_PULSE = 0.5;   // seconds of one pulse of an armed sell button
+    var INK = "#3a3530";
+    var PAPER = "#f6f1e6";
+    var FONT = "bold 22px system-ui, -apple-system, Segoe UI, sans-serif";
+    var TOWERS = ["t0", "t1", "t2", "t3"];
+    // each screen drawing, its separate button image and the button's action
+    var SCREENS = {
+        splash: { image: "splash_play", id: "play" },
+        map_won: { image: "map_won_button", id: "next" },
+        game_lost: { image: "game_lost_button", id: "retry" },
+        game_won: { image: "game_won_button", id: "restart" }
+    };
+
+    // digit variants from the sprite table: character -> sprite names
+    var DIGITS = {};
+    Object.keys(cfg.sprites).forEach(function (n) {
+        var m = /^digit_(\d|slash)_\d+$/.exec(n);
+        if (!m) return;
+        var ch = m[1] === "slash" ? "/" : m[1];
+        (DIGITS[ch] = DIGITS[ch] || []).push(n);
+    });
+
+    // all screens share one scale, set by the largest drawing, so they keep
+    // the sizes of the drawings relative to each other
+    function screenScale(w, h) {
+        var mw = 0, mh = 0;
+        Object.keys(SCREENS).forEach(function (n) {
+            mw = Math.max(mw, cfg.sprites[n][0]);
+            mh = Math.max(mh, cfg.sprites[n][1]);
+        });
+        return Math.min(1, 0.92 * w / mw, 0.9 * h / mh);
+    }
+
+    // positions of everything on screen for a window of w x h css pixels
+    function layout(w, h, map) {
+        var land = w >= h;
+        var area = land ? { x: 0, y: TOP, w: w - SHOP, h: h - TOP }
+                        : { x: 0, y: TOP, w: w, h: h - TOP - SHOP };
+        var scale = Math.min(area.w / map.width, area.h / map.height);
+        var L = {
+            w: w, h: h, land: land, area: area, scale: scale,
+            ox: area.x + (area.w - map.width * scale) / 2,
+            oy: area.y + (area.h - map.height * scale) / 2,
+            shop: land ? { x: w - SHOP, y: TOP, w: SHOP, h: h - TOP }
+                       : { x: 0, y: h - SHOP, w: w, h: SHOP },
+            coinIcon: { x: 24, y: TOP / 2, size: 32 },
+            screen: screenScale(w, h)
+        };
+        return L;
+    }
+
+    // the screen shown over the map, or null during play
+    function screenName(game) {
+        if (game.splash) return "splash";
+        if (game.result === "lost") return "game_lost";
+        if (game.result) return game.lastMap() ? "game_won" : "map_won";
+        return null;
+    }
+
+    // the drawing of a screen centred in the window, and its button
+    function screenRects(name, L) {
+        var k = L.screen, s = cfg.sprites[name];
+        var bs = cfg.sprites[SCREENS[name].image], at = cfg.art.screen[name];
+        var p = { x: (L.w - s[0] * k) / 2, y: (L.h - s[1] * k) / 2, w: s[0] * k, h: s[1] * k };
+        return { panel: p, button: { x: p.x + at[0] * k, y: p.y + at[1] * k, w: bs[0] * k, h: bs[1] * k } };
+    }
+
+    // the tower menu: a bubble above the selected tower, or below it when
+    // there is no room above, kept inside the map area. upgrade and sell each
+    // take half of the bubble; at the top level there is no upgrade and sell
+    // takes all of it. cx is where the button's drawing is centred.
+    function towerMenu(game, L) {
+        var t = game.selected, a = L.area, gap = 8;
+        var s = cfg.sprites.tower_popup, w = POPUP_W, h = POPUP_W * s[1] / s[0];
+        var x = L.ox + t.x * L.scale, y = L.oy + t.y * L.scale;
+        var half = A.size(MM.tower.sprite(t), cfg.scale.sprite)[1] / 2 * L.scale + gap;
+        var top = y - half - h;
+        if (top < a.y + gap) top = y + half;
+        var left = MM.util.clamp(x - w / 2, a.x + gap, a.x + a.w - w - gap);
+        var bubble = { x: left, y: top, w: w, h: h };
+        if (!MM.tower.upgradeCost(t)) {
+            return [{ id: "sell", x: left, y: top, w: w, h: h, cx: left + w / 2, bubble: bubble }];
+        }
+        return [
+            { id: "upgrade", x: left, y: top, w: w / 2, h: h, cx: left + w * 0.34, bubble: bubble },
+            { id: "sell", x: left + w / 2, y: top, w: w / 2, h: h, cx: left + w * 0.66, bubble: bubble }
+        ];
+    }
+
+    // the buttons for the current state, each {id, x, y, w, h}
+    function buttons(game, L) {
+        var out = [];
+        var name = screenName(game);
+        if (name) {
+            var b = screenRects(name, L).button;
+            b.id = SCREENS[name].id;
+            b.screen = name;
+            out.push(b);
+            return out;
+        }
+        // top bar, right to left
+        var y = (TOP - BUTTON) / 2, x = L.w - 8;
+        ["pause", "speed", "sound"].forEach(function (id) {
+            x -= BUTTON;
+            out.push({ id: id, x: x, y: y, w: BUTTON, h: BUTTON });
+            x -= 8;
+        });
+        if (game.waves.phase === "break") {
+            var s = cfg.sprites.next_wave, w = BUTTON * s[0] / s[1];
+            out.push({ id: "early", x: x - w, y: y, w: w, h: BUTTON });
+        }
+        TOWERS.forEach(function (t, i) {
+            var b = L.land ? { x: L.shop.x + (SHOP - SHOP_W) / 2, y: L.shop.y + 10 + i * (SHOP_H + 10) }
+                           : { x: L.shop.x + 10 + i * (SHOP_W + 10), y: L.shop.y + (SHOP - SHOP_H) / 2 };
+            b.id = "shop";
+            b.tower = t;
+            b.w = SHOP_W;
+            b.h = SHOP_H;
+            out.push(b);
+        });
+        if (game.selected) out = out.concat(towerMenu(game, L));
+        return out;
+    }
+
+    function inside(b, x, y) {
+        return x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + b.h;
+    }
+
+    function hit(game, L, x, y) {
+        var list = buttons(game, L);
+        for (var i = 0; i < list.length; i++) {
+            if (inside(list[i], x, y)) return list[i];
+        }
+        return null;
+    }
+
+    // system font text, for the debug stats only
+    function text(ctx, s, x, y, align, size) {
+        ctx.font = size ? FONT.replace("22px", size + "px") : FONT;
+        ctx.textAlign = align || "left";
+        ctx.textBaseline = "middle";
+        ctx.lineWidth = 4;
+        ctx.strokeStyle = PAPER;
+        ctx.strokeText(s, x, y);
+        ctx.fillStyle = INK;
+        ctx.fillText(s, x, y);
+    }
+
+    // a sprite fitted into a box of w x h centred on x, y, keeping its shape
+    function fit(ctx, name, x, y, w, h) {
+        var s = cfg.sprites[name], k = Math.min(w / s[0], h / s[1]);
+        ctx.drawImage(A.img(name), x - s[0] * k / 2, y - s[1] * k / 2, s[0] * k, s[1] * k);
+    }
+
+    // the digit sprites for string s. the variant of each digit depends on
+    // the digit and its place counted from the right, so a number keeps its
+    // look while other places change.
+    function glyphs(s) {
+        var out = [];
+        for (var i = 0; i < s.length; i++) {
+            var list = DIGITS[s[i]];
+            if (!list) continue;
+            var place = s.length - 1 - i;
+            out.push(list[(place * 5 + s.charCodeAt(i)) % list.length]);
+        }
+        return out;
+    }
+
+    function numberWidth(s, h) {
+        var g = glyphs(s), w = 0;
+        g.forEach(function (n) { w += cfg.sprites[n][0] * h / cfg.sprites[n][1]; });
+        return w + Math.max(0, g.length - 1) * h * DIGIT_GAP;
+    }
+
+    // number s in digits of height h, vertically centred on y. align is
+    // "left", "center" or "right" of x.
+    function number(ctx, s, x, y, h, align) {
+        s = String(s);
+        var w = numberWidth(s, h);
+        if (align === "center") x -= w / 2;
+        else if (align === "right") x -= w;
+        glyphs(s).forEach(function (n) {
+            var gw = cfg.sprites[n][0] * h / cfg.sprites[n][1];
+            ctx.drawImage(A.img(n), x, y - h / 2, gw, h);
+            x += gw + h * DIGIT_GAP;
+        });
+    }
+
+    // a price, the coin icon followed by the amount, centred on x, y
+    function price(ctx, amount, x, y) {
+        var s = String(amount), coin = PRICE * 0.8, gap = 3;
+        var left = x - (coin + gap + numberWidth(s, PRICE)) / 2;
+        fit(ctx, "coin_icon", left + coin / 2, y, coin, coin);
+        number(ctx, s, left + coin + gap, y, PRICE, "left");
+    }
+
+    function box(ctx, b, fill, line) {
+        ctx.fillStyle = fill;
+        ctx.strokeStyle = line || INK;
+        ctx.lineWidth = 2;
+        ctx.beginPath();
+        if (ctx.roundRect) ctx.roundRect(b.x, b.y, b.w, b.h, 10);
+        else ctx.rect(b.x, b.y, b.w, b.h);
+        ctx.fill();
+        ctx.stroke();
+    }
+
+    // a screen's button image over the same button in the drawing. it pulses
+    // slowly as a cue to tap; under the mouse it is drawn larger, lifted by
+    // a shadow.
+    function screenButton(ctx, b, view) {
+        var cx = b.x + b.w / 2, cy = b.y + b.h / 2;
+        var hover = view.hover && inside(b, view.hover.x, view.hover.y);
+        var k = hover ? 1.08 : 1 + 0.04 * (0.5 - 0.5 * Math.cos(2 * Math.PI * view.now / 1000 / PULSE));
+        var w = b.w * k, h = b.h * k;
+        ctx.save();
+        if (hover) {
+            ctx.shadowColor = "rgba(0, 0, 0, 0.35)";
+            ctx.shadowBlur = 12;
+            ctx.shadowOffsetY = 3;
+        }
+        ctx.drawImage(A.img(SCREENS[b.screen].image), cx - w / 2, cy - h / 2, w, h);
+        ctx.restore();
+    }
+
+    function drawButton(ctx, game, b, view) {
+        var cx = b.x + b.w / 2, cy = b.y + b.h / 2;
+        if (b.screen) {
+            screenButton(ctx, b, view);
+        } else if (b.id === "pause") {
+            // shows what a tap does: pause while running, play while paused
+            fit(ctx, game.paused ? "play_button" : "pause_button", cx, cy, b.w, b.h);
+        } else if (b.id === "speed") {
+            // debug speeds have no drawing and show their number
+            var sp = game.speed(), name = "speed_x" + sp;
+            if (cfg.sprites[name]) {
+                fit(ctx, name, cx, cy, b.w, b.h);
+            } else {
+                box(ctx, b, PAPER);
+                number(ctx, sp, cx, cy, DIGIT, "center");
+            }
+        } else if (b.id === "sound") {
+            fit(ctx, MM.audio.enabled() ? "sound_on" : "sound_off", cx, cy, b.w, b.h);
+        } else if (b.id === "early") {
+            // the countdown fills the empty right part of the drawing
+            ctx.drawImage(A.img("next_wave"), b.x, b.y, b.w, b.h);
+            number(ctx, Math.ceil(game.waves.left), b.x + b.w * 0.66, cy, DIGIT, "center");
+        } else if (b.id === "shop") {
+            var def = cfg.tower[b.tower];
+            // the chosen item's bubble switches between its two drawings
+            var bubble = game.shop !== b.tower ? "shop_bubble"
+                : Math.floor(view.now / BUBBLE_FLIP) % 2 ? "shop_bubble_dark2" : "shop_bubble_dark";
+            ctx.drawImage(A.img(bubble), b.x, b.y, b.w, b.h);
+            ctx.globalAlpha = game.canAfford(def.cost[0]) && !game.paused ? 1 : 0.35;
+            fit(ctx, b.tower, cx, b.y + 28, 44, 38);
+            price(ctx, def.cost[0], cx, b.y + b.h - 15);
+            ctx.globalAlpha = 1;
+        } else if (b.id === "upgrade") {
+            var cost = MM.tower.upgradeCost(game.selected);
+            ctx.globalAlpha = game.canAfford(cost) ? 1 : 0.35;
+            fit(ctx, "upgrade_button", b.cx, b.bubble.y + b.bubble.h * 0.4, 46, 44);
+            price(ctx, cost, b.cx, b.bubble.y + b.bubble.h * 0.7);
+            ctx.globalAlpha = 1;
+        } else if (b.id === "sell") {
+            // armed by a first tap: a fast pulse with a red glow until the
+            // second tap sells
+            var k = 1;
+            ctx.save();
+            if (game.sellArmed) {
+                k = 1 + 0.15 * (0.5 - 0.5 * Math.cos(2 * Math.PI * view.now / 1000 / WARN_PULSE));
+                ctx.shadowColor = "rgba(220, 30, 20, 0.9)";
+                ctx.shadowBlur = 14;
+            }
+            fit(ctx, "sell_button", b.cx, b.bubble.y + b.bubble.h * 0.4, 46 * k, 44 * k);
+            ctx.restore();
+            price(ctx, MM.tower.refund(game.selected), b.cx,
+                  b.bubble.y + b.bubble.h * 0.7);
+        }
+    }
+
+    function draw(ctx, game, L, view) {
+        var dpr = view.dpr;
+        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+
+        // top bar: coins, hearts, wave
+        ctx.fillStyle = "rgba(246, 241, 230, 0.92)";
+        ctx.fillRect(0, 0, L.w, TOP);
+        ctx.fillStyle = "rgba(246, 241, 230, 0.92)";
+        ctx.fillRect(L.shop.x, L.shop.y, L.shop.w, L.shop.h);
+        ctx.fillStyle = "rgba(58, 53, 48, 0.25)";
+        ctx.fillRect(0, TOP - 2, L.w, 2);
+        // each counter takes at least the width of its widest usual value, so
+        // the next one does not move while the numbers change
+        var ic = L.coinIcon, x = ic.x - ic.size / 2;
+        [["coin_icon", game.coins, "000"], ["heart", game.hearts, "00"],
+         ["monster_icon", game.waves.shown() + "/" + game.waves.list.length, "00/00"]
+        ].forEach(function (c) {
+            var s = String(c[1]);
+            fit(ctx, c[0], x + ic.size / 2, TOP / 2, ic.size, ic.size);
+            number(ctx, s, x + ic.size + 6, TOP / 2, DIGIT, "left");
+            x += ic.size + 6 + Math.max(numberWidth(s, DIGIT), numberWidth(c[2], DIGIT)) + 18;
+        });
+
+        var screen = screenName(game);
+        var list = buttons(game, L);
+        if (game.paused && !screen) {
+            ctx.fillStyle = "rgba(255, 255, 255, 0.18)";
+            ctx.fillRect(L.ox, L.oy, game.map.width * L.scale, game.map.height * L.scale);
+        }
+        if (screen) {
+            ctx.fillStyle = game.splash ? "rgba(246, 241, 230, 0.55)" : "rgba(40, 35, 30, 0.45)";
+            ctx.fillRect(0, 0, L.w, L.h);
+            var p = screenRects(screen, L).panel;
+            ctx.drawImage(A.img(screen), p.x, p.y, p.w, p.h);
+        } else if (game.selected) {
+            var bub = list[list.length - 1].bubble;
+            ctx.drawImage(A.img("tower_popup"), bub.x, bub.y, bub.w, bub.h);
+        }
+        list.forEach(function (b) { drawButton(ctx, game, b, view); });
+
+        if (cfg.debug.show_stats && view.stats) {
+            var st = view.stats;
+            text(ctx, st.ms.toFixed(1) + " ms  " + game.monsters.length + " m  " +
+                 game.towers.length + " t  " + game.projectiles.length + " p  seed " + game.seed,
+                 8, L.h - 14, "left", 14);
+        }
+    }
+
+    return { layout: layout, hit: hit, draw: draw, BUBBLE_FLIP: BUBBLE_FLIP };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/util.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,58 @@
+// vector maths, random numbers, easing
+
+window.MM = window.MM || {};
+
+MM.util = (function () {
+    "use strict";
+
+    function clamp(v, lo, hi) {
+        return v < lo ? lo : v > hi ? hi : v;
+    }
+
+    function lerp(a, b, t) {
+        return a + (b - a) * t;
+    }
+
+    function dist(ax, ay, bx, by) {
+        return Math.hypot(bx - ax, by - ay);
+    }
+
+    function deg(d) {
+        return d * Math.PI / 180;
+    }
+
+    function easeIn(t) {
+        return t * t;
+    }
+
+    function easeOut(t) {
+        return 1 - (1 - t) * (1 - t);
+    }
+
+    // seeded random numbers (mulberry32): returns a function giving [0, 1)
+    function rng(seed) {
+        var a = seed >>> 0;
+        return function () {
+            a = (a + 0x6d2b79f5) >>> 0;
+            var t = a;
+            t = Math.imul(t ^ (t >>> 15), t | 1);
+            t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+            return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+        };
+    }
+
+    // pick an index from a list of weights with the random function r
+    function pick(weights, r) {
+        var total = 0, i;
+        for (i = 0; i < weights.length; i++) total += weights[i];
+        var x = r() * total;
+        for (i = 0; i < weights.length; i++) {
+            x -= weights[i];
+            if (x < 0) return i;
+        }
+        return weights.length - 1;
+    }
+
+    return { clamp: clamp, lerp: lerp, dist: dist, deg: deg, easeIn: easeIn,
+             easeOut: easeOut, rng: rng, pick: pick };
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/wave.js	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,94 @@
+// wave timing: breaks with countdown, spawning, early start bonus
+
+window.MM = window.MM || {};
+
+MM.Waves = (function () {
+    "use strict";
+
+    var cfg = MM.config;
+
+    // phases: "break" counts down to the next wave, "spawning" releases
+    // the wave's monsters, "clearing" waits until the wave's monsters are
+    // gone, "done" follows the last wave. random gives numbers in [0, 1).
+    function Waves(mapIndex, firstWave, random) {
+        var mc = cfg.maps[mapIndex];
+        this.list = mc.waves;
+        this.rate = mc.early_bonus;
+        this.interval = mc.spawn_interval !== undefined ? mc.spawn_interval : cfg.waves.spawn_interval;
+        this.random = random;
+        this.next = firstWave;
+        this.phase = "break";
+        this.left = cfg.waves.first_break;
+        this.pending = [];      // monster kinds of the wave not spawned yet
+        this.wait = 0;          // seconds until the next spawn
+    }
+
+    // take the next monster out of pending: a boss if one is left,
+    // otherwise a random one, each monster left equally likely
+    Waves.prototype.take = function () {
+        var i;
+        for (i = 0; i < this.pending.length; i++) {
+            if (cfg.monster[this.pending[i]].boss) break;
+        }
+        if (i === this.pending.length) i = Math.floor(this.random() * this.pending.length);
+        return this.pending.splice(i, 1)[0];
+    };
+
+    // number of the wave shown in the top bar, from 1
+    Waves.prototype.shown = function () {
+        return Math.min(this.next + (this.phase === "break" ? 1 : 0), this.list.length);
+    };
+
+    Waves.prototype.bonus = function () {
+        return this.phase === "break" ? Math.floor(this.left * this.rate) : 0;
+    };
+
+    Waves.prototype.start = function () {
+        var counts = this.list[this.next].monsters;
+        this.pending = [];
+        for (var kind in counts) {
+            for (var i = 0; i < counts[kind]; i++) this.pending.push(kind);
+        }
+        this.wait = 0;
+        this.phase = "spawning";
+        this.next++;
+        MM.audio.play("wave_start");
+    };
+
+    // start the next wave during a break. returns the bonus coins.
+    Waves.prototype.startEarly = function () {
+        if (this.phase !== "break") return 0;
+        var b = this.bonus();
+        this.start();
+        return b;
+    };
+
+    // advance by dt. spawn(kind) creates a monster; alive is the number of
+    // monsters on the map.
+    Waves.prototype.update = function (dt, alive, spawn) {
+        if (this.phase === "break") {
+            this.left -= dt;
+            if (this.left <= 0) this.start();
+            return;
+        }
+        if (this.phase === "spawning") {
+            this.wait -= dt;
+            while (this.pending.length && this.wait <= 0) {
+                spawn(this.take());
+                this.wait += this.interval;
+            }
+            if (!this.pending.length) this.phase = "clearing";
+            return;
+        }
+        if (this.phase === "clearing" && alive === 0) {
+            if (this.next >= this.list.length) {
+                this.phase = "done";
+            } else {
+                this.phase = "break";
+                this.left = cfg.waves.break;
+            }
+        }
+    };
+
+    return Waves;
+})();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/style.css	Tue Oct 20 00:12:36 2026 +0200
@@ -0,0 +1,20 @@
+html, body {
+    margin: 0;
+    padding: 0;
+    height: 100%;
+    overflow: hidden;
+    background: #e8e2d4;
+}
+
+canvas {
+    display: block;
+    width: 100vw;
+    height: 100vh;
+    height: 100dvh;
+    /* no browser zoom, scroll or selection gestures on the game */
+    touch-action: none;
+    user-select: none;
+    -webkit-user-select: none;
+    -webkit-touch-callout: none;
+    -webkit-tap-highlight-color: transparent;
+}
--- a/tools/build.py	Mon Oct 19 23:47:22 2026 +0200
+++ b/tools/build.py	Tue Oct 20 00:12:36 2026 +0200
@@ -1,14 +1,14 @@
 #!/usr/bin/env python3
 """
-build the game data from art/ and config/ into game/assets/ and game/data/.
+build the runnable game into www/: the game data from art/ and config/ into
+www/assets/ and www/data/, and a copy of the hand-written files in game/.
 
 usage: python3 tools/build.py [--force] [--watch]
 
-steps: sprites, tower levels, maps, masks, sounds, config, checks, previews.
-a step
-is skipped when all its outputs are newer than its inputs and the build
-scripts; --force runs every step. --watch reruns the build whenever a file
-in art/, art/sounds/, art/digits/ or config/ changes.
+steps: sprites, tower levels, maps, masks, sounds, config, checks, previews,
+game files. a step is skipped when all its outputs are newer than its inputs
+and the build scripts; --force runs every step. --watch reruns the build
+whenever a file in art/, art/sounds/, art/digits/, config/ or game/ changes.
 
 requires python 3.11 or later and pillow.
 """
@@ -17,6 +17,7 @@
 import json
 import math
 import re
+import shutil
 import sys
 import time
 import tomllib
@@ -36,8 +37,10 @@
 SOUNDS = ART / "sounds"
 DIGITS = ART / "digits"
 CONFIG = ROOT / "config"
-ASSETS = ROOT / "game" / "assets"
-DATA = ROOT / "game" / "data"
+GAME = ROOT / "game"
+WWW = ROOT / "www"
+ASSETS = WWW / "assets"
+DATA = WWW / "data"
 TEMP = ROOT / "temp"
 PREVIEW = TEMP / "preview"
 # route data of the last mask step, read when the step is skipped
@@ -289,7 +292,7 @@
 
 def step_sounds(cfg, force):
     """
-    embed art/sounds/*.mp3 as base64 in game/data/sounds.js, grouped by
+    embed art/sounds/*.mp3 as base64 in www/data/sounds.js, grouped by
     event: NAME.mp3 or the variants NAME_1.mp3, NAME_2.mp3 and so on.
     """
     inputs = sorted(SOUNDS.glob("*.mp3"))
@@ -403,7 +406,7 @@
 
 
 def sprite_table():
-    """name -> [width, height] of every image in game/assets/ except maps."""
+    """name -> [width, height] of every image in www/assets/ except maps."""
     out = {}
     for p in sorted(ASSETS.glob("*.png")):
         with Image.open(p) as im:
@@ -430,7 +433,7 @@
     write_text(dst, HEADER.format(src="config/game.toml")
                + "window.MM = window.MM || {};\nMM.config = "
                + json.dumps(out, indent=1) + ";\n")
-    print("config: wrote game/data/config.js")
+    print("config: wrote www/data/config.js")
 
 
 # 7. checks
@@ -520,6 +523,49 @@
     print(f"previews: wrote {PREVIEW.relative_to(ROOT)}/")
 
 
+# 9. game files
+
+def game_files():
+    """the hand-written files in game/, as paths relative to it."""
+    return sorted(p.relative_to(GAME) for p in GAME.rglob("*")
+                  if p.is_file() and p.name != ".DS_Store")
+
+
+def step_game(force):
+    """
+    copy the files in game/ to www/ when they differ in time or size, and
+    remove files from www/ that are no longer in game/. www/assets/ and
+    www/data/ are left alone, as the other steps write them.
+    """
+    files = game_files()
+    copied = 0
+    for rel in files:
+        src, dst = GAME / rel, WWW / rel
+        a = src.stat()
+        if not force and dst.exists():
+            b = dst.stat()
+            if b.st_mtime == a.st_mtime and b.st_size == a.st_size:
+                continue
+        dst.parent.mkdir(parents=True, exist_ok=True)
+        shutil.copy2(src, dst)
+        copied += 1
+    keep = set(files)
+    removed = 0
+    for p in sorted(WWW.rglob("*"), reverse=True):
+        rel = p.relative_to(WWW)
+        if rel.parts[0] in (ASSETS.name, DATA.name) or rel in keep:
+            continue
+        if p.is_file():
+            p.unlink()
+            removed += 1
+        elif not any(p.iterdir()):
+            p.rmdir()
+    if copied or removed:
+        print(f"game files: copied {copied}, removed {removed}")
+    else:
+        print("game files: up to date")
+
+
 def build(force):
     warnings.clear()
     try:
@@ -536,6 +582,7 @@
     step_config(cfg, force, changed)
     step_checks(cfg, maps)
     step_previews(cfg, maps, force, changed or masks_changed)
+    step_game(force)
     print(f"\n{len(warnings)} warning(s)")
     return True
 
@@ -543,7 +590,7 @@
 def watch():
     def snapshot():
         files = (list(ART.iterdir()) + list(SOUNDS.glob("*.mp3")) + list(DIGITS.glob("*.png"))
-                 + list(CONFIG.iterdir()) + TOOLS)
+                 + list(CONFIG.iterdir()) + [GAME / p for p in game_files()] + TOOLS)
         return {p: p.stat().st_mtime for p in files if p.is_file()}
 
     seen = None