changeset 23:2f555a54c332

layout fixes and balancing
author ark
date 2026-10-20 12:04 +0200
parents ad1b478fc4dc
children 3f2811aebb3d
files config/game.toml config/routes.toml doc/architecture.md doc/balance.md doc/game_design.md doc/roadmap.md game/js/game.js game/js/map.js game/js/render.js game/js/ui.js game/js/wave.js tools/balance.py tools/build.py tools/cut_digits.py tools/preview.py tools/simulate.js
diffstat 15 files changed, 1315 insertions(+), 466 deletions(-) [+]
line wrap: on
line diff
--- a/config/game.toml	Tue Oct 20 03:08:56 2026 +0200
+++ b/config/game.toml	Tue Oct 20 12:04:42 2026 +0200
@@ -19,82 +19,83 @@
 hp_bar = 0.25       # guess
 
 
-# monsters. coins: monsters and bosses drop 0.2 coins per hp (derived).
+# monsters. coins are set apart from hp (decided): regular monsters drop
+# 0.10 to 0.20 coins per hp, bosses 0.2.
 # hit_radius is a share of the scaled sprite's smaller side.
 
 [monster.m0]
-hp = 5              # notes
-coins = 1           # notes
-speed = 35          # guess
+hp = 5
+coins = 1
+speed = 35
 
 [monster.m1]
-hp = 10             # notes
-coins = 2           # notes
-speed = 40          # guess
+hp = 10
+coins = 1
+speed = 40
 
 [monster.m2]
-hp = 15             # notes
-coins = 3           # notes
-speed = 45          # guess
+hp = 15
+coins = 2
+speed = 55
 
 [monster.m3]
-hp = 20             # notes
-coins = 4           # notes
-speed = 40          # guess
+hp = 20
+coins = 2
+speed = 40
 
 [monster.m4]
-hp = 30             # notes
-coins = 6           # notes
-speed = 35          # guess
+hp = 30
+coins = 3
+speed = 45
 
 [monster.b0]
-hp = 150            # decided, 5 x the notes (30)
-coins = 30          # notes
-speed = 25          # guess
+hp = 150
+coins = 10
+speed = 25
 boss = true
 
 [monster.b1]
-hp = 250            # decided, 5 x the notes (50)
-coins = 50          # notes
-speed = 25          # guess
+hp = 300
+coins = 20
+speed = 20
 boss = true
 
 [monster.b2]
-hp = 350            # decided, 5 x the notes (70)
-coins = 70          # notes
-speed = 25          # guess
+hp = 350
+coins = 30
+speed = 30
 boss = true
 
 [monster.b3]
-hp = 500            # decided, 5 x the notes (100)
-coins = 100         # notes
-speed = 25          # guess
+hp = 500
+coins = 40
+speed = 25
 boss = true
 
 
 [animation]
-hop_time = 0.35     # guess
-hop_height = 5      # guess
-squash = 0.06       # guess, on landing, wider and flatter
-stretch = 0.04      # guess, in the air
-idle_bob = 0.02     # guess
-hit_radius = 0.4    # proto, share of the monster sprite's smaller side
-death_puff = 0.4    # guess, seconds the death puff shows
+hop_time = 0.35
+hop_height = 5
+squash = 0.06       # on landing, wider and flatter
+stretch = 0.04      # in the air
+idle_bob = 0.02
+hit_radius = 0.4    # share of the monster sprite's smaller side
+death_puff = 0.4    # seconds the death puff shows
 
 
 # variation between monsters, so they do not walk in single file
 [movement]
-speed_variation = 0.05  # guess, each monster's speed differs by up to this share either way
-offset = 0.45           # guess, largest sideways offset from the centre line, share of the road half width
-lean = 0.5              # guess, fixed part of a monster's offset, share of the largest offset
-wander_step = 40        # guess, distance along the route between the wandering part's values
-fade_in = 20            # guess, distance from the route start over which the offset grows from 0
+speed_variation = 0.05  # each monster's speed differs by up to this share either way
+offset = 0.45           # largest sideways offset from the centre line, share of the road half width
+lean = 0.5              # fixed part of a monster's offset, share of the largest offset
+wander_step = 40        # distance along the route between the wandering part's values
+fade_in = 20            # distance from the route start over which the offset grows from 0
 
 
 [route_preference]
-reference_speed = 40    # guess
-bias = 3                # guess
-min_weight = 0.1        # guess
+reference_speed = 40
+bias = 3
+min_weight = 0.1
 
 
 # towers have 5 levels. damage, range, slow and cost give the values at
@@ -104,77 +105,77 @@
 # between attacks, the same at every level (decided). projectile_speed 0
 # means a melee tower: each attack damages every monster in range.
 
+# melee tower. low damage because it often hits multiple monsters.
 [tower.t0]
-damage = [5, 25]                    # notes
-cost = [5, 25]                      # notes, level n was 5 x n (decided)
-range = [60, 72]                    # level 1: decided (was 45), 5: guess
-attack_time = 1.5                   # guess, slower than the others (decided)
+damage = [2, 6]
+cost = [5, 25]
+range = [60, 70]
+attack_time = 1.5
 projectile = "p0"
-projectile_speed = 0                # notes (melee)
+projectile_speed = 0
 
+# standard tower
 [tower.t1]
-damage = [3, 23]                    # notes, which had 7 and 17 for levels 2 and 4
-cost = [10, 50]                     # notes, level n was 10 x n (decided)
-range = [100, 116]                  # guess
-attack_time = 0.7                   # guess
+damage = [3, 15]
+cost = [10, 30]
+range = [100, 116]
+attack_time = 0.7
 projectile = "p1"
-projectile_speed = 300              # guess
+projectile_speed = 300
 
+# freeze tower, minimal damage
 [tower.t2]
-damage = [1, 9]                     # 1: notes, 5: guess
-cost = [20, 100]                    # notes, level n was 20 x n (decided)
-range = [90, 106]                   # guess
-attack_time = 1.2                   # guess
+damage = [1, 5]
+cost = [20, 40]
+range = [90, 106]
+attack_time = 1.2
 projectile = "p2"
-projectile_speed = 220              # guess
-slow = [0.60, 0.40]                 # guess, share of speed left
-slow_time = 2.0                     # guess
+projectile_speed = 220
+slow = [0.60, 0.30]
+slow_time = 2.0
 
+# sniper tower. slightly weaker, slower and more expensive than standard tower
+# to balance much higher range
 [tower.t3]
-damage = [1, 13]                    # 1: notes, 5: guess. notes had 5 for level 2
-cost = [25, 125]                    # decided (was 40), level n was 25 x n
-range = [220, 260]                  # guess
-attack_time = 1.3                   # decided, amount guessed
+damage = [2, 13]
+cost = [15, 35]
+range = [220, 260]
+attack_time = 0.9
 projectile = "p3"
-projectile_speed = 800              # guess
+projectile_speed = 800
 
 [tower_rules]
-sell_refund = 0.5       # decided, half of everything paid for the tower, rounded down
+sell_refund = 0.5       # half of everything paid for the tower, rounded down
 
 
 [placement]
-footprint_radius = 16   # guess
-max_gap = 14            # guess, largest gap between footprint and path edge
-min_tower_distance = 40 # decided, keeps towers apart (was 32, two footprints)
-edge_distance = 16      # guess
-snap_radius = 48        # guess
-grid_cell = 4           # guess
-
-
-[economy]
-coin_total_factor = 10  # notes, coins dropped per map = 10 x starting coins
-coin_tolerance = 0.05   # notes for the build check: warn when more than 5 % off
+footprint_radius = 16
+max_gap = 14
+min_tower_distance = 40
+edge_distance = 16
+snap_radius = 48
+grid_cell = 4
 
 
 [waves]
-first_break = 40        # guess
-break = 25              # guess ("longer", decided)
-spawn_interval = 1.0    # guess, default for maps without their own
+first_break = 40
+break = 30
+spawn_interval = 1.0
 
 
 [hearts]
-per_map = 10            # decided
-monster = 1             # decided
-boss = 5                # decided
+per_map = 10
+monster = 1
+boss = 10
 
 
 [coins]
-flight_time = 0.7       # guess
-max_sprites = 8         # guess
+flight_time = 0.7
+max_sprites = 8
 
 
 [controls]
-speeds = [1, 2, 4]      # decided
+speeds = [1, 2, 4]
 
 
 # sound events (doc/sound.md). the recordings come from art/sounds/, named
@@ -183,37 +184,38 @@
 # the placeholder for an event without a recording, as notes of [frequency in
 # Hz, seconds].
 [sound]
-enabled = true          # proto, until the player switches sound on or off in the game
-volume = 0.8            # guess, all sounds
-beep_wave = "square"    # proto
+enabled = true          # until the player switches sound on or off in the game
+volume = 0.8            # base for all sounds
+beep_wave = "square"
 
 [sound.event]
-t0_attack = { volume = 0.6 }        # guess
-t1_shot = { volume = 0.4 }          # guess
-t2_shot = { volume = 0.4 }          # guess
-t3_shot = { volume = 0.5 }          # guess
-monster_enter = { volume = 0.4 }    # guess, every monster for now (decided, to playtest)
-monster_exit = { volume = 0.8 }     # guess
-monster_die = { volume = 0.5 }      # guess
-monster_hit = { volume = 0.2, min_interval = 0.05, beep = [[1200, 0.03]] }    # guess
-boss_enter = { volume = 1.0 }       # guess
-boss_exit = { volume = 1.0 }        # guess
-boss_die = { volume = 1.0 }         # guess
-coins_arrive = { volume = 0.25, min_interval = 0.08, beep = [[1568, 0.04], [2093, 0.06]] }    # guess
-wave_start = { volume = 0.4, beep = [[440, 0.1], [660, 0.15]] }     # guess
-early_bonus = { volume = 0.4, beep = [[880, 0.06], [1175, 0.06], [1760, 0.1]] }   # guess
-tower_built = { volume = 0.4, beep = [[330, 0.05], [494, 0.08]] }   # guess
-tower_upgraded = { volume = 0.4, beep = [[392, 0.05], [587, 0.05], [784, 0.08]] }   # guess
-tower_sold = { volume = 0.4, beep = [[494, 0.05], [330, 0.08]] }    # guess
-placement_refused = { volume = 0.4, beep = [[220, 0.12], [165, 0.18]] }   # guess
-button_tap = { volume = 0.3, beep = [[1000, 0.02]] }    # guess
-map_won = { volume = 1.0 }          # guess
-map_lost = { volume = 1.0 }         # guess
+t0_attack = { volume = 0.6 }
+t1_shot = { volume = 0.4 }
+t2_shot = { volume = 0.4 }
+t3_shot = { volume = 0.5 }
+monster_enter = { volume = 0.4 }
+monster_exit = { volume = 0.8 }
+monster_die = { volume = 0.5 }
+monster_hit = { volume = 0.2, min_interval = 0.05, beep = [[1200, 0.03]] }
+boss_enter = { volume = 1.0 }
+boss_exit = { volume = 1.0 }
+boss_die = { volume = 1.0 }
+coins_arrive = { volume = 0.25, min_interval = 0.08, beep = [[1568, 0.04], [2093, 0.06]] }
+wave_start = { volume = 0.4, beep = [[440, 0.1], [660, 0.15]] }
+early_bonus = { volume = 0.4, beep = [[880, 0.06], [1175, 0.06], [1760, 0.1]] }
+tower_built = { volume = 0.4, beep = [[330, 0.05], [494, 0.08]] }
+tower_upgraded = { volume = 0.4, beep = [[392, 0.05], [587, 0.05], [784, 0.08]] }
+tower_sold = { volume = 0.4, beep = [[494, 0.05], [330, 0.08]] }
+placement_refused = { volume = 0.4, beep = [[220, 0.12], [165, 0.18]] }
+button_tap = { volume = 0.3, beep = [[1000, 0.02]] }
+map_won = { volume = 1.0 }
+map_lost = { volume = 1.0 }
 
 
 # sprite drawing direction (art.md): angle the drawing points to as drawn,
 # 0 right, -90 up. sprites not listed do not turn. set by hand, the towers
 # checked in temp/preview/towers.png.
+# adjusted by hand.
 [art.angle]
 t1 = -2
 t1_2 = -3
@@ -239,7 +241,8 @@
 # temp/preview/towers.png. t1: the centre of the base square measured on
 # source_sheet_2 cutouts. t2: the middle of the rows at least 60 % as wide as
 # the widest row, which leaves out the barrel. t3: the centroid of the shape
-# with parts narrower than 41 pixels removed, an estimate adjusted by hand.
+# with parts narrower than 41 pixels removed.
+# adjusted by hand.
 [art.pivot]
 t1 = [0.37, 0.5]
 t1_2 = [0.30, 0.5]
@@ -285,160 +288,173 @@
 
 # maps. waves: number of each monster in the wave. the boss spawns first, the
 # others follow one per spawn interval, in random order. the boss is in the
-# last wave.
+# last wave. monster_share, wave_size and first_wave are the numbers
+# tools/balance.py --draft makes wave lists from; the game does not use them.
 
 [map.0]
-starting_coins = 10                     # notes
-early_bonus = 0.05                      # guess (starting coins / 200), coins per second left
-wave_count = 6                          # guess
-monster_share = [40, 25, 15, 10, 10]    # guess, % of regular monster coins, m0-m4
-spawn_interval = 1.0                    # proto, seconds between spawns
+starting_coins = 10
+early_bonus = 0.05
+wave_count = 6
+monster_share = [36, 25, 18, 12, 9]     # fitted in tools/simulate.js; % of regular monsters by count, m0-m4
+wave_size = [4, 7]                      # fitted; regular monsters in the first and the last wave (draft, tools/balance.py)
+first_wave = [1, 2, 2, 4, 5]            # fitted; wave in which each monster level first appears, m0-m4 (draft)
+spawn_interval = 1.0                    # fitted; seconds between spawns
 path_half_width = 19                    # measured from the earlier masks, centre line to road edge
-spawn_distance = 50                     # decided, from where the path leaves the entrance
-exit_distance = 40                      # decided, from where the path enters the exit
+spawn_distance = 50
+exit_distance = 40
 
 [map.1]
-starting_coins = 20                     # notes
-early_bonus = 0.1                       # guess
-wave_count = 8                          # guess
-monster_share = [30, 25, 20, 15, 10]    # guess
-spawn_interval = 1.0                    # proto, seconds between spawns
-path_half_width = 17                    # measured from the earlier masks, centre line to road edge
-spawn_distance = 50                     # decided, from where the path leaves the entrance
-exit_distance = 40                      # decided, from where the path enters the exit
+starting_coins = 20
+early_bonus = 0.1
+wave_count = 8
+monster_share = [36, 25, 18, 12, 9]
+wave_size = [6, 17]
+first_wave = [1, 2, 3, 5, 6]
+spawn_interval = 0.65
+path_half_width = 17
+spawn_distance = 50
+exit_distance = 40
 
 [map.2]
-starting_coins = 40                     # notes
-early_bonus = 0.2                       # guess
-wave_count = 10                         # guess
-monster_share = [20, 20, 20, 20, 20]    # guess
-spawn_interval = 0.8                    # proto, seconds between spawns
-path_half_width = 16                    # measured from the earlier masks, centre line to road edge
-spawn_distance = 50                     # decided, from where the path leaves the entrance
-exit_distance = 40                      # decided, from where the path enters the exit
+starting_coins = 30
+early_bonus = 0.2
+wave_count = 10
+monster_share = [39, 26, 17, 11, 7]
+wave_size = [10, 36]
+first_wave = [1, 2, 4, 6, 8]
+spawn_interval = 0.65
+path_half_width = 16
+spawn_distance = 50
+exit_distance = 40
 
 [map.3]
-starting_coins = 60                     # notes (the sheet says 50)
-early_bonus = 0.3                       # guess
-wave_count = 12                         # guess
-monster_share = [15, 15, 20, 25, 25]    # guess
-spawn_interval = 0.7                    # proto, seconds between spawns
-path_half_width = 22                    # measured from the earlier masks, centre line to road edge
-spawn_distance = 50                     # decided, from where the path leaves the entrance
-exit_distance = 40                      # decided, from where the path enters the exit
+starting_coins = 40
+early_bonus = 0.3
+wave_count = 12
+monster_share = [52, 26, 13, 6, 3]
+wave_size = [5, 16]
+first_wave = [1, 2, 4, 6, 9]
+spawn_interval = 0.5
+path_half_width = 22
+spawn_distance = 50
+exit_distance = 40
+
+# map0: drafted by tools/balance.py --draft from wave_count 6, wave_size [4, 7],
+# monster_share [36, 25, 18, 12, 9], first_wave [1, 2, 2, 4, 5]
+
+[[map.0.wave]]   # wave 1, 4 monsters, 20 hp, 4 coins
+monsters = { m0 = 4 }
+
+[[map.0.wave]]   # wave 2, 5 monsters, 45 hp, 6 coins
+monsters = { m0 = 2, m1 = 2, m2 = 1 }
+
+[[map.0.wave]]   # wave 3, 5 monsters, 45 hp, 6 coins
+monsters = { m0 = 2, m1 = 2, m2 = 1 }
+
+[[map.0.wave]]   # wave 4, 6 monsters, 65 hp, 8 coins
+monsters = { m0 = 2, m1 = 2, m2 = 1, m3 = 1 }
+
+[[map.0.wave]]   # wave 5, 6 monsters, 90 hp, 10 coins
+monsters = { m0 = 1, m1 = 2, m2 = 1, m3 = 1, m4 = 1 }
+
+[[map.0.wave]]   # wave 6, 7 monsters, 130 hp, 14 coins + boss 30
+monsters = { m0 = 1, m1 = 1, m2 = 1, m3 = 2, m4 = 2, b0 = 1 }
+
+# map1: drafted by tools/balance.py --draft from wave_count 8, wave_size [6, 17],
+# monster_share [36, 25, 18, 12, 9], first_wave [1, 2, 3, 5, 6]
+
+[[map.1.wave]]   # wave 1, 6 monsters, 30 hp, 6 coins
+monsters = { m0 = 6 }
+
+[[map.1.wave]]   # wave 2, 8 monsters, 55 hp, 8 coins
+monsters = { m0 = 5, m1 = 3 }
+
+[[map.1.wave]]   # wave 3, 9 monsters, 80 hp, 11 coins
+monsters = { m0 = 4, m1 = 3, m2 = 2 }
+
+[[map.1.wave]]   # wave 4, 11 monsters, 105 hp, 14 coins
+monsters = { m0 = 4, m1 = 4, m2 = 3 }
+
+[[map.1.wave]]   # wave 5, 12 monsters, 135 hp, 17 coins
+monsters = { m0 = 4, m1 = 3, m2 = 3, m3 = 2 }
 
-# map0: draft, made from the monster shares; coin value grows with the wave number
+[[map.1.wave]]   # wave 6, 14 monsters, 210 hp, 24 coins
+monsters = { m0 = 3, m1 = 3, m2 = 3, m3 = 3, m4 = 2 }
+
+[[map.1.wave]]   # wave 7, 15 monsters, 240 hp, 27 coins
+monsters = { m0 = 3, m1 = 3, m2 = 3, m3 = 3, m4 = 3 }
+
+[[map.1.wave]]   # wave 8, 17 monsters, 290 hp, 32 coins + boss 50
+monsters = { m0 = 3, m1 = 3, m2 = 3, m3 = 4, m4 = 4, b1 = 1 }
+
+# map2: drafted by tools/balance.py --draft from wave_count 10, wave_size [10, 36],
+# monster_share [39, 26, 17, 11, 7], first_wave [1, 2, 4, 6, 8]
+
+[[map.2.wave]]   # wave 1, 10 monsters, 50 hp, 10 coins
+monsters = { m0 = 10 }
+
+[[map.2.wave]]   # wave 2, 13 monsters, 85 hp, 13 coins
+monsters = { m0 = 9, m1 = 4 }
+
+[[map.2.wave]]   # wave 3, 16 monsters, 110 hp, 16 coins
+monsters = { m0 = 10, m1 = 6 }
+
+[[map.2.wave]]   # wave 4, 19 monsters, 160 hp, 22 coins
+monsters = { m0 = 9, m1 = 7, m2 = 3 }
 
-[[map.0.wave]]   # wave 1, 4 coins
-monsters = { m0 = 2, m1 = 1 }
+[[map.2.wave]]   # wave 5, 22 monsters, 195 hp, 27 coins
+monsters = { m0 = 10, m1 = 7, m2 = 5 }
+
+[[map.2.wave]]   # wave 6, 24 monsters, 250 hp, 32 coins
+monsters = { m0 = 9, m1 = 7, m2 = 5, m3 = 3 }
+
+[[map.2.wave]]   # wave 7, 27 monsters, 305 hp, 38 coins
+monsters = { m0 = 9, m1 = 7, m2 = 6, m3 = 5 }
+
+[[map.2.wave]]   # wave 8, 30 monsters, 410 hp, 48 coins
+monsters = { m0 = 8, m1 = 7, m2 = 6, m3 = 6, m4 = 3 }
 
-[[map.0.wave]]   # wave 2, 7 coins
+[[map.2.wave]]   # wave 9, 33 monsters, 485 hp, 56 coins
+monsters = { m0 = 8, m1 = 7, m2 = 7, m3 = 6, m4 = 5 }
+
+[[map.2.wave]]   # wave 10, 36 monsters, 565 hp, 64 coins + boss 70
+monsters = { m0 = 8, m1 = 7, m2 = 7, m3 = 7, m4 = 7, b2 = 1 }
+
+# map3: drafted by tools/balance.py --draft from wave_count 12, wave_size [5, 16],
+# monster_share [52, 26, 13, 6, 3], first_wave [1, 2, 4, 6, 9]
+
+[[map.3.wave]]   # wave 1, 5 monsters, 25 hp, 5 coins
+monsters = { m0 = 5 }
+
+[[map.3.wave]]   # wave 2, 6 monsters, 35 hp, 6 coins
 monsters = { m0 = 5, m1 = 1 }
 
-[[map.0.wave]]   # wave 3, 10 coins
-monsters = { m0 = 3, m1 = 2, m2 = 1 }
-
-[[map.0.wave]]   # wave 4, 14 coins
-monsters = { m0 = 7, m1 = 2, m2 = 1 }
-
-[[map.0.wave]]   # wave 5, 17 coins
-monsters = { m0 = 6, m1 = 2, m2 = 1, m3 = 1 }
+[[map.3.wave]]   # wave 3, 7 monsters, 45 hp, 7 coins
+monsters = { m0 = 5, m1 = 2 }
 
-[[map.0.wave]]   # wave 6, 20 coins + boss 30
-monsters = { m0 = 5, m1 = 1, m2 = 1, m3 = 1, m4 = 1, b0 = 1 }
-
-# map1: draft, made from the monster shares; coin value grows with the wave number
-
-[[map.1.wave]]   # wave 1, 4 coins
-monsters = { m0 = 4 }
-
-[[map.1.wave]]   # wave 2, 8 coins
-monsters = { m0 = 4, m1 = 2 }
-
-[[map.1.wave]]   # wave 3, 12 coins
+[[map.3.wave]]   # wave 4, 8 monsters, 60 hp, 9 coins
 monsters = { m0 = 5, m1 = 2, m2 = 1 }
 
-[[map.1.wave]]   # wave 4, 17 coins
-monsters = { m0 = 6, m1 = 2, m2 = 1, m3 = 1 }
+[[map.3.wave]]   # wave 5, 9 monsters, 70 hp, 10 coins
+monsters = { m0 = 5, m1 = 3, m2 = 1 }
 
-[[map.1.wave]]   # wave 5, 21 coins
+[[map.3.wave]]   # wave 6, 10 monsters, 85 hp, 12 coins
+monsters = { m0 = 5, m1 = 3, m2 = 2 }
+
+[[map.3.wave]]   # wave 7, 11 monsters, 105 hp, 14 coins
 monsters = { m0 = 5, m1 = 3, m2 = 2, m3 = 1 }
 
-[[map.1.wave]]   # wave 6, 25 coins
-monsters = { m0 = 7, m1 = 4, m2 = 2, m3 = 1 }
-
-[[map.1.wave]]   # wave 7, 29 coins
-monsters = { m0 = 7, m1 = 3, m2 = 2, m3 = 1, m4 = 1 }
-
-[[map.1.wave]]   # wave 8, 33 coins + boss 50
-monsters = { m0 = 7, m1 = 3, m2 = 2, m3 = 2, m4 = 1, b1 = 1 }
-
-# map2: draft, made from the monster shares; coin value grows with the wave number
-
-[[map.2.wave]]   # wave 1, 6 coins
-monsters = { m0 = 6 }
-
-[[map.2.wave]]   # wave 2, 12 coins
-monsters = { m0 = 6, m1 = 3 }
+[[map.3.wave]]   # wave 8, 12 monsters, 110 hp, 15 coins
+monsters = { m0 = 6, m1 = 3, m2 = 2, m3 = 1 }
 
-[[map.2.wave]]   # wave 3, 18 coins
-monsters = { m0 = 8, m1 = 5 }
-
-[[map.2.wave]]   # wave 4, 24 coins
-monsters = { m0 = 7, m1 = 4, m2 = 3 }
-
-[[map.2.wave]]   # wave 5, 30 coins
-monsters = { m0 = 5, m1 = 2, m2 = 3, m3 = 3 }
-
-[[map.2.wave]]   # wave 6, 36 coins
-monsters = { m0 = 6, m1 = 2, m2 = 2, m3 = 2, m4 = 2 }
-
-[[map.2.wave]]   # wave 7, 42 coins
-monsters = { m0 = 7, m1 = 3, m2 = 3, m3 = 2, m4 = 2 }
-
-[[map.2.wave]]   # wave 8, 48 coins
-monsters = { m0 = 7, m1 = 4, m2 = 3, m3 = 3, m4 = 2 }
-
-[[map.2.wave]]   # wave 9, 53 coins
-monsters = { m0 = 7, m1 = 5, m2 = 4, m3 = 3, m4 = 2 }
+[[map.3.wave]]   # wave 9, 13 monsters, 120 hp, 16 coins
+monsters = { m0 = 6, m1 = 4, m2 = 2, m3 = 1 }
 
-[[map.2.wave]]   # wave 10, 59 coins + boss 70
-monsters = { m0 = 7, m1 = 5, m2 = 4, m3 = 3, m4 = 3, b2 = 1 }
-
-# map3: draft, made from the monster shares; coin value grows with the wave number
-
-[[map.3.wave]]   # wave 1, 6 coins
-monsters = { m0 = 6 }
-
-[[map.3.wave]]   # wave 2, 13 coins
-monsters = { m0 = 7, m1 = 3 }
-
-[[map.3.wave]]   # wave 3, 19 coins
-monsters = { m0 = 9, m1 = 5 }
-
-[[map.3.wave]]   # wave 4, 26 coins
-monsters = { m0 = 6, m1 = 4, m2 = 4 }
-
-[[map.3.wave]]   # wave 5, 32 coins
-monsters = { m0 = 7, m1 = 5, m2 = 5 }
+[[map.3.wave]]   # wave 10, 14 monsters, 150 hp, 19 coins
+monsters = { m0 = 6, m1 = 4, m2 = 2, m3 = 1, m4 = 1 }
 
-[[map.3.wave]]   # wave 6, 38 coins
-monsters = { m0 = 5, m1 = 4, m2 = 3, m3 = 4 }
-
-[[map.3.wave]]   # wave 7, 45 coins
-monsters = { m0 = 7, m1 = 3, m2 = 4, m3 = 5 }
-
-[[map.3.wave]]   # wave 8, 51 coins
-monsters = { m0 = 4, m1 = 2, m2 = 3, m3 = 4, m4 = 3 }
+[[map.3.wave]]   # wave 11, 15 monsters, 170 hp, 21 coins
+monsters = { m0 = 6, m1 = 4, m2 = 2, m3 = 2, m4 = 1 }
 
-[[map.3.wave]]   # wave 9, 58 coins
-monsters = { m0 = 5, m1 = 2, m2 = 3, m3 = 4, m4 = 4 }
-
-[[map.3.wave]]   # wave 10, 64 coins
-monsters = { m0 = 6, m1 = 3, m2 = 4, m3 = 4, m4 = 4 }
-
-[[map.3.wave]]   # wave 11, 71 coins
-monsters = { m0 = 6, m1 = 3, m2 = 3, m3 = 5, m4 = 5 }
-
-[[map.3.wave]]   # wave 12, 77 coins + boss 100
-monsters = { m0 = 7, m1 = 4, m2 = 4, m3 = 5, m4 = 5, b3 = 1 }
+[[map.3.wave]]   # wave 12, 16 monsters, 185 hp, 23 coins + boss 100
+monsters = { m0 = 6, m1 = 4, m2 = 3, m3 = 2, m4 = 1, b3 = 1 }
--- a/config/routes.toml	Tue Oct 20 03:08:56 2026 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,15 +0,0 @@
-# manual corrections to the routes that tools/build.py extracts from the masks.
-#
-# route numbers are those the build prints, counted from 0 per map, before
-# any correction. they change when a mask changes, so check the build output
-# and temp/preview/ after editing a mask.
-#
-# per map, all optional:
-#
-#   [map.2]
-#   drop = [1, 3]                   # remove these routes
-#   weights = { "0" = 2.0 }         # fixed weights, no route preference
-#
-#   [[map.2.route]]                 # replace a route with hand-placed points
-#   replace = 4                     # leave out to add a new route
-#   points = [[90, 85], [240, 90], [250, 400]]
--- a/doc/architecture.md	Tue Oct 20 03:08:56 2026 +0200
+++ b/doc/architecture.md	Tue Oct 20 12:04:42 2026 +0200
@@ -21,7 +21,6 @@
         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
-        routes.toml     manual corrections to the extracted routes
     tools/          python build scripts
     game/           hand-written game files
         index.html
@@ -155,15 +154,52 @@
   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 factor on all monster hp
+  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.
 
-a headless simulation will check the calculation. it runs the game logic
-from game/js/ in node, with MM.audio and MM.assets.size replaced by stubs,
-and plays the naive and greedy players. the seeded random generator makes a
-run repeatable. it is built after the calculation.
+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:
+
+    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 and main.js are left out. 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. the debug switches are forced off.
+
+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.
+
+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.
+
+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.
 
 
 routes
@@ -186,9 +222,7 @@
 6. record length and turning for each route
 
 map0 and map3 give one route each. map1 and map2 give several; map2 may give
-more than wanted. config/routes.toml can drop routes, set fixed weights, or
-replace a route with hand-placed points, for cases where the automatic result
-is wrong.
+more than wanted. where the automatic result is wrong, the mask is redrawn.
 
 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
@@ -275,8 +309,8 @@
 - 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 and
-  pause. the
-  tower shop sits on the right in landscape and at the bottom in portrait
+  pause. 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
 
 input:
--- a/doc/balance.md	Tue Oct 20 03:08:56 2026 +0200
+++ b/doc/balance.md	Tue Oct 20 12:04:42 2026 +0200
@@ -48,20 +48,27 @@
 monsters
 --------
 
-| monster | hp | coins | speed | source |
-|---------|----|-------|-------|--------|
-| m0      | 5  | 1     | 35    | hp, coins: notes; speed: guess |
-| m1      | 10 | 2     | 40    | as above |
-| m2      | 15 | 3     | 45    | as above |
-| m3      | 20 | 4     | 40    | as above |
-| m4      | 30 | 6     | 35    | as above |
-| b0      | 150 | 30   | 25    | hp: decided, 5 x the notes; coins: notes; speed: guess |
-| b1      | 250 | 50   | 25    | as above |
-| b2      | 350 | 70   | 25    | as above |
-| b3      | 500 | 100  | 25    | as above |
+| monster | hp | coins | coins per hp | speed | source |
+|---------|----|-------|--------------|-------|--------|
+| m0      | 5  | 1     | 0.20         | 35    | hp, coins: notes; speed: guess |
+| m1      | 10 | 1     | 0.10         | 40    | hp: notes; coins: decided (was 2); speed: guess |
+| m2      | 15 | 2     | 0.13         | 45    | hp: notes; coins: decided (was 3); speed: guess |
+| m3      | 20 | 2     | 0.10         | 40    | hp: notes; coins: decided (was 4); speed: guess |
+| m4      | 30 | 3     | 0.10         | 35    | hp: notes; coins: decided (was 6); speed: guess |
+| b0      | 150 | 30   | 0.20         | 25    | hp: decided, 5 x the notes; coins: notes; speed: guess |
+| b1      | 250 | 50   | 0.20         | 25    | as above |
+| b2      | 350 | 70   | 0.20         | 25    | as above |
+| b3      | 500 | 100  | 0.20         | 25    | as above |
 
-monsters and bosses drop 0.2 coins per hp (derived). the notes gave bosses
-hp equal to their coins; balancing raised it to 5 times that (decided).
+monster hp is the same on every map (decided). a monster that took two hits
+on one map must not take four on a later one. a map gets harder through the
+size of its waves and the mix of monsters.
+
+the notes had every monster drop 0.2 coins per hp. regular monster coins are
+now set apart from hp (decided): m0 keeps 0.2, the others drop 0.10 to 0.13.
+the mix of monsters then sets the coins per hp of a map. the notes gave
+bosses hp equal to their coins; balancing raised it to 5 times that
+(decided).
 
 time to walk the whole path at 35-45 speed (derived): map0 about 50 s, map3
 about 23 s.
@@ -107,8 +114,7 @@
   divided by the reference speed, limited to -1..1
 - route weight = 1 + bias * speed factor * (2 * route value - 1), at least 0.1
 - a monster at the reference speed sees all routes as equally likely
-- a boss always takes the shortest route (decided). a route with a fixed
-  weight of 0 is left out
+- a boss always takes the shortest route (decided)
 
 | parameter       | value | source |
 |-----------------|-------|--------|
@@ -222,41 +228,35 @@
 economy
 -------
 
-| map  | starting coins | coins dropped in total | boss coins | regular monster coins | regular monster hp |
-|------|----------------|------------------------|------------|-----------------------|--------------------|
-| map0 | 10             | 100                    | 30         | 70                    | 350                |
-| map1 | 20             | 200                    | 50         | 150                   | 750                |
-| map2 | 40             | 400                    | 70         | 330                   | 1650               |
-| map3 | 60             | 600                    | 100        | 500                   | 2500               |
+| map  | starting coins |
+|------|----------------|
+| map0 | 10             |
+| map1 | 20             |
+| map2 | 40             |
+| map3 | 60             |
 
-starting coins and the 10 x starting coins total are from the notes; the rest
-is derived. early wave bonuses come on top of this total.
-
-the source sheet gives 50 starting coins for map3. the notes raise it to 60 to
-make the step from map1 to map3 more even (10, 20, 40, 60 instead of 10, 20,
-40, 50). likely to change after playtesting.
-
-share of the regular monster coins by monster level (guess). all monster
-levels appear on all maps (decided):
+starting coins are from the notes. the source sheet gives 50 for map3. the
+notes raise it to 60 to make the step from map1 to map3 more even (10, 20,
+40, 60 instead of 10, 20, 40, 50). likely to change after playtesting.
 
-| map  | m0   | m1   | m2   | m3   | m4   |
-|------|------|------|------|------|------|
-| map0 | 40 % | 25 % | 15 % | 10 % | 10 % |
-| map1 | 30 % | 25 % | 20 % | 15 % | 10 % |
-| map2 | 20 % | 20 % | 20 % | 20 % | 20 % |
-| map3 | 15 % | 15 % | 20 % | 25 % | 25 % |
+the notes set the coins dropped per map to 10 times the starting coins. this
+is no longer a target (decided): the coins a map pays follow from its waves.
+the build prints, per map, the coins dropped by regular monsters and the
+boss, the total with the starting coins, and the coins per hp of the regular
+monsters.
 
-resulting monster counts (derived, rounded):
+coins per map from the current wave lists (derived):
 
-| map  | m0 | m1 | m2 | m3 | m4 | monsters | coins |
-|------|----|----|----|----|----|----------|-------|
-| map0 | 28 | 9  | 4  | 2  | 1  | 44       | 72    |
-| map1 | 45 | 19 | 10 | 6  | 2  | 82       | 149   |
-| map2 | 66 | 33 | 22 | 16 | 11 | 148      | 328   |
-| map3 | 75 | 38 | 33 | 31 | 21 | 198      | 500   |
+| map  | regular monsters | boss | dropped in all | with starting coins | regular hp | coins per hp |
+|------|------------------|------|----------------|---------------------|------------|--------------|
+| map0 | 48               | 30   | 78             | 88                  | 395        | 0.12         |
+| map1 | 139              | 50   | 189            | 209                 | 1145       | 0.12         |
+| map2 | 326              | 70   | 396            | 436                 | 2615       | 0.12         |
+| map3 | 157              | 100  | 257            | 317                 | 1160       | 0.14         |
 
-the build prints these totals from the actual wave lists and warns when a map
-is more than 5 % off its coin total.
+early start bonuses come on top.
+
+all monster levels appear on all maps (decided).
 
 
 waves
@@ -266,17 +266,58 @@
 |------------------------------------|---------------------|--------|
 | waves per map                      | 6, 8, 10, 12        | guess  |
 | break before the first wave        | 40 s                | guess  |
-| break between waves               | 25 s                | guess ("longer", decided) |
-| time between spawns               | 1.0, 1.0, 0.8, 0.7 s by map | guess |
+| break between waves, from the last spawn of a wave | 25 s | guess ("longer", decided) |
+| time between spawns               | 1.0, 0.65, 0.65, 0.5 s by map | guess, fitted in the simulation |
 | early start bonus, coins per second left | 0.05, 0.1, 0.2, 0.3 by map | guess (starting coins / 200) |
 
 the bonus is rounded down. if every break is skipped at once, the bonus adds
 about 6, 17, 45 and 82 coins per map (derived).
 
-suggested shape of a map's waves (guess): the coin value of wave n grows in
-proportion to n, so the last wave is the largest. the boss comes in the last
-wave and spawns first. later waves mix monster levels; early waves are mostly
-m0 and m1.
+shape of a map's waves (decided): each wave is at least as hard as the one
+before, and the last wave is the largest. the boss comes in the last wave and
+spawns first. early waves are mostly m0 and m1; later waves mix monster
+levels.
+
+the wave lists in the config are drafted by tools/balance.py
+(architecture.md) from a few numbers per map, and may be edited by hand
+afterwards:
+
+- the number of waves
+- the number of regular monsters in the first and in the last wave. the waves
+  between grow in equal steps
+- the share of each monster level in the map's regular monsters, by count
+- the wave in which each monster level first appears
+
+each monster level gets a weight per wave that grows by one per wave from its
+first wave. the weights are scaled until the wave sizes and the shares are
+met, then rounded to whole monsters per wave. later waves therefore hold more
+of the levels that came in late. every level keeps at least one monster.
+
+the draft numbers are kept in the map's section of the config, next to the
+other map settings. the game does not read them.
+
+draft numbers, fitted in the simulation to the targets in balancing
+(guess):
+
+| map  | waves | regular monsters, first and last wave | share by count, m0-m4 | first wave of m0-m4 |
+|------|-------|-----------------|---------------------|---------------|
+| map0 | 6     | 4, 7            | 36, 25, 18, 12, 9 % | 1, 2, 2, 4, 5 |
+| map1 | 8     | 6, 17           | 36, 25, 18, 12, 9 % | 1, 2, 3, 5, 6 |
+| map2 | 10    | 10, 36          | 39, 26, 17, 11, 7 % | 1, 2, 4, 6, 8 |
+| map3 | 12    | 5, 16           | 52, 26, 13, 6, 3 %  | 1, 2, 4, 6, 9 |
+
+resulting monster counts (derived):
+
+| map  | m0 | m1 | m2 | m3 | m4 | regular monsters |
+|------|----|----|----|----|----|------------------|
+| map0 | 12 | 9  | 5  | 4  | 3  | 33               |
+| map1 | 32 | 22 | 17 | 12 | 9  | 92               |
+| map2 | 90 | 59 | 39 | 27 | 15 | 230              |
+| map3 | 65 | 33 | 17 | 8  | 3  | 126              |
+
+map3 has fewer and weaker monsters than map2. its 60 starting coins already
+pay for much of what the naive player needs against b3, so the waves before
+may pay only about 130 coins (see balancing).
 
 
 hearts
@@ -298,7 +339,8 @@
 | most coin sprites for one death  | 8     | guess  |
 
 coins are added to the counter at the moment the monster dies; the flying
-coins only show it (guess). this keeps the counter correct for a player who
+coins only show it (guess). the same holds for an early start bonus, whose
+coins fly from the exits. this keeps the counter correct for a player who
 builds right after a kill.
 
 
@@ -313,9 +355,9 @@
 balancing
 ---------
 
-the values above were set without a way to estimate their effect, and the
-game is far too easy. two t1 towers win every map, t2 is never needed, and
-many coins are left over when a map is won. the aim is a game where the
+the first values were set without a way to estimate their effect, and the
+game was far too easy. two t1 towers won every map, t2 was never needed, and
+many coins were left over when a map was won. the aim is a game where the
 player has to think about where to place towers and which ones to build. a
 player who only buys plain firepower should need nearly every coin a map
 pays in order to win it. coins left over then come from better choices.
@@ -336,9 +378,11 @@
   attack times
 - shop prices are set first. hp, damage and the wave mix are then fitted to
   them
-- the main control is coins per hp. regular monsters drop 0.2 coins per hp,
-  so a map's difficulty and its income grow together. a map gets harder when
-  its hp go up while its coins stay the same
+- the main control is coins per hp, set by the mix of monsters. m0 drops
+  0.2 coins per hp, the other regular monsters 0.10 to 0.13. a mix with
+  fewer m0 pays less for the same hp
+- monster hp stays the same on every map. wave size and the mix make a map
+  harder
 
 the coins of the last wave, the boss's included, arrive when the map is as
 good as won. leftover coins are therefore measured at the start of the last
@@ -402,13 +446,45 @@
 level 1 reaches 0.67 against a single target, kills an m0 in one hit and
 damages every monster in range. it may be the better buy for a naive
 player than t1, so the calculation lists value per coin for every tower and
-level, area damage included.
+level, area damage included. the simulation measures 1.2 to 1.7 monsters
+hit per t0 attack over whole runs, on median cells as on the best ones.
+at that rate t0 at level 1 gives 0.8 to 1.1 against m0, two to three times
+t1.
 
 t2 works as a time multiplier. a slow to 0.6 of the speed gives 1.67 times
 the time in range for every tower covering the same stretch. this only
 helps against the single target demand, so t2 needs faster monsters or
 tough monsters spaced apart to pay off. it is tuned after the t1 baseline.
 
+tools/simulate.js (architecture.md) plays the same two players in the game
+code. with the fitted waves, the two tools agree on the coins on hand at
+each wave. they differ in the coins a wave needs:
+
+- the boss needs 5 to 20 % more in the simulation: 49, 143, 338 and 206
+  coins for the naive player against 40, 130, 320 and 170 in the
+  calculation. faster monsters overtake the boss and draw fire away from it
+- regular waves on map2 need up to 1.5 times as much. towers on median
+  cells cover the six routes unevenly, and monsters on a route with little
+  cover get through. the mean over routes hides this
+- about a tenth of the shots are lost because the target died before the
+  projectile arrived
+- route preference changes nothing: with bias 0 the results are the same,
+  since the speeds lie close to the reference speed
+- the players in the simulation also build during a wave, with coins from
+  the monsters killed in it
+
+tools/balance.py was left as it is. the waves were fitted with the
+simulation.
+
+with the fitted waves the naive player loses hearts to regular monsters
+only in the first two or three waves. towers stay and add up. what a wave
+demands, hp arriving per second, follows from the mix and the spawn
+interval; wave size sets how long the wave lasts and what it pays. the boss
+is the one demand that grows faster than the coins. the naive player loses
+its hearts there, 5 at once, in most runs. the target of about 5 hearts
+left is met on average over the seeds: the boss gets through in most runs
+and dies in a few.
+
 order of work (decided):
 
 1. the calculation, tools/balance.py (architecture.md): value per coin for
--- a/doc/game_design.md	Tue Oct 20 03:08:56 2026 +0200
+++ b/doc/game_design.md	Tue Oct 20 12:04:42 2026 +0200
@@ -91,8 +91,9 @@
 monsters
 --------
 
-- monsters m0-m4 are monster levels, drop 1/2/3/4/6 coins on death
-    hp 5/10/15/20/30
+- monsters m0-m4 are monster levels, drop 1/1/2/2/3 coins on death
+    hp 5/10/15/20/30, the same on every map
+    (the notes had 1/2/3/4/6 coins; balance.md, monsters)
 - all monster levels appear on all maps, in different amounts and proportions.
   low levels stay in the mix on later maps to balance the larger numbers
 - monsters emulate animation with slight bobbing, squish/stretch on x and y by a
@@ -105,7 +106,8 @@
 - hp bars are always shown above every monster. the boss uses its own bar, also
   above the boss. the bar turns blue while t2 slows the monster
 - dropped coins fly to the coin counter on their own. each coin uses a random
-  one of c0-c3
+  one of c0-c3. the coins of an early start bonus fly the same way, from the
+  level exit
 
 economy and waves
 -----------------
@@ -113,8 +115,9 @@
 - starting coins per map level: 10, 20, 40, 60
 - balance of monster speed vs tower fire frequency tbd, see balance.md,
   balancing
-- several monster waves per map with breaks between them, total 10*map
-  starting coins, last wave includes boss
+- several monster waves per map with breaks between them, last wave
+  includes boss. the notes set the coins per map to 10 times the starting
+  coins; this is no longer a target (balance.md, economy)
 - the break between waves counts down, and the next wave starts on its own
   when it runs out. a button starts the next wave early and pays a coin bonus
   based on the seconds left. this is how most tower defense games handle it
--- a/doc/roadmap.md	Tue Oct 20 03:08:56 2026 +0200
+++ b/doc/roadmap.md	Tue Oct 20 12:04:42 2026 +0200
@@ -9,8 +9,7 @@
       config.js
     - check: the processed tower levels look right
 2. maps and routes
-    - mask classification, placement grid, route extraction, routes.toml
-      corrections
+    - mask classification, placement grid, route extraction
     - previews in temp/preview/
     - check: routes on all four maps follow the paths, placement grid looks
       sensible
@@ -117,13 +116,12 @@
   simplified to 0.8 pixel tolerance
 - straightness for the route value is the least turning of the map's routes
   divided by the route's turning. turning is the total, not per length
-- routes.toml names routes by their number in the build output. the numbers
-  change when a mask changes
 - the road half widths are the median distance from the centre line to the
   edge of the earlier masks, which covered the whole road. map0's route is
   2068 long
-- the coin check compares all coins dropped, boss included, with 10 x
-  starting coins
+- the build prints the coins dropped per map, boss included, with and
+  without the starting coins. the earlier check against 10 x the starting
+  coins is gone (balance.md, economy)
 - the build prints the early start bonus for skipping every break, including
   the one before the first wave: 8, 21, 53, 94. balance.md gives 6, 17, 45,
   82, which leaves that break out. the game pays the bonus before the first
@@ -131,8 +129,9 @@
 
 config:
 
-- per map: [map.N] holds starting_coins, early_bonus, wave_count and
-  monster_share, followed by the [[map.N.wave]] lists
+- per map: [map.N] holds starting_coins, early_bonus, wave_count, the
+  draft numbers monster_share, wave_size and first_wave, followed by the
+  [[map.N.wave]] lists
 - added: hit_radius in [animation] (0.4 of the monster sprite's smaller
   side), min_weight in [route_preference] (the "at least 0.1" of the rule),
   [art.angle] and [art.pivot]. the turning towers turn around the middle of
@@ -167,9 +166,9 @@
   drawing; [art.screen] in game.toml holds where, measured by matching the
   images. its tap area is the button image. it pulses by 4 % over 1.2 s;
   under the mouse it is 8 % larger with a shadow
-- a break starts when all monsters of the wave are gone, killed or escaped,
-  not when the last one has spawned. during a break the wave counter shows
-  the next wave
+- a break starts when the last monster of the wave has spawned, not when
+  all of them are gone. monsters of the wave may still be on the map during
+  the break. during a break the wave counter shows the next wave
 - monsters move at constant speed; the hop is drawn only. a hop spends 80 %
   of its time in the air and 20 % landing. the idle bob is a slow breathing
   (1.3 s) on top of the hops, as monsters never stand still
@@ -218,10 +217,15 @@
   grows while the chosen shop item shows shop_bubble_dark and shrinks while
   it shows shop_bubble_dark2. the range circle does not pulse
 - flying coins: one sprite per coin, at most 8, started 0.05 s apart, flying
-  in game time on an arc. they are dropped when the map ends
+  in game time on an arc. they are dropped when the map ends. early start
+  bonus coins start at the exits, taking turns on a map with several, within
+  the exit's radius
 - top bar: coin_icon, heart and monster_icon with their counters. each
   counter keeps the width of a usual largest value (3, 2 and 5
-  characters), so the next one does not move. pause shows pause_button
+  characters), so the next one does not move. when the counters at those
+  widths and the buttons, early start included, do not fit side by side
+  (below about 750 css pixels), the buttons get a second row under the
+  counters, right-aligned as before. pause shows pause_button
   while the game runs and play_button while it is paused. speed shows the
   drawing of the current speed; debug speeds show their number. the early
   start button shows the countdown on next_wave, without the bonus. the top
--- a/game/js/game.js	Tue Oct 20 03:08:56 2026 +0200
+++ b/game/js/game.js	Tue Oct 20 12:04:42 2026 +0200
@@ -70,7 +70,7 @@
         if (this.result) return;
         var self = this;
         this.time += dt;
-        this.waves.update(dt, this.monsters.length, function (kind) {
+        this.waves.update(dt, function (kind) {
             var m = MM.monster.create(self, kind);
             self.monsters.push(m);
             MM.audio.play(m.boss ? "boss_enter" : "monster_enter");
@@ -127,20 +127,35 @@
         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
-            });
+            this.flight(m.x + (this.random() - 0.5) * m.w,
+                        m.y - m.h / 2 + (this.random() - 0.5) * m.h / 2, i);
         }
     };
 
+    // the i-th coin of a group flying from (x, y) to the counter
+    Game.prototype.flight = function (x, y, i) {
+        this.flights.push({
+            x: x,
+            y: y,
+            sprite: "c" + Math.floor(this.random() * 4),
+            // stagger the coins a little
+            t: -i * 0.05
+        });
+    };
+
+    // the bonus coins count at once and fly from the exits, taking turns
+    // if there are several
     Game.prototype.startEarly = function () {
         var bonus = this.waves.startEarly();
+        if (bonus <= 0) return;
         this.coins += bonus;
-        if (bonus > 0) MM.audio.play("early_bonus");
+        MM.audio.play("early_bonus");
+        var exits = this.map.data.exits;
+        var n = exits.length ? Math.min(bonus, cfg.coins.max_sprites) : 0;
+        for (var i = 0; i < n; i++) {
+            var e = exits[i % exits.length];
+            this.flight(e[0] + (this.random() - 0.5) * e[2], e[1] + (this.random() - 0.5) * e[2], i);
+        }
     };
 
     Game.prototype.towerAt = function (x, y) {
--- a/game/js/map.js	Tue Oct 20 03:08:56 2026 +0200
+++ b/game/js/map.js	Tue Oct 20 12:04:42 2026 +0200
@@ -28,7 +28,6 @@
         }
         this.length = d;
         this.value = data.value;
-        this.weight = data.weight;
         this.sideways(maxOffset);
     }
 
@@ -207,22 +206,19 @@
     };
 
     // route weights for a monster of the given speed (balance.md, route
-    // preference). fixed weights from routes.toml take precedence.
+    // preference)
     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
+    // index of the shortest route
     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;
--- a/game/js/render.js	Tue Oct 20 03:08:56 2026 +0200
+++ b/game/js/render.js	Tue Oct 20 12:04:42 2026 +0200
@@ -176,7 +176,8 @@
         }
     }
 
-    // coins flying from the monster to the coin counter, in screen pixels
+    // coins flying from a monster or an exit 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);
--- a/game/js/ui.js	Tue Oct 20 03:08:56 2026 +0200
+++ b/game/js/ui.js	Tue Oct 20 12:04:42 2026 +0200
@@ -9,7 +9,7 @@
 
     var cfg = MM.config;
     var A = MM.assets;
-    var TOP = 60;           // top bar height, css pixels
+    var TOP = 60;           // height of one top bar row, 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
@@ -25,6 +25,8 @@
     var PAPER = "#f6f1e6";
     var FONT = "bold 22px system-ui, -apple-system, Segoe UI, sans-serif";
     var TOWERS = ["t0", "t1", "t2", "t3"];
+    // widest usual values of the coin, heart and wave counters
+    var USUAL = ["000", "00", "00/00"];
     // each screen drawing, its separate button image and the button's action
     var SCREENS = {
         splash: { image: "splash_play", id: "play" },
@@ -53,19 +55,39 @@
         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
+    // width of the top bar counters, each at its widest usual value, for
+    // icons of the given size
+    function countersWidth(icon) {
+        var w = 0;
+        USUAL.forEach(function (s) { w += icon + 6 + numberWidth(s, DIGIT) + 18; });
+        return w - 18;
+    }
+
+    // width of the top bar buttons, the early start button included
+    function buttonsWidth() {
+        var s = cfg.sprites.next_wave;
+        return 3 * (BUTTON + 8) + BUTTON * s[0] / s[1];
+    }
+
+    // positions of everything on screen for a window of w x h css pixels.
+    // when the counters and the buttons do not fit side by side, the buttons
+    // get a second top bar row under the counters.
     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 land = w >= h, icon = 32;
+        var rows = 8 + countersWidth(icon) + 16 + buttonsWidth() + 8 > w ? 2 : 1;
+        var top = rows * TOP;
+        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,
+            top: top,                   // top bar height
+            buttonRow: top - TOP,       // top of the button row
             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 }
+            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 },
+            coinIcon: { x: 8 + icon / 2, y: TOP / 2, size: icon },
             screen: screenScale(w, h)
         };
         return L;
@@ -121,7 +143,7 @@
             return out;
         }
         // top bar, right to left
-        var y = (TOP - BUTTON) / 2, x = L.w - 8;
+        var y = L.buttonRow + (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 });
@@ -306,21 +328,21 @@
 
         // top bar: coins, hearts, wave
         ctx.fillStyle = "rgba(246, 241, 230, 0.92)";
-        ctx.fillRect(0, 0, L.w, TOP);
+        ctx.fillRect(0, 0, L.w, L.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);
+        ctx.fillRect(0, L.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) {
+        [["coin_icon", game.coins], ["heart", game.hearts],
+         ["monster_icon", game.waves.shown() + "/" + game.waves.list.length]
+        ].forEach(function (c, i) {
             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;
+            fit(ctx, c[0], x + ic.size / 2, ic.y, ic.size, ic.size);
+            number(ctx, s, x + ic.size + 6, ic.y, DIGIT, "left");
+            x += ic.size + 6 + Math.max(numberWidth(s, DIGIT), numberWidth(USUAL[i], DIGIT)) + 18;
         });
 
         var screen = screenName(game);
--- a/game/js/wave.js	Tue Oct 20 03:08:56 2026 +0200
+++ b/game/js/wave.js	Tue Oct 20 12:04:42 2026 +0200
@@ -8,8 +8,9 @@
     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).
+    // the wave's monsters, "done" follows the last wave. a break starts when
+    // the last monster of a wave has spawned, so monsters may still be on
+    // the map. random gives numbers in [0, 1).
     function Waves(mapIndex, firstWave, random) {
         var mc = cfg.maps[mapIndex];
         this.list = mc.waves;
@@ -63,9 +64,8 @@
         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) {
+    // advance by dt. spawn(kind) creates a monster.
+    Waves.prototype.update = function (dt, spawn) {
         if (this.phase === "break") {
             this.left -= dt;
             if (this.left <= 0) this.start();
@@ -77,10 +77,7 @@
                 spawn(this.take());
                 this.wait += this.interval;
             }
-            if (!this.pending.length) this.phase = "clearing";
-            return;
-        }
-        if (this.phase === "clearing" && alive === 0) {
+            if (this.pending.length) return;
             if (this.next >= this.list.length) {
                 this.phase = "done";
             } else {
--- a/tools/balance.py	Tue Oct 20 03:08:56 2026 +0200
+++ b/tools/balance.py	Tue Oct 20 12:04:42 2026 +0200
@@ -6,6 +6,7 @@
 temp/preview/balance.txt and the charts temp/preview/balance_*.png.
 
 usage: python3 tools/balance.py
+       python3 tools/balance.py --draft [MAP]
 
 towers are t1 only for the wave demands. two players: naive builds level 1
 towers on cells of median coverage whenever it can afford one; greedy picks
@@ -13,6 +14,12 @@
 damage per coin than a new tower. greedy also starts every wave early for
 the bonus.
 
+--draft prints wave lists for every map, or for map MAP, as toml to paste
+into config/game.toml. they are made from monster_share, wave_size and
+first_wave in the map's section (see draft_waves). the calculation then
+runs on the drafted lists instead of the ones in game.toml; balance.txt and
+the charts are not written.
+
 requires python 3.11 or later, numpy and matplotlib.
 """
 
@@ -38,8 +45,8 @@
 GREEDY_CELLS = 120
 # the tower the wave demands are measured against
 TOWER = "t1"
-# hp factors scanned for the margin charts
-FACTORS = np.round(np.arange(0.5, 6.001, 0.05), 2)
+# wave size factors scanned for the margin charts
+FACTORS = np.round(np.arange(0.5, 3.001, 0.05), 2)
 # hearts the naive player should have left at the end of a map (decided)
 HEARTS_TARGET = 5
 
@@ -69,8 +76,7 @@
 class MapCoverage:
     """
     legal placement cells of a map and the route samples each can reach.
-    routes with a fixed weight of 0 are left out; the boss route is the
-    shortest one.
+    the boss route is the shortest one.
     """
 
     def __init__(self, mp):
@@ -78,7 +84,7 @@
         idx = np.array([i for i, c in enumerate(mp["grid"]) if c == "1"])
         self.cells = np.column_stack([(idx % cols) * cell + cell // 2,
                                       (idx // cols) * cell + cell // 2]).astype(float)
-        routes = [r for r in mp["routes"] if r["weight"] != 0]
+        routes = mp["routes"]
         self.routes = [resample(r["points"], SAMPLE_STEP) for r in routes]
         self.boss_route = min(range(len(routes)), key=lambda i: routes[i]["length"])
         self.lengths = [r["length"] for r in routes]
@@ -125,15 +131,27 @@
 
 # waves
 
+def scale_counts(cfg, monsters, f):
+    """
+    a wave's monster counts with the regular ones scaled by f, rounded, at
+    least one regular monster left. the boss stays.
+    """
+    mons = cfg["monster"]
+    out = {k: (n if mons[k].get("boss") else math.floor(n * f + 0.5)) for k, n in monsters.items()}
+    reg = [k for k in monsters if not mons[k].get("boss")]
+    if reg and not any(out[k] for k in reg):
+        out[max(reg, key=lambda k: monsters[k])] = 1
+    return out
+
+
 class Wave:
     """
-    one wave with hp scaled by factor f (whole numbers, at least 1).
-    kinds: list of (count, hp, speed, coins, boss).
+    one wave. kinds: list of (count, hp, speed, coins, boss).
     """
 
-    def __init__(self, cfg, monsters, f, interval):
+    def __init__(self, cfg, monsters, interval):
         mons = cfg["monster"]
-        self.kinds = [(n, max(1, round(mons[k]["hp"] * f)), mons[k]["speed"], mons[k]["coins"],
+        self.kinds = [(n, mons[k]["hp"], mons[k]["speed"], mons[k]["coins"],
                        bool(mons[k].get("boss"))) for k, n in monsters.items() if n]
         reg = [k for k in self.kinds if not k[4]]
         self.boss = next((k for k in self.kinds if k[4]), None)
@@ -287,6 +305,77 @@
     return rows
 
 
+# drafting
+
+def draft_waves(cfg, m):
+    """
+    wave lists for map m from the draft numbers in its section: wave_count
+    waves, regular monster counts growing in equal steps from wave_size[0]
+    to wave_size[1], monster level i absent before wave first_wave[i]. the
+    counts of each level over the whole map follow monster_share.
+
+    each level starts with a weight that grows by one per wave from its
+    first wave, so later waves lean to the levels that came in later. the
+    weights are then scaled, alternately per wave and per level, until the
+    wave sizes and the level totals are met, and rounded per wave. every
+    level keeps at least one monster. the boss is added to the last wave.
+    returns a list of {monster: count}.
+    """
+    c = cfg["map"][str(m)]
+    regular = sorted(k for k, v in cfg["monster"].items() if not v.get("boss"))
+    n = c["wave_count"]
+    first, last = c["wave_size"]
+    sizes = np.array([round(first + (last - first) * w / max(1, n - 1)) for w in range(n)], float)
+    share = np.array(c["monster_share"], float)
+    totals = share / share.sum() * sizes.sum()
+    intro = np.array(c["first_wave"]) - 1
+    a = np.maximum(0, np.arange(n)[:, None] - intro[None, :] + 1).astype(float)
+    for _ in range(500):
+        a *= (sizes / np.maximum(a.sum(axis=1), 1e-12))[:, None]
+        a *= (totals / np.maximum(a.sum(axis=0), 1e-12))[None, :]
+    a *= (sizes / np.maximum(a.sum(axis=1), 1e-12))[:, None]
+    counts = np.floor(a).astype(int)
+    for w in range(n):
+        # largest remainders fill the wave up to its size
+        short = int(sizes[w]) - counts[w].sum()
+        for i in np.argsort(-(a[w] - counts[w]))[:short]:
+            counts[w, i] += 1
+    for i in range(len(regular)):
+        if counts[:, i].sum() == 0 and intro[i] < n:
+            counts[n - 1, i] += 1
+            counts[n - 1, int(np.argmax(counts[n - 1]))] -= 1
+    waves = [{k: int(v) for k, v in zip(regular, row) if v} for row in counts]
+    waves[-1][f"b{m}"] = 1
+    return waves
+
+
+def draft_toml(cfg, m, waves):
+    """the drafted waves as toml lines, each wave with its count, hp and coins."""
+    c = cfg["map"][str(m)]
+    mons = cfg["monster"]
+    lines = [f"# map{m}: drafted by tools/balance.py --draft from wave_count {c['wave_count']},"
+             f" wave_size {c['wave_size']},",
+             f"# monster_share {c['monster_share']}, first_wave {c['first_wave']}", ""]
+    for w, wave in enumerate(waves, start=1):
+        reg = {k: v for k, v in wave.items() if not mons[k].get("boss")}
+        boss = [k for k in wave if mons[k].get("boss")]
+        hp = sum(v * mons[k]["hp"] for k, v in reg.items())
+        coins = sum(v * mons[k]["coins"] for k, v in reg.items())
+        extra = "".join(f" + boss {mons[k]['coins']}" for k in boss)
+        lines += [f"[[map.{m}.wave]]   # wave {w}, {sum(reg.values())} monsters, {hp} hp,"
+                  f" {coins} coins{extra}",
+                  "monsters = { " + ", ".join(f"{k} = {v}" for k, v in wave.items()) + " }", ""]
+    return lines
+
+
+def draft_check(cfg, waves):
+    """warnings for drafted waves: a wave with less hp than the one before."""
+    mons = cfg["monster"]
+    hp = [sum(v * mons[k]["hp"] for k, v in w.items() if not mons[k].get("boss")) for w in waves]
+    return [f"wave {w + 1} has less hp than wave {w} ({hp[w]} < {hp[w - 1]})"
+            for w in range(1, len(hp)) if hp[w] < hp[w - 1]]
+
+
 # calculation
 
 def tower_table(cfg):
@@ -296,9 +385,10 @@
 
 
 def map_waves(cfg, m, f):
+    """the map's waves with regular monster counts scaled by f."""
     c = cfg["map"][str(m)]
     interval = c.get("spawn_interval", cfg["waves"]["spawn_interval"])
-    return [Wave(cfg, w["monsters"], f, interval) for w in c["wave"]]
+    return [Wave(cfg, scale_counts(cfg, w["monsters"], f), interval) for w in c["wave"]]
 
 
 def bonuses(cfg, m):
@@ -350,12 +440,21 @@
     return sum(r["res"]["hearts"] for r in rows)
 
 
-def factor_for_target(scan):
-    """smallest hp factor at which naive keeps HEARTS_TARGET hearts or fewer."""
-    for s in scan:
-        if hearts_lost(s["naive"]) >= HEARTS_TARGET:
-            return s["f"]
-    return None
+def factors_at_target(scan):
+    """
+    the wave size factors at which naive ends with HEARTS_TARGET hearts or
+    fewer, as a list of (lowest, highest) ranges of neighbouring scan
+    points. larger waves also pay more coins, so there may be several.
+    """
+    out = []
+    for i, s in enumerate(scan):
+        if hearts_lost(s["naive"]) < 10 - HEARTS_TARGET:
+            continue
+        if out and out[-1][2] == i - 1:
+            out[-1] = (out[-1][0], s["f"], i)
+        else:
+            out.append((s["f"], s["f"], i))
+    return [(lo, hi) for lo, hi, _ in out]
 
 
 # report
@@ -380,6 +479,49 @@
     return lines
 
 
+def t0_table(cfg, towers, analyses):
+    """
+    t0's value per coin with area damage: the single target value times the
+    monsters hit per attack. hits per attack as measured by tools/simulate.js
+    (temp/preview/simulate.json, players naive_t0 and naive_mix) where
+    available, otherwise the estimate from coverage and spacing.
+    """
+    measured = {}
+    sim = PREVIEW / "simulate.json"
+    if sim.exists():
+        for r in json.loads(sim.read_text()):
+            if r.get("t0Hits") is not None:
+                measured.setdefault(r["map"], []).append(r["t0Hits"])
+    t0, t1 = towers["t0"], towers[TOWER]
+    lines = ["t0 with area damage: hp per second per coin, whole shots, times the",
+             "monsters hit per attack. est: monsters in range of a median t0 cell at",
+             "the mean spacing. sim: measured by tools/simulate.js over whole runs of",
+             "the naive t0 players, if it was run. t1 level 1 for comparison.", "",
+             f"{'map':5}{'est':>6}{'sim':>6}  level" + "".join(f"{'vs ' + k:>8}" for k in ("m0", "m4"))]
+    for a in analyses:
+        m = a["m"]
+        est = a["coverage"]["t0"][0] / a["spacing"]
+        sim_h = sum(measured[m]) / len(measured[m]) if m in measured else None
+        hits = sim_h if sim_h is not None else est
+        paid = 0
+        for lv in range(len(t0["damage"])):
+            d, at = t0["damage"][lv], t0["attack_time"]
+            paid += t0["cost"][lv]
+            row = (f"map{m:<2}{est:>6.1f}{'-' if sim_h is None else f'{sim_h:.2f}':>6}" if lv == 0
+                   else " " * 17)
+            row += f"{lv + 1:>7}"
+            for k in ("m0", "m4"):
+                hp = cfg["monster"][k]["hp"]
+                row += f"{hits * hp / (math.ceil(hp / d) * at) / paid:>8.2f}"
+            lines.append(row)
+        row = " " * 17 + f"{'t1 1':>7}"
+        for k in ("m0", "m4"):
+            hp = cfg["monster"][k]["hp"]
+            row += f"{hp / (math.ceil(hp / t1['damage'][0]) * t1['attack_time']) / t1['cost'][0]:>8.2f}"
+        lines.append(row)
+    return lines + [""]
+
+
 def map_report(cfg, a):
     m, c = a["m"], cfg["map"][str(a["m"])]
     lens = a["lengths"]
@@ -393,11 +535,12 @@
         lines.append(f"{tid:6}{med:>8.0f}{top:>8.0f}{best:>8.0f}{hits}")
     lines += ["", "t0 hits: monsters in range of a median t0 cell at the mean spacing,",
               "the number one t0 attack damages in a full wave.", "",
-              "waves, t1 only, hp factor 1. need/s: hp per second the towers have to",
-              "kill (throughput, median cell). single: damage the toughest monster",
-              "takes from the naive towers while in range, against its hp. budget:",
-              "coins on hand plus coins spent. need: coins of the purchases that hold",
-              "the wave. lost: hearts lost, leaks by throughput plus 5 for a boss.", "",
+              "waves, t1 only, wave size factor 1. need/s: hp per second the towers",
+              "have to kill (throughput, median cell). single: damage the toughest",
+              "monster takes from the naive towers while in range, against its hp.",
+              "budget: coins on hand plus coins spent. need: coins of the purchases",
+              "that hold the wave. lost: hearts lost, leaks by throughput plus 5 for",
+              "a boss.", "",
               f"{'wave':>4}{'count':>6}{'hp':>6}{'coins':>6}{'need/s':>8}{'single':>12}"
               f"   naive{'budget':>8}{'need':>6}{'lost':>6}   greedy{'budget':>8}{'need':>6}{'lost':>6}"]
     med = float(np.median(a["cov"]))
@@ -413,13 +556,13 @@
                      f"        {n['budget']:>8.0f}{need(n):>6}{n['res']['hearts']:>6.1f}"
                      f"         {g['budget']:>8.0f}{need(g):>6}{g['res']['hearts']:>6.1f}")
     one = next(s for s in a["scan"] if s["f"] == 1.0)
-    target = factor_for_target(a["scan"])
+    target = factors_at_target(a["scan"])
     fmt = lambda v: "-" if v is None else f"{v:.0f}"
-    lines += ["", f"hp factor 1: naive loses {hearts_lost(one['naive']):.1f} hearts, surplus at the last wave"
-              f" {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f},"
+    lines += ["", f"wave size factor 1: naive loses {hearts_lost(one['naive']):.1f} hearts,"
+              f" surplus at the last wave {fmt(surplus(one['naive']))}; greedy loses {hearts_lost(one['greedy']):.1f},"
               f" surplus {fmt(surplus(one['greedy']))}",
-              f"hp factor at which naive is down to {HEARTS_TARGET} hearts: "
-              + ("beyond the scan" if target is None else f"{target:.2f}"), ""]
+              f"wave size factors at which naive ends with {HEARTS_TARGET} hearts or fewer: "
+              + (", ".join(f"{lo:.2f} to {hi:.2f}" for lo, hi in target) or "none in the scan"), ""]
     return lines
 
 
@@ -452,7 +595,7 @@
     fig, axes = plt.subplots(1, 3, figsize=(15, 4.4), facecolor=SURFACE)
     waves = range(1, len(a["waves"]) + 1)
     ax = axes[0]
-    style(ax, f"map{a['m']}: coins per wave, hp factor 1", "wave", "coins")
+    style(ax, f"map{a['m']}: coins per wave, wave size factor 1", "wave", "coins")
     line(ax, waves, [r["budget"] for r in a["naive"]], 0, "budget (naive)")
     line(ax, waves, [r["need"] for r in a["naive"]], 1, "needed, naive")
     line(ax, waves, [r["need"] for r in a["greedy"]], 2, "needed, greedy")
@@ -461,14 +604,14 @@
 
     f = [s["f"] for s in a["scan"]]
     ax = axes[1]
-    style(ax, "surplus at the last wave", "hp factor", "coins")
+    style(ax, "surplus at the last wave", "wave size factor", "coins")
     ax.axhline(0, color=INK2, linewidth=1)
     line(ax, f, [surplus(s["naive"]) for s in a["scan"]], 1, "naive", markevery=10)
     line(ax, f, [surplus(s["greedy"]) for s in a["scan"]], 2, "greedy", markevery=10)
     legend(ax)
 
     ax = axes[2]
-    style(ax, "hearts left at the end", "hp factor", "hearts")
+    style(ax, "hearts left at the end", "wave size factor", "hearts")
     ax.axhline(HEARTS_TARGET, color=INK2, linewidth=1, linestyle="--")
     ax.text(f[-1], HEARTS_TARGET + 0.2, "target, naive", color=INK2, fontsize=8, ha="right")
     line(ax, f, [max(0, 10 - hearts_lost(s["naive"])) for s in a["scan"]], 1, "naive", markevery=10)
@@ -496,22 +639,44 @@
     plt.close(fig)
 
 
+def draft(cfg, towers, maps, only):
+    """print drafted wave lists as toml and what the calculation makes of them."""
+    for m in range(MAPS) if only is None else [only]:
+        waves = draft_waves(cfg, m)
+        print("\n".join(draft_toml(cfg, m, waves)))
+        for msg in draft_check(cfg, waves):
+            print(f"# warning: {msg}")
+        cfg["map"][str(m)]["wave"] = [{"monsters": w} for w in waves]
+        report = map_report(cfg, analyse_map(cfg, towers, maps[m], m))
+        print("\n".join("# " + l for l in report[-3:-1]), end="\n\n")
+    return 0
+
+
 def main():
+    args = sys.argv[1:]
+    if args and args[0] not in ("--draft",) or len(args) > 2:
+        print(__doc__.split("\n\n")[1])
+        return 2
     cfg = tomllib.loads((CONFIG / "game.toml").read_text())
     if not MAPS_CACHE.exists():
         print("no route data: run tools/build.py first")
         return 1
     maps = json.loads(MAPS_CACHE.read_text())["maps"]
     towers = tower_table(cfg)
+    if args:
+        return draft(cfg, towers, maps, int(args[1]) if len(args) > 1 else None)
     PREVIEW.mkdir(parents=True, exist_ok=True)
     lines = ["balance estimate, written by tools/balance.py", ""] + value_table(cfg, towers) + [""]
     value_chart(cfg, towers, PREVIEW / "balance_value.png")
+    analyses = []
     for m in range(MAPS):
         a = analyse_map(cfg, towers, maps[m], m)
+        analyses.append(a)
         report = map_report(cfg, a)
         lines += report
-        print("\n".join(report[-3:-1]).replace("hp factor 1", f"map{m}, hp factor 1"))
+        print("\n".join(report[-3:-1]).replace("wave size factor 1:", f"map{m}, wave size factor 1:"))
         map_chart(a, PREVIEW / f"balance_map{m}.png")
+    lines += t0_table(cfg, towers, analyses)
     (PREVIEW / "balance.txt").write_text("\n".join(lines))
     print("balance: wrote temp/preview/balance.txt, balance_*.png")
     return 0
--- a/tools/build.py	Tue Oct 20 03:08:56 2026 +0200
+++ b/tools/build.py	Tue Oct 20 12:04:42 2026 +0200
@@ -166,28 +166,6 @@
 
 # 4. masks
 
-def apply_corrections(m, routes, fix):
-    """
-    apply routes.toml corrections for map m to a list of route dicts.
-    each route dict has points, and gets a fixed weight or None.
-    """
-    for r in routes:
-        r["weight"] = None
-    for spec in fix.get("route", []):
-        pts = [tuple(p) for p in spec["points"]]
-        if "replace" in spec:
-            routes[spec["replace"]]["points"] = pts
-            routes[spec["replace"]]["manual"] = True
-        else:
-            routes.append({"points": pts, "weight": None, "manual": True})
-    for k, v in fix.get("weights", {}).items():
-        routes[int(k)]["weight"] = float(v)
-    drop = set(fix.get("drop", []))
-    for i, r in enumerate(routes):
-        r["number"] = i
-    return [r for i, r in enumerate(routes) if i not in drop]
-
-
 def route_values(routes):
     """
     fill in length, turning and value of each route (balance.md, route
@@ -208,8 +186,7 @@
     placement = cfg["placement"]
     settings = {"placement": placement,
                 "maps": [{k: cfg["map"][str(m)][k] for k in MASK_SETTINGS} for m in range(MAPS)]}
-    routes_toml = CONFIG / "routes.toml"
-    inputs = [ART / f"map{m}mask.png" for m in range(MAPS)] + [routes_toml]
+    inputs = [ART / f"map{m}mask.png" for m in range(MAPS)]
     outputs = [DATA / "maps.js", MAPS_CACHE]
     cached = None
     if MAPS_CACHE.exists():
@@ -219,7 +196,6 @@
         print("masks: up to date")
         return cached["maps"], False
 
-    fixes = tomllib.loads(routes_toml.read_text()).get("map", {})
     out = []
     for m in range(MAPS):
         t0 = time.time()
@@ -230,8 +206,7 @@
                   (found["exit_points"], mc["exit_distance"])]
         cols, rows, grid = masks.placement_grid(mask, placement, found["centre"],
                                                 mc["path_half_width"], spaces)
-        routes = [{"points": pts, "manual": False} for pts in found["routes"]]
-        routes = apply_corrections(m, routes, fixes.get(str(m), {}))
+        routes = [{"points": pts} for pts in found["routes"]]
         route_values(routes)
         g = found["graph"]
         out.append({
@@ -281,11 +256,10 @@
                 "length": rnd(r["length"]),
                 "turning": rnd(r["turning"]),
                 "value": round(r["value"], 3),
-                "weight": r["weight"],
             } for r in mp["routes"]],
         })
     body = ",\n".join(json.dumps(m, separators=(",", ":")) for m in js)
-    write_text(DATA / "maps.js", HEADER.format(src="art/map*mask.png and config/routes.toml")
+    write_text(DATA / "maps.js", HEADER.format(src="art/map*mask.png")
                + "window.MM = window.MM || {};\nMM.maps = [\n" + body + "\n];\n")
 
 
@@ -337,7 +311,7 @@
 def check_config(cfg):
     """raise ConfigError on missing or malformed settings."""
     for sec in ("scale", "monster", "animation", "movement", "route_preference", "tower",
-                "placement", "economy", "waves", "hearts", "coins", "controls", "art", "debug",
+                "placement", "waves", "hearts", "coins", "controls", "art", "debug",
                 "sound", "map"):
         if sec not in cfg:
             raise ConfigError(f"section [{sec}] missing")
@@ -380,7 +354,10 @@
         where = f"map.{m}"
         for k in ("starting_coins", "early_bonus", "wave_count") + MASK_SETTINGS:
             need(mp, k, float, where)
-        need(mp, "monster_share", list, where)
+        for k, n in (("monster_share", 5), ("wave_size", 2), ("first_wave", 5)):
+            v = need(mp, k, list, where)
+            if len(v) != n or not all(isinstance(x, int) and not isinstance(x, bool) for x in v):
+                raise ConfigError(f"{where}: {k} should be {n} whole numbers, is {v!r}")
         if "spawn_interval" in mp:
             need(mp, "spawn_interval", float, where)
         for w, wave in enumerate(mp.get("wave", []), start=1):
@@ -465,12 +442,10 @@
             warn(f"map{m}: no entrance or no exit found")
         if not mp["routes"]:
             warn(f"map{m}: no routes")
-        for r in mp["routes"]:
+        for k, r in enumerate(mp["routes"]):
             times = ", ".join(f"{r['length'] / s:.0f}" for s in speeds)
-            fixed = f", weight {r['weight']}" if r["weight"] is not None else ""
-            manual = ", manual" if r.get("manual") else ""
-            print(f"  route {r['number']}: length {r['length']:.0f}, turning {r['turning']:.0f} deg,"
-                  f" value {r['value']:.2f}{fixed}{manual}; walk time {times} s"
+            print(f"  route {k}: length {r['length']:.0f}, turning {r['turning']:.0f} deg,"
+                  f" value {r['value']:.2f}; walk time {times} s"
                   f" at speed {', '.join(str(s) for s in speeds)}")
 
         waves = c.get("wave", [])
@@ -479,18 +454,15 @@
         if not waves:
             continue
         counts, reg, boss, hp = wave_totals(cfg, waves)
-        target = c["starting_coins"] * cfg["economy"]["coin_total_factor"]
-        total = reg + boss
+        n_reg = sum(counts.get(k, 0) for k in regular)
         print("  monsters: " + ", ".join(f"{k} {counts.get(k, 0)}" for k in sorted(counts))
               + f", {sum(counts.values())} in all")
-        share = [100 * counts.get(k, 0) * mons[k]["coins"] / reg if reg else 0 for k in regular]
-        print("  coin share %: " + ", ".join(f"{k} {s:.0f} ({t})" for k, s, t
-                                             in zip(regular, share, c["monster_share"])))
-        print(f"  coins: regular {reg}, boss {boss}, total {total}, target {target:.0f};"
-              f" regular hp {hp}")
-        if abs(total - target) > cfg["economy"]["coin_tolerance"] * target:
-            warn(f"map{m}: coins {total} are more than"
-                 f" {cfg['economy']['coin_tolerance'] * 100:.0f} % off the target {target:.0f}")
+        share = [100 * counts.get(k, 0) / n_reg if n_reg else 0 for k in regular]
+        print("  share by count %: " + ", ".join(f"{k} {s:.0f} ({t})" for k, s, t
+                                                 in zip(regular, share, c["monster_share"])))
+        print(f"  coins: regular {reg}, boss {boss}, total {reg + boss},"
+              f" {reg + boss + c['starting_coins']} with the starting coins;"
+              f" regular hp {hp}, {reg / hp if hp else 0:.2f} coins per hp")
         per_wave = []
         for w, wave in enumerate(waves, start=1):
             _, r, b, _ = wave_totals(cfg, [wave])
--- a/tools/preview.py	Tue Oct 20 03:08:56 2026 +0200
+++ b/tools/preview.py	Tue Oct 20 12:04:42 2026 +0200
@@ -60,7 +60,7 @@
     _ends(draw, mp)
     for k, r in enumerate(mp["routes"]):
         x, y = r["points"][len(r["points"]) // 3]
-        draw.text((x + 6, y + 6 + 10 * k), f"route {r['number']}", fill=(0, 0, 0))
+        draw.text((x + 6, y + 6 + 10 * k), f"route {k}", fill=(0, 0, 0))
     return im
 
 
@@ -71,7 +71,7 @@
         im, draw = _base(map_path, mp)
         _route(draw, r["points"], ROUTE_COLOURS[k % len(ROUTE_COLOURS)], 5)
         _ends(draw, mp)
-        draw.text((10, 10), f"route {r['number']}: length {r['length']:.0f},"
+        draw.text((10, 10), f"route {k}: length {r['length']:.0f},"
                   f" turning {r['turning']:.0f}, value {r['value']:.2f}", fill=(0, 0, 0))
         panels.append(im.resize((im.width // 2, im.height // 2)))
     cols = min(3, len(panels))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/simulate.js	Tue Oct 20 12:04:42 2026 +0200
@@ -0,0 +1,563 @@
+#!/usr/bin/env node
+// headless simulation of the game with scripted players (doc/balance.md,
+// balancing). runs the game logic from www/ after a build: data/config.js,
+// data/maps.js and the js/ files of the simulation, with MM.audio replaced
+// by a stub. writes temp/preview/simulate.txt, the results as json in
+// temp/preview/simulate.json (read by tools/balance.py), and prints a
+// summary.
+//
+// usage: node tools/simulate.js [options]
+//
+//   --maps 0,1      maps to play (default all)
+//   --players a,b   players (default naive,greedy); also naive_t0, naive_mix
+//   --seeds n       seeds per map and player, 1 to n (default 5)
+//   --need all      measure the coins needed for every wave, not only the
+//                   last one (slower)
+//   --waves file    json {"0": [{"monsters": {...}}, ...], ...}: wave lists
+//                   that replace the config's for the maps named
+//   --config file   a config.js to use instead of www/data/config.js
+//   --json          print the results as json instead of the summary, and
+//                   write no files
+//
+// players (all build at the first moment they can afford the next
+// purchase, through the game's own shop, preview and upgrade functions):
+//
+//   naive       t1 only, level 1, on cells of median t1 coverage. never
+//               starts a wave early
+//   greedy      t1, cells picked by coverage of route not yet covered, and
+//               upgrades when that adds more damage per second per coin
+//               than a new tower (the rules of tools/balance.py). starts
+//               every wave early for the bonus
+//   naive_t0    as naive, t0 only, on cells of median t0 coverage
+//   naive_mix   as naive, t1 and t0 in turn, each on cells of median
+//               coverage for its own range
+//
+// coverage of a cell is the route length within range, the mean over the
+// map's routes, as in tools/balance.py. the coins a wave needs are the cost of the smallest
+// number of the player's purchases, in its order, that hold the wave
+// without losing a heart. it is measured by playing the wave on its own
+// from an empty map, with the same seed.
+
+"use strict";
+
+var fs = require("fs");
+var path = require("path");
+var vm = require("vm");
+
+var ROOT = path.resolve(__dirname, "..");
+var WWW = path.join(ROOT, "www");
+var OUT = path.join(ROOT, "temp", "preview", "simulate.txt");
+var OUT_JSON = path.join(ROOT, "temp", "preview", "simulate.json");
+var DT = 1 / 60;
+// distance between route samples for coverage, as in tools/balance.py
+var SAMPLE_STEP = 4;
+// naive cells: coverage within this share of the median counts as median
+var MEDIAN_BAND = 0.05;
+// longest purchase lists
+var MAX_TOWERS = 80;
+var MAX_SPENT = 4000;
+// a run stops after this much game time
+var MAX_TIME = 4000;
+// hearts the naive player should have left (decided)
+var HEARTS_TARGET = 5;
+
+// options
+
+function options(argv) {
+    var o = { maps: null, players: ["naive", "greedy"], seeds: 5, needAll: false,
+              waves: null, config: path.join(WWW, "data", "config.js"), json: false };
+    for (var i = 0; i < argv.length; i++) {
+        var a = argv[i];
+        if (a === "--maps") o.maps = argv[++i].split(",").map(Number);
+        else if (a === "--players") o.players = argv[++i].split(",");
+        else if (a === "--seeds") o.seeds = Number(argv[++i]);
+        else if (a === "--need") o.needAll = argv[++i] === "all";
+        else if (a === "--waves") o.waves = JSON.parse(fs.readFileSync(argv[++i], "utf8"));
+        else if (a === "--config") o.config = path.resolve(argv[++i]);
+        else if (a === "--json") o.json = true;
+        else {
+            console.error("unknown option " + a + "; see the comment at the top of tools/simulate.js");
+            process.exit(2);
+        }
+    }
+    return o;
+}
+
+// load the game logic into this context, as the browser would
+function load(configFile, waves) {
+    globalThis.window = globalThis;
+    var files = [configFile, path.join(WWW, "data", "maps.js")];
+    ["util", "assets", "map", "monster", "tower", "projectile", "wave", "game"].forEach(function (f) {
+        files.push(path.join(WWW, "js", f + ".js"));
+    });
+    files.forEach(function (f, i) {
+        vm.runInThisContext(fs.readFileSync(f, "utf8"), { filename: f });
+        if (i === files.length - 1) countMelee();
+        if (i === 1) {
+            var cfg = MM.config;
+            // debug switches off, whatever the config says
+            cfg.debug.start_coins = -1;
+            cfg.debug.unlimited_coins = false;
+            cfg.debug.no_heart_loss = false;
+            cfg.debug.extra_speeds = [];
+            if (waves) {
+                Object.keys(waves).forEach(function (m) { cfg.maps[m].waves = waves[m]; });
+            }
+            MM.audio = { play: function () {} };
+        }
+    });
+}
+
+// melee attacks and the monsters they hit, by tower type, counted from the
+// game's own tower update and damage functions
+var melee = {};
+
+function countMelee() {
+    var update = MM.tower.update, damage = MM.Game.prototype.damage, current = null;
+    MM.tower.update = function (t, game, dt) {
+        var before = t.cooldown;
+        current = t.def.projectile_speed === 0 ? t : null;
+        update(t, game, dt);
+        if (current && t.cooldown > before) {
+            var c = melee[t.type] || (melee[t.type] = { attacks: 0, hits: 0 });
+            c.attacks++;
+            c.hits += current.hitsNow || 0;
+        }
+        if (current) current.hitsNow = 0;
+        current = null;
+    };
+    MM.Game.prototype.damage = function (m, amount) {
+        if (current && m.alive) current.hitsNow = (current.hitsNow || 0) + 1;
+        return damage.call(this, m, amount);
+    };
+}
+
+// coverage
+
+// route samples about SAMPLE_STEP apart, in the middle of equal pieces:
+// {xs, ys, weight}, weight being the length of a piece
+function resample(r) {
+    var n = r.xs.length, cum = r.at, len = r.length;
+    var k = Math.max(1, Math.ceil(len / SAMPLE_STEP));
+    var xs = [], ys = [], seg = 1;
+    for (var i = 0; i < k; i++) {
+        var s = (i + 0.5) * len / k;
+        while (seg < n - 1 && cum[seg] < s) seg++;
+        var t = (s - cum[seg - 1]) / (cum[seg] - cum[seg - 1]);
+        xs.push(r.xs[seg - 1] + (r.xs[seg] - r.xs[seg - 1]) * t);
+        ys.push(r.ys[seg - 1] + (r.ys[seg] - r.ys[seg - 1]) * t);
+    }
+    return { xs: xs, ys: ys, weight: len / k };
+}
+
+// legal cells and route samples of a map
+function MapData(index) {
+    var gm = new MM.GameMap(index), d = gm.data;
+    this.index = index;
+    this.cells = [];
+    for (var i = 0; i < d.grid.length; i++) {
+        if (d.grid.charCodeAt(i) === 49) {
+            this.cells.push([(i % d.cols) * d.cell + d.cell / 2, Math.floor(i / d.cols) * d.cell + d.cell / 2]);
+        }
+    }
+    this.routes = gm.routes.map(resample);
+    this.cache = {};
+}
+
+// per route, per cell: indices of the samples within range rng
+MapData.prototype.within = function (rng) {
+    if (this.cache[rng]) return this.cache[rng];
+    var r2 = rng * rng, cells = this.cells;
+    var out = this.routes.map(function (r) {
+        return cells.map(function (c) {
+            var hit = [];
+            for (var i = 0; i < r.xs.length; i++) {
+                var dx = r.xs[i] - c[0], dy = r.ys[i] - c[1];
+                if (dx * dx + dy * dy <= r2) hit.push(i);
+            }
+            return hit;
+        });
+    });
+    this.cache[rng] = out;
+    return out;
+};
+
+// per cell: route length within range, the mean over routes
+MapData.prototype.coverage = function (rng) {
+    var w = this.within(rng), routes = this.routes;
+    return this.cells.map(function (c, j) {
+        var sum = 0;
+        for (var r = 0; r < routes.length; r++) sum += w[r][j].length * routes[r].weight;
+        return sum / routes.length;
+    });
+};
+
+function median(v) {
+    var s = v.slice().sort(function (a, b) { return a - b; }), n = s.length;
+    return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
+}
+
+function farEnough(cells, picked, j, minDist) {
+    for (var i = 0; i < picked.length; i++) {
+        var a = cells[picked[i]], b = cells[j];
+        if (Math.hypot(a[0] - b[0], a[1] - b[1]) < minDist) return false;
+    }
+    return true;
+}
+
+// cells for the naive players: the cells within MEDIAN_BAND of the median
+// coverage in random order, then the others by distance from the median.
+// towers keep the minimum distance from each other. returns cell indices.
+function medianCells(md, rng, random, count, picked) {
+    var cov = md.coverage(rng), med = median(cov);
+    var idx = cov.map(function (_, j) { return j; });
+    var band = idx.filter(function (j) { return Math.abs(cov[j] - med) <= MEDIAN_BAND * med; });
+    for (var i = band.length - 1; i > 0; i--) {
+        var k = Math.floor(random() * (i + 1)), t = band[i];
+        band[i] = band[k];
+        band[k] = t;
+    }
+    var rest = idx.filter(function (j) { return Math.abs(cov[j] - med) > MEDIAN_BAND * med; });
+    rest.sort(function (a, b) { return Math.abs(cov[a] - med) - Math.abs(cov[b] - med); });
+    var order = band.concat(rest), out = [];
+    var minDist = MM.config.placement.min_tower_distance;
+    for (i = 0; i < order.length && out.length < count; i++) {
+        if (farEnough(md.cells, picked, order[i], minDist)) {
+            out.push(order[i]);
+            picked.push(order[i]);
+        }
+    }
+    return out;
+}
+
+// cells picked one after the other by the route length in range that no
+// earlier pick covers, mean over routes, keeping the minimum distance. once
+// all route is covered, the cell with the most route in range is next.
+function greedyCells(md, rng, count) {
+    var w = md.within(rng), routes = md.routes, cells = md.cells;
+    var full = md.coverage(rng);
+    var covered = routes.map(function (r) { return new Uint8Array(r.xs.length); });
+    var free = cells.map(function () { return true; });
+    var minDist = MM.config.placement.min_tower_distance;
+    var order = [];
+    while (order.length < count) {
+        var best = -1, bestGain = 0, bestFull = -1, bestFullV = -1;
+        for (var j = 0; j < cells.length; j++) {
+            if (!free[j]) continue;
+            var gain = 0;
+            for (var r = 0; r < routes.length; r++) {
+                var hit = w[r][j], cv = covered[r], n = 0;
+                for (var i = 0; i < hit.length; i++) if (!cv[hit[i]]) n++;
+                gain += n * routes[r].weight;
+            }
+            gain /= routes.length;
+            if (gain > bestGain) { bestGain = gain; best = j; }
+            if (full[j] > bestFullV) { bestFullV = full[j]; bestFull = j; }
+        }
+        if (best < 0) best = bestFull;
+        if (best < 0) break;
+        order.push(best);
+        for (r = 0; r < routes.length; r++) {
+            w[r][best].forEach(function (i) { covered[r][i] = 1; });
+        }
+        for (j = 0; j < cells.length; j++) {
+            if (free[j] && Math.hypot(cells[j][0] - cells[best][0], cells[j][1] - cells[best][1]) < minDist)
+                free[j] = false;
+        }
+    }
+    return order;
+}
+
+// players: a purchase list, each entry {type, x, y} for a new tower or
+// {up: n} for an upgrade of the n-th tower built, with its cost
+
+function mapSpacing(index) {
+    var mc = MM.config.maps[index], mons = MM.config.monster;
+    var interval = mc.spawn_interval !== undefined ? mc.spawn_interval : MM.config.waves.spawn_interval;
+    var sum = 0, count = 0;
+    mc.waves.forEach(function (w) {
+        for (var k in w.monsters) {
+            if (mons[k].boss) continue;
+            sum += w.monsters[k] * mons[k].speed * interval;
+            count += w.monsters[k];
+        }
+    });
+    return sum / count;
+}
+
+function naiveList(md, types, seed) {
+    var random = MM.util.rng(seed * 7919 + 17), picked = [], list = [], spent = 0;
+    var cfg = MM.config;
+    while (list.length < MAX_TOWERS && spent < MAX_SPENT) {
+        var type = types[list.length % types.length], def = cfg.tower[type];
+        var c = medianCells(md, def.range[0], random, 1, picked);
+        if (!c.length) break;
+        var cell = md.cells[c[0]];
+        list.push({ type: type, x: cell[0], y: cell[1], cost: def.cost[0] });
+        spent += def.cost[0];
+    }
+    return list;
+}
+
+function greedyList(md, index) {
+    var def = MM.config.tower.t1, dmg = def.damage, cost = def.cost, at = def.attack_time;
+    var cells = greedyCells(md, def.range[0], MAX_TOWERS);
+    var cov = md.coverage(def.range[0]), spacing = mapSpacing(index);
+    function busy(j) { return 1 - Math.exp(-cov[j] / spacing); }
+    var levels = [], list = [], next = 0, spent = 0;
+    while (spent < MAX_SPENT) {
+        var best = 0, choice = null;
+        if (next < cells.length) {
+            best = dmg[0] / at * busy(cells[next]) / cost[0];
+            choice = -1;
+        }
+        levels.forEach(function (t, n) {
+            if (t.level >= dmg.length) return;
+            var v = (dmg[t.level] - dmg[t.level - 1]) / at * busy(t.cell) / cost[t.level];
+            if (v > best) { best = v; choice = n; }
+        });
+        if (choice === null) break;
+        if (choice < 0) {
+            var cell = md.cells[cells[next]];
+            levels.push({ cell: cells[next], level: 1 });
+            list.push({ type: "t1", x: cell[0], y: cell[1], cost: cost[0] });
+            next++;
+            spent += cost[0];
+        } else {
+            var t = levels[choice];
+            list.push({ up: choice, cost: cost[t.level] });
+            spent += cost[t.level];
+            t.level++;
+        }
+    }
+    return list;
+}
+
+function makePlayer(name, md, index, seed) {
+    if (name === "naive") return { name: name, list: naiveList(md, ["t1"], seed), early: false };
+    if (name === "naive_t0") return { name: name, list: naiveList(md, ["t0"], seed), early: false };
+    if (name === "naive_mix") return { name: name, list: naiveList(md, ["t1", "t0"], seed), early: false };
+    if (name === "greedy") return { name: name, list: greedyList(md, index), early: true };
+    throw new Error("unknown player " + name);
+}
+
+// make purchase p through the game's functions. built: the towers built so
+// far, in order. returns false when it could not be made.
+function buy(g, p, built) {
+    if (p.up !== undefined) {
+        var t = built[p.up];
+        g.selected = null;
+        g.shop = null;
+        g.pressMap(t.x, t.y, 0);
+        if (g.selected !== t) return false;
+        var level = t.level;
+        g.upgrade();
+        g.selected = null;
+        return t.level > level;
+    }
+    if (g.shop !== p.type) g.chooseShop(p.type);
+    if (!g.movePreview(p.x, p.y) || g.preview.x !== p.x || g.preview.y !== p.y) {
+        g.shop = null;
+        g.preview = null;
+        return false;
+    }
+    var n = g.towers.length;
+    if (!g.build()) return false;
+    built.push(g.towers[n]);
+    return true;
+}
+
+// play
+
+function spentOn(g) {
+    return g.towers.reduce(function (s, t) { return s + t.paid; }, 0);
+}
+
+// play map index with the player. returns per wave the coins on hand and
+// the budget (coins on hand plus coins spent) at its start and the hearts
+// lost in it, and the result.
+function play(index, player, seed) {
+    melee = {};
+    var g = new MM.Game(index, seed, 1);
+    var built = [], k = 0, recorded = 0, rows = [], stuck = false;
+    function act() {
+        while (k < player.list.length && g.canAfford(player.list[k].cost)) {
+            if (!buy(g, player.list[k], built)) { stuck = true; break; }
+            k++;
+        }
+    }
+    while (!g.result && g.time < MAX_TIME) {
+        act();
+        if (player.early && g.waves.phase === "break") {
+            g.startEarly();
+            act();
+        }
+        if (g.waves.next !== recorded) {
+            if (rows.length) rows[rows.length - 1].lost -= g.hearts;
+            recorded = g.waves.next;
+            rows.push({ coins: g.coins, budget: g.coins + spentOn(g), towers: g.towers.length,
+                        bought: k, lost: g.hearts });
+        }
+        g.step(DT);
+    }
+    if (rows.length) rows[rows.length - 1].lost -= g.hearts;
+    return { rows: rows, hearts: g.hearts, won: g.result === "won", stuck: stuck,
+             coinsEnd: g.coins, purchases: k, melee: melee };
+}
+
+// hearts lost in wave w (from 0) played on its own from an empty map with
+// the first k purchases of the player
+function waveLoss(index, player, seed, w, k) {
+    var g = new MM.Game(index, seed, w + 1), built = [];
+    g.coins = 1e9;
+    for (var i = 0; i < k; i++) {
+        if (!buy(g, player.list[i], built)) throw new Error("purchase " + i + " failed in a wave test");
+    }
+    var h = g.hearts;
+    g.startEarly();
+    // the break after the wave starts while its monsters are still on the
+    // map; it is held so the next wave does not start
+    while (!g.result && (g.waves.phase === "spawning" || g.monsters.length) && g.time < MAX_TIME) {
+        if (g.waves.phase === "break") g.waves.left = Infinity;
+        g.step(DT);
+    }
+    return h - g.hearts;
+}
+
+// coins of the smallest purchase prefix that holds wave w, null if none in
+// the list does
+function need(index, player, seed, w) {
+    var lo = 0, hi = player.list.length;
+    if (waveLoss(index, player, seed, w, hi) > 0) return null;
+    while (lo < hi) {
+        var mid = (lo + hi) >> 1;
+        if (waveLoss(index, player, seed, w, mid) === 0) hi = mid;
+        else lo = mid + 1;
+    }
+    var c = 0;
+    for (var i = 0; i < lo; i++) c += player.list[i].cost;
+    return c;
+}
+
+// report
+
+function mean(v) {
+    return v.reduce(function (a, b) { return a + b; }, 0) / v.length;
+}
+
+function pad(s, n) {
+    s = String(s);
+    return s.length >= n ? s : " ".repeat(n - s.length) + s;
+}
+
+function fmt(v, d) {
+    return v === null || v === undefined || Number.isNaN(v) ? "-" : v.toFixed(d || 0);
+}
+
+function summary(index, name, runs) {
+    var last = runs.map(function (r) { return r.rows[r.rows.length - 1]; });
+    var needs = runs.map(function (r) { return r.need[r.need.length - 1]; });
+    var surplus = runs.map(function (r, i) {
+        return needs[i] === null || !last[i] ? null : last[i].budget - needs[i];
+    });
+    var ok = surplus.filter(function (v) { return v !== null; });
+    return {
+        map: index, player: name, seeds: runs.length,
+        won: runs.filter(function (r) { return r.won; }).length,
+        hearts: mean(runs.map(function (r) { return r.hearts; })),
+        heartsMin: Math.min.apply(null, runs.map(function (r) { return r.hearts; })),
+        heartsMax: Math.max.apply(null, runs.map(function (r) { return r.hearts; })),
+        coinsLast: mean(last.map(function (r) { return r ? r.coins : 0; })),
+        budgetLast: mean(last.map(function (r) { return r ? r.budget : 0; })),
+        needLast: ok.length ? mean(needs.filter(function (v) { return v !== null; })) : null,
+        surplus: ok.length === runs.length ? mean(ok) : null,
+        lost: runs[0].rows.map(function (_, w) {
+            return mean(runs.map(function (r) { return r.rows[w] ? r.rows[w].lost : 0; }));
+        }),
+        need: runs[0].need.map(function (_, w) {
+            var v = runs.map(function (r) { return r.need[w]; });
+            return v.indexOf(null) >= 0 || v[0] === undefined ? null : mean(v);
+        }),
+        budget: runs[0].rows.map(function (_, w) {
+            return mean(runs.map(function (r) { return r.rows[w] ? r.rows[w].budget : 0; }));
+        }),
+        stuck: runs.some(function (r) { return r.stuck; }),
+        // monsters hit per t0 attack, over all runs
+        t0Hits: (function () {
+            var a = 0, h = 0;
+            runs.forEach(function (r) { if (r.melee.t0) { a += r.melee.t0.attacks; h += r.melee.t0.hits; } });
+            return a ? h / a : null;
+        })()
+    };
+}
+
+function table(results, o) {
+    var lines = ["simulation, written by tools/simulate.js", "",
+                 "seeds 1 to " + o.seeds + " per map and player. hearts: left at the end, mean (min to max).",
+                 "coins: on hand at the start of the last wave. budget: coins on hand plus",
+                 "coins spent then. need: coins of the purchases that hold the last wave",
+                 "on its own. surplus: budget minus need, at the last wave. per wave: hearts",
+                 "lost, mean over seeds; budget and need by wave where measured.", "",
+                 "map  player      won   hearts          coins  budget   need  surplus"];
+    results.forEach(function (s) {
+        lines.push(pad("map" + s.map, 4) + "  " + (s.player + "          ").slice(0, 10)
+                   + pad(s.won + "/" + s.seeds, 5)
+                   + pad(fmt(s.hearts, 1), 7) + " (" + s.heartsMin + " to " + s.heartsMax + ")"
+                   + pad("", 13 - (" (" + s.heartsMin + " to " + s.heartsMax + ")").length)
+                   + pad(fmt(s.coinsLast, 1), 7) + pad(fmt(s.budgetLast), 8) + pad(fmt(s.needLast), 7)
+                   + pad(fmt(s.surplus), 9) + (s.stuck ? "  (a purchase failed)" : "")
+                   + (s.t0Hits !== null ? "  t0 hits per attack " + fmt(s.t0Hits, 2) : ""));
+    });
+    results.forEach(function (s) {
+        lines.push("", "map" + s.map + " " + s.player + ", per wave:",
+                   "  lost   " + s.lost.map(function (v) { return pad(fmt(v, 1), 6); }).join(""),
+                   "  budget " + s.budget.map(function (v) { return pad(fmt(v), 6); }).join(""),
+                   "  need   " + s.need.map(function (v) { return pad(fmt(v), 6); }).join(""));
+    });
+    return lines;
+}
+
+function main() {
+    var o = options(process.argv.slice(2));
+    load(o.config, o.waves);
+    var maps = o.maps || MM.maps.map(function (_, i) { return i; });
+    var results = [];
+    maps.forEach(function (index) {
+        var md = new MapData(index);
+        var n = MM.config.maps[index].waves.length;
+        o.players.forEach(function (name) {
+            var runs = [];
+            for (var seed = 1; seed <= o.seeds; seed++) {
+                var player = makePlayer(name, md, index, seed);
+                var run = play(index, player, seed);
+                run.need = [];
+                for (var w = 0; w < n; w++) {
+                    run.need.push(o.needAll || w === n - 1 ? need(index, player, seed, w) : undefined);
+                }
+                runs.push(run);
+            }
+            results.push(summary(index, name, runs));
+        });
+    });
+    if (o.json) {
+        console.log(JSON.stringify(results));
+        return;
+    }
+    var lines = table(results, o);
+    fs.mkdirSync(path.dirname(OUT), { recursive: true });
+    fs.writeFileSync(OUT, lines.join("\n") + "\n");
+    fs.writeFileSync(OUT_JSON, JSON.stringify(results, null, 1) + "\n");
+    results.forEach(function (s) {
+        console.log("map" + s.map + " " + s.player + ": won " + s.won + "/" + s.seeds + ", hearts "
+                    + fmt(s.hearts, 1) + ", coins at the last wave " + fmt(s.coinsLast, 1)
+                    + ", surplus " + fmt(s.surplus) + (s.player === "naive" && s.hearts > HEARTS_TARGET + 1
+                    ? " (target " + HEARTS_TARGET + " hearts)" : ""));
+    });
+    console.log("simulate: wrote temp/preview/simulate.txt, simulate.json");
+}
+
+if (require.main === module) main();
+
+module.exports = { options: options, load: load, MapData: MapData, greedyCells: greedyCells,
+                   makePlayer: makePlayer, play: play, need: need, waveLoss: waveLoss,
+                   summary: summary };