diff doc/architecture.md @ 36:a464bd43b76c 1.0.0

clean documentation rewrite
author ark
date 2026-10-21 22:34 +0200
parents 85d23328a215
children
line wrap: on
line diff
--- a/doc/architecture.md	Tue Oct 20 19:54:56 2026 +0200
+++ b/doc/architecture.md	Wed Oct 21 22:34:43 2026 +0200
@@ -1,372 +1,239 @@
-architecture
+Architecture
 ------------
 
-the game is a static html page with plain javascript, drawn on a 2d canvas. it
-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.
+The game is a static HTML page with plain JavaScript, drawn on a 2D canvas.
+It uses no JavaScript libraries. A Python build script prepares everything
+that can be calculated in advance: processed images, map data, route data,
+embedded sounds and the config. It writes them to www/, together with a
+copy of the hand-written game files from game/. The www/ directory 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.
+The details of the algorithms and their constants are in implementation.md.
 
 
-directory layout
+Directory layout
 ----------------
 
-proposed:
-
-    art/            drawings as supplied: scans, masks, sprites
+    art/            drawings and recordings as supplied, and files cut from them
+        art_sources/    the scans the drawings were cut from
+        digits/         digits cut from digits.png (tools/cut_digits.py)
         sound_sources/  voice recordings as supplied
         sounds/         sounds cut from the recordings (tools/cut_sounds.py)
-    config/         hand-edited game settings (toml)
-        game.toml       numbers from balance.md, waves, debug switches
-    tools/          python build scripts
+    config/
+        game.toml       every game setting, the wave lists, debug switches
+    doc/            documentation
     game/           hand-written game files
         index.html
         style.css
         js/             game code
-    doc/            design and technical notes
-    www/            the built game, opened as www/index.html (generated, ignored)
+    tools/          build, cutting, balancing and release scripts
+    www/            the built game (generated, ignored)
         index.html      copied from game/, as are style.css and js/
         assets/         processed images
-        data/           maps.js, sounds.js, config.js
-    dist/           tarballs for distribution (ignored)
-    temp/           scratch files, build previews (ignored)
-
-generated files carry a header line saying so and naming the script that made
-them.
-
-
-running the game
-----------------
-
-- 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. the
-  tarball 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
-
-opening the page from disk (file://) limits what the browser allows. chrome
-blocks javascript modules, fetch() and reading pixels back from a canvas
-there. so:
+        data/           config.js, maps.js, sounds.js
+    dist/           release tarballs (ignored)
+    temp/           build cache and previews (ignored)
+        build/maps.json route and placement data of the last build
+        preview/        preview images, balance and simulation reports
 
-- scripts are loaded with plain script tags in a fixed order, and share one
-  global namespace object
-- data files are javascript files that assign to that object, not json files
-- the game never reads mask pixels; the build turns the masks into data
-- images are loaded with image elements, which works from disk
-- recorded sounds are embedded by the build as base64 data in a javascript
-  file, so they can be decoded without fetch()
-
-
-screenshots
------------
-
-firefox's own --screenshot captures at the load event. the game loads its
-images and draws its first frame after that, so the capture shows an empty
-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/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
-javascript after the wait, and -S waits again before capturing. a pointer
-event sent to the canvas counts as a tap at that position in css pixels.
-a fresh firefox profile has no stored settings, so the splash screen first
-shows the sound button over the play button (sound.md). this taps it, and
-the play button a second later, at 1024 x 768:
-
-    ff_screenshot -w 1024,768 -s 2 -S 3 -J 'function tap() {
-        document.getElementById("game").dispatchEvent(new PointerEvent(
-        "pointerdown", {clientX: 497, clientY: 560, bubbles: true})) }
-        tap(); setTimeout(tap, 1000)' \
-        file://$PWD/www/index.html temp/play.png
-
-`ff_screenshot -h` lists the other options.
+Generated files have a header line saying so and naming the script that
+made them.
 
 
-build
------
+Running and deploying
+---------------------
 
-one command, `python3 tools/build.py`, runs all steps. each step skips its work
-when its inputs have not changed. requires python 3.11 or later (for the
-built-in toml reader) and pillow. numpy is optional, if the pure python image
-steps turn out too slow.
-
-tools/cut_sheet.py, tools/cut_digits.py and tools/cut_sounds.py are run by
-hand and write to art/.
-cut_sounds.py also needs ffmpeg with mp3 support, so the build itself does not
-depend on it. see sound.md.
-
-steps:
+- Local: build, then open www/index.html from disk, or serve www/ with any
+  static web server
+- Server: `tools/make_dist.sh` runs a release build and packs www/ into
+  dist/minor_monsters_VERSION.tar.gz, which unpacks into a directory
+  minor_monsters. That directory is what the web server serves
 
-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)
-2. tower levels: t0-t3 are level 1. split each t*p strip into four images,
-   levels 2-5. fill the inside of the outline with white (flood fill from
-   outside, everything not reached is inside), trim, write as t0_2..t0_5 and
-   so on. see art.md
-3. maps: copy the map images, possibly converted to a smaller format
-4. masks: for each map
-    - classify pixels as path, entrance, exit or free by their exact colour.
-      masks must have hard edges: a pixel that is neither fully transparent
-      nor opaque pure red, blue or green stops the build (art.md)
-    - extract routes, see below
-    - 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 www/data/sounds.js,
-   grouped by event
-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. towers.png
-   shows the tower levels, each turned by its drawing direction to face up,
-   with its pivot and footprint
-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 release build writes
-   www/js/debug.js empty
+The page also runs from disk (file://), where Chrome blocks JavaScript
+modules, fetch() and reading pixels back from a canvas. So:
 
-a watch mode (`tools/build.py --watch`) reruns the build when a file in
-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/build.py --release` leaves the debug code out: it writes
-www/js/debug.js empty and leaves [debug] out of config.js. the game then
-runs as with every debug switch off.
-
-`tools/make_dist.sh` runs a release build and packs www/ into
-dist/minor_monsters_VERSION.tar.gz, which unpacks into a directory
-minor_monsters. the version comes from `tools/get_version.sh -f`: the
-latest tag, with a timestamp appended when the working directory is not
-clean or not at the tagged revision. `--debug` builds with the debug code
-in place of a release build. www/ keeps the build the script made, so a
-plain build afterwards brings the debug code back.
+- Scripts are loaded with plain script tags in a fixed order, and share one
+  global namespace object, MM
+- Data files are JavaScript files that assign to MM, not JSON files
+- The game never reads mask pixels; the build turns the masks into data
+- Images are loaded with image elements
+- Sounds are embedded as base64 in a JavaScript file, so they can be
+  decoded without fetch()
 
 
-balance tools
--------------
-
-tools/balance.py estimates, map by map and wave by wave, whether the coins
-a map pays buy enough firepower (balance.md, balancing). it is run by hand
-after a build: it reads config/game.toml, and the routes and placement grid
-from temp/build/maps.json. it only calculates and leaves the images alone.
-it writes tables and charts (numpy, matplotlib) to temp/preview/:
+Build
+-----
 
-- balance.txt: value per coin for every tower and level; per map the
-  coverage of each tower's range, and per wave the coins on hand, the
-  damage rate both demands need and the coins the naive and greedy players
-  need to hold the wave
-- balance_value.png: value per coin by tower level
-- balance_map0.png to balance_map3.png: coins per wave, and the surplus at
-  the last wave and the hearts left against a wave size factor. the factor
-  scales the number of regular monsters in every wave; the coins they drop
-  follow
-
-`tools/balance.py --draft` prints wave lists made from the draft numbers in
-each map's section of the config (balance.md, waves), as toml to paste over
-the map's [[map.N.wave]] lists. `--draft 2` does map2 only. below each map
-it prints what the calculation makes of the drafted lists. nothing is
-written in this mode.
-
-tools/build.py does not count balance.py as one of its inputs, so changing
-it does not rebuild the game.
-
-tools/simulate.js checks the calculation by playing the real game logic
-with scripted players. it is run by hand with node after a build:
+`python3 tools/build.py` runs all steps. It needs Python 3.11 or later, for
+the built-in TOML reader, and Pillow. A step is skipped when its outputs
+are newer than its inputs and the build scripts; `--force` runs every step.
 
-    node tools/simulate.js
-    node tools/simulate.js --maps 2 --players naive,naive_t0 --seeds 10
-
-it loads www/data/config.js, www/data/maps.js and the logic files util.js,
-assets.js, map.js, monster.js, tower.js, projectile.js, wave.js and
-game.js, as the browser would, with window set to the global object.
-render.js, ui.js, input.js, debug.js and main.js are left out, so the
-debug switches have no effect. MM.audio is the only stub; assets.js loads
-unchanged, since sprite sizes come from the config and images are only
-loaded by main.js.
+1. Sprites: trim transparent edges and write to www/assets/. This covers
+   monsters, towers, projectiles, coins, HP bars, icons, buttons, screens
+   and the digits, written as digit_NAME_N. The HP bars also get an empty
+   variant and blue variants for slowed monsters
+2. Tower levels: split each t*p strip into levels 2 to 5, fill the inside
+   of each outline with white, trim, and write t0_2 to t3_5
+3. Maps: write the map scans as JPEG
+4. Masks: classify the mask pixels, extract the routes and write the
+   placement grid to www/data/maps.js. The result is also kept in
+   temp/build/maps.json, for the later steps and the balance tools. This
+   step also reruns when the placement settings or a map's road and spawn
+   settings change
+5. Sounds: embed art/sounds/*.mp3 in www/data/sounds.js, grouped by event
+6. Config: check config/game.toml, fill in the tower values for every
+   level, add the size of every sprite, and write www/data/config.js
+7. Checks: print per map its routes with length, turning and walk times,
+   the monster counts and shares, the coins and hit points of its waves, and
+   the early start bonus for skipping every break. Warn on problems, such as
+   a wave count that does not match the lists, or a boss missing from the
+   last wave
+8. Previews: write temp/preview/mapN.png with routes, entrances, exits and
+   placement grid, mapN_routes.png for maps with several routes, and
+   towers.png with every tower level, its rotation point and footprint
+9. Game files: copy the files in game/ to www/ when their time or size
+   differs. Files no longer in game/ are removed from www/, apart from
+   www/assets/ and www/data/
 
-the game advances in steps of 1/60 s, as in the browser; game speed plays
-no part. each run has its own seed, passed to the game. the players build,
-upgrade and start waves through the game's own functions (shop choice,
-preview, build, tower selection, upgrade, early start), so placement rules
-and prices are the game's. the players and their rules are listed at the
-top of the file; naive and greedy follow balance.md, balancing, and pick
-cells as tools/balance.py does, from the placement grid in maps.js.
+Options:
+
+- `--watch` reruns the build when a file in art/, art/sounds/, art/digits/,
+  config/ or game/, or a build script, changes. Changes to the game code
+  show in www/ only after the build has copied them
+- `--release` writes www/js/debug.js empty and leaves [debug] out of
+  config.js. The game then runs as with every debug switch off
 
-the coins a wave needs are measured by playing that wave alone from an
-empty map with the first purchases of the player's list, and searching
-for the fewest that lose no heart. every wave starts on an empty map in
-the game, so this matches the wave in a full run, apart from towers
-bought during the wave.
+`tools/make_dist.sh` takes its version from `tools/get_version.sh -f`: the
+latest Mercurial tag, with a timestamp appended when the working directory
+is not clean or not at the tagged revision. `--debug` packs a build with
+the debug code. The www/ directory keeps the build the script made, so a
+plain build afterwards brings the debug code back.
+
+Scripts run by hand, not by the build:
 
-it writes temp/preview/simulate.txt (per map and player: maps won, hearts
-left, coins on hand and the surplus at the start of the last wave, hearts
-lost per wave) and temp/preview/simulate.json, which tools/balance.py reads
-for the hits per t0 attack. `--need all` measures the coins needed for
-every wave, `--waves` takes wave lists from a json file in place of the
-config's, for trying drafts without a build.
+- tools/cut_sheet.py cuts the monster, tower, projectile and HP bar
+  sprites from a drawing sheet into art/ (art.md)
+- tools/cut_digits.py cuts art/digits.png into art/digits/
+- tools/cut_sounds.py cuts the recordings into art/sounds/. It needs FFmpeg
+  with MP3 support, which the build does not
+- tools/balance.py and tools/simulate.js estimate and test the balance of
+  the game (balancing.md)
 
 
-routes
+Config
 ------
 
-a route is a list of points from an entrance to an exit. a map has one or
-more routes. a monster picks a route at spawn (weights in balance.md) and
-follows it to the end. this handles the branches on map1 and map2 without
-junction logic at runtime.
+The file config/game.toml holds every game setting. The build checks it and
+turns it into www/data/config.js. There is no in-game editor: values are
+changed in the file and the game is rebuilt. Units are map pixels (pixels
+of the map scan), seconds, and map pixels per second.
 
-extraction in the build:
+Sections:
 
-1. thin the path pixels to a one-pixel centre line (skeleton)
-2. turn the skeleton into a graph of junctions and segments, and drop short
-   dead ends left by uneven strokes
-3. find the graph nodes nearest to each entrance and exit blob
-4. list every path through the graph from an entrance to an exit that visits
-   no junction twice
-5. smooth each route and reduce it to a few points per bend
-6. record length and turning for each route
+- [scale]: drawing scale of maps, sprites, coins and HP bars
+- [monster.*]: hit points, coins and speed of each monster; boss marks
+  the bosses
+- [animation], [movement]: hops, puffs, and the spread of monsters on the
+  road
+- [route_preference]: the route weights (game.md, routes)
+- [tower.*], [tower_rules]: tower values at level 1 and level 5, attack
+  time, projectile, slow, sell refund
+- [placement]: where towers may stand
+- [waves], [hearts], [coins], [controls]: breaks, heart costs, flying
+  coins, game speeds
+- [sound], [sound.event]: volume, the minimum time between two plays, and
+  a placeholder beep per event
+- [art.angle], [art.pivot], [art.screen]: drawing direction and rotation
+  point of turning sprites, and where buttons sit on the screen drawings
+  (art.md)
+- [links]: the logo's web page and the email address of the help popup
+- [debug]: debug switches
+- [map.N]: per map the starting coins, early start bonus, spawn interval,
+  road half width, distances from spawn and exit points, the draft numbers
+  for tools/balance.py, and the wave lists [[map.N.wave]]
 
-map0 and map3 give one route each. map1 and map2 give several; map2 may give
-more than wanted. where the automatic result is wrong, the mask is redrawn.
+Debug switches, all off by default:
 
-the game walks a monster along the route's centre line, by distance, and
-draws it beside the line. the offset is set per monster at spawn
-(balance.md, monsters) and needs no route data from the build. when a map
-loads, each route works out the sideways direction at its points and how far
-an offset may go on the inside of each bend. towers rank monsters by their
-distance along the centre line, so the offset does not change the order.
+- Start coins, unlimited coins, no heart loss
+- Start map and wave. The start map counts as the first map: the play
+  button starts it, and a lost map returns to it. Only that map starts at
+  the start wave
+- Show routes, placement grid, tower ranges, hit areas
+- Frame time and entity counts on screen
+- A fixed random seed; 0 picks a new one per map
+
+The file js/debug.js holds the code for all of them. It replaces functions
+of the game and the UI, and render.js calls it to draw over the map image
+and over the monsters. The start-up in main.js takes the start map, wave
+and seed from it.
+In a release build the file is empty and none of this is left.
 
 
-config
-------
-
-config/game.toml holds every number in balance.md, the wave lists, and debug
-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:
-
-    [[map.0.wave]]
-    monsters = { m0 = 5, m1 = 1, m2 = 1, b0 = 1 }
-
-a wave lists how many of each monster it holds. when the wave starts, the
-boss spawns first: it is the slowest monster and the others overtake it. the
-rest follow one per spawn interval, each drawn at random from the monsters
-left in the wave. the spawn interval is set per map. the boss is in the last
-wave.
-
-debug switches, all off by default:
-
-- start coins override, unlimited coins
-- start at a given map and wave. that map counts as the first map: the play
-  button starts it, and a lost map returns to it
-- no heart loss
-- show routes, placement grid, tower ranges, hit areas
-- on-screen frame time and entity counts
-- a fixed random seed
-
-js/debug.js holds the code for all of them. it replaces functions of the
-game and the top bar drawing, and render.js calls it to draw over the map
-image and over the monsters. main.js takes the start map, wave and seed
-from it. without it, as in a release build, nothing of this is left.
-
-there is no in-game config editor: values are changed in the toml file.
-
-
-runtime
+Runtime
 -------
 
-script files, in load order:
+Script files, in load order:
 
     data/config.js  generated settings
     data/maps.js    generated map data
     data/sounds.js  generated sound data
-    js/util.js      vector maths, random numbers, easing
+    js/util.js      vector maths, seeded random numbers, easing
     js/storage.js   settings kept in the browser
-    js/assets.js    image loading, sprite table
-    js/audio.js     recorded sounds, placeholder beeps for the other events,
-                    splash screen music
-    js/map.js       placement lookup, snapping, route sampling
-    js/monster.js   movement along a route, hops, slow, hp
-    js/tower.js     targeting, attacks, upgrade, sell
-    js/projectile.js
-    js/wave.js      wave timing, countdown, early start bonus
-    js/game.js      game state, rules, win and loss
-    js/render.js    drawing
-    js/ui.js        top bar, shop, tower menu, screens
+    js/assets.js    image loading, sprite drawing with angle and pivot
+    js/audio.js     recordings, placeholder beeps, splash screen music
+    js/map.js       routes and sideways offsets, placement lookup, snapping,
+                    t0 spike sides, route weights
+    js/monster.js   movement along a route, hops, slows
+    js/tower.js     targeting, attacks, upgrade cost, refund
+    js/projectile.js  flight to the target, damage, p2 freeze splash
+    js/wave.js      breaks, spawning, early start bonus
+    js/game.js      game state and rules: coins, hearts, building, upgrade,
+                    sell, win and loss
+    js/render.js    drawing of the map and everything on it
+    js/ui.js        layout, top bar, shop, tower menu, screens, help popup
     js/input.js     pointer events
     js/debug.js     debug switches, empty in a release build
-    js/main.js      start-up and main loop
-
-game loop:
+    js/main.js      start-up, screen flow and main loop
 
-- the simulation advances in fixed steps of 1/60 s. drawing happens once per
-  browser frame and is independent of it
-- game speed 2x runs two simulation steps per frame
-- pause stops the simulation; drawing and the top bar buttons continue
-- a frame that takes too long runs at most a few steps and drops the rest, so
-  the game slows down rather than freezing after the tab was in the background
-
-state:
+Game loop:
 
-- game state is plain objects: monsters, towers, projectiles, coins in flight,
-  wave state, coins, hearts. rendering reads it and does not change it
-- random numbers come from one seeded generator, so a run can be repeated with
-  the same seed when chasing a bug
-
-display:
+- The simulation advances in fixed steps of 1/60 s, driven by the
+  browser's frame clock. Drawing happens once per frame
+- Game speed n runs n times as many steps per frame
+- Pause stops the simulation; drawing and the top bar buttons go on
+- A long frame runs at most a few steps per speed step and drops the rest,
+  so the game slows down rather than freezing after the tab was in the
+  background
 
-- the canvas fills the window. the map is scaled to fit and centred, with
-  borders where the shapes differ
-- the canvas resolution follows the device pixel ratio, so drawings stay sharp
-  on high-resolution screens
-- layout: top bar with coins, hearts, wave, countdown, sound, speed, pause
-  and help. on a narrow screen the buttons move to a second row under the
-  counters. the tower shop sits on the right in landscape and at the bottom in portrait
-- buttons are at least 48 css pixels for touch
+State:
 
-input:
+- The game state is plain objects: monsters, towers, projectiles, coins in
+  flight, puffs, freeze splashes, wave state, coins and hearts. Rendering
+  reads it and does not change it
+- The game's random numbers come from one seeded generator, so a run can
+  be repeated with the same seed. Sound variants use Math.random, so sound
+  does not change a run
 
-- pointer events cover mouse and touch alike
-- nothing relies on hover; selection and confirmation are by tap. with a
-  mouse, hover enlarges the screen buttons and shows the pointer cursor over
-  any button
-- buttons and tower selection act when the pointer goes down. placing
-  follows the pointer until it is let go, and building happens then
-- the page blocks browser zoom and scroll gestures on the canvas
+Display:
 
-placement:
+- The canvas fills the window. The map is scaled to fit the area left by
+  the top bar and the shop, and centred
+- The canvas resolution follows the device pixel ratio
+- Buttons are at least 48 CSS pixels for touch
 
-- the build's placement grid marks every cell where a tower may stand
-- while the pointer is down, the game searches outward from it for the
-  nearest legal cell that keeps the minimum distance to other towers, within
-  the snap radius. where there is none, the preview stays where it was
-- t0 checks once, at placement, which of its four sides face the path, and
-  only draws spikes on those
+Input:
 
-persistence:
+- Pointer events cover mouse and touch alike
+- Buttons and tower selection act when the pointer goes down. Placing
+  follows the pointer until it is let go. The logo and the email address
+  act on release, as some browsers open a page or a mail only then
+- The page blocks browser zoom, scroll, double tap and context menu
+  gestures on the canvas
 
-- nothing is stored for now. maps are played in order and a lost map goes
-  back to the first map, so there is no progress to keep. a reload starts at
-  the splash screen with a fresh game
-- settings, so far only sound on or off, are stored by js/storage.js. it
-  wraps localStorage, and one entry holds them
-- all access is wrapped so the game still runs when storage is unavailable,
-  for example in private browsing; settings are then not kept
-- the entry carries a version number for later format changes
+Persistence:
 
-
-not planned
------------
-
-- in-browser editors or tuning panels
+- Game progress is not stored. Settings, so far only sound on or off, are
+  kept by js/storage.js in one localStorage entry with a format version
+- All access is wrapped, so the game still runs when storage is
+  unavailable, for example in private browsing; settings are then not kept