Difficulty picker (Easy/Normal/Hard) and a balance pass
Difficulty: - TD.DIFFICULTIES (starting credits, lives, enemy hp/shield, kill reward), validated create-room / newgame option, state carries it; solo menu picker and co-op lobby picker (44px segmented control, reachable on every layout), HUD/room/end-screen labels, best-wave record per map AND difficulty (Normal keeps the legacy key), Play again keeps the running game's difficulty for host and guest Balance (12 bot runs, deterministic, 48/48 games replay identically in QA): - Normal ~71% bot wins at wave 30 (was 94%), Easy 100%, Hard 25% on open - credits tamed: reward growth 3% -> 2% per wave, clear bonus 10+2n -> 10+n, hp scaling eased, Rootkit pays 60 (was 100) but is tougher, flyers slower; unspent credits at wave 30: 1309 -> 335 - IDS Sniper is now a slow heavy hitter (essential, no longer sufficient: IDS-only dies by wave 7); Mortar, Arc and Filter buffed - Orbital Uplink price step per owned unit 30% (buy and upgrade) - remaining imbalances documented in docs/BALANCE.md Tests: difficulty (19) and balance (8) unit suites, 14-difficulty e2e, layout matrix reachability of the picker. 156 unit tests, 17 e2e scenarios. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
parent
28502984ec
commit
b4ae6cb57d
19 changed files with 1348 additions and 156 deletions
|
|
@ -163,17 +163,18 @@ the trailing slash). A dedicated sub-domain is simpler.
|
||||||
| **Goal** | Survive 30 waves (then keep going in endless mode) on one of seven maps. Every packet that reaches the server costs integrity. |
|
| **Goal** | Survive 30 waves (then keep going in endless mode) on one of seven maps. Every packet that reaches the server costs integrity. |
|
||||||
| **Firewall** (5) | A wall. Packets path-find around it; the route preview shows how much longer it makes their trip. |
|
| **Firewall** (5) | A wall. Packets path-find around it; the route preview shows how much longer it makes their trip. |
|
||||||
| **Packet Filter** | Fast and cheap. Weak against armour. |
|
| **Packet Filter** | Fast and cheap. Weak against armour. |
|
||||||
| **IDS Sniper** | Long range, hits hard, slow. The answer to armour and bosses. |
|
| **IDS Sniper** | Long range, hits hard, slow. The answer to armour and bosses, but a poor answer to swarms of weak packets (use Filters, Mortars and Arcs for those). |
|
||||||
| **Flood Mortar** | Splash damage on ground swarms. Cannot hit flyers. |
|
| **Flood Mortar** | Splash damage on ground swarms. Cannot hit flyers. |
|
||||||
| **Rate Limiter** | Slows everything in range. Rootkits resist it. |
|
| **Rate Limiter** | Slows everything in range. Rootkits resist it. |
|
||||||
| **Router Arc** | Chain lightning between nearby packets. |
|
| **Router Arc** | Chain lightning between nearby packets. |
|
||||||
| **Sandbox** | Control tower, no damage: pulses a stun on every packet in range (bosses are stunned half as long). |
|
| **Sandbox** | Control tower, no damage: pulses a stun on every packet in range (bosses are stunned half as long). |
|
||||||
| **Load Balancer** | Support tower, no attack: nearby attack turrets fire 15 / 25 / 35% faster (the best balancer in range applies, they do not stack). |
|
| **Load Balancer** | Support tower, no attack: nearby attack turrets fire 15 / 25 / 35% faster (the best balancer in range applies, they do not stack). |
|
||||||
| **Orbital Uplink** | The endgame weapon: a piercing beam that ignores armour, hits ground and air, blasts and slows around the target and reaches across most of the map. Extremely expensive: 1500 credits, upgrades 1200 / 2000 / 3200 (4 levels), and **every Uplink you already own makes the next one 25% dearer, to buy and to upgrade** (1500, 1880, 2340, 2930, ...), so kill rewards cannot buy a carpet of them. |
|
| **Orbital Uplink** | The endgame weapon: a piercing beam that ignores armour, hits ground and air, blasts and slows around the target and reaches across most of the map. Extremely expensive: 1500 credits, upgrades 1200 / 2000 / 3200 (4 levels), and **every Uplink you already own makes the next one 30% dearer, to buy and to upgrade** (1500, 1950, 2540, 3300, ...), so kill rewards cannot buy a carpet of them. |
|
||||||
| **Spoofed packets** | Fly straight over your maze: keep some anti-air. Botnet drones are fast flying swarms. |
|
| **Spoofed packets** | Fly straight over your maze: keep some anti-air. Botnet drones are fast flying swarms. |
|
||||||
| **Daemons** | Healers: they restore nearby packets (up to 12% of max health per second), so kill them first. |
|
| **Daemons** | Healers: they restore nearby packets (up to 12% of max health per second), so kill them first. |
|
||||||
| **Proxies** | Shielded packets: the shield soaks damage first and regrows after 3 s without being hit. |
|
| **Proxies** | Shielded packets: the shield soaks damage first and regrows after 3 s without being hit. |
|
||||||
| **Credits** | From kills and cleared waves. Upgrade turrets (3 levels, 4 for the Uplink); selling returns 70% (walls 100%). |
|
| **Credits** | From kills and cleared waves. Upgrade turrets (3 levels, 4 for the Uplink); selling returns 70% (walls 100%). |
|
||||||
|
| **Difficulty** | **Easy / Normal / Hard**, picked in the menu (solo) or by the host when creating a co-op room, and shown next to the next-wave list and on the end screen. It scales the starting credits and integrity, the hit points of every packet and what a kill pays (the table is `DIFFICULTIES` in `public/js/sim.js`). Normal uses the base tables of the game with every multiplier at 1. Your best wave is kept per map **and** difficulty. |
|
||||||
|
|
||||||
Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`9` pick a tower, `Space` next wave,
|
Controls, desktop: click to build, drag to paint walls, right-click cancels, `1`-`9` pick a tower, `Space` next wave,
|
||||||
`U` upgrade, `X` sell, `T` change targeting, `P` pause, `F` speed, `A` auto-waves, `M` mute, wheel zoom, Alt+click pings.
|
`U` upgrade, `X` sell, `T` change targeting, `P` pause, `F` speed, `A` auto-waves, `M` mute, wheel zoom, Alt+click pings.
|
||||||
|
|
|
||||||
205
docs/BALANCE.md
205
docs/BALANCE.md
|
|
@ -1,21 +1,165 @@
|
||||||
# Balance notes (baseline measured 2026-10-09, nothing tuned yet)
|
# Balance notes (tuned 2026-10-10, wave 4 pass; the untuned baseline was measured the same day)
|
||||||
|
|
||||||
`public/js/sim.js` still holds my first-guess numbers. A balance engineer agent built `tools/bot.js` (a headless player that
|
`public/js/sim.js` holds the tuned tables. The numbers were measured with `tools/bot.js`, a headless player that drives the sim
|
||||||
drives the sim through `sim.cmd()` / `sim.preview()`) and measured the untouched numbers; it was stopped before it applied any
|
through `sim.cmd()` / `sim.preview()`. No test pins a tuned number: `test/sim.test.js` and `test/difficulty.test.js` derive values
|
||||||
tuning. `test/sim.test.js` was already updated by it so that no test hard-codes a tunable number (they derive values from
|
from the tables, and `test/balance.test.js` pins the *design rules* the pass relied on (credit budget, boss pay, upgrade
|
||||||
the `TOWERS` / `ENEMIES` tables), plus one test that pins the table *shape* the client and server depend on.
|
efficiency, IDS role, Uplink price share, difficulty ladder), each derived from the tables too.
|
||||||
|
|
||||||
|
The pass was time-boxed (12 runs of the bot, counting two short smoke tests of the tool itself; 8 seeds per cell in the final ones). With 8 seeds one win more or less is 12 points:
|
||||||
|
read the tables as bands, not as exact rates.
|
||||||
|
|
||||||
|
## What a player should notice
|
||||||
|
|
||||||
|
* Kill money is smaller and flatter: a defence earns about 22% fewer credits over 30 waves (7676 -> 5980), a boss is worth
|
||||||
|
about half as much, and the clear bonus grows by 1 a wave instead of 2. Packet hit points are 14 to 21% lower than before
|
||||||
|
(they scale slower), which pays the credit cut back: Normal stays winnable, but no longer by a wide margin.
|
||||||
|
* The IDS Sniper is now a slow heavy sniper (fewer, harder shots): the same damage per second as before against a tank, worse
|
||||||
|
against a swarm of weak packets, so a defence made of IDS alone dies in the first swarm waves. It is still the backbone of
|
||||||
|
every strong build against bosses and armour.
|
||||||
|
* Mortar, Arc and Filter are better value; upgrades are cheaper for them (and dearer for the IDS), so credits go into
|
||||||
|
upgrading and into a mix.
|
||||||
|
* Flyers are slower (longer in range), Trojans and Rootkits are more armoured, the opening waves are unchanged.
|
||||||
|
|
||||||
|
## Constants changed, and why (all in `public/js/sim.js`)
|
||||||
|
|
||||||
|
| constant | before | after | reason |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `rewardScale(n)` | 1 + 0.03 (n-1) | 1 + 0.02 (n-1) | late kills paid too much; credits snowballed |
|
||||||
|
| Rootkit `reward` | 100 | 60 | a boss wave paid the price of ~2 IDS; now about one (wave 10: 127 -> 71 credits, wave 30 with 3 bosses: 561 -> 285) |
|
||||||
|
| Rootkit `buyCost` | 300 | 180 | keeps the "about 3x the kill reward" rule of the future versus mode (`docs/VERSUS.md` number updated) |
|
||||||
|
| clear bonus | 10 + 2 n | 10 + n (`CLEAR_BONUS`, `CLEAR_BONUS_PER_WAVE`, `clearBonus(n)` exported) | the bonus alone was 16% of all credits; only constants were extracted, the formula is the same |
|
||||||
|
| `hpScale(n)` | 1 + 0.16 (n-1) + 0.022 (n-1)^2 | 1 + 0.145 (n-1) + 0.0165 (n-1)^2 | pays back the credit cut: 14% lower at wave 10, 19% at 20, 21% at 30 than the untuned game |
|
||||||
|
| Trojan `armor` | 3 | 4 | armour should matter a little more against Filters |
|
||||||
|
| Rootkit `armor` | 5 | 7 | same, and the boss is the IDS / Mortar / Uplink job |
|
||||||
|
| Spoof (ghost) `speed` | 1.6 | 1.3 | flyers ignore the maze, so they get little time in range; they were a cliff at waves 7, 13, 15, 23 |
|
||||||
|
| Botnet `speed` | 2.6 | 2.2 | same |
|
||||||
|
| IDS cost (L1/L2/L3) | 60 / 70 / 110 | 70 / 80 / 130 | the best tower per credit by far; 58 of them were built per game |
|
||||||
|
| IDS dmg | 50 / 85 / 150 | 83 / 143 / 250 | same dps against a tank as before... |
|
||||||
|
| IDS rate | 0.70 / 0.75 / 0.80 | 0.42 / 0.445 / 0.48 | ...but fewer shots, so swarms of weak packets are not its job (IDS-only now dies by wave 7) |
|
||||||
|
| IDS range | 6.5 / 7.2 / 8.0 | 6.2 / 6.8 / 7.5 | slightly less coverage per credit |
|
||||||
|
| IDS description | "...bosses." | "...bosses, poor against swarms." | the player is told |
|
||||||
|
| Filter range | 3.2 / 3.5 / 3.9 | 3.5 / 3.8 / 4.2 | the cheap swarm / anti-air tower had too little coverage |
|
||||||
|
| Filter upgrade cost (L2/L3) | 30 / 55 | 25 / 45 | an upgrade gave 58% of the dps per credit of a new tower |
|
||||||
|
| Mortar cost / dmg / range | 55 60 100 / 28 45 75 / 4.8 5.2 5.6 | 55 60 95 / 31 50 82 / 4.9 5.3 5.7 | far too weak; now the answer to ground swarms |
|
||||||
|
| Arc cost / dmg | 75 70 120 / 16 24 36 | 70 60 105 / 17 26 38 | far too weak alone; the first buff (dmg 20 30 44, 65 / 50 / 90) let Arc-only win 6 of 8 on `open`, so this is the middle |
|
||||||
|
| Arc range | 3.6 / 3.8 / 4.2 | 3.8 / 4.0 / 4.4 | |
|
||||||
|
| `DIFFICULTIES.hard` | gold 0.8, lives 0.7, hp 1.3, reward 0.9 | gold 0.9, lives 0.85, hp 1.08, reward 0.97 | the first row was a wall (0 wins in 35 games). The whole row (+8% hp, -3% rewards, -10% credits, -15% lives) takes `open` from 75% to 25% |
|
||||||
|
| `DIFFICULTIES.easy` | 1.5 / 1.5 / 0.8 / 1.1 | unchanged | already 56 of 56 |
|
||||||
|
|
||||||
|
Not changed: `START_GOLD` 140, `START_LIVES` 20, `WAVE_INTERVAL` 28, `SELL_RATIO` 0.7, every `waveGroups` count and gap, Throttle,
|
||||||
|
Sandbox, Load Balancer, and the Orbital Uplink (1500 / 1200 / 2000 / 3200, each owned Uplink makes the next one and its
|
||||||
|
upgrades 30% dearer: the user's request, kept). Wall price and wall count are untouched on purpose (user decision: the maze stays strong).
|
||||||
|
|
||||||
|
## Results (Normal unless stated; "win" = the wave 30 clear)
|
||||||
|
|
||||||
|
Before = the untuned numbers, 5 seeds. After = the shipped numbers, 8 seeds (Easy and Hard rows: `maze@easy`, `maze@hard`).
|
||||||
|
|
||||||
|
| mixed maze bot | before | after | target |
|
||||||
|
|---|---|---|---|
|
||||||
|
| open | 4/5 | 6/8 | 70-80% |
|
||||||
|
| twin | 5/5 | 5/8 | 50-70% |
|
||||||
|
| hub | 5/5 | 6/8 | 40-50% |
|
||||||
|
| canyon | 5/5 | 8/8 | 50-70% |
|
||||||
|
| archipelago | 5/5 | 5/8 | 50-70% |
|
||||||
|
| fortress | 4/5 | 5/8 | 50-70% |
|
||||||
|
| pinwheel | 5/5 | 5/8 | 40-50% |
|
||||||
|
| all maps | 33/35 (94%), 12-20 lives left | 40/56 (71%), 12 lives left (open 10) | about 58% |
|
||||||
|
| Easy, all maps | 35/35 | 56/56 (27-30 lives left of 30) | 90%+ |
|
||||||
|
| Hard, open / twin / hub | 0/35 on all maps (dies wave 7-29) | 2/8 / 1/8 / 0/8 (mean wave 25.6 / 21.5 / 20.9) | 20-35% on open |
|
||||||
|
|
||||||
|
| single-tower and ablation builds (8 seeds) | before | after |
|
||||||
|
|---|---|---|
|
||||||
|
| spam-ids (open+twin) | 35/35 (all maps) | 0/16, dies in wave 3-7 (swarm waves) |
|
||||||
|
| spam-filter (open+twin) | 0/35 (all maps), wave 12-23 | 0/16, wave 12-22 |
|
||||||
|
| spam-mortar (open, twin, hub) | 0/24, wave 6-8 (old doc) | 0/16 (open, twin), wave 6-8 (flyers: no anti-air) |
|
||||||
|
| spam-arc (open, twin, hub) | 0/24, wave 14-22 (old doc) | 0/16 (open, twin), wave 15-26 |
|
||||||
|
| mixed without IDS (open) | 0/5, dies wave 16-29 | 1/8 (mixed: 6/8) |
|
||||||
|
| mixed without Mortar (open) | not measured | 1/8 |
|
||||||
|
| mixed without Throttle (open) | not measured | 2/8 |
|
||||||
|
| mixed without Arc (open) | not measured | 6/8 |
|
||||||
|
| mixed without Filter (open) | not measured | 8/8 |
|
||||||
|
|
||||||
|
| economy (mixed bot) | before | after |
|
||||||
|
|---|---|---|
|
||||||
|
| credits paid by wave 10 / 15 / 20 / 25 / 30 (gold + invested, games that got that far, all maps) | 874 / 1551 / 2370 / 3560 / 6577 | 773 / 1320 / 2040 / 2860 / 5190 |
|
||||||
|
| credits in hand at wave 10 / 15 / 20 / 25 | 33 / 39 / 33 / 38 | 32 / 33 / 33 / 30 (always spent) |
|
||||||
|
| credits in hand at wave 30 (the bot stops buying when no wave is left to prepare for) | 1309 | 335 |
|
||||||
|
| full-clear income to wave 30 (table arithmetic, `income()` in `test/balance.test.js`) | 7676 | 5980 |
|
||||||
|
| IDS towers at wave 30 (open / twin / hub) | 58 / 49 / 44 (80-97% of all damage) | 25 / 30 / 25 (49% / 76% / 69%) |
|
||||||
|
| lives lost in waves 1-5 (sum over games) | 5 in 35 games | 3 in 56 games |
|
||||||
|
|
||||||
|
Where the lives go (mixed bot, all maps): Rootkit leaks (5 lives each) 66% before and 53% after; then Trojans 15%, Spoofs 10%,
|
||||||
|
Proxies 9%, Botnets 6%, Worms 5% (after).
|
||||||
|
|
||||||
|
## Targets scorecard
|
||||||
|
|
||||||
|
| target | state |
|
||||||
|
|---|---|
|
||||||
|
| maze beats no-maze, no-maze survives the first 8-10 waves, lazy dies early, no leaks in waves 1-5 | holds (8 seeds): mixed maze 6/8, 5/8, 6/8 on open / twin / hub against no-maze 1/8, 0/8, 0/8 (they die at wave 21-30, on hub all 8 in the wave 30 boss wave); lazy dies in wave 9 / 4 / 7; waves 1-5 lose 3 lives in 56 games |
|
||||||
|
| Normal open 70-80% | 75% (6/8) |
|
||||||
|
| twin, new maps 50-70% | twin 63, archipelago 63, fortress 63; **canyon 100%** |
|
||||||
|
| hub, pinwheel 40-50% | 75% and 63%: a little easy (not fixable with global tables, see below) |
|
||||||
|
| every spam strategy loses | **yes**, all four 0/16 |
|
||||||
|
| each tower type matters in the best mix | IDS (1/8 without), Mortar (1/8), Throttle (2/8): yes. **Filter and Arc: no** (the mix wins as often, or more, without them) |
|
||||||
|
| credits neither pile up nor starve | spent to the credit at every wave up to 25 (30-33 in hand), 335 at wave 30 (1309 before) |
|
||||||
|
| Easy 90%+, Hard 20-35% on open | 100%, 25% |
|
||||||
|
|
||||||
|
## Remaining known imbalances
|
||||||
|
|
||||||
|
1. **Filter and Arc do not pull their weight in the bot's best build.** Without Filters the mixed build wins 8/8 (with: 6/8)
|
||||||
|
on `open`; the bot over-buys them (23 on `open` at wave 30, 18% of damage) because its surrogate overrates cheap towers. The
|
||||||
|
bot buys almost no Arc (0 to 1.5 a game), though an Arc-only build now reaches wave 15-26. Either the towers still need a
|
||||||
|
role (Arc: chain on dense late swarms, Filter: early game and flyers) or the bot's model undervalues them; a human playtest
|
||||||
|
should decide. Throttle matters (2/8 without it).
|
||||||
|
2. **IDS is still the backbone**: 49 to 76% of the damage of the mixed builds and a build without it wins 1/8, but it is no
|
||||||
|
longer sufficient (IDS-only dies in wave 3-7). A mixed build with ~25 IDS and a handful of Mortars is what the bot finds best.
|
||||||
|
3. **Map spread is not tunable with global tables.** `canyon` (rating 1) is a 100% map, `hub` and `pinwheel` are easier than
|
||||||
|
asked, `archipelago` and `fortress` are about right. Hard is tuned to `open` (25%): on `twin` and `hub` it is 0 to 12%.
|
||||||
|
4. **Boss leaks decide games**: a Rootkit that gets through costs 5 of 20 lives and is the main cause of death. They are
|
||||||
|
dangerous on purpose (the user wanted bosses to hurt); if playtests find it too swingy, lower the Rootkit `leak` to 4 before
|
||||||
|
touching hp. Rootkits walk about 200 s through a long maze, so they overlap 6 to 7 later waves when waves are called on the
|
||||||
|
28 s timer: the bot's per-wave life-loss log attributes such a leak to the wave that was current when it happened.
|
||||||
|
5. **Sandbox, Load Balancer and Orbital Uplink are not valued well by the bot.** It never builds a Sandbox and rarely a Load
|
||||||
|
Balancer, so nothing can be said about them from the numbers. The Uplink was tested with a "save for it" rule: a bot that
|
||||||
|
saves from wave 12 to 16 starves its defence and dies (1/8, mean wave 18.6) before it can pay 1500. Judged on paper: the
|
||||||
|
first Uplink is 1500 = 25% of the 5980 credits a full run pays (the second 1950, the third 2540), and 1500 credits of IDS L1
|
||||||
|
is ~21 towers; the Uplink is an endless-mode purchase, not a way to win wave 30. Nothing was changed.
|
||||||
|
6. The waves were not touched. Flyer waves (`(n-1) % 8` = 4 and 6; from wave 14 with the Botnet swarm) and wave 28 are
|
||||||
|
still where defences break first; the Daemon, Proxy and Botnet themselves are not a leading cause of lost lives
|
||||||
|
(1 to 15% of leaks each).
|
||||||
|
7. The balance of Normal, Easy and Hard is steep: the whole Hard row (8% more packet hit points, 3% less pay, 10% fewer opening
|
||||||
|
credits, 15% fewer lives) moves `open` from 75% to 25%. Re-measure after *any* number change, with at least 8 seeds.
|
||||||
|
|
||||||
## Re-running the measurement
|
## Re-running the measurement
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
node tools/bot.js --maps open,twin,hub \
|
node tools/bot.js --maps open,twin,hub,canyon,archipelago,fortress,pinwheel \
|
||||||
--strategies maze,nomaze,spam-filter,spam-ids,spam-mortar,spam-arc,lazy,maze-no-ids,maze-no-filter,maze-no-mortar,maze-no-throttle,maze-no-arc \
|
--strategies "maze;maze@easy#open;maze@hard#open;maze-no-ids#open;maze-no-filter#open;maze-no-mortar#open;maze-no-arc#open;maze-no-throttle#open;spam-ids#open+twin;spam-arc#open+twin;spam-filter#open+twin;spam-mortar#open+twin" \
|
||||||
--seeds 8 --max 45
|
--seeds 8 --max 30 --verbose --json out.json
|
||||||
```
|
|
||||||
(runs on all cores; `--sim other/sim.js` measures another copy; `--json out.json --detail` for raw games.) Strategies: `maze`
|
|
||||||
(the mixed build), `nomaze`, `spam-<type>` (maze + one turret type), `maze-no-<type>` (ablation), `lazy`.
|
|
||||||
|
|
||||||
## Baseline results (8 seeds, waves up to 45; "win" = survived to wave 45)
|
# the Easy (all maps) and Hard (open, twin, hub) rows of the results table
|
||||||
|
node tools/bot.js --maps open,twin,hub,canyon,archipelago,fortress,pinwheel \
|
||||||
|
--strategies "maze@easy;maze@hard#open+twin+hub" --seeds 8 --max 30 --verbose --json out-diff.json
|
||||||
|
```
|
||||||
|
|
||||||
|
(about 3 to 10 minutes on 6 cores; it uses all of them. `--sim other/sim.js` measures another copy; `--json out.json --detail`
|
||||||
|
for raw games; `--gold N` overrides the opening credits.) Strategy names: `maze` (the mixed build), `nomaze`, `spam-<type>`,
|
||||||
|
`maze-no-<type>`, `lazy`, `full` (mixed + Sandbox + Load Balancer + Uplink) and `maze+<type>` (mixed + one extra type), with
|
||||||
|
optional `:key=value` overrides (see `DEFAULTS` in the bot; use `;` between strategies that carry them). A strategy can carry a
|
||||||
|
game difficulty after `@` and the only maps it runs on after `#` (`maze@hard#open+twin`). The tables now print `gold@25` and a
|
||||||
|
"credits seen" block (gold + everything invested, games that reached the wave only). Tips: results depend on the bot's own
|
||||||
|
heuristics as much as on the numbers; `full` and `maze+uplink` save for the Uplink from wave 16 (12 with the override), which starves the
|
||||||
|
defence, so do not read their rows as balance data; the bot waits for each wave to clear but calls the next one after at most 28 s; for a
|
||||||
|
Uplink experiment `maze+uplink:uplinkFrom=12` makes it save for one from that wave.
|
||||||
|
|
||||||
|
The bot is deterministic: the same sim and the same seeds replay the same games, so every number above can be reproduced exactly
|
||||||
|
(an independent QA re-run of `maze`, `maze@easy` and `maze@hard` on open / hub / canyon, seeds 1-6, matched all 48 recorded games
|
||||||
|
move for move, outcome and lives left). `maze@hard` on `canyon` was not measured in the pass: 4 of 6 won in the QA re-run.
|
||||||
|
|
||||||
|
The bot's model of the support towers is crude: a Sandbox counts as a slow of `stun / pulse`, a Load Balancer as a fire-rate boost
|
||||||
|
on the turrets in its range, the Uplink as armour-ignoring damage with a pierce factor. Treat their rows as "not measured".
|
||||||
|
|
||||||
|
## The untuned baseline (for the record; 8 seeds, waves up to 45, 2026-10-09)
|
||||||
|
|
||||||
| strategy | open | twin | hub |
|
| strategy | open | twin | hub |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
|
|
@ -26,39 +170,8 @@ node tools/bot.js --maps open,twin,hub \
|
||||||
| spam-mortar | 0/8 (wave 8) | 0/8 (wave 6-8) | 0/8 (wave 6-7) |
|
| spam-mortar | 0/8 (wave 8) | 0/8 (wave 6-8) | 0/8 (wave 6-7) |
|
||||||
| spam-arc | 0/8 (wave 14-22) | 0/8 | 0/8 |
|
| spam-arc | 0/8 (wave 14-22) | 0/8 | 0/8 |
|
||||||
| maze without IDS | 0/8 (wave 14-29) | 0/8 | 0/8 |
|
| maze without IDS | 0/8 (wave 14-29) | 0/8 | 0/8 |
|
||||||
| maze without filter / throttle / arc | still wins (7-8 of 8) | still wins (7-8 of 8) | still wins (7-8 of 8) |
|
|
||||||
| lazy | dies wave 8-9 | wave 3-4 | wave 6 |
|
| lazy | dies wave 8-9 | wave 3-4 | wave 6 |
|
||||||
|
|
||||||
Route length at wave 30 with the maze strategy, per gateway: about 150 cells on open, ~165 on twin and ~136 on hub, versus
|
Its findings: IDS mandatory and sufficient; the maze a near-guaranteed win; no-maze too viable on `open`; the economy snowballed
|
||||||
roughly 25 for the unobstructed path (the bot reports the sum over gateways: 150 / 330 / 409). Credits at wave 30: about 280 unspent.
|
(about 280 credits unspent at wave 30 and ~60 IDS per game) while the early game was tight. This pass answered them with the
|
||||||
|
credit cut, the sniper role for the IDS and better Mortar / Arc / Filter value; the wall rule was ruled out by the user.
|
||||||
## What the numbers say
|
|
||||||
|
|
||||||
1. **IDS Sniper is mandatory and sufficient.** Every build without it collapses around wave 15-28; a maze + IDS-only
|
|
||||||
build wins everything on every map. That breaks the design goal that no single tower dominates and that flyers/armour
|
|
||||||
force a mixed defence. IDS needs a cost/damage/range nerf, or the other towers need real roles (Mortar and Arc are
|
|
||||||
far too weak on their own: they die by wave 8 / 15-22).
|
|
||||||
2. **The maze is a near-guaranteed win.** Cheap 5-credit walls stretch routes about 5 to 6 times, and the game is too easy
|
|
||||||
once you do it. Mazing should be rewarding but not a solved game. Candidate levers (a design decision, see NEXT.md):
|
|
||||||
escalating wall price (for example +1 credit per 10 walls), a wall cap, faster late waves, or armour/regen that punishes
|
|
||||||
long exposure.
|
|
||||||
3. **No-maze is too viable on open** (reaches wave 29-43). Early waves are too gentle, or turrets too strong without a maze.
|
|
||||||
4. **Economy snowballs** (about 280 credits unspent at wave 30) while the early game is tight (about 30-45 credits spare
|
|
||||||
around waves 5-10). Cut late-game rewards or add sinks (upgrade costs, escalating prices).
|
|
||||||
5. Throttle, Filter and Arc individually add little (removing any one still wins): either buff their roles or accept they
|
|
||||||
are support pieces.
|
|
||||||
|
|
||||||
## Targets the tuning should hit (from the original brief)
|
|
||||||
|
|
||||||
* Maze clearly beats no-maze; no-maze still survives the first 8-10 waves; lazy dies early.
|
|
||||||
* On `open`, a good maze build wins wave 30 in most seeds with a few lives to spare but not with a perfect record; no leaks
|
|
||||||
in waves 1-5.
|
|
||||||
* `twin` harder than `open`; `hub` hardest (maze build reaching roughly waves 24-30).
|
|
||||||
* Every single-tower spam strategy loses before wave 30 on `open`; every tower type is part of the best mixed build at least
|
|
||||||
sometimes. Flyer waves must punish a defence without anti-air, boss/Trojan waves must punish pure Filter spam.
|
|
||||||
* Credits neither snowball nor starve.
|
|
||||||
|
|
||||||
Only constants and tables in `sim.js` should need to change (costs, damage, range, rates, enemy hp/speed/armor/reward,
|
|
||||||
`waveGroups` counts, `hpScale`, `rewardScale`, `START_GOLD`, `SELL_RATIO`). Keep every table key, the 3-entry `levels`
|
|
||||||
arrays and the field names: the client UI and the server read them. A wall price escalation would be a logic change in
|
|
||||||
`Sim.place` and in the client's cost display.
|
|
||||||
|
|
|
||||||
20
docs/NEXT.md
20
docs/NEXT.md
|
|
@ -3,18 +3,18 @@
|
||||||
Netwall is playable and pushed: solo (desktop + phone), two-player co-op through the Node server, music, PWA, deploy docs.
|
Netwall is playable and pushed: solo (desktop + phone), two-player co-op through the Node server, music, PWA, deploy docs.
|
||||||
Development was paused on purpose before the fix stage. This file is the entry point for the next session.
|
Development was paused on purpose before the fix stage. This file is the entry point for the next session.
|
||||||
|
|
||||||
## State of the repo
|
## State of the repo (2026-10-11)
|
||||||
|
|
||||||
| Area | State |
|
| Area | State |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `public/js/sim.js` | Shared rules. 20 unit tests. **Balance not tuned yet** (see `docs/BALANCE.md`). |
|
| `public/js/sim.js` | Shared rules: 7 maps, 9 towers (Sandbox, Load Balancer, 4-level Orbital Uplink with escalating prices), 9 enemy kinds, Easy/Normal/Hard. **Balance tuned once** (Normal ~71% bot wins, see `docs/BALANCE.md`); remaining imbalances are listed there. |
|
||||||
| `server/` | Done and reviewed by an independent adversarial pass (5 real issues found and fixed: pid leak/slot hijack, room-flood lockout, spoofable X-Forwarded-For, startup crash in restricted sandboxes, clock-step in rate limiter). 59 tests. |
|
| `server/` | Adversarially reviewed (pid leak, room flood, XFF, ...) and proxy-tested against real nginx with Proxy Manager's config. Co-op robustness fixed (stalls, half-open sockets, idempotent commands). |
|
||||||
| `public/` client | Works, but a second review pass found many issues. **None fixed yet.** See `docs/review-2026-10-09/findings.md`. |
|
| `public/` client | Phone-first layout (action bars, scrollable palette, pinned overlay footers), touch precision (nothing commits on pointerdown, nudge arrows), a11y/audio fixes, difficulty picker. Tested across 33 viewports incl. tablets and foldables (emulated). |
|
||||||
| `e2e/` | `npm run e2e`: smoke, touch, end flow, co-op (two browsers incl. reconnect), 14-size layout matrix. All passed at the last run. |
|
| `e2e/` | `npm run e2e`: 17 scenarios (smoke, touch, touch precision, select/sell, info-panel stability, UI states, a11y, audio, content gallery, co-op chaos, session UI, Uplink price, difficulty, 33-layout matrix ~8 min). Timing checks can flake on a loaded machine: rerun a scenario alone before concluding anything. |
|
||||||
| `tools/bot.js` | Headless balance bot (dev tool). Complete; its results are summarised in `docs/BALANCE.md`. |
|
| `tools/bot.js` | Headless defender bot (dev tool; deterministic). Does not build Sandbox / Load Balancer / Uplink. |
|
||||||
| Deploy | `docs/DEPLOY.md`, `deploy/netwall.service`, README setup guide. Never run against a real nginx Proxy Manager or on a phone yet (an NPM-style review found doc inaccuracies, listed in the findings). |
|
| Deploy | `docs/DEPLOY.md`, `deploy/netwall.service`, README setup guide; proxy behaviour verified against nginx 1.26 with Proxy Manager v2.16's rendered config (not the NPM app itself, not a real LXC). |
|
||||||
|
|
||||||
`npm test` = 91 passing. `npm run e2e` = 9 scenarios (22-layout matrix, touch precision, selection/sell, info-panel stability, UI states, co-op). Verified from a fresh `git clone` earlier (2026-10-09).
|
`npm test` = 156 passing.
|
||||||
|
|
||||||
## Fixed since this was written
|
## Fixed since this was written
|
||||||
|
|
||||||
|
|
@ -31,8 +31,8 @@ and a check that the layout holds on **tablets and foldables**.
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| 1 | Phone panels/layout + touch precision, proxy/server doc fixes, QA | **done 2026-10-10** |
|
| 1 | Phone panels/layout + touch precision, proxy/server doc fixes, QA | **done 2026-10-10** |
|
||||||
| 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave, restart message), audio + keyboard + a11y | **done 2026-10-10** (QA passed) |
|
| 2 | Co-op robustness (stalled-render tower loss, half-open sockets, idempotent upgrade/wave, restart message), audio + keyboard + a11y | **done 2026-10-10** (QA passed) |
|
||||||
| 3 | New enemies (Daemon healer, Proxy shielded, Botnet swarm) and towers (Sandbox stun, Load Balancer buff), glyphs/shapes, gallery e2e; Orbital Uplink (4 levels, priced 1500 + 25% per owned, upgrades scale equally); 4 new maps | **done 2026-10-10** (QA passed) |
|
| 3 | New enemies (Daemon healer, Proxy shielded, Botnet swarm) and towers (Sandbox stun, Load Balancer buff), glyphs/shapes, gallery e2e; Orbital Uplink (4 levels, priced 1500 + 25% per owned, upgrades scale equally; ); 4 new maps | **done 2026-10-10** (QA passed) |
|
||||||
| 4 | Difficulty picker (Easy/Normal/Hard) + ONE time-boxed balance pass (IDS dominance, weak Mortar/Arc, credit snowball and boss rewards, new content) | drafted (`wave4d`) |
|
| 4 | Difficulty picker (Easy/Normal/Hard) + ONE time-boxed balance pass (IDS no longer sufficient, credit snowball tamed, Mortar/Arc/Filter buffed, flyers slower); Uplink price step set to 30% per owned | **done 2026-10-11** (QA passed) |
|
||||||
| 5 | Attack-vs-defend versus mode, bots for both sides | design in `docs/VERSUS.md`, workflow drafted |
|
| 5 | Attack-vs-defend versus mode, bots for both sides | design in `docs/VERSUS.md`, workflow drafted |
|
||||||
| 6 | Server leaderboard (needs `StateDirectory=netwall` + `DATA_DIR`; solo scores are client-reported) and an opt-in public room list | after 5 |
|
| 6 | Server leaderboard (needs `StateDirectory=netwall` + `DATA_DIR`; solo scores are client-reported) and an opt-in public room list | after 5 |
|
||||||
| any | Fold/tablet real-device check; open items below | |
|
| any | Fold/tablet real-device check; open items below | |
|
||||||
|
|
|
||||||
|
|
@ -78,16 +78,20 @@ at a domain root and under a path prefix the proxy strips.
|
||||||
Client's first message:
|
Client's first message:
|
||||||
|
|
||||||
```
|
```
|
||||||
{ t:'join', pid, name, room?, map? }
|
{ t:'join', pid, name, room?, map?, difficulty? }
|
||||||
```
|
```
|
||||||
* `pid` `^[A-Za-z0-9_-]{8,40}$` - random, generated by the client, kept in `sessionStorage` (stable across reloads).
|
* `pid` `^[A-Za-z0-9_-]{8,40}$` - random, generated by the client, kept in `sessionStorage` (stable across reloads).
|
||||||
* `name` any string; server trims, strips control chars, caps at 16 chars, default `"Player"`.
|
* `name` any string; server trims, strips control chars, caps at 16 chars, default `"Player"`.
|
||||||
* `room` absent -> **create** a room. `map` must be a key of `TD.MAPS` (default `'open'`).
|
* `room` absent -> **create** a room. `map` must be a key of `TD.MAPS` (default `'open'`). `difficulty` must be a key of
|
||||||
|
`TD.DIFFICULTIES` (`'easy'`, `'normal'`, `'hard'`; default `'normal'`, `null` counts as absent), see "Difficulty" below.
|
||||||
Server generates a 4 character code from `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, unique among rooms.
|
Server generates a 4 character code from `ABCDEFGHJKLMNPQRSTUVWXYZ23456789`, unique among rooms.
|
||||||
* `room` present (`^[A-Za-z0-9]{4}$`, case-insensitive -> upper-cased) -> **join**.
|
* `room` present (`^[A-Za-z0-9]{4}$`, case-insensitive -> upper-cased) -> **join**. `map` and `difficulty` are ignored on a join (not even
|
||||||
|
validated): the joiner gets the room's, in `state.map` / `state.difficulty` of the `joined` message. A reconnect (same `pid`) is a join.
|
||||||
|
|
||||||
Failure: `{ t:'error', code, msg }` then the server closes the socket (code 4000+).
|
Failure: `{ t:'error', code, msg }` then the server closes the socket (code 4000+).
|
||||||
Codes: `bad_request`, `no_room`, `full` (two *other* pids already hold the slots), `too_many_rooms`, `bad_map`.
|
Codes: `bad_request`, `no_room`, `full` (two *other* pids already hold the slots), `too_many_rooms`, `bad_map`, `bad_difficulty`
|
||||||
|
(a creating join whose `difficulty` is not one of the table's keys: wrong type, `'toString'`, `'__proto__'`, ... all refused, no room is
|
||||||
|
created, the socket closes with 4400; a bad `map` is checked first).
|
||||||
|
|
||||||
Success: reply to the joiner
|
Success: reply to the joiner
|
||||||
|
|
||||||
|
|
@ -121,7 +125,7 @@ pid for the viewer's own entry and an opaque, stable per-room alias for the othe
|
||||||
| `{t:'mark', x, y}` | map ping; at most 1 per 400 ms per player; server broadcasts `mark` (below) |
|
| `{t:'mark', x, y}` | map ping; at most 1 per 400 ms per player; server broadcasts `mark` (below) |
|
||||||
| `{t:'rtt', ts}` | latency probe; reply immediately with the same `ts` |
|
| `{t:'rtt', ts}` | latency probe; reply immediately with the same `ts` |
|
||||||
| `{t:'sync'}` | ask for a full state resend |
|
| `{t:'sync'}` | ask for a full state resend |
|
||||||
| `{t:'newgame', map}` | **host only**: replace the sim with a fresh `new Sim({map})`; resets pause/speed |
|
| `{t:'newgame', map?, difficulty?}` | **host only**: replace the sim with a fresh `new Sim({map, difficulty})`; resets pause/speed. An absent (or `null`) `map` / `difficulty` keeps the room's current one, so a plain `{t:'newgame'}` is "play again" |
|
||||||
| `{t:'leave'}` | leave now |
|
| `{t:'leave'}` | leave now |
|
||||||
|
|
||||||
**Idempotent `upgrade` and `wave`.** Two players who press Upgrade (or Next wave) at the same moment both send the command; without
|
**Idempotent `upgrade` and `wave`.** Two players who press Upgrade (or Next wave) at the same moment both send the command; without
|
||||||
|
|
@ -137,7 +141,8 @@ Command validation is the server's job: `t:'cmd'` must carry a string `c` in the
|
||||||
`c`, non-object, etc. count as malformed. A command the sim refuses (`{ok:false, reason}`) gets
|
`c`, non-object, etc. count as malformed. A command the sim refuses (`{ok:false, reason}`) gets
|
||||||
`{ t:'reject', c, reason, x?, y?, id? }` sent **to the sender only** (echo `x,y`/`id` when present).
|
`{ t:'reject', c, reason, x?, y?, id? }` sent **to the sender only** (echo `x,y`/`id` when present).
|
||||||
Successful commands send nothing extra; the effect arrives via `snap`.
|
Successful commands send nothing extra; the effect arrives via `snap`.
|
||||||
`newgame` from a non-host -> `reject` with `reason:'not_host'`; `newgame` with a bad map -> `reject` `bad_map`.
|
`newgame` from a non-host -> `reject` with `reason:'not_host'`; `newgame` with a bad map -> `reject` `bad_map`; with a bad difficulty
|
||||||
|
-> `reject` `bad_difficulty` (checked in the order not_host, bad_map, bad_difficulty; a rejected `newgame` changes nothing and sends no `state`).
|
||||||
|
|
||||||
## Client behaviour that the protocol relies on
|
## Client behaviour that the protocol relies on
|
||||||
|
|
||||||
|
|
@ -167,6 +172,9 @@ Successful commands send nothing extra; the effect arrives via `snap`.
|
||||||
{ t:'reject', c, reason, ... }
|
{ t:'reject', c, reason, ... }
|
||||||
{ t:'error', code, msg }
|
{ t:'error', code, msg }
|
||||||
```
|
```
|
||||||
|
* `state.difficulty` (also in the `joined` message) is the room's difficulty id. It is a field of `fullState()`, added next to `map`,
|
||||||
|
`rev`, `towers`, `winWave` and `maxLives`; an older server sends none and a client then assumes `'normal'`. The per-tick `snap` does
|
||||||
|
not repeat it: it cannot change without a `state` message (only the host's `newgame` changes it, and that sends one).
|
||||||
* `seq` increments by 1 per snapshot per room.
|
* `seq` increments by 1 per snapshot per room.
|
||||||
* Snapshots are sent every `1000/snapshotHz` ms **whether or not** the sim advanced (paused rooms still send, so
|
* Snapshots are sent every `1000/snapshotHz` ms **whether or not** the sim advanced (paused rooms still send, so
|
||||||
cursors keep moving) but only to online players, and only if at least one player is online.
|
cursors keep moving) but only to online players, and only if at least one player is online.
|
||||||
|
|
@ -183,6 +191,21 @@ Successful commands send nothing extra; the effect arrives via `snap`.
|
||||||
* Because WebSocket is reliable and ordered, `tw` deltas cannot be lost; `snap.rev` lets a client detect a
|
* Because WebSocket is reliable and ordered, `tw` deltas cannot be lost; `snap.rev` lets a client detect a
|
||||||
bug/desync (`rev` differs from the `rev` it last applied and no `tw` came along) and ask for `sync`.
|
bug/desync (`rev` differs from the `rev` it last applied and no `tw` came along) and ask for `sync`.
|
||||||
|
|
||||||
|
## Difficulty
|
||||||
|
|
||||||
|
`TD.DIFFICULTIES` (`sim.js`) has one row per difficulty, `{ id, name, gold, lives, hp, reward }`, every number a multiplier on the normal
|
||||||
|
game; `TD.DIFFICULTY_ORDER` is `['easy', 'normal', 'hard']` (append-only: the ids are on the wire). `new Sim({ map, difficulty })`:
|
||||||
|
|
||||||
|
* `gold`, `lives`: the starting credits and integrity are `START_GOLD` / `START_LIVES` times it (rounded, integrity at least 1;
|
||||||
|
`state.maxLives` follows). An explicit `gold` / `lives` option of the Sim (tests, the balance bot) is used as given.
|
||||||
|
* `hp`: the hit points of every enemy **and its shield**, so the snapshot's `hp + shield` / `maxhp + maxShield` encoding (the client splits
|
||||||
|
the two by the kind's base ratio) stays right.
|
||||||
|
* `reward`: what a kill pays (at least 1). The wave clear bonus and the tower prices do not change.
|
||||||
|
* An unknown value in `new Sim` is `'normal'`; the server refuses it (`bad_difficulty`) instead.
|
||||||
|
|
||||||
|
Normal is all 1: it plays the base tables of `sim.js` as they are (those tables were retuned in the wave 4 balance pass, see `docs/BALANCE.md`). The room's difficulty is fixed for a game: the host picks
|
||||||
|
it when creating the room (`join.difficulty`) or when starting a new game (`newgame.difficulty`).
|
||||||
|
|
||||||
## Tick loop
|
## Tick loop
|
||||||
|
|
||||||
Fixed step `TD.STEP` (1/60 s) with an accumulator driven by `process.hrtime.bigint()`; real time elapsed is
|
Fixed step `TD.STEP` (1/60 s) with an accumulator driven by `process.hrtime.bigint()`; real time elapsed is
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ opponent for either side so it can be played alone.
|
||||||
| Base income | 4 credits/s, rising slowly (+0.02/s per second of the round) |
|
| Base income | 4 credits/s, rising slowly (+0.02/s per second of the round) |
|
||||||
| **Lifetime bonus** | every living attacker unit earns `cost x 0.004` credits per second alive, capped at 50% of its cost in total |
|
| **Lifetime bonus** | every living attacker unit earns `cost x 0.004` credits per second alive, capped at 50% of its cost in total |
|
||||||
| Leak bonus | a unit that reaches the server pays back its full cost (and damages integrity) |
|
| Leak bonus | a unit that reaches the server pays back its full cost (and damages integrity) |
|
||||||
| Unit shop | every enemy kind has a `buyCost` in the sim's `ENEMIES` table (currently ping 10, worm 6, spam 3, ghost 15, trojan 30, daemon 25, proxy 30, botnet 3, rootkit 300; about 3x the kill reward, to be tuned by the versus balance pass) |
|
| Unit shop | every enemy kind has a `buyCost` in the sim's `ENEMIES` table (currently ping 10, worm 6, spam 3, ghost 15, trojan 30, daemon 25, proxy 30, botnet 3, rootkit 180; about 3x the kill reward, to be tuned by the versus balance pass) |
|
||||||
| Caps | at most 250 units alive, 200 staged (performance) |
|
| Caps | at most 250 units alive, 200 staged (performance) |
|
||||||
|
|
||||||
**Save up and launch.** Units can be bought instantly (`spawn`) or **staged** (`stage`): the price is paid now, the units wait in
|
**Save up and launch.** Units can be bought instantly (`spawn`) or **staged** (`stage`): the price is paid now, the units wait in
|
||||||
|
|
|
||||||
|
|
@ -133,6 +133,16 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
||||||
|
|
||||||
// main menu: primary buttons always reachable (with 8 maps in the picker)
|
// main menu: primary buttons always reachable (with 8 maps in the picker)
|
||||||
await must(page, '#btnSolo', 'menu Play solo'); await must(page, '#btnCoop', 'menu Co-op');
|
await must(page, '#btnSolo', 'menu Play solo'); await must(page, '#btnCoop', 'menu Co-op');
|
||||||
|
// the difficulty picker: every segment on screen, uncovered and (on phones) a 44px target; a real tap picks one, a second tap puts it back
|
||||||
|
const diffIds = await page.evaluate(() => TD.DIFFICULTY_ORDER.slice());
|
||||||
|
check(diffIds.length >= 3, `the picker offers only ${diffIds.length} difficulties`);
|
||||||
|
for (const id of diffIds) await must(page, `#diffPick [data-diff="${id}"]`, `menu difficulty ${id}`);
|
||||||
|
const diffState = () => page.evaluate(() => [...document.querySelectorAll('#diffPick button')].filter((b) => b.getAttribute('aria-checked') === 'true').map((b) => b.dataset.diff).join());
|
||||||
|
check(await diffState() === 'normal', 'the difficulty picker does not start on normal');
|
||||||
|
await tapBtn(page, `#diffPick [data-diff="${diffIds[diffIds.length - 1]}"]`, 'menu difficulty (last)');
|
||||||
|
check(await diffState() === diffIds[diffIds.length - 1], `tapping the last difficulty did not pick it (${await diffState()})`);
|
||||||
|
await tapBtn(page, '#diffPick [data-diff="normal"]', 'menu difficulty normal');
|
||||||
|
check(await diffState() === 'normal', 'tapping normal did not pick it again');
|
||||||
await noOverflow(page, 'menu'); await allButtonsBigEnough(page, 'menu');
|
await noOverflow(page, 'menu'); await allButtonsBigEnough(page, 'menu');
|
||||||
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-menu.png` });
|
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-menu.png` });
|
||||||
const p0 = await probe(page, '#btnSolo');
|
const p0 = await probe(page, '#btnSolo');
|
||||||
|
|
@ -273,6 +283,11 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
||||||
await page.goto(URL); await sleep(250);
|
await page.goto(URL); await sleep(250);
|
||||||
await tapBtn(page, '#btnCoop', 'menu Co-op');
|
await tapBtn(page, '#btnCoop', 'menu Co-op');
|
||||||
await must(page, '#btnCreate', 'lobby Create room'); await must(page, '#btnJoin', 'lobby Join'); await must(page, '#btnLobbyBack', 'lobby Back');
|
await must(page, '#btnCreate', 'lobby Create room'); await must(page, '#btnJoin', 'lobby Join'); await must(page, '#btnLobbyBack', 'lobby Back');
|
||||||
|
// the host picks the difficulty here: reachable at every size, and the room is created on it
|
||||||
|
const lobbyIds = await page.evaluate(() => TD.DIFFICULTY_ORDER.slice());
|
||||||
|
for (const id of lobbyIds) await must(page, `#lobbyDiff [data-diff="${id}"]`, `lobby difficulty ${id}`);
|
||||||
|
await tapBtn(page, `#lobbyDiff [data-diff="hard"]`, 'lobby difficulty hard');
|
||||||
|
check(await page.evaluate(() => [...document.querySelectorAll('#lobbyDiff button')].filter((b) => b.getAttribute('aria-checked') === 'true').map((b) => b.dataset.diff).join()) === 'hard', 'tapping Hard in the lobby did not pick it');
|
||||||
await noOverflow(page, 'lobby'); await allButtonsBigEnough(page, 'lobby');
|
await noOverflow(page, 'lobby'); await allButtonsBigEnough(page, 'lobby');
|
||||||
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-lobby.png` });
|
await page.screenshot({ path: `${OUT}matrix-${w}x${h}-${kind}-${nTowers}-lobby.png` });
|
||||||
await tapBtn(page, '#btnCreate', 'lobby Create room');
|
await tapBtn(page, '#btnCreate', 'lobby Create room');
|
||||||
|
|
@ -281,6 +296,7 @@ module.exports = async function ({ browser, url: URL, out: OUT }) {
|
||||||
if (!joined) fails.push('could not create a co-op room');
|
if (!joined) fails.push('could not create a co-op room');
|
||||||
else {
|
else {
|
||||||
await sleep(300);
|
await sleep(300);
|
||||||
|
check(await page.evaluate(() => NW.app.ctrl.view.difficulty) === 'hard', 'the room was not created on the difficulty picked in the lobby');
|
||||||
// a first-time co-op player gets the first-run help too (code-26): same rule as solo, it needs a visible "Got it"
|
// a first-time co-op player gets the first-run help too (code-26): same rule as solo, it needs a visible "Got it"
|
||||||
check(await page.evaluate(() => !document.getElementById('help').hidden), 'co-op first run: help overlay did not open');
|
check(await page.evaluate(() => !document.getElementById('help').hidden), 'co-op first run: help overlay did not open');
|
||||||
await must(page, '#btnHelpClose', 'co-op help Got it');
|
await must(page, '#btnHelpClose', 'co-op help Got it');
|
||||||
|
|
|
||||||
|
|
@ -32,7 +32,9 @@ module.exports = async function ({ browser, url: URL }) {
|
||||||
assert(g1 === 20000 - base, `the first Uplink was charged ${base}`);
|
assert(g1 === 20000 - base, `the first Uplink was charged ${base}`);
|
||||||
t = await tile();
|
t = await tile();
|
||||||
const second = await page.evaluate(() => TD.priceFor('uplink', NW.app.ctrl.view.towers));
|
const second = await page.evaluate(() => TD.priceFor('uplink', NW.app.ctrl.view.towers));
|
||||||
assert(second > base * 1.2 && second < base * 1.3 && t.cost === String(second), `the tile now shows the second one at ${second} (about 25% dearer)`);
|
const growth = await page.evaluate(() => TD.TOWERS.uplink.priceGrowth);
|
||||||
|
assert(growth > 1.25 && growth <= 1.4, `each Uplink owned makes the next dearer by ${Math.round((growth - 1) * 100)}% (more than the old 25%, still slight)`);
|
||||||
|
assert(Math.abs(second - base * growth) <= 5 && t.cost === String(second), `the tile now shows the second one at ${second} (${Math.round((growth - 1) * 100)}% dearer)`);
|
||||||
assert((await page.locator('#info').innerText()).includes(String(second) + ' credits'), 'and so does the armed panel');
|
assert((await page.locator('#info').innerText()).includes(String(second) + ' credits'), 'and so does the armed panel');
|
||||||
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(250);
|
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(250);
|
||||||
assert((await page.evaluate(() => NW.app.ctrl.view.gold)) === g1 - second, `the second one was charged ${second}`);
|
assert((await page.evaluate(() => NW.app.ctrl.view.gold)) === g1 - second, `the second one was charged ${second}`);
|
||||||
|
|
@ -46,7 +48,7 @@ module.exports = async function ({ browser, url: URL }) {
|
||||||
await page.keyboard.press('Escape');
|
await page.keyboard.press('Escape');
|
||||||
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(250);
|
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(250);
|
||||||
const secondUp = await page.evaluate(() => { const t = NW.app.ctrl.view.towers.filter((x) => x.type === 'uplink')[1]; return TD.upgradePrice('uplink', t.level, t.pm); });
|
const secondUp = await page.evaluate(() => { const t = NW.app.ctrl.view.towers.filter((x) => x.type === 'uplink')[1]; return TD.upgradePrice('uplink', t.level, t.pm); });
|
||||||
assert(secondUp > firstUp * 1.2 && (await upBtn()) === String(secondUp), `the second Uplink upgrades for ${secondUp} (the same 25% more)`);
|
assert(Math.abs(secondUp - firstUp * growth) <= 5 && (await upBtn()) === String(secondUp), `the second Uplink upgrades for ${secondUp} (the same ${Math.round((growth - 1) * 100)}% more)`);
|
||||||
await page.keyboard.press('Escape');
|
await page.keyboard.press('Escape');
|
||||||
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(200);
|
p = await pt(9, 5); await page.mouse.click(p.x, p.y); await sleep(200);
|
||||||
|
|
||||||
|
|
|
||||||
211
e2e/scenarios/14-difficulty.js
Normal file
211
e2e/scenarios/14-difficulty.js
Normal file
|
|
@ -0,0 +1,211 @@
|
||||||
|
// Easy / Normal / Hard. Solo: the picker in the menu (every difficulty, remembered, validated), what each one does to the real game
|
||||||
|
// (credits, lives, packet hit points, shown next to the next-wave list), Play again keeps it, the end screen names it, and the best wave
|
||||||
|
// is per map AND difficulty (a record from before difficulties existed counts as normal). Co-op: the host picks it in the lobby when
|
||||||
|
// creating the room, the guest's own screen shows the host's choice, and Play again keeps it for both. Expected numbers come from
|
||||||
|
// TD.DIFFICULTIES in the page, so a retune of the table does not break this.
|
||||||
|
const assert = (c, m) => { if (!c) throw new Error('ASSERT: ' + m); console.log('ok -', m); };
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
async function until(fn, ms, what) { const t0 = Date.now(); for (;;) { try { const v = await fn(); if (v) return v; } catch (e) { /* retry */ } if (Date.now() - t0 > ms) throw new Error('TIMEOUT: ' + what); await sleep(50); } }
|
||||||
|
|
||||||
|
module.exports = async function ({ browser, url: URL, out: OUT }) {
|
||||||
|
const errors = [];
|
||||||
|
const mk = async (name, opts, init) => {
|
||||||
|
const ctx = await browser.newContext(opts);
|
||||||
|
await ctx.addInitScript(() => { try { localStorage.setItem('nw.helped', 'true'); } catch (e) { /* ignore */ } }); // no first-run help in the way
|
||||||
|
if (init) await ctx.addInitScript(init);
|
||||||
|
const page = await ctx.newPage();
|
||||||
|
page.on('pageerror', (e) => errors.push(`[${name}] pageerror: ${e.message}`));
|
||||||
|
page.on('console', (m) => { if (m.type() === 'error') errors.push(`[${name}] console.error: ${m.text()}`); });
|
||||||
|
return { ctx, page };
|
||||||
|
};
|
||||||
|
const table = (page) => page.evaluate(() => ({ order: TD.DIFFICULTY_ORDER.slice(), d: JSON.parse(JSON.stringify(TD.DIFFICULTIES)), gold: TD.START_GOLD, lives: TD.START_LIVES }));
|
||||||
|
const startGold = (T, id) => Math.round(T.gold * T.d[id].gold);
|
||||||
|
const startLives = (T, id) => Math.max(1, Math.round(T.lives * T.d[id].lives));
|
||||||
|
const checked = (page, box) => page.evaluate((b) => [...document.querySelectorAll(b + ' button')].filter((x) => x.getAttribute('aria-checked') === 'true').map((x) => x.dataset.diff), box);
|
||||||
|
const hud = (page) => page.evaluate(() => ({
|
||||||
|
gold: document.getElementById('vGold').textContent, lives: document.getElementById('vLives').textContent,
|
||||||
|
tag: (document.querySelector('#nextwave .dtag') || {}).textContent || null, tagD: (document.querySelector('#nextwave .dtag') || { dataset: {} }).dataset.d || null,
|
||||||
|
view: NW.app.ctrl.view.difficulty,
|
||||||
|
}));
|
||||||
|
const endRows = (page) => page.evaluate(() => Object.fromEntries([...document.querySelectorAll('#endStats > div')].map((d) => [d.firstChild.textContent, d.lastChild.textContent])));
|
||||||
|
// The HUD catches up with a new game a frame or two later (more on a loaded machine): wait for it instead of sleeping and hoping.
|
||||||
|
let T = null;
|
||||||
|
const waitHud = async (page, id, what) => {
|
||||||
|
let h = null;
|
||||||
|
try { await until(async () => { h = await hud(page); return h.view === id && h.gold === String(startGold(T, id)) && h.lives === String(startLives(T, id)) && h.tag === T.d[id].name; }, 6000, what); } catch (e) { throw new Error(`${e.message} (last HUD: ${JSON.stringify(h)})`); }
|
||||||
|
return h;
|
||||||
|
};
|
||||||
|
const loseNow = (page, wave) => page.evaluate((w) => { const s = NW.app.ctrl.sim; s.wave = w; s.lives = 0; s.state = 'lost'; }, wave);
|
||||||
|
|
||||||
|
// ================================================================ solo
|
||||||
|
const S = await mk('solo', { viewport: { width: 1100, height: 760 } });
|
||||||
|
const p = S.page;
|
||||||
|
await p.goto(URL); await sleep(300);
|
||||||
|
T = await table(p);
|
||||||
|
assert(T.order.length >= 3 && T.order[0] === 'easy' && T.order.includes('normal') && T.order.includes('hard'), `the table has ${T.order.join(', ')}`);
|
||||||
|
|
||||||
|
// the picker: one radio per difficulty, normal checked on a first visit, 44px targets, and it does not steal the dialog's focus
|
||||||
|
const seg = await p.evaluate(() => {
|
||||||
|
const box = document.getElementById('diffPick'), bs = [...box.querySelectorAll('button')];
|
||||||
|
return { role: box.getAttribute('role'), label: box.getAttribute('aria-label'), ids: bs.map((b) => b.dataset.diff), roles: bs.map((b) => b.getAttribute('role')), h: Math.min(...bs.map((b) => b.getBoundingClientRect().height)), primary: bs.some((b) => b.classList.contains('primary')), active: document.activeElement.id, text: bs.map((b) => b.textContent) };
|
||||||
|
});
|
||||||
|
assert(seg.role === 'radiogroup' && /difficulty/i.test(seg.label) && seg.roles.every((r) => r === 'radio'), 'the picker is a labelled radiogroup of radios');
|
||||||
|
assert(JSON.stringify(seg.ids) === JSON.stringify(T.order), 'one segment per difficulty, in table order: ' + seg.ids);
|
||||||
|
assert(seg.text.every((t, i) => t === T.d[T.order[i]].name), 'labelled with the table\'s names: ' + seg.text);
|
||||||
|
assert(seg.h >= 43.5, 'every segment is at least 44px high (' + seg.h + ')');
|
||||||
|
assert(!seg.primary && seg.active === 'btnSolo', 'no segment is .primary, so the menu still focuses Play solo (' + seg.active + ')');
|
||||||
|
assert(JSON.stringify(await checked(p, '#diffPick')) === '["normal"]', 'normal is picked on a first visit');
|
||||||
|
assert(/standard/i.test(await p.textContent('#diffNote')), 'and the note says it is the standard game');
|
||||||
|
|
||||||
|
// every difficulty: pick it, play, and the game on the screen is that game
|
||||||
|
const startedGold = {};
|
||||||
|
for (const id of T.order) {
|
||||||
|
const inGame = await p.evaluate(() => NW.app.inGame);
|
||||||
|
if (inGame) { await p.click('#btnMenu'); await sleep(150); }
|
||||||
|
await p.click(`#diffPick [data-diff="${id}"]`);
|
||||||
|
assert(JSON.stringify(await checked(p, '#diffPick')) === JSON.stringify([id]), `picking ${id} checks only ${id}`);
|
||||||
|
assert((await p.evaluate(() => localStorage.getItem('nw.difficulty'))) === JSON.stringify(id), `${id} is remembered`);
|
||||||
|
const note = await p.textContent('#diffNote');
|
||||||
|
assert(inGame ? /^This game: /.test(note) && note.includes('next game: ' + T.d[id].name) : note.length > 5, `the note under the picker: "${note}"`);
|
||||||
|
await p.click('#btnSolo');
|
||||||
|
const h = await waitHud(p, id, `${id}: the new game's HUD`);
|
||||||
|
assert(h.gold === String(startGold(T, id)) && h.lives === String(startLives(T, id)), `${id}: the HUD shows ${startGold(T, id)} credits and ${startLives(T, id)} integrity (${h.gold} / ${h.lives})`);
|
||||||
|
assert(h.view === id && h.tag === T.d[id].name && h.tagD === id, `${id}: the next-wave panel names it ("${h.tag}")`);
|
||||||
|
assert(await p.evaluate(() => NW.app.ctrl.sim.difficulty) === id, `${id}: the local sim runs it`);
|
||||||
|
startedGold[id] = startGold(T, id);
|
||||||
|
// a real packet has the difficulty's hit points
|
||||||
|
await p.evaluate(() => { NW.app.ctrl.send({ c: 'wave' }); });
|
||||||
|
await until(() => p.evaluate(() => NW.app.ctrl.sim.monsters.length > 0), 5000, 'a packet spawns');
|
||||||
|
const mon = await p.evaluate(() => { const m = NW.app.ctrl.sim.monsters[0]; return { kind: m.kind, maxhp: m.maxhp, reward: m.reward }; });
|
||||||
|
const want = await p.evaluate(([k, id2]) => Math.round(TD.ENEMIES[k].hp * TD.hpScale(1) * TD.DIFFICULTIES[id2].hp), [mon.kind, id]);
|
||||||
|
assert(mon.maxhp === want, `${id}: a ${mon.kind} has ${mon.maxhp} hit points (table says ${want})`);
|
||||||
|
}
|
||||||
|
assert(startedGold.easy > startedGold.normal && startedGold.normal > startedGold.hard, 'more credits on easy than on normal than on hard: ' + JSON.stringify(startedGold));
|
||||||
|
|
||||||
|
// the pick survives a reload; a stored value that is not a difficulty is normal (and 'toString' is not one)
|
||||||
|
await p.reload(); await sleep(400);
|
||||||
|
const last = await p.evaluate(() => JSON.parse(localStorage.getItem('nw.difficulty')));
|
||||||
|
assert(last === T.order[T.order.length - 1], `the last pick (${last}) was stored`);
|
||||||
|
assert(JSON.stringify(await checked(p, '#diffPick')) === JSON.stringify([last]), `after a reload the picker shows it: ${JSON.stringify(await checked(p, '#diffPick'))}`);
|
||||||
|
for (const junk of ['"toString"', '"__proto__"', '17', 'not json', '"EASY"']) {
|
||||||
|
await p.evaluate((j) => localStorage.setItem('nw.difficulty', j), junk); await p.reload(); await sleep(300);
|
||||||
|
assert(JSON.stringify(await checked(p, '#diffPick')) === '["normal"]', `a stored ${junk} falls back to normal`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the menu pick is for the NEXT game: Play again and the end screen belong to the game that was played
|
||||||
|
await p.click('#diffPick [data-diff="easy"]'); await p.click('#btnSolo'); await sleep(300);
|
||||||
|
await p.click('#btnMenu'); await sleep(150);
|
||||||
|
await p.click('#diffPick [data-diff="hard"]');
|
||||||
|
const liveNote = await p.textContent('#diffNote');
|
||||||
|
assert(/This game: Easy/.test(liveNote) && /next game: Hard/.test(liveNote), 'the menu of a running game says which game it is and what the pick is for: "' + liveNote + '"');
|
||||||
|
await p.click('#btnCloseMenu'); await sleep(200);
|
||||||
|
assert((await hud(p)).view === 'easy', 'closing the menu leaves the running game on easy');
|
||||||
|
await p.evaluate(() => { localStorage.removeItem('nw.best.open'); localStorage.removeItem('nw.best.open.easy'); });
|
||||||
|
await loseNow(p, 3);
|
||||||
|
await until(() => p.evaluate(() => !document.getElementById('end').hidden), 5000, 'the end screen');
|
||||||
|
let rows = await endRows(p);
|
||||||
|
assert(rows.Difficulty === T.d.easy.name, 'the end screen names the difficulty of the game that ended: ' + JSON.stringify(rows));
|
||||||
|
assert(rows['Best on ' + T.d.easy.name] === '3', 'and the best wave on it: ' + JSON.stringify(rows));
|
||||||
|
assert((await p.evaluate(() => localStorage.getItem('nw.best.open.easy'))) === '3' && (await p.evaluate(() => localStorage.getItem('nw.best.open'))) === null, 'the record went to the easy key, not to the normal one');
|
||||||
|
await p.screenshot({ path: OUT + 'difficulty-end-easy.png' });
|
||||||
|
await p.click('#btnAgain');
|
||||||
|
const again = await waitHud(p, 'easy', 'Play again: the HUD of a fresh easy game');
|
||||||
|
assert(again.view === 'easy' && again.gold === String(startGold(T, 'easy')) && again.lives === String(startLives(T, 'easy')) && again.tag === T.d.easy.name, 'Play again keeps easy, not the menu\'s hard: ' + JSON.stringify(again));
|
||||||
|
assert(JSON.stringify(await checked(p, '#diffPick')) === '["hard"]', 'the menu pick is still hard for the next new game');
|
||||||
|
await S.ctx.close();
|
||||||
|
|
||||||
|
// ---- best wave per map AND difficulty; a record from before difficulties existed is the normal one
|
||||||
|
const M = await mk('migrate', { viewport: { width: 1100, height: 760 } }, () => { try { if (localStorage.getItem('nw.best.open') === null) localStorage.setItem('nw.best.open', '7'); } catch (e) { /* ignore */ } });
|
||||||
|
const m = M.page;
|
||||||
|
await m.goto(URL); await sleep(300);
|
||||||
|
await m.click('#btnSolo'); await sleep(300);
|
||||||
|
await loseNow(m, 2);
|
||||||
|
await until(() => m.evaluate(() => !document.getElementById('end').hidden), 5000, 'normal end screen');
|
||||||
|
rows = await endRows(m);
|
||||||
|
assert(rows['Best on Normal'] === '7' && rows.Difficulty === 'Normal', 'the old record (7) is the normal best, nothing was lost: ' + JSON.stringify(rows));
|
||||||
|
assert((await m.evaluate(() => localStorage.getItem('nw.best.open'))) === '7', 'and the old key is still there, untouched');
|
||||||
|
await m.click('#btnEndMenu'); await sleep(300);
|
||||||
|
await m.click('#diffPick [data-diff="hard"]'); await m.click('#btnSolo'); await sleep(300);
|
||||||
|
await loseNow(m, 2);
|
||||||
|
await until(() => m.evaluate(() => !document.getElementById('end').hidden), 5000, 'hard end screen');
|
||||||
|
rows = await endRows(m);
|
||||||
|
assert(rows['Best on Hard'] === '2' && rows.Difficulty === 'Hard', 'hard has its own record (2), the 7 is not shown there: ' + JSON.stringify(rows));
|
||||||
|
const keys = await m.evaluate(() => ({ normal: localStorage.getItem('nw.best.open'), hard: localStorage.getItem('nw.best.open.hard'), easy: localStorage.getItem('nw.best.open.easy') }));
|
||||||
|
assert(keys.normal === '7' && keys.hard === '2' && keys.easy === null, 'the keys are per map and difficulty: ' + JSON.stringify(keys));
|
||||||
|
await m.click('#btnEndMenu'); await sleep(300);
|
||||||
|
await m.click('.mapcard[data-map="twin"]');
|
||||||
|
await m.click('#btnSolo'); await sleep(300); // another map on hard: its own (empty) record
|
||||||
|
await loseNow(m, 1);
|
||||||
|
await until(() => m.evaluate(() => !document.getElementById('end').hidden), 5000, 'twin end screen');
|
||||||
|
rows = await endRows(m);
|
||||||
|
assert(rows['Best on Hard'] === '1', 'another map has its own record: ' + JSON.stringify(rows));
|
||||||
|
await M.ctx.close();
|
||||||
|
|
||||||
|
// ================================================================ co-op: the host picks it in the lobby, the guest sees it
|
||||||
|
const A = await mk('host', { viewport: { width: 1280, height: 800 } });
|
||||||
|
const B = await mk('guest', { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true });
|
||||||
|
await A.page.goto(URL); await sleep(300);
|
||||||
|
await A.page.click('#btnCoop'); await sleep(150);
|
||||||
|
assert(JSON.stringify(await checked(A.page, '#lobbyDiff')) === '["normal"]', 'the lobby\'s picker starts on normal');
|
||||||
|
const lobbySeg = await A.page.evaluate(() => [...document.querySelectorAll('#lobbyDiff button')].map((b) => [b.dataset.diff, Math.round(b.getBoundingClientRect().height), b.getAttribute('role')]));
|
||||||
|
assert(lobbySeg.length === T.order.length && lobbySeg.every((x) => x[1] >= 44 && x[2] === 'radio'), 'one 44px radio per difficulty in the lobby: ' + JSON.stringify(lobbySeg));
|
||||||
|
assert(await A.page.evaluate(() => document.activeElement.id) === 'btnCreate', 'the lobby still focuses Create room');
|
||||||
|
await A.page.click('#lobbyDiff [data-diff="hard"]');
|
||||||
|
assert(JSON.stringify(await checked(A.page, '#lobbyDiff')) === '["hard"]' && JSON.stringify(await checked(A.page, '#diffPick')) === '["hard"]', 'picking hard in the lobby checks it there and in the menu\'s picker (one setting)');
|
||||||
|
await A.page.fill('#inName', 'Alice');
|
||||||
|
await A.page.click('#btnCreate');
|
||||||
|
await until(() => A.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'), 5000, 'host joined');
|
||||||
|
const room = await A.page.evaluate(() => NW.app.ctrl.room);
|
||||||
|
const ah = await waitHud(A.page, 'hard', 'the host\'s HUD shows the hard room');
|
||||||
|
assert(ah.view === 'hard' && ah.gold === String(startGold(T, 'hard')) && ah.lives === String(startLives(T, 'hard')), `the host's room is hard: ${startGold(T, 'hard')} credits, ${startLives(T, 'hard')} integrity (${JSON.stringify(ah)})`);
|
||||||
|
assert(ah.tag === T.d.hard.name, 'the host sees it next to the wave list');
|
||||||
|
assert(await A.page.evaluate(() => document.querySelector('#players .dtag').textContent) === T.d.hard.name, 'and in the room panel');
|
||||||
|
assert(/Hard/.test(await A.page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|'))), 'the host\'s join toast names it');
|
||||||
|
|
||||||
|
await B.page.goto(URL + '?room=' + room); await sleep(300);
|
||||||
|
await B.page.fill('#inName', 'Bob'); await B.page.tap('#btnJoin');
|
||||||
|
await until(() => B.page.evaluate(() => NW.app.ctrl.kind === 'remote' && NW.app.ctrl.status === 'joined'), 5000, 'guest joined');
|
||||||
|
const bh = await waitHud(B.page, 'hard', 'the guest\'s HUD shows the host\'s hard room');
|
||||||
|
assert(bh.view === 'hard', 'the guest\'s controller is on the host\'s difficulty: ' + bh.view);
|
||||||
|
assert(bh.gold === String(startGold(T, 'hard')) && bh.lives === String(startLives(T, 'hard')), `the guest's screen shows the hard game's credits and integrity (${bh.gold} / ${bh.lives})`);
|
||||||
|
assert(bh.tag === T.d.hard.name && bh.tagD === 'hard', 'the guest\'s next-wave panel says Hard');
|
||||||
|
assert(await B.page.evaluate(() => document.querySelector('#players .dtag').textContent) === T.d.hard.name, 'and so does the guest\'s room panel');
|
||||||
|
assert(/Hard/.test(await B.page.evaluate(() => [...document.querySelectorAll('.toast')].map((t) => t.textContent).join('|'))), 'the guest is told on joining');
|
||||||
|
assert((await B.page.evaluate(() => localStorage.getItem('nw.difficulty'))) === null, 'the guest\'s own pick was not touched by joining');
|
||||||
|
await B.page.tap('#btnMenu'); await sleep(200);
|
||||||
|
const gnote = await B.page.textContent('#diffNote');
|
||||||
|
assert(/This game: Hard/.test(gnote), 'the guest\'s menu says which game this is: "' + gnote + '"');
|
||||||
|
await B.page.tap('#btnCloseMenu'); await sleep(200);
|
||||||
|
await A.page.screenshot({ path: OUT + 'difficulty-coop-host.png' });
|
||||||
|
await B.page.screenshot({ path: OUT + 'difficulty-coop-guest.png' });
|
||||||
|
|
||||||
|
// the host's menu pick is for the host's NEXT solo game only: with Easy picked there, Play again in this Hard room must still repeat Hard
|
||||||
|
// (without this the host's pick and the room are both Hard, and a Play again that sent the menu's pick would pass unnoticed)
|
||||||
|
await A.page.click('#btnMenu'); await sleep(150);
|
||||||
|
await A.page.click('#diffPick [data-diff="easy"]');
|
||||||
|
assert(JSON.stringify(await checked(A.page, '#diffPick')) === '["easy"]' && /This game: Hard/.test(await A.page.textContent('#diffNote')), 'the host picked Easy for a later game while the room runs Hard: "' + await A.page.textContent('#diffNote') + '"');
|
||||||
|
await A.page.click('#btnCloseMenu'); await sleep(150);
|
||||||
|
|
||||||
|
// lose fast (three waves at once, speed 3, nothing built): the end screen names it and Play again keeps it for both
|
||||||
|
await A.page.evaluate(() => { NW.app.ctrl.ctl('speed', 3); for (const n of [1, 2, 3]) NW.app.ctrl.send({ c: 'wave', n }); });
|
||||||
|
await until(() => A.page.evaluate(() => !document.getElementById('end').hidden), 120000, 'the host\'s end screen');
|
||||||
|
await until(() => B.page.evaluate(() => !document.getElementById('end').hidden), 20000, 'the guest\'s end screen');
|
||||||
|
for (const [name, X] of [['host', A], ['guest', B]]) {
|
||||||
|
const r = await endRows(X.page);
|
||||||
|
assert(r.Difficulty === T.d.hard.name && ('Best on ' + T.d.hard.name) in r, `the ${name}'s end screen names the difficulty: ${JSON.stringify(r)}`);
|
||||||
|
}
|
||||||
|
assert(await B.page.evaluate(() => document.getElementById('btnAgain').hidden), 'only the host can start the next game');
|
||||||
|
await A.page.click('#btnAgain');
|
||||||
|
await until(() => B.page.evaluate(() => document.getElementById('end').hidden && NW.app.ctrl.view.state === 'playing' && NW.app.ctrl.view.wave === 0), 8000, 'the guest is in the new game');
|
||||||
|
await until(() => A.page.evaluate(() => document.getElementById('end').hidden && NW.app.ctrl.view.state === 'playing'), 8000, 'the host is in the new game');
|
||||||
|
for (const [name, X] of [['host', A], ['guest', B]]) {
|
||||||
|
const h = await waitHud(X.page, 'hard', `${name}: a fresh hard game`);
|
||||||
|
assert(h.view === 'hard' && h.tag === T.d.hard.name && h.gold === String(startGold(T, 'hard')), `Play again keeps hard on the ${name}'s screen (${JSON.stringify(h)})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await A.page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } });
|
||||||
|
await B.page.evaluate(() => { try { NW.app.ctrl.close(); } catch (e) { /* ignore */ } });
|
||||||
|
await A.ctx.close(); await B.ctx.close();
|
||||||
|
if (errors.length) throw new Error('console errors:\n' + errors.join('\n'));
|
||||||
|
console.log('no console errors');
|
||||||
|
};
|
||||||
|
|
@ -259,6 +259,10 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(
|
||||||
#app[data-ui="compact"] .info-head canvas { width: 32px; height: 32px; }
|
#app[data-ui="compact"] .info-head canvas { width: 32px; height: 32px; }
|
||||||
|
|
||||||
#nextwave .panel { padding: 8px 10px; }
|
#nextwave .panel { padding: 8px 10px; }
|
||||||
|
#side h4 .dtag { margin-left: auto; padding: 0 6px; border: 1px solid var(--line); border-radius: 6px; font-size: 10px; letter-spacing: .1em; font-weight: 700; color: var(--dim); } /* the game's difficulty, quietly */
|
||||||
|
#side h4 .dtag[data-d="easy"] { color: var(--green); border-color: #1c6a55; }
|
||||||
|
#side h4 .dtag[data-d="hard"] { color: var(--red); border-color: #6a2336; }
|
||||||
|
#nextwave h4, #players h4 { display: flex; align-items: center; flex-wrap: wrap; gap: 2px 8px; }
|
||||||
.wv { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; font-family: var(--mono); font-size: 12.5px; }
|
.wv { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; font-family: var(--mono); font-size: 12.5px; }
|
||||||
.wv .e { display: inline-flex; align-items: center; gap: 4px; }
|
.wv .e { display: inline-flex; align-items: center; gap: 4px; }
|
||||||
.wv .e i { width: 12px; height: 12px; display: inline-block; background: var(--c); flex: none; } /* shape per enemy kind, not just a colour (see .sh-*) */
|
.wv .e i { width: 12px; height: 12px; display: inline-block; background: var(--c); flex: none; } /* shape per enemy kind, not just a colour (see .sh-*) */
|
||||||
|
|
@ -299,8 +303,22 @@ button.floating { position: absolute; right: 8px; bottom: 8px; background: rgba(
|
||||||
.row { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin-top: 12px; }
|
.row { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; margin-top: 12px; }
|
||||||
.row.small { margin-top: 4px; }
|
.row.small { margin-top: 4px; }
|
||||||
.row > .big { flex: 1 1 180px; }
|
.row > .big { flex: 1 1 180px; }
|
||||||
.opts { display: flex; gap: 8px; justify-content: center; flex-wrap: wrap; margin-bottom: 10px; } /* difficulty selector goes here */
|
.opts { display: flex; flex-direction: column; align-items: center; gap: 4px; margin-bottom: 10px; } /* the difficulty selector */
|
||||||
.opts:empty { display: none; }
|
.opts:empty { display: none; }
|
||||||
|
/* segmented control (difficulty): one radiogroup of equal buttons, every one a full 44px touch target. The checked one is marked by a
|
||||||
|
* tick and a cyan frame, never by colour alone, and it is NOT .primary (the dialogs focus their first .primary button). */
|
||||||
|
.seg { display: flex; width: 100%; max-width: 380px; border: 1px solid #2c4372; border-radius: 12px; overflow: hidden; background: var(--panel); }
|
||||||
|
.seg button { position: relative; flex: 1 1 0; min-width: 0; min-height: 44px; border: 0; border-radius: 0; background: transparent; padding: 0 4px; font-size: 15px; font-weight: 600; color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block; line-height: 44px; }
|
||||||
|
.seg button + button { border-left: 1px solid var(--line); }
|
||||||
|
.seg button:hover { background: #15233f; color: var(--text); }
|
||||||
|
.seg button[aria-checked="true"] { background: #0f3550; color: var(--cyan); box-shadow: inset 0 0 0 2px var(--cyan); }
|
||||||
|
.seg button[aria-checked="true"]::after { content: "\2713"; position: absolute; top: 3px; right: 6px; font-size: 11px; line-height: 1; } /* the tick sits in the corner so it never takes room from the word */
|
||||||
|
.seg button:focus-visible { outline-offset: -4px; }
|
||||||
|
.diffnote { margin: 0; min-height: 2.7em; max-width: 380px; text-align: center; color: var(--dim); font-size: 12.5px; line-height: 1.3; }
|
||||||
|
.diffnote.live { min-height: 1.3em; } /* a game is running: one short line saying which difficulty it is on */
|
||||||
|
.diffnote:empty { display: none; }
|
||||||
|
@media (max-width: 480px) { .seg button { font-size: 14px; } }
|
||||||
|
@media (max-height: 640px) { .diffnote:not(.live) { display: none; } .opts { margin-bottom: 8px; } } /* small phones: the description makes way for the maps and buttons */
|
||||||
.msg { min-height: 1.4em; text-align: center; color: var(--amber); margin: 0 0 4px; }
|
.msg { min-height: 1.4em; text-align: center; color: var(--amber); margin: 0 0 4px; }
|
||||||
.msg.bad { color: var(--red); }
|
.msg.bad { color: var(--red); }
|
||||||
.msg:empty { min-height: 0; margin: 0; }
|
.msg:empty { min-height: 0; margin: 0; }
|
||||||
|
|
@ -422,7 +440,7 @@ input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono);
|
||||||
|
|
||||||
/* Windows high contrast: selection must not depend on colours the UA replaces */
|
/* Windows high contrast: selection must not depend on colours the UA replaces */
|
||||||
@media (forced-colors: active) {
|
@media (forced-colors: active) {
|
||||||
.tbtn.sel, .mapcard[aria-checked="true"], button.toggle[aria-pressed="true"], button#btnPause[aria-pressed="true"] { outline: 3px solid Highlight; outline-offset: -3px; forced-color-adjust: none; background: Highlight; color: HighlightText; }
|
.tbtn.sel, .mapcard[aria-checked="true"], .seg button[aria-checked="true"], button.toggle[aria-pressed="true"], button#btnPause[aria-pressed="true"] { outline: 3px solid Highlight; outline-offset: -3px; forced-color-adjust: none; background: Highlight; color: HighlightText; }
|
||||||
.tbtn.sel .nm, .tbtn.sel .cost, .mapcard[aria-checked="true"] .df, .mapcard[aria-checked="true"] .df b { color: HighlightText; }
|
.tbtn.sel .nm, .tbtn.sel .cost, .mapcard[aria-checked="true"] .df, .mapcard[aria-checked="true"] .df b { color: HighlightText; }
|
||||||
.overlay { background: Canvas; }
|
.overlay { background: Canvas; }
|
||||||
#side { border-color: CanvasText; }
|
#side { border-color: CanvasText; }
|
||||||
|
|
|
||||||
|
|
@ -94,7 +94,10 @@
|
||||||
<p id="mapDesc" class="mapdesc"></p>
|
<p id="mapDesc" class="mapdesc"></p>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-foot">
|
<div class="card-foot">
|
||||||
<div id="menuOpts" class="opts"></div><!-- room for the difficulty selector (Easy / Normal / Hard) -->
|
<div id="menuOpts" class="opts">
|
||||||
|
<div id="diffPick" class="seg" role="radiogroup" aria-label="Difficulty"></div><!-- Easy / Normal / Hard, built by main.js from TD.DIFFICULTIES -->
|
||||||
|
<p id="diffNote" class="diffnote"></p>
|
||||||
|
</div>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<button id="btnSolo" class="primary big"><svg class="ic"><use href="#i-play"/></svg>Play solo</button>
|
<button id="btnSolo" class="primary big"><svg class="ic"><use href="#i-play"/></svg>Play solo</button>
|
||||||
<button id="btnCoop" class="big"><svg class="ic"><use href="#i-users"/></svg>Co-op online</button>
|
<button id="btnCoop" class="big"><svg class="ic"><use href="#i-users"/></svg>Co-op online</button>
|
||||||
|
|
@ -121,6 +124,7 @@
|
||||||
<div class="col">
|
<div class="col">
|
||||||
<h3>Host a game</h3>
|
<h3>Host a game</h3>
|
||||||
<p class="muted small" id="lobbyMapName"></p>
|
<p class="muted small" id="lobbyMapName"></p>
|
||||||
|
<div id="lobbyDiff" class="seg" role="radiogroup" aria-label="Difficulty"></div>
|
||||||
<button id="btnCreate" class="primary big">Create room</button>
|
<button id="btnCreate" class="primary big">Create room</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="col">
|
<div class="col">
|
||||||
|
|
|
||||||
|
|
@ -5,13 +5,14 @@
|
||||||
* ctrl.kind 'local' | 'remote'
|
* ctrl.kind 'local' | 'remote'
|
||||||
* ctrl.board TD.Board (own for local, a mirror for remote: used for route previews)
|
* ctrl.board TD.Board (own for local, a mirror for remote: used for route previews)
|
||||||
* ctrl.view render state, refreshed by ctrl.update(nowMs):
|
* ctrl.view render state, refreshed by ctrl.update(nowMs):
|
||||||
* gold lives maxLives wave state auto nextWaveIn kills winWave rev queued speed paused
|
* gold lives maxLives wave state auto nextWaveIn kills winWave rev queued speed paused difficulty
|
||||||
* towers[{id,type,x,y,level,mode,spent,owner,tgt,kills}]
|
* towers[{id,type,x,y,level,mode,spent,owner,tgt,kills}]
|
||||||
* monsters[{id,kind,x,y,hp,maxhp,slow,air}] bullets[{id,k,x,y}] cursors[{slot,x,y}]
|
* monsters[{id,kind,x,y,hp,maxhp,slow,air}] bullets[{id,k,x,y}] cursors[{slot,x,y}]
|
||||||
* ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue. An upgrade carries the level the player saw (lv)
|
* ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue. An upgrade carries the level the player saw (lv)
|
||||||
* and a wave carries the wave it expects to start (n), filled in here from the view: a second player who
|
* and a wave carries the wave it expects to start (n), filled in here from the view: a second player who
|
||||||
* pressed the same button at the same moment is refused as 'stale' (see sim.js) instead of paying twice.
|
* pressed the same button at the same moment is refused as 'stale' (see sim.js) instead of paying twice.
|
||||||
* ctrl.ctl(c, v) 'pause' | 'speed'
|
* ctrl.ctl(c, v) 'pause' | 'speed'
|
||||||
|
* ctrl.difficulty the game's difficulty id (TD.DIFFICULTIES); `newGame(map, difficulty)` keeps the current one when none is given
|
||||||
* ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route?
|
* ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route?
|
||||||
* events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt'
|
* events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt'
|
||||||
*/
|
*/
|
||||||
|
|
@ -55,18 +56,19 @@
|
||||||
super();
|
super();
|
||||||
this.kind = 'local';
|
this.kind = 'local';
|
||||||
this.mapId = (opts && opts.map) || 'open';
|
this.mapId = (opts && opts.map) || 'open';
|
||||||
|
this.difficulty = TD.difficultyId(opts && opts.difficulty);
|
||||||
this.speed = 1; this.paused = false;
|
this.speed = 1; this.paused = false;
|
||||||
this.players = [{ slot: 0, name: 'You', online: true, host: true }];
|
this.players = [{ slot: 0, name: 'You', online: true, host: true }];
|
||||||
this.you = { slot: 0, host: true };
|
this.you = { slot: 0, host: true };
|
||||||
this._fresh();
|
this._fresh();
|
||||||
}
|
}
|
||||||
_fresh() {
|
_fresh() {
|
||||||
this.sim = new TD.Sim({ map: this.mapId });
|
this.sim = new TD.Sim({ map: this.mapId, difficulty: this.difficulty });
|
||||||
this.board = this.sim.board;
|
this.board = this.sim.board;
|
||||||
this.acc = 0; this.last = 0;
|
this.acc = 0; this.last = 0;
|
||||||
this.view = {
|
this.view = {
|
||||||
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
|
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
|
||||||
speed: this.speed, paused: this.paused, time: 0,
|
speed: this.speed, paused: this.paused, time: 0, difficulty: this.difficulty,
|
||||||
towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [],
|
towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [],
|
||||||
};
|
};
|
||||||
this._sync();
|
this._sync();
|
||||||
|
|
@ -76,7 +78,7 @@
|
||||||
v.gold = s.gold; v.lives = s.lives; v.maxLives = s.maxLives; v.wave = s.wave; v.state = s.state;
|
v.gold = s.gold; v.lives = s.lives; v.maxLives = s.maxLives; v.wave = s.wave; v.state = s.state;
|
||||||
v.auto = s.autoWaves; v.nextWaveIn = s.autoWaves ? s.nextWaveIn : -1; v.kills = s.kills;
|
v.auto = s.autoWaves; v.nextWaveIn = s.autoWaves ? s.nextWaveIn : -1; v.kills = s.kills;
|
||||||
v.winWave = isFinite(s.winWave) ? s.winWave : 0; v.rev = s.rev; v.queued = s.spawnQ.length;
|
v.winWave = isFinite(s.winWave) ? s.winWave : 0; v.rev = s.rev; v.queued = s.spawnQ.length;
|
||||||
v.speed = this.speed; v.paused = this.paused; v.time = s.time;
|
v.speed = this.speed; v.paused = this.paused; v.time = s.time; v.difficulty = s.difficulty;
|
||||||
v.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets;
|
v.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets;
|
||||||
}
|
}
|
||||||
update(now) {
|
update(now) {
|
||||||
|
|
@ -102,7 +104,12 @@
|
||||||
this._sync();
|
this._sync();
|
||||||
}
|
}
|
||||||
preview(x, y, routes) { return this.sim.preview(x, y, routes); }
|
preview(x, y, routes) { return this.sim.preview(x, y, routes); }
|
||||||
newGame(map) { if (map) this.mapId = map; this._fresh(); this.emit('newgame'); }
|
// `difficulty` absent: the same one again ("Play again"); an unknown one is normal (the sim's rule)
|
||||||
|
newGame(map, difficulty) {
|
||||||
|
if (map) this.mapId = map;
|
||||||
|
if (difficulty !== undefined && difficulty !== null) this.difficulty = TD.difficultyId(difficulty);
|
||||||
|
this._fresh(); this.emit('newgame');
|
||||||
|
}
|
||||||
sendCursor() {}
|
sendCursor() {}
|
||||||
sendMark(x, y) { this.emit('mark', { slot: 0, x, y }); }
|
sendMark(x, y) { this.emit('mark', { slot: 0, x, y }); }
|
||||||
requestSync() {}
|
requestSync() {}
|
||||||
|
|
@ -118,6 +125,7 @@
|
||||||
this.pid = opts.pid; this.name = opts.name || 'Player';
|
this.pid = opts.pid; this.name = opts.name || 'Player';
|
||||||
this.room = opts.room || null; // null => create a room on first connect
|
this.room = opts.room || null; // null => create a room on first connect
|
||||||
this.mapId = opts.map || 'open';
|
this.mapId = opts.map || 'open';
|
||||||
|
this.difficulty = TD.difficultyId(opts.difficulty); // what a CREATING join asks for; afterwards whatever the server's state says
|
||||||
this.status = 'idle'; // idle | connecting | joined | reconnecting | closed
|
this.status = 'idle'; // idle | connecting | joined | reconnecting | closed
|
||||||
this.ws = null; this.players = []; this.you = null; this.board = null;
|
this.ws = null; this.players = []; this.you = null; this.board = null;
|
||||||
this.buf = []; this.delay = 120;
|
this.buf = []; this.delay = 120;
|
||||||
|
|
@ -132,7 +140,7 @@
|
||||||
this.speed = 1; this.paused = false;
|
this.speed = 1; this.paused = false;
|
||||||
this.view = {
|
this.view = {
|
||||||
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
|
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
|
||||||
speed: 1, paused: false, time: 0, towers: [], monsters: [], bullets: [], cursors: [],
|
speed: 1, paused: false, time: 0, difficulty: this.difficulty, towers: [], monsters: [], bullets: [], cursors: [],
|
||||||
};
|
};
|
||||||
this._onVis = () => { if (!document.hidden) this._wake(); };
|
this._onVis = () => { if (!document.hidden) this._wake(); };
|
||||||
document.addEventListener('visibilitychange', this._onVis);
|
document.addEventListener('visibilitychange', this._onVis);
|
||||||
|
|
@ -154,7 +162,7 @@
|
||||||
this.ws = ws;
|
this.ws = ws;
|
||||||
ws.onopen = () => {
|
ws.onopen = () => {
|
||||||
const j = { t: 'join', pid: this.pid, name: this.name };
|
const j = { t: 'join', pid: this.pid, name: this.name };
|
||||||
if (this.room) j.room = this.room; else j.map = this.mapId;
|
if (this.room) j.room = this.room; else { j.map = this.mapId; j.difficulty = this.difficulty; } // only a creating join carries them: a joiner takes the room's
|
||||||
this._send(j);
|
this._send(j);
|
||||||
};
|
};
|
||||||
ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); };
|
ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); };
|
||||||
|
|
@ -260,7 +268,7 @@
|
||||||
this._die('restarted', this.everJoined ? 'The server restarted, your game was lost.' : 'That co-op game is gone: the server restarted or the room timed out.');
|
this._die('restarted', this.everJoined ? 'The server restarted, your game was lost.' : 'That co-op game is gone: the server restarted or the room timed out.');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.' };
|
const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.', bad_difficulty: 'Unknown difficulty.' };
|
||||||
this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.');
|
this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
@ -282,6 +290,8 @@
|
||||||
this._setTowers(state.towers);
|
this._setTowers(state.towers);
|
||||||
this.rev = this.recvRev = state.rev;
|
this.rev = this.recvRev = state.rev;
|
||||||
this.maxLives = state.maxLives; this.winWave = state.winWave;
|
this.maxLives = state.maxLives; this.winWave = state.winWave;
|
||||||
|
this.difficulty = TD.isDifficulty(state.difficulty) ? state.difficulty : 'normal'; // (a server from before difficulties sends none)
|
||||||
|
this.view.difficulty = this.difficulty;
|
||||||
this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear();
|
this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear();
|
||||||
if (snap) this._push(snap, true);
|
if (snap) this._push(snap, true);
|
||||||
}
|
}
|
||||||
|
|
@ -384,7 +394,7 @@
|
||||||
for (const m of this.view.monsters) if (!m.air) reserved.add(Math.floor(m.y) * this.board.cols + Math.floor(m.x));
|
for (const m of this.view.monsters) if (!m.air) reserved.add(Math.floor(m.y) * this.board.cols + Math.floor(m.x));
|
||||||
return this.board.trial(x, y, reserved, null, routes);
|
return this.board.trial(x, y, reserved, null, routes);
|
||||||
}
|
}
|
||||||
newGame(map) { this._send({ t: 'newgame', map }); }
|
newGame(map, difficulty) { this._send({ t: 'newgame', map, difficulty }); } // (JSON drops an undefined difficulty: the server keeps the room's)
|
||||||
// Moves are throttled to one per 70 ms. A clear (x === null) or `force` always goes out, so the final position / the
|
// Moves are throttled to one per 70 ms. A clear (x === null) or `force` always goes out, so the final position / the
|
||||||
// "cursor gone" message of a touch is never swallowed by the throttle (touch-9).
|
// "cursor gone" message of a touch is never swallowed by the throttle (touch-9).
|
||||||
sendCursor(x, y, force) {
|
sendCursor(x, y, force) {
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@
|
||||||
bounds: 'Out of bounds', obstacle: 'That node is dead. Pick another cell', occupied: 'Something is already there', spawn: "Can't build on a gateway",
|
bounds: 'Out of bounds', obstacle: 'That node is dead. Pick another cell', occupied: 'Something is already there', spawn: "Can't build on a gateway",
|
||||||
core: "Can't build on the server", monster: 'A packet is in the way', blocks: 'That would seal the route. Leave a path!', gold: 'Not enough credits',
|
core: "Can't build on the server", monster: 'A packet is in the way', blocks: 'That would seal the route. Leave a path!', gold: 'Not enough credits',
|
||||||
over: 'The game is over', no_tower: 'That tower no longer exists', max: 'Already at max level', not_host: 'Only the host can do that',
|
over: 'The game is over', no_tower: 'That tower no longer exists', max: 'Already at max level', not_host: 'Only the host can do that',
|
||||||
bad_map: 'Unknown map', bad_type: 'Unknown tower', bad_cmd: 'Invalid command', not_won: 'Nothing to continue',
|
bad_map: 'Unknown map', bad_difficulty: 'Unknown difficulty', bad_type: 'Unknown tower', bad_cmd: 'Invalid command', not_won: 'Nothing to continue',
|
||||||
};
|
};
|
||||||
const MODE_NAMES = { first: 'First', last: 'Last', strong: 'Strongest', close: 'Closest' };
|
const MODE_NAMES = { first: 'First', last: 'Last', strong: 'Strongest', close: 'Closest' };
|
||||||
|
|
||||||
|
|
@ -43,6 +43,7 @@
|
||||||
const app = {
|
const app = {
|
||||||
ctrl: null, renderer: null, screen: 'menu', inGame: false,
|
ctrl: null, renderer: null, screen: 'menu', inGame: false,
|
||||||
mapId: store.get('nw.map', 'open'),
|
mapId: store.get('nw.map', 'open'),
|
||||||
|
difficulty: 'normal', // the player's pick for the NEXT game (the running game's is ctrl.view.difficulty); loaded below
|
||||||
selType: null, selTower: 0,
|
selType: null, selTower: 0,
|
||||||
hover: null, pending: null, preview: null, valid: true, previewDirty: true, lastPreviewAt: 0,
|
hover: null, pending: null, preview: null, valid: true, previewDirty: true, lastPreviewAt: 0,
|
||||||
zoomed: false, last: {}, names: {}, started: false, lastBossCheck: 0, bossMusic: false,
|
zoomed: false, last: {}, names: {}, started: false, lastBossCheck: 0, bossMusic: false,
|
||||||
|
|
@ -54,6 +55,7 @@
|
||||||
const renderer = new NW.Renderer(canvas);
|
const renderer = new NW.Renderer(canvas);
|
||||||
app.renderer = renderer;
|
app.renderer = renderer;
|
||||||
if (!TD.MAPS[app.mapId]) app.mapId = 'open';
|
if (!TD.MAPS[app.mapId]) app.mapId = 'open';
|
||||||
|
{ const d = store.get('nw.difficulty', 'normal'); app.difficulty = TD.isDifficulty(d) ? d : 'normal'; } // (a stored value that is not a difficulty any more is normal)
|
||||||
|
|
||||||
// ------------------------------------------------------------------ small UI helpers
|
// ------------------------------------------------------------------ small UI helpers
|
||||||
let lastToast = '', lastToastAt = 0;
|
let lastToast = '', lastToastAt = 0;
|
||||||
|
|
@ -149,6 +151,7 @@
|
||||||
ctrl.on('newgame', () => {
|
ctrl.on('newgame', () => {
|
||||||
resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true;
|
resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true;
|
||||||
app.bossMusic = false; if (app.inGame) Audio.music('battle'); // a new game starts its music on every client, not only on the one that pressed Play again (code-5)
|
app.bossMusic = false; if (app.inGame) Audio.music('battle'); // a new game starts its music on every client, not only on the one that pressed Play again (code-5)
|
||||||
|
if (ctrl.kind === 'remote') renderPlayers(); // (the room header names the difficulty, which a new game may have changed)
|
||||||
});
|
});
|
||||||
adoptBoard(true);
|
adoptBoard(true);
|
||||||
}
|
}
|
||||||
|
|
@ -171,7 +174,7 @@
|
||||||
cancelPending(); // a co-op join that is still connecting must not take this game over (code-3)
|
cancelPending(); // a co-op join that is still connecting must not take this game over (code-3)
|
||||||
leaveRemote(true);
|
leaveRemote(true);
|
||||||
app.mapId = mapId; store.set('nw.map', mapId);
|
app.mapId = mapId; store.set('nw.map', mapId);
|
||||||
const c = new NW.LocalController({ map: mapId });
|
const c = new NW.LocalController({ map: mapId, difficulty: app.difficulty });
|
||||||
useController(c);
|
useController(c);
|
||||||
app.inGame = true; app.started = true; app.endShown = false; app.last = {};
|
app.inGame = true; app.started = true; app.endShown = false; app.last = {};
|
||||||
resetSelection(); setScreen('playing'); showOverlay(null);
|
resetSelection(); setScreen('playing'); showOverlay(null);
|
||||||
|
|
@ -428,14 +431,15 @@
|
||||||
|
|
||||||
function renderWavePanel(view) {
|
function renderWavePanel(view) {
|
||||||
const n = view.wave + 1;
|
const n = view.wave + 1;
|
||||||
const key = n + ':' + view.state;
|
const dif = viewDifficulty(view);
|
||||||
|
const key = n + ':' + view.state + ':' + dif;
|
||||||
if (app.last.waveKey === key) return;
|
if (app.last.waveKey === key) return;
|
||||||
app.last.waveKey = key;
|
app.last.waveKey = key;
|
||||||
const box = $('nextwave');
|
const box = $('nextwave');
|
||||||
if (view.state !== 'playing') { box.textContent = ''; return; }
|
if (view.state !== 'playing') { box.textContent = ''; return; }
|
||||||
if (n % 10 === 9 || n % 10 === 0) Audio.preload('boss'); // the boss theme is fetched a wave or two ahead, so it starts with the boss instead of seconds later (code-12)
|
if (n % 10 === 9 || n % 10 === 0) Audio.preload('boss'); // the boss theme is fetched a wave or two ahead, so it starts with the boss instead of seconds later (code-12)
|
||||||
const sum = TD.waveSummary(n);
|
const sum = TD.waveSummary(n);
|
||||||
let html = '<div class="panel"><h4>Next · wave ' + n + '</h4><div class="wv">';
|
let html = '<div class="panel"><h4>Next · wave ' + n + '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span></h4><div class="wv">';
|
||||||
let air = false;
|
let air = false;
|
||||||
for (const g of sum) {
|
for (const g of sum) {
|
||||||
const d = TD.ENEMIES[g.k];
|
const d = TD.ENEMIES[g.k];
|
||||||
|
|
@ -467,7 +471,8 @@
|
||||||
const ctrl = app.ctrl, box = $('players');
|
const ctrl = app.ctrl, box = $('players');
|
||||||
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
|
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
|
||||||
box.hidden = false;
|
box.hidden = false;
|
||||||
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + ' <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
|
const dif = viewDifficulty(ctrl.view);
|
||||||
|
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span> <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
|
||||||
for (const p of ctrl.players) {
|
for (const p of ctrl.players) {
|
||||||
html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' +
|
html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' +
|
||||||
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>';
|
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>';
|
||||||
|
|
@ -551,11 +556,12 @@
|
||||||
const won = view.state === 'won';
|
const won = view.state === 'won';
|
||||||
$('endTitle').textContent = won ? 'Server secured!' : 'Breach!';
|
$('endTitle').textContent = won ? 'Server secured!' : 'Breach!';
|
||||||
$('endTitle').style.color = won ? 'var(--green)' : 'var(--red)';
|
$('endTitle').style.color = won ? 'var(--green)' : 'var(--red)';
|
||||||
const best = store.get('nw.best.' + ctrl.board.mapId, 0);
|
const dif = viewDifficulty(view), bk = bestKey(ctrl.board.mapId, dif);
|
||||||
if (view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave); // a win counts too (code-25)
|
const best = +store.get(bk, 0) || 0;
|
||||||
|
if (view.wave > best) store.set(bk, view.wave); // a win counts too (code-25)
|
||||||
$('endText').textContent = won ? 'You held the line through wave ' + view.wave + '. Every packet was filtered.' : 'The server fell on wave ' + view.wave + '.';
|
$('endText').textContent = won ? 'You held the line through wave ' + view.wave + '. Every packet was filtered.' : 'The server fell on wave ' + view.wave + '.';
|
||||||
const walls = view.towers.filter((t) => t.type === 'wall').length;
|
const walls = view.towers.filter((t) => t.type === 'wall').length;
|
||||||
const rows = [['Wave', view.wave], ['Packets killed', view.kills], ['Turrets', view.towers.length - walls], ['Firewalls', walls], ['Integrity left', view.lives], ['Best (map)', Math.max(best, view.wave)]];
|
const rows = [['Wave', view.wave], ['Packets killed', view.kills], ['Turrets', view.towers.length - walls], ['Firewalls', walls], ['Integrity left', view.lives], ['Difficulty', diffName(dif)], ['Best on ' + diffName(dif), Math.max(best, view.wave)]];
|
||||||
$('endStats').innerHTML = rows.map((r) => '<div><span>' + r[0] + '</span><b>' + esc(r[1]) + '</b></div>').join(''); // (in co-op these numbers come from the server)
|
$('endStats').innerHTML = rows.map((r) => '<div><span>' + r[0] + '</span><b>' + esc(r[1]) + '</b></div>').join(''); // (in co-op these numbers come from the server)
|
||||||
syncEndButtons();
|
syncEndButtons();
|
||||||
$('btnContinue').hidden = !won;
|
$('btnContinue').hidden = !won;
|
||||||
|
|
@ -958,6 +964,55 @@
|
||||||
$('pausedTag').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', false); });
|
$('pausedTag').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', false); });
|
||||||
$('netChip').addEventListener('click', () => { if (app.ctrl && app.ctrl.kind === 'remote') { Audio.sfx('click'); invite(); } }); // room code chip: tap to invite
|
$('netChip').addEventListener('click', () => { if (app.ctrl && app.ctrl.kind === 'remote') { Audio.sfx('click'); invite(); } }); // room code chip: tap to invite
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ difficulty
|
||||||
|
// The picker (menu, and the co-op lobby for the host) sets app.difficulty, the pick for the NEXT game, and remembers it. A game that is
|
||||||
|
// running keeps its own (view.difficulty): Play again repeats that one, and every screen about the running game shows it.
|
||||||
|
const diffName = (id) => (TD.DIFFICULTIES[id] ? TD.DIFFICULTIES[id].name : String(id));
|
||||||
|
const viewDifficulty = (view) => (view && TD.isDifficulty(view.difficulty) ? view.difficulty : 'normal');
|
||||||
|
// The best wave per map AND difficulty. Normal keeps the key the game always used (nw.best.<map>), so every record from before
|
||||||
|
// difficulties existed is simply the normal one and nothing is lost or migrated; easy and hard get their own suffix.
|
||||||
|
const bestKey = (map, dif) => 'nw.best.' + map + (dif === 'normal' ? '' : '.' + dif);
|
||||||
|
// What a difficulty changes, worded from the table (so a retune cannot leave this text wrong).
|
||||||
|
function diffSummary(id) {
|
||||||
|
const d = TD.DIFFICULTIES[id], out = [];
|
||||||
|
if (!d) return '';
|
||||||
|
const pct = (m) => Math.round(Math.abs(m - 1) * 100) + '%';
|
||||||
|
if (d.gold !== 1) out.push(pct(d.gold) + (d.gold > 1 ? ' more' : ' fewer') + ' starting credits');
|
||||||
|
if (d.lives !== 1) out.push(pct(d.lives) + (d.lives > 1 ? ' more' : ' less') + ' integrity');
|
||||||
|
if (d.hp !== 1) out.push('packets ' + pct(d.hp) + (d.hp < 1 ? ' weaker' : ' tougher'));
|
||||||
|
if (d.reward !== 1) out.push('kills pay ' + pct(d.reward) + (d.reward > 1 ? ' more' : ' less'));
|
||||||
|
return out.length ? out.join(', ') : 'The standard game.';
|
||||||
|
}
|
||||||
|
const diffBoxes = () => [$('diffPick'), $('lobbyDiff')].filter(Boolean);
|
||||||
|
function buildDiffPickers() {
|
||||||
|
for (const box of diffBoxes()) {
|
||||||
|
box.textContent = '';
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const b = document.createElement('button');
|
||||||
|
b.type = 'button'; b.dataset.diff = id; b.setAttribute('role', 'radio');
|
||||||
|
b.textContent = diffName(id);
|
||||||
|
b.title = diffSummary(id);
|
||||||
|
b.addEventListener('click', () => { Audio.sfx('click'); chooseDifficulty(id); });
|
||||||
|
box.appendChild(b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chooseDifficulty(app.difficulty, true);
|
||||||
|
}
|
||||||
|
function chooseDifficulty(id, silent) {
|
||||||
|
if (!TD.isDifficulty(id)) id = 'normal';
|
||||||
|
app.difficulty = id;
|
||||||
|
if (!silent) store.set('nw.difficulty', id);
|
||||||
|
for (const box of diffBoxes()) for (const b of box.children) b.setAttribute('aria-checked', b.dataset.diff === id ? 'true' : 'false');
|
||||||
|
renderDiffNote();
|
||||||
|
}
|
||||||
|
// One line under the picker: what the picked difficulty does; while a game is running, which one that game is on.
|
||||||
|
function renderDiffNote() {
|
||||||
|
const n = $('diffNote'); if (!n) return;
|
||||||
|
const cur = app.inGame && app.ctrl ? viewDifficulty(app.ctrl.view) : null;
|
||||||
|
n.className = 'diffnote' + (cur ? ' live' : '');
|
||||||
|
n.textContent = cur ? 'This game: ' + diffName(cur) + (cur !== app.difficulty ? ' \u00b7 next game: ' + diffName(app.difficulty) : '') : diffSummary(app.difficulty);
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ menu / lobby
|
// ------------------------------------------------------------------ menu / lobby
|
||||||
function buildMapPicker() {
|
function buildMapPicker() {
|
||||||
const box = $('mapPick'); box.textContent = '';
|
const box = $('mapPick'); box.textContent = '';
|
||||||
|
|
@ -965,7 +1020,7 @@
|
||||||
const def = TD.MAPS[id];
|
const def = TD.MAPS[id];
|
||||||
const b = document.createElement('button');
|
const b = document.createElement('button');
|
||||||
b.type = 'button'; b.className = 'mapcard'; b.dataset.map = id; b.setAttribute('role', 'radio');
|
b.type = 'button'; b.className = 'mapcard'; b.dataset.map = id; b.setAttribute('role', 'radio');
|
||||||
b.innerHTML = '<canvas width="208" height="128"></canvas><span class="nm"></span><span class="df">DIFFICULTY <b></b></span>';
|
b.innerHTML = '<canvas width="208" height="128"></canvas><span class="nm"></span><span class="df">RATING <b></b></span>';
|
||||||
b.querySelector('.nm').textContent = def.name;
|
b.querySelector('.nm').textContent = def.name;
|
||||||
b.querySelector('.df b').textContent = '●'.repeat(def.difficulty) + '○'.repeat(3 - def.difficulty);
|
b.querySelector('.df b').textContent = '●'.repeat(def.difficulty) + '○'.repeat(3 - def.difficulty);
|
||||||
drawMapPreview(b.querySelector('canvas'), def);
|
drawMapPreview(b.querySelector('canvas'), def);
|
||||||
|
|
@ -997,6 +1052,7 @@
|
||||||
$('btnCloseMenu').hidden = !app.inGame;
|
$('btnCloseMenu').hidden = !app.inGame;
|
||||||
$('btnSolo').lastChild.textContent = app.inGame ? 'New solo game' : 'Play solo';
|
$('btnSolo').lastChild.textContent = app.inGame ? 'New solo game' : 'Play solo';
|
||||||
showOverlay('menu');
|
showOverlay('menu');
|
||||||
|
renderDiffNote();
|
||||||
if (!app.inGame) Audio.music('theme');
|
if (!app.inGame) Audio.music('theme');
|
||||||
updateResumeButton();
|
updateResumeButton();
|
||||||
}
|
}
|
||||||
|
|
@ -1028,8 +1084,9 @@
|
||||||
|
|
||||||
$('btnAgain').addEventListener('click', () => {
|
$('btnAgain').addEventListener('click', () => {
|
||||||
Audio.sfx('click');
|
Audio.sfx('click');
|
||||||
if (app.ctrl.kind === 'local') { app.ctrl.newGame(app.ctrl.mapId); Audio.music('battle'); }
|
// Play again keeps the difficulty of the game that just ended (not the menu's pick, which is for a NEW game)
|
||||||
else { app.ctrl.newGame(app.ctrl.board.mapId); }
|
if (app.ctrl.kind === 'local') { app.ctrl.newGame(app.ctrl.mapId, app.ctrl.difficulty); Audio.music('battle'); }
|
||||||
|
else { app.ctrl.newGame(app.ctrl.board.mapId, app.ctrl.difficulty); }
|
||||||
});
|
});
|
||||||
$('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); });
|
$('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); });
|
||||||
$('btnEndMenu').addEventListener('click', () => { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } });
|
$('btnEndMenu').addEventListener('click', () => { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } });
|
||||||
|
|
@ -1045,7 +1102,7 @@
|
||||||
$('btnCoop').addEventListener('click', () => { Audio.unlock(); openLobby(); });
|
$('btnCoop').addEventListener('click', () => { Audio.unlock(); openLobby(); });
|
||||||
$('btnLobbyBack').addEventListener('click', () => { cancelPending(); lobbyMsg(''); if (app.inGame) closeOverlayToGame(); else openMenu(); });
|
$('btnLobbyBack').addEventListener('click', () => { cancelPending(); lobbyMsg(''); if (app.inGame) closeOverlayToGame(); else openMenu(); });
|
||||||
$('inCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
|
$('inCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
|
||||||
$('btnCreate').addEventListener('click', () => connectRemote({ room: null, map: app.mapId }));
|
$('btnCreate').addEventListener('click', () => connectRemote({ room: null, map: app.mapId, difficulty: app.difficulty }));
|
||||||
$('btnJoin').addEventListener('click', () => {
|
$('btnJoin').addEventListener('click', () => {
|
||||||
const code = $('inCode').value.trim().toUpperCase();
|
const code = $('inCode').value.trim().toUpperCase();
|
||||||
if (!/^[A-Z0-9]{4}$/.test(code)) { lobbyMsg('Enter the 4 character room code.', true); return; }
|
if (!/^[A-Z0-9]{4}$/.test(code)) { lobbyMsg('Enter the 4 character room code.', true); return; }
|
||||||
|
|
@ -1072,7 +1129,7 @@
|
||||||
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
|
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
|
||||||
store.set('nw.name', name);
|
store.set('nw.name', name);
|
||||||
lobbyMsg('Connecting…');
|
lobbyMsg('Connecting…');
|
||||||
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, resume: !!opts.resume });
|
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, difficulty: opts.difficulty, resume: !!opts.resume });
|
||||||
pendingRc = rc; setLobbyBusy(true);
|
pendingRc = rc; setLobbyBusy(true);
|
||||||
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); };
|
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); };
|
||||||
let first = true;
|
let first = true;
|
||||||
|
|
@ -1088,7 +1145,7 @@
|
||||||
resetSelection(); setScreen('playing'); showOverlay(null);
|
resetSelection(); setScreen('playing'); showOverlay(null);
|
||||||
onPlayers(rc.players);
|
onPlayers(rc.players);
|
||||||
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
|
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
|
||||||
toast('Room ' + rc.room + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good');
|
toast('Room ' + rc.room + ' \u00b7 ' + diffName(viewDifficulty(rc.view)) + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); // (a joiner learns the host's difficulty here)
|
||||||
Audio.music('battle'); requestWakeLock();
|
Audio.music('battle'); requestWakeLock();
|
||||||
firstRunHelp(); // an invited player is new to the game too (code-26)
|
firstRunHelp(); // an invited player is new to the game too (code-26)
|
||||||
} else { toast('Reconnected', 'good'); adoptBoard(); }
|
} else { toast('Reconnected', 'good'); adoptBoard(); }
|
||||||
|
|
@ -1232,7 +1289,7 @@
|
||||||
|
|
||||||
// ------------------------------------------------------------------ boot
|
// ------------------------------------------------------------------ boot
|
||||||
function boot() {
|
function boot() {
|
||||||
buildPalette(); buildMapPicker();
|
buildPalette(); buildMapPicker(); buildDiffPickers();
|
||||||
{ const keys = TD.TOWER_ORDER.map((t) => TD.TOWERS[t].key); $('helpKeys').textContent = keys[0] + '\u2013' + keys[keys.length - 1]; }
|
{ const keys = TD.TOWER_ORDER.map((t) => TD.TOWERS[t].key); $('helpKeys').textContent = keys[0] + '\u2013' + keys[keys.length - 1]; }
|
||||||
previewMap(app.mapId);
|
previewMap(app.mapId);
|
||||||
setScreen('menu'); showOverlay('menu');
|
setScreen('menu'); showOverlay('menu');
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,29 @@
|
||||||
const START_LIVES = 20;
|
const START_LIVES = 20;
|
||||||
const SELL_RATIO = 0.7;
|
const SELL_RATIO = 0.7;
|
||||||
const WIN_WAVE = 30;
|
const WIN_WAVE = 30;
|
||||||
|
// Clearing wave n pays CLEAR_BONUS + CLEAR_BONUS_PER_WAVE * n credits on top of the kills (the same on every difficulty).
|
||||||
|
const CLEAR_BONUS = 10;
|
||||||
|
const CLEAR_BONUS_PER_WAVE = 1;
|
||||||
|
function clearBonus(n) { return CLEAR_BONUS + CLEAR_BONUS_PER_WAVE * n; }
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- difficulty
|
||||||
|
// One row per difficulty; every number is a multiplier on the base tables below (normal is all 1, so it plays exactly the tuned base game):
|
||||||
|
// gold the starting credits (START_GOLD) lives the starting integrity (START_LIVES), at least 1
|
||||||
|
// hp every enemy's hit points AND its shield reward what a kill pays (a kill always pays at least 1)
|
||||||
|
// The wave clear bonus and the tower prices do not change. Nothing outside this table may hard-code a number from it: tests, the
|
||||||
|
// UI and the balance bot read the table. The ids travel on the wire (create-room option, newgame, fullState), so only ever APPEND.
|
||||||
|
// (Not to be confused with the `difficulty` 1-3 of a MAP below: that is the layout's own rating, drawn as dots on the map cards.)
|
||||||
|
const DIFFICULTY_ORDER = ['easy', 'normal', 'hard'];
|
||||||
|
const DEFAULT_DIFFICULTY = 'normal';
|
||||||
|
const DIFFICULTIES = {
|
||||||
|
easy: { id: 'easy', name: 'Easy', gold: 1.5, lives: 1.5, hp: 0.8, reward: 1.1 },
|
||||||
|
normal: { id: 'normal', name: 'Normal', gold: 1, lives: 1, hp: 1, reward: 1 },
|
||||||
|
hard: { id: 'hard', name: 'Hard', gold: 0.9, lives: 0.85, hp: 1.08, reward: 0.97 },
|
||||||
|
};
|
||||||
|
// Is `v` the id of a difficulty? (own keys only: 'toString' and '__proto__' are not difficulties)
|
||||||
|
function isDifficulty(v) { return typeof v === 'string' && Object.prototype.hasOwnProperty.call(DIFFICULTIES, v); }
|
||||||
|
// `v` if it is a difficulty, otherwise normal (what the Sim does with an unknown value; the server rejects those instead).
|
||||||
|
function difficultyId(v) { return isDifficulty(v) ? v : DEFAULT_DIFFICULTY; }
|
||||||
|
|
||||||
// ---------------------------------------------------------------- maps
|
// ---------------------------------------------------------------- maps
|
||||||
// '.' open, '#' dead node (permanent obstacle), 'S' spawn (internet gateway), 'C' core (the server)
|
// '.' open, '#' dead node (permanent obstacle), 'S' spawn (internet gateway), 'C' core (the server)
|
||||||
|
|
@ -208,6 +231,7 @@
|
||||||
// Hotkeys: one unique key 1-9 per tower, in palette order.
|
// Hotkeys: one unique key 1-9 per tower, in palette order.
|
||||||
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'sandbox', 'balancer', 'uplink'];
|
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc', 'sandbox', 'balancer', 'uplink'];
|
||||||
const TARGET_MODES = ['first', 'last', 'strong', 'close'];
|
const TARGET_MODES = ['first', 'last', 'strong', 'close'];
|
||||||
|
const UPLINK_GROWTH = 1.3; // each Orbital Uplink you own makes the next one (and its upgrades) this much dearer; was 1.25
|
||||||
const TOWERS = {
|
const TOWERS = {
|
||||||
wall: {
|
wall: {
|
||||||
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1, role: 'wall',
|
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1, role: 'wall',
|
||||||
|
|
@ -218,28 +242,28 @@
|
||||||
name: 'Packet Filter', key: '2', color: '#35e0a1', role: 'attack', air: true, ground: true,
|
name: 'Packet Filter', key: '2', color: '#35e0a1', role: 'attack', air: true, ground: true,
|
||||||
desc: 'Fast, cheap rapid fire. Weak against armour.',
|
desc: 'Fast, cheap rapid fire. Weak against armour.',
|
||||||
levels: [
|
levels: [
|
||||||
{ cost: 25, dmg: 6, range: 3.2, rate: 3.0 },
|
{ cost: 25, dmg: 6, range: 3.5, rate: 3.0 },
|
||||||
{ cost: 30, dmg: 9, range: 3.5, rate: 3.4 },
|
{ cost: 25, dmg: 9, range: 3.8, rate: 3.4 },
|
||||||
{ cost: 55, dmg: 13, range: 3.9, rate: 4.0 },
|
{ cost: 45, dmg: 13, range: 4.2, rate: 4.0 },
|
||||||
],
|
],
|
||||||
bulletSpeed: 14,
|
bulletSpeed: 14,
|
||||||
},
|
},
|
||||||
ids: {
|
ids: {
|
||||||
name: 'IDS Sniper', key: '3', color: '#b78cff', role: 'attack', air: true, ground: true,
|
name: 'IDS Sniper', key: '3', color: '#b78cff', role: 'attack', air: true, ground: true,
|
||||||
desc: 'Long range, hard hitting, slow. Great against armour and bosses.',
|
desc: 'Long range, hard hitting, slow. Great against armour and bosses, poor against swarms.',
|
||||||
levels: [
|
levels: [
|
||||||
{ cost: 60, dmg: 50, range: 6.5, rate: 0.7 },
|
{ cost: 70, dmg: 83, range: 6.2, rate: 0.42 },
|
||||||
{ cost: 70, dmg: 85, range: 7.2, rate: 0.75 },
|
{ cost: 80, dmg: 143, range: 6.8, rate: 0.445 },
|
||||||
{ cost: 110, dmg: 150, range: 8.0, rate: 0.8 },
|
{ cost: 130, dmg: 250, range: 7.5, rate: 0.48 },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
mortar: {
|
mortar: {
|
||||||
name: 'Flood Mortar', key: '4', color: '#d4f04a', role: 'attack', air: false, ground: true,
|
name: 'Flood Mortar', key: '4', color: '#d4f04a', role: 'attack', air: false, ground: true,
|
||||||
desc: 'Splash damage against ground swarms. Cannot hit flyers.',
|
desc: 'Splash damage against ground swarms. Cannot hit flyers.',
|
||||||
levels: [
|
levels: [
|
||||||
{ cost: 55, dmg: 28, range: 4.8, rate: 0.8, splash: 1.3 },
|
{ cost: 55, dmg: 31, range: 4.9, rate: 0.8, splash: 1.3 },
|
||||||
{ cost: 60, dmg: 45, range: 5.2, rate: 0.85, splash: 1.5 },
|
{ cost: 60, dmg: 50, range: 5.3, rate: 0.85, splash: 1.5 },
|
||||||
{ cost: 100, dmg: 75, range: 5.6, rate: 0.9, splash: 1.7 },
|
{ cost: 95, dmg: 82, range: 5.7, rate: 0.9, splash: 1.7 },
|
||||||
],
|
],
|
||||||
shellSpeed: 5.5,
|
shellSpeed: 5.5,
|
||||||
},
|
},
|
||||||
|
|
@ -256,9 +280,9 @@
|
||||||
name: 'Router Arc', key: '6', color: '#ff7ad9', role: 'attack', air: true, ground: true,
|
name: 'Router Arc', key: '6', color: '#ff7ad9', role: 'attack', air: true, ground: true,
|
||||||
desc: 'Chain lightning that jumps between nearby packets.',
|
desc: 'Chain lightning that jumps between nearby packets.',
|
||||||
levels: [
|
levels: [
|
||||||
{ cost: 75, dmg: 16, range: 3.6, rate: 1.2, chains: 2, chainRange: 1.9, falloff: 0.7 },
|
{ cost: 70, dmg: 17, range: 3.8, rate: 1.2, chains: 2, chainRange: 1.9, falloff: 0.7 },
|
||||||
{ cost: 70, dmg: 24, range: 3.8, rate: 1.25, chains: 3, chainRange: 2.0, falloff: 0.72 },
|
{ cost: 60, dmg: 26, range: 4.0, rate: 1.25, chains: 3, chainRange: 2.0, falloff: 0.72 },
|
||||||
{ cost: 120, dmg: 36, range: 4.2, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
|
{ cost: 105, dmg: 38, range: 4.4, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
sandbox: {
|
sandbox: {
|
||||||
|
|
@ -281,8 +305,8 @@
|
||||||
},
|
},
|
||||||
uplink: {
|
uplink: {
|
||||||
name: 'Orbital Uplink', key: '9', color: '#ffe27a', role: 'attack', air: true, ground: true,
|
name: 'Orbital Uplink', key: '9', color: '#ffe27a', role: 'attack', air: true, ground: true,
|
||||||
desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Extremely expensive to build and to upgrade, and every Uplink you already own makes the next one 25% dearer, and its upgrades too.',
|
desc: 'Endgame weapon. A piercing orbital beam that ignores armour, scorches everything in its line, blasts and slows the rest around the target, and reaches across most of the map. Extremely expensive to build and to upgrade, and every Uplink you already own makes the next one ' + Math.round((UPLINK_GROWTH - 1) * 100) + '% dearer, and its upgrades too.',
|
||||||
priceGrowth: 1.25, // the Nth Uplink costs cost * 1.25^(N-1) to buy AND to upgrade (see priceMult), so kill rewards cannot buy a carpet of them
|
priceGrowth: UPLINK_GROWTH, // the Nth Uplink costs cost * UPLINK_GROWTH^(N-1) to buy AND to upgrade (see priceMult), so kill rewards cannot buy a carpet of them
|
||||||
levels: [
|
levels: [
|
||||||
{ cost: 1500, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
|
{ cost: 1500, dmg: 260, range: 11, rate: 0.45, width: 0.5, splash: 1.3, slowOnHit: 0.4, slowFor: 1.5 },
|
||||||
{ cost: 1200, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
|
{ cost: 1200, dmg: 400, range: 12, rate: 0.5, width: 0.55, splash: 1.5, slowOnHit: 0.45, slowFor: 1.75 },
|
||||||
|
|
@ -324,16 +348,16 @@
|
||||||
const ENEMIES = {
|
const ENEMIES = {
|
||||||
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a', buyCost: 10 },
|
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a', buyCost: 10 },
|
||||||
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43', buyCost: 6 },
|
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43', buyCost: 6 },
|
||||||
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b', buyCost: 30 },
|
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 4, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b', buyCost: 30 },
|
||||||
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166', buyCost: 3 },
|
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166', buyCost: 3 },
|
||||||
ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff', buyCost: 15 },
|
ghost: { name: 'Spoof', hp: 40, speed: 1.3, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff', buyCost: 15 },
|
||||||
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', buyCost: 300, slowRes: 0.5 },
|
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 7, reward: 60, leak: 5, air: false, r: 0.55, color: '#ff3b3b', buyCost: 180, slowRes: 0.5 },
|
||||||
// Healer: every HEAL_EVERY s it restores 'heal' of the max hp of every other enemy within healRange (several daemons stack up to HEAL_CAP).
|
// Healer: every HEAL_EVERY s it restores 'heal' of the max hp of every other enemy within healRange (several daemons stack up to HEAL_CAP).
|
||||||
daemon: { name: 'Daemon', hp: 70, speed: 1.1, armor: 0, reward: 8, leak: 1, air: false, r: 0.3, color: '#7ee08a', buyCost: 25, heal: 0.06, healRange: 2.2 },
|
daemon: { name: 'Daemon', hp: 70, speed: 1.1, armor: 0, reward: 8, leak: 1, air: false, r: 0.3, color: '#7ee08a', buyCost: 25, heal: 0.06, healRange: 2.2 },
|
||||||
// Shielded: 'shield' extra hit points (scaled like hp) that soak damage first and regrow shieldRegen/s of their max after shieldDelay s unhurt.
|
// Shielded: 'shield' extra hit points (scaled like hp) that soak damage first and regrow shieldRegen/s of their max after shieldDelay s unhurt.
|
||||||
proxy: { name: 'Proxy', hp: 90, speed: 1.0, armor: 1, reward: 10, leak: 1, air: false, r: 0.34, color: '#7aa2ff', buyCost: 30, shield: 120, shieldRegen: 0.1, shieldDelay: 3 },
|
proxy: { name: 'Proxy', hp: 90, speed: 1.0, armor: 1, reward: 10, leak: 1, air: false, r: 0.34, color: '#7aa2ff', buyCost: 30, shield: 120, shieldRegen: 0.1, shieldDelay: 3 },
|
||||||
// Swarm flyer.
|
// Swarm flyer.
|
||||||
botnet: { name: 'Botnet', hp: 12, speed: 2.6, armor: 0, reward: 1, leak: 1, air: true, r: 0.14, color: '#4dd0c8', buyCost: 3 },
|
botnet: { name: 'Botnet', hp: 12, speed: 2.2, armor: 0, reward: 1, leak: 1, air: true, r: 0.14, color: '#4dd0c8', buyCost: 3 },
|
||||||
};
|
};
|
||||||
const HEAL_EVERY = 1; // seconds between daemon pulses (one global clock, so the 12%/s cap is exact)
|
const HEAL_EVERY = 1; // seconds between daemon pulses (one global clock, so the 12%/s cap is exact)
|
||||||
const HEAL_CAP = 0.12; // most max-hp fraction one enemy can be healed per pulse, however many daemons are near
|
const HEAL_CAP = 0.12; // most max-hp fraction one enemy can be healed per pulse, however many daemons are near
|
||||||
|
|
@ -391,8 +415,10 @@
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
function hpScale(n) { return 1 + 0.16 * (n - 1) + 0.022 * (n - 1) * (n - 1); }
|
// Tuned numbers (docs/BALANCE.md): enemy hit points per wave and what a kill pays. Kill credits grow slower than the packets' hit points,
|
||||||
function rewardScale(n) { return 1 + 0.03 * (n - 1); }
|
// so credits stay a constraint all game; bosses pay little per hit point (a rootkit is a danger, not a payday).
|
||||||
|
function hpScale(n) { return 1 + 0.145 * (n - 1) + 0.0165 * (n - 1) * (n - 1); }
|
||||||
|
function rewardScale(n) { return 1 + 0.02 * (n - 1); }
|
||||||
|
|
||||||
// ---------------------------------------------------------------- path finding
|
// ---------------------------------------------------------------- path finding
|
||||||
class MinHeap {
|
class MinHeap {
|
||||||
|
|
@ -561,8 +587,11 @@
|
||||||
this.board = new Board(opts.map || 'open');
|
this.board = new Board(opts.map || 'open');
|
||||||
this.mapId = this.board.mapId;
|
this.mapId = this.board.mapId;
|
||||||
this.winWave = opts.winWave === undefined ? WIN_WAVE : opts.winWave;
|
this.winWave = opts.winWave === undefined ? WIN_WAVE : opts.winWave;
|
||||||
this.gold = opts.gold === undefined ? START_GOLD : opts.gold;
|
// An explicit `gold` / `lives` (tests, the bot) is used exactly as given; the difficulty scales only the defaults.
|
||||||
this.lives = opts.lives === undefined ? START_LIVES : opts.lives;
|
this.difficulty = difficultyId(opts.difficulty);
|
||||||
|
this.diff = DIFFICULTIES[this.difficulty];
|
||||||
|
this.gold = opts.gold === undefined ? Math.round(START_GOLD * this.diff.gold) : opts.gold;
|
||||||
|
this.lives = opts.lives === undefined ? Math.max(1, Math.round(START_LIVES * this.diff.lives)) : opts.lives;
|
||||||
this.maxLives = this.lives;
|
this.maxLives = this.lives;
|
||||||
this.collectEvents = opts.events !== false;
|
this.collectEvents = opts.events !== false;
|
||||||
|
|
||||||
|
|
@ -740,13 +769,14 @@
|
||||||
const def = ENEMIES[q.k];
|
const def = ENEMIES[q.k];
|
||||||
const b = this.board;
|
const b = this.board;
|
||||||
const s = b.spawns[this.spawnRR++ % b.spawns.length];
|
const s = b.spawns[this.spawnRR++ % b.spawns.length];
|
||||||
const hp = Math.round(def.hp * hpScale(q.wave));
|
const dm = this.diff; // the difficulty scales hit points and shield alike (the wire derives the shield bar from their ratio)
|
||||||
const shield = def.shield ? Math.round(def.shield * hpScale(q.wave)) : 0;
|
const hp = Math.max(1, Math.round(def.hp * hpScale(q.wave) * dm.hp));
|
||||||
|
const shield = def.shield ? Math.max(1, Math.round(def.shield * hpScale(q.wave) * dm.hp)) : 0;
|
||||||
const m = {
|
const m = {
|
||||||
id: this.nid++, kind: q.k, air: !!def.air,
|
id: this.nid++, kind: q.k, air: !!def.air,
|
||||||
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1,
|
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1,
|
||||||
hp, maxhp: hp, armor: def.armor, speed: def.speed,
|
hp, maxhp: hp, armor: def.armor, speed: def.speed,
|
||||||
reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave))),
|
reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave) * dm.reward)),
|
||||||
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
|
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
|
||||||
shield, maxShield: shield, shieldT: 0,
|
shield, maxShield: shield, shieldT: 0,
|
||||||
rem: 0, dead: false, wave: q.wave,
|
rem: 0, dead: false, wave: q.wave,
|
||||||
|
|
@ -793,7 +823,7 @@
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.wave > this.bonusWave && !this.monsters.length && !this.spawnQ.length) {
|
if (this.wave > this.bonusWave && !this.monsters.length && !this.spawnQ.length) {
|
||||||
const bonus = 10 + 2 * this.wave;
|
const bonus = clearBonus(this.wave);
|
||||||
this.gold += bonus;
|
this.gold += bonus;
|
||||||
this.bonusWave = this.wave;
|
this.bonusWave = this.wave;
|
||||||
this.emit({ e: 'clear', n: this.wave, bonus });
|
this.emit({ e: 'clear', n: this.wave, bonus });
|
||||||
|
|
@ -1094,6 +1124,7 @@
|
||||||
map: this.mapId, rev: this.rev, towers: this.towerList(),
|
map: this.mapId, rev: this.rev, towers: this.towerList(),
|
||||||
winWave: this.winWave === Infinity ? 0 : this.winWave,
|
winWave: this.winWave === Infinity ? 0 : this.winWave,
|
||||||
maxLives: this.maxLives,
|
maxLives: this.maxLives,
|
||||||
|
difficulty: this.difficulty,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1117,8 +1148,9 @@
|
||||||
|
|
||||||
return {
|
return {
|
||||||
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP,
|
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP,
|
||||||
|
DIFFICULTIES, DIFFICULTY_ORDER, DEFAULT_DIFFICULTY, isDifficulty, difficultyId,
|
||||||
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
|
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
|
||||||
priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale,
|
priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale, clearBonus,
|
||||||
buildField, nextCell, traceRoute, parseMap, Board, Sim, round2,
|
buildField, nextCell, traceRoute, parseMap, Board, Sim, round2,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,7 @@ const PID_RE = /^[A-Za-z0-9_-]{8,40}$/;
|
||||||
const ROOM_RE = /^[A-Za-z0-9]{4}$/;
|
const ROOM_RE = /^[A-Za-z0-9]{4}$/;
|
||||||
const NAME_STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g');
|
const NAME_STRIP = new RegExp('[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069\\ufeff]', 'g');
|
||||||
// Close codes for a failed join (the 'error' message carries the machine-readable code).
|
// Close codes for a failed join (the 'error' message carries the machine-readable code).
|
||||||
const JOIN_CLOSE = { bad_request: 4400, bad_map: 4400, no_room: 4404, full: 4409, too_many_rooms: 4503 };
|
const JOIN_CLOSE = { bad_request: 4400, bad_map: 4400, bad_difficulty: 4400, no_room: 4404, full: 4409, too_many_rooms: 4503 };
|
||||||
|
|
||||||
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||||
const noop = () => {};
|
const noop = () => {};
|
||||||
|
|
@ -202,7 +202,12 @@ async function createServer(userOpts) {
|
||||||
if (typeof msg.map !== 'string' || !hasOwn(TD.MAPS, msg.map)) return failJoin(ctx, 'bad_map', 'unknown map');
|
if (typeof msg.map !== 'string' || !hasOwn(TD.MAPS, msg.map)) return failJoin(ctx, 'bad_map', 'unknown map');
|
||||||
map = msg.map;
|
map = msg.map;
|
||||||
}
|
}
|
||||||
room = manager.create(map);
|
let difficulty = TD.DEFAULT_DIFFICULTY; // like the map, only a creating join carries it (a join to a room takes the room's)
|
||||||
|
if (msg.difficulty !== undefined && msg.difficulty !== null) {
|
||||||
|
if (!TD.isDifficulty(msg.difficulty)) return failJoin(ctx, 'bad_difficulty', 'unknown difficulty');
|
||||||
|
difficulty = msg.difficulty;
|
||||||
|
}
|
||||||
|
room = manager.create(map, difficulty);
|
||||||
if (!room) return failJoin(ctx, 'too_many_rooms', 'the server has reached its room limit');
|
if (!room) return failJoin(ctx, 'too_many_rooms', 'the server has reached its room limit');
|
||||||
why = 'created';
|
why = 'created';
|
||||||
} else {
|
} else {
|
||||||
|
|
|
||||||
|
|
@ -32,10 +32,10 @@ function sendRaw(conn, str) {
|
||||||
}
|
}
|
||||||
|
|
||||||
class Room {
|
class Room {
|
||||||
constructor(manager, code, mapId) {
|
constructor(manager, code, mapId, difficulty) {
|
||||||
this.manager = manager;
|
this.manager = manager;
|
||||||
this.code = code;
|
this.code = code;
|
||||||
this.sim = new TD.Sim({ map: mapId });
|
this.sim = new TD.Sim({ map: mapId, difficulty });
|
||||||
this.speed = 1;
|
this.speed = 1;
|
||||||
this.paused = false;
|
this.paused = false;
|
||||||
this.seq = 0;
|
this.seq = 0;
|
||||||
|
|
@ -248,10 +248,12 @@ class Room {
|
||||||
if (!p.host) { this.reject(p, 'newgame', 'not_host'); return true; }
|
if (!p.host) { this.reject(p, 'newgame', 'not_host'); return true; }
|
||||||
const map = msg.map === undefined || msg.map === null ? this.sim.mapId : msg.map;
|
const map = msg.map === undefined || msg.map === null ? this.sim.mapId : msg.map;
|
||||||
if (typeof map !== 'string' || !hasOwn(TD.MAPS, map)) { this.reject(p, 'newgame', 'bad_map'); return true; }
|
if (typeof map !== 'string' || !hasOwn(TD.MAPS, map)) { this.reject(p, 'newgame', 'bad_map'); return true; }
|
||||||
this.sim = new TD.Sim({ map });
|
const difficulty = msg.difficulty === undefined || msg.difficulty === null ? this.sim.difficulty : msg.difficulty; // absent: keep the room's
|
||||||
|
if (!TD.isDifficulty(difficulty)) { this.reject(p, 'newgame', 'bad_difficulty'); return true; }
|
||||||
|
this.sim = new TD.Sim({ map, difficulty });
|
||||||
this.speed = 1; this.paused = false; this.acc = 0;
|
this.speed = 1; this.paused = false; this.acc = 0;
|
||||||
this.lastSentRev = this.sim.rev; // the 'state' below carries the tower list
|
this.lastSentRev = this.sim.rev; // the 'state' below carries the tower list
|
||||||
this.log('new game on map ' + map + ' started by ' + p.name);
|
this.log('new game on map ' + map + ' (' + difficulty + ') started by ' + p.name);
|
||||||
this.broadcast(this.stateMsg({ newgame: true }));
|
this.broadcast(this.stateMsg({ newgame: true }));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
@ -363,7 +365,7 @@ class RoomManager {
|
||||||
// null when the room limit is reached. A full table first drops a room that nobody is online in (it is only
|
// null when the room limit is reached. A full table first drops a room that nobody is online in (it is only
|
||||||
// being held for its grace period): otherwise one client could fill all slots for a minute at a time by
|
// being held for its grace period): otherwise one client could fill all slots for a minute at a time by
|
||||||
// creating rooms and closing the sockets, which costs nothing and is not limited by any per-IP socket cap.
|
// creating rooms and closing the sockets, which costs nothing and is not limited by any per-IP socket cap.
|
||||||
create(mapId) {
|
create(mapId, difficulty) {
|
||||||
if (this.closed) return null;
|
if (this.closed) return null;
|
||||||
if (this.rooms.size >= this.maxRooms) {
|
if (this.rooms.size >= this.maxRooms) {
|
||||||
const victim = this.abandonedRoom();
|
const victim = this.abandonedRoom();
|
||||||
|
|
@ -372,9 +374,9 @@ class RoomManager {
|
||||||
}
|
}
|
||||||
const code = this.newCode();
|
const code = this.newCode();
|
||||||
if (!code) return null;
|
if (!code) return null;
|
||||||
const room = new Room(this, code, mapId);
|
const room = new Room(this, code, mapId, difficulty);
|
||||||
this.rooms.set(code, room);
|
this.rooms.set(code, room);
|
||||||
room.log('created (map ' + mapId + '); ' + this.rooms.size + ' room(s)');
|
room.log('created (map ' + mapId + ', ' + room.sim.difficulty + '); ' + this.rooms.size + ' room(s)');
|
||||||
this.startLoop();
|
this.startLoop();
|
||||||
return room;
|
return room;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
112
test/balance.test.js
Normal file
112
test/balance.test.js
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Design invariants of the tuned numbers (docs/BALANCE.md). These do NOT pin tuned values: every expectation is derived from the
|
||||||
|
* TOWERS / ENEMIES / DIFFICULTIES tables and the wave functions, and states a relationship the balance pass relies on. When a future
|
||||||
|
* pass retunes a number and one of these fails, either the pass broke a design rule (fix the number) or the rule moved (change it here
|
||||||
|
* and in docs/BALANCE.md together).
|
||||||
|
*/
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const TD = require('../public/js/sim.js');
|
||||||
|
const { TOWERS, ENEMIES, Sim, STEP } = TD;
|
||||||
|
|
||||||
|
// Everything a defence is paid for clearing waves 1..n on a difficulty (the opening credits + every kill + every clear bonus).
|
||||||
|
function income(n, difficulty) {
|
||||||
|
const dm = TD.DIFFICULTIES[difficulty || 'normal'];
|
||||||
|
let c = Math.round(TD.START_GOLD * dm.gold);
|
||||||
|
for (let w = 1; w <= n; w++) {
|
||||||
|
for (const g of TD.waveGroups(w)) c += g.c * Math.max(1, Math.round(ENEMIES[g.k].reward * TD.rewardScale(w) * dm.reward));
|
||||||
|
c += TD.clearBonus(w);
|
||||||
|
}
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
const dps = (lv) => lv.dmg * lv.rate;
|
||||||
|
|
||||||
|
test('the clear bonus is what the sim pays, and the same on every difficulty', () => {
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const s = new Sim({ map: 'open', gold: 0, difficulty: id, winWave: 99 });
|
||||||
|
for (let w = 1; w <= 3; w++) {
|
||||||
|
s.startWave(); s.spawnQ.length = 0; s.monsters.length = 0;
|
||||||
|
const g = s.gold; s.tick(STEP);
|
||||||
|
assert.equal(s.gold - g, TD.clearBonus(w), id + ' wave ' + w + ' pays clearBonus(' + w + ')');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (let w = 2; w <= 60; w++) assert.ok(TD.clearBonus(w) >= TD.clearBonus(w - 1), 'the bonus never shrinks');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('economy: the credits a whole run pays are bounded, so they stay a constraint, and not starved either', () => {
|
||||||
|
const total = income(TD.WIN_WAVE) / TD.START_GOLD;
|
||||||
|
assert.ok(total <= 46, 'clearing 30 waves pays at most about 46 opening purses (the untuned game paid 55): ' + total.toFixed(1));
|
||||||
|
assert.ok(total >= 25, 'and at least 25, or credits starve');
|
||||||
|
// the snowball: late waves may pay more per wave, but the last ten must not pay more than the first twenty put together
|
||||||
|
const last10 = income(TD.WIN_WAVE) - income(TD.WIN_WAVE - 10), first20 = income(20) - income(0);
|
||||||
|
assert.ok(last10 <= first20 * 1.5, 'waves 21-30 pay ' + last10 + ' against ' + first20 + ' for waves 1-20');
|
||||||
|
// a harder game pays less, an easier one more, wave for wave
|
||||||
|
for (let n = 5; n <= 30; n += 5) assert.ok(income(n, 'easy') > income(n) && income(n) > income(n, 'hard'), 'income order at wave ' + n);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bosses are dangerous but are not a payday', () => {
|
||||||
|
const boss = ENEMIES.rootkit;
|
||||||
|
for (const k of TD.ENEMY_ORDER) {
|
||||||
|
if (k === 'rootkit') continue;
|
||||||
|
const e = ENEMIES[k];
|
||||||
|
assert.ok(boss.reward / boss.hp <= e.reward / (e.hp + (e.shield || 0)) + 1e-9, 'a rootkit pays no better per hit point than a ' + k);
|
||||||
|
}
|
||||||
|
for (let w = 10; w <= 60; w += 10) {
|
||||||
|
let bosses = 0;
|
||||||
|
for (const g of TD.waveGroups(w)) if (g.k === 'rootkit') bosses += g.c * Math.max(1, Math.round(ENEMIES.rootkit.reward * TD.rewardScale(w)));
|
||||||
|
assert.ok(bosses > 0, 'wave ' + w + ' has bosses');
|
||||||
|
assert.ok(bosses <= 0.09 * income(w), 'the bosses of wave ' + w + ' pay ' + bosses + ' credits, ' + (100 * bosses / income(w)).toFixed(1) + '% of everything earned so far (the untuned game: 12%)');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('upgrades are a fair deal next to buying another tower, and a real sink', () => {
|
||||||
|
for (const k of ['filter', 'ids', 'mortar', 'arc']) {
|
||||||
|
const L = TOWERS[k].levels, base = dps(L[0]) / L[0].cost;
|
||||||
|
for (let i = 1; i < L.length; i++) {
|
||||||
|
const per = (dps(L[i]) - dps(L[i - 1])) / L[i].cost;
|
||||||
|
assert.ok(per >= 0.5 * base, k + ' L' + (i + 1) + ': an upgrade gives at least half the dps per credit of a new L1 (' + (per / base).toFixed(2) + 'x)');
|
||||||
|
assert.ok(per <= 1.3 * base, k + ' L' + (i + 1) + ': and is not so cheap that nobody buys a second tower (' + (per / base).toFixed(2) + 'x)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// a fully upgraded tower costs clearly more than its first level: upgrading is where late credits go
|
||||||
|
for (const k of TD.TOWER_ORDER) {
|
||||||
|
if (k === 'wall') continue;
|
||||||
|
const L = TOWERS[k].levels;
|
||||||
|
assert.ok(L.reduce((a, l) => a + l.cost, 0) >= 2 * L[0].cost, k + ' upgrades add at least as much as the tower itself');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('roles: the IDS Sniper is the heavy slow shot, so swarms are for the other towers', () => {
|
||||||
|
const ids = TOWERS.ids.levels;
|
||||||
|
for (const k of ['filter', 'mortar', 'arc']) {
|
||||||
|
TOWERS[k].levels.forEach((lv, i) => {
|
||||||
|
assert.ok(ids[i].dmg > lv.dmg, 'IDS L' + (i + 1) + ' hits harder than ' + k + ' L' + (i + 1));
|
||||||
|
assert.ok(ids[i].rate < lv.rate, 'and fires slower, so a swarm of 1-hit packets is not its job (' + k + ')');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const reach = Math.max(...['filter', 'mortar', 'arc'].map((k) => Math.max(...TOWERS[k].levels.map((l) => l.range))));
|
||||||
|
assert.ok(ids[0].range > reach * 0.9, 'it out-ranges the other attack towers (a level 1 IDS against their best)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('flyers: the botnet drone is still the fast swarm and the Spoof the slower, tougher flyer', () => {
|
||||||
|
assert.ok(ENEMIES.botnet.speed > ENEMIES.ghost.speed, 'a botnet drone is faster than a Spoof');
|
||||||
|
assert.ok(ENEMIES.botnet.hp < ENEMIES.ghost.hp, 'and has far fewer hit points');
|
||||||
|
for (const k of TD.ENEMY_ORDER) if (ENEMIES[k].air) assert.ok(ENEMIES[k].speed >= ENEMIES.rootkit.speed, k + ' flies at least as fast as the slowest boss walks');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the Orbital Uplink stays a luxury: about a quarter of what a run pays, never a carpet of them', () => {
|
||||||
|
const first = TD.priceFor('uplink', 0), total = income(TD.WIN_WAVE);
|
||||||
|
assert.ok(first >= 0.2 * total && first <= 0.4 * total, 'the first Uplink costs ' + (100 * first / total).toFixed(0) + '% of the 30-wave economy');
|
||||||
|
let three = 0; for (let n = 0; n < 4; n++) three += TD.priceFor('uplink', n);
|
||||||
|
assert.ok(three > total, 'four Uplinks cost more than a whole 30-wave run pays');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('difficulty rows are a ladder of the whole game, not only of the first minute', () => {
|
||||||
|
const E = TD.DIFFICULTIES.easy, H = TD.DIFFICULTIES.hard;
|
||||||
|
const power = (d) => d.hp > 0 ? d.reward / d.hp : 0; // credits earned per hit point of enemy, the long-run strength of a defence
|
||||||
|
assert.ok(power(E) / power(TD.DIFFICULTIES.normal) >= 1.2, 'easy is clearly easier than normal');
|
||||||
|
assert.ok(power(TD.DIFFICULTIES.normal) / power(H) >= 1.05, 'hard is clearly harder than normal');
|
||||||
|
assert.ok(power(E) / power(H) <= 2.0, 'but the two ends are not a different game');
|
||||||
|
assert.ok(Math.round(TD.START_LIVES * H.lives) >= 10, 'hard still leaves room for a couple of leaks');
|
||||||
|
});
|
||||||
493
test/difficulty.test.js
Normal file
493
test/difficulty.test.js
Normal file
|
|
@ -0,0 +1,493 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Difficulty (Easy / Normal / Hard): the rules in sim.js, the create-room / newgame option on the server, and the two controllers.
|
||||||
|
* Expected numbers are derived from TD.DIFFICULTIES (the balance pass retunes the table), only the relationships between the rows
|
||||||
|
* (easy is more generous than normal, normal than hard) and "normal is the base tables with every multiplier at 1" are pinned.
|
||||||
|
*/
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
const TD = require('../public/js/sim.js');
|
||||||
|
const { createServer } = require('../server');
|
||||||
|
|
||||||
|
const { Sim, ENEMIES, STEP, DIFFICULTIES } = TD;
|
||||||
|
const NOT_DIFFICULTIES = ['nope', '', 'EASY', ' hard', 'toString', '__proto__', 'constructor', 'hasOwnProperty', 42, true, {}, []];
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- the table
|
||||||
|
test('DIFFICULTIES: easy, normal and hard, in that order; normal is the base game (all multipliers 1); the others lean the right way', () => {
|
||||||
|
assert.deepEqual(TD.DIFFICULTY_ORDER.slice(0, 3), ['easy', 'normal', 'hard']);
|
||||||
|
assert.equal(TD.DEFAULT_DIFFICULTY, 'normal');
|
||||||
|
assert.deepEqual(Object.keys(DIFFICULTIES).sort(), TD.DIFFICULTY_ORDER.slice().sort(), 'the order lists exactly the table\'s rows');
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const d = DIFFICULTIES[id];
|
||||||
|
assert.equal(d.id, id);
|
||||||
|
assert.ok(typeof d.name === 'string' && d.name.length > 0, id + ' has a name');
|
||||||
|
for (const k of ['gold', 'lives', 'hp', 'reward']) assert.ok(Number.isFinite(d[k]) && d[k] > 0, id + '.' + k + ' is a positive multiplier');
|
||||||
|
}
|
||||||
|
for (const k of ['gold', 'lives', 'hp', 'reward']) assert.equal(DIFFICULTIES.normal[k], 1, 'normal.' + k + ' is 1: normal plays the base tables as they are');
|
||||||
|
const E = DIFFICULTIES.easy, N = DIFFICULTIES.normal, H = DIFFICULTIES.hard;
|
||||||
|
for (const k of ['gold', 'lives', 'reward']) assert.ok(E[k] >= N[k] && N[k] >= H[k] && E[k] > H[k], k + ': easy gives more than normal, normal more than hard');
|
||||||
|
assert.ok(E.hp <= N.hp && N.hp <= H.hp && E.hp < H.hp, 'hp: easy packets are weaker than normal, hard ones tougher');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('isDifficulty / difficultyId only accept the table\'s own ids', () => {
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) { assert.equal(TD.isDifficulty(id), true); assert.equal(TD.difficultyId(id), id); }
|
||||||
|
for (const v of NOT_DIFFICULTIES.concat([undefined, null])) {
|
||||||
|
assert.equal(TD.isDifficulty(v), false, JSON.stringify(v));
|
||||||
|
assert.equal(TD.difficultyId(v), 'normal', 'anything else is normal: ' + JSON.stringify(v));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- the sim
|
||||||
|
test('a Sim without a difficulty, or with an unknown one, is a normal game', () => {
|
||||||
|
const plain = new Sim({ map: 'open' });
|
||||||
|
assert.equal(plain.difficulty, 'normal');
|
||||||
|
assert.equal(plain.gold, TD.START_GOLD);
|
||||||
|
assert.equal(plain.lives, TD.START_LIVES);
|
||||||
|
assert.equal(new Sim().difficulty, 'normal', 'no options at all');
|
||||||
|
for (const v of NOT_DIFFICULTIES.concat([undefined, null])) {
|
||||||
|
const s = new Sim({ map: 'open', difficulty: v });
|
||||||
|
assert.equal(s.difficulty, 'normal', JSON.stringify(v));
|
||||||
|
assert.equal(s.gold, plain.gold); assert.equal(s.lives, plain.lives); assert.equal(s.maxLives, plain.maxLives);
|
||||||
|
assert.equal(s.fullState().difficulty, 'normal');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('starting credits and lives follow the table; an explicit gold / lives is used as given', () => {
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const d = DIFFICULTIES[id], s = new Sim({ map: 'open', difficulty: id });
|
||||||
|
assert.equal(s.difficulty, id);
|
||||||
|
assert.equal(s.gold, Math.round(TD.START_GOLD * d.gold), id + ' credits');
|
||||||
|
assert.equal(s.lives, Math.max(1, Math.round(TD.START_LIVES * d.lives)), id + ' lives');
|
||||||
|
assert.equal(s.maxLives, s.lives, id + ': the integrity bar is full at the start');
|
||||||
|
assert.equal(s.snapshot().g, s.gold); assert.equal(s.snapshot().l, s.lives);
|
||||||
|
const given = new Sim({ map: 'open', difficulty: id, gold: 1234, lives: 7 });
|
||||||
|
assert.equal(given.gold, 1234); assert.equal(given.lives, 7); assert.equal(given.maxLives, 7);
|
||||||
|
assert.equal(given.difficulty, id, 'the difficulty still applies to the packets');
|
||||||
|
}
|
||||||
|
const [e, n, h] = ['easy', 'normal', 'hard'].map((id) => new Sim({ map: 'open', difficulty: id }));
|
||||||
|
assert.ok(e.gold > n.gold && n.gold > h.gold, 'more credits on easy than on normal than on hard');
|
||||||
|
assert.ok(e.lives > n.lives && n.lives > h.lives, 'and more lives');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the table drives everything: a made-up row with tiny multipliers still leaves one life, a hit point and a credit per kill', () => {
|
||||||
|
DIFFICULTIES.tiny = { id: 'tiny', name: 'Tiny', gold: 0.001, lives: 0.001, hp: 0.001, reward: 0.001 };
|
||||||
|
try {
|
||||||
|
assert.equal(TD.isDifficulty('tiny'), true);
|
||||||
|
const s = new Sim({ map: 'open', difficulty: 'tiny' });
|
||||||
|
assert.equal(s.lives, 1, 'a game always starts with at least one life');
|
||||||
|
assert.equal(s.maxLives, 1);
|
||||||
|
assert.equal(s.gold, 0);
|
||||||
|
s.spawnMonster({ k: 'spam', wave: 1 });
|
||||||
|
assert.ok(s.monsters[0].hp >= 1 && s.monsters[0].reward >= 1, 'a packet always has hit points and pays at least one credit');
|
||||||
|
} finally { delete DIFFICULTIES.tiny; }
|
||||||
|
assert.equal(TD.isDifficulty('tiny'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
// A packet of `kind` on wave `wave`, as the sim spawns it.
|
||||||
|
function spawned(difficulty, kind, wave) {
|
||||||
|
const s = new Sim({ map: 'open', difficulty });
|
||||||
|
s.spawnMonster({ k: kind, wave });
|
||||||
|
return s.monsters[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
test('normal packets are exactly the base tables (hp, shield and reward: the multiplier is 1)', () => {
|
||||||
|
for (const kind of TD.ENEMY_ORDER) {
|
||||||
|
for (const wave of [1, 7, 20, 45]) {
|
||||||
|
const def = ENEMIES[kind], m = spawned('normal', kind, wave), dflt = spawned(undefined, kind, wave);
|
||||||
|
assert.equal(m.maxhp, Math.round(def.hp * TD.hpScale(wave)), kind + ' hp on wave ' + wave);
|
||||||
|
assert.equal(m.maxShield, def.shield ? Math.round(def.shield * TD.hpScale(wave)) : 0, kind + ' shield');
|
||||||
|
assert.equal(m.reward, Math.max(1, Math.round(def.reward * TD.rewardScale(wave))), kind + ' reward');
|
||||||
|
assert.deepEqual([dflt.maxhp, dflt.maxShield, dflt.reward], [m.maxhp, m.maxShield, m.reward], 'no difficulty is normal');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('enemy hit points and shields scale with the difficulty\'s hp multiplier', () => {
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const d = DIFFICULTIES[id];
|
||||||
|
for (const kind of ['ping', 'trojan', 'rootkit', 'proxy']) {
|
||||||
|
for (const wave of [1, 12, 30]) {
|
||||||
|
const def = ENEMIES[kind], m = spawned(id, kind, wave);
|
||||||
|
assert.equal(m.maxhp, Math.max(1, Math.round(def.hp * TD.hpScale(wave) * d.hp)), id + ' ' + kind + ' hp, wave ' + wave);
|
||||||
|
assert.equal(m.hp, m.maxhp);
|
||||||
|
assert.equal(m.maxShield, def.shield ? Math.round(def.shield * TD.hpScale(wave) * d.hp) : 0, id + ' ' + kind + ' shield');
|
||||||
|
assert.equal(m.shield, m.maxShield);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const [e, n, h] = ['easy', 'normal', 'hard'].map((id) => spawned(id, 'trojan', 10));
|
||||||
|
assert.ok(e.maxhp < n.maxhp && n.maxhp < h.maxhp, 'a Trojan is softer on easy and tougher on hard');
|
||||||
|
// the wire sends hp + shield out of maxhp + maxShield and the client splits it by the kind's base ratio: scaling both keeps the split
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const m = spawned(id, 'proxy', 20), def = ENEMIES.proxy;
|
||||||
|
assert.ok(Math.abs(m.maxShield / (m.maxhp + m.maxShield) - def.shield / (def.hp + def.shield)) < 0.01, id + ': the shield keeps its share of the total');
|
||||||
|
}
|
||||||
|
// other stats are not touched
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) { const m = spawned(id, 'rootkit', 10); assert.equal(m.speed, ENEMIES.rootkit.speed); assert.equal(m.armor, ENEMIES.rootkit.armor); assert.equal(m.leak, ENEMIES.rootkit.leak); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a kill pays the reward multiplier of the difficulty (checked on kinds that pay more than a credit)', () => {
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const d = DIFFICULTIES[id];
|
||||||
|
for (const kind of ['rootkit', 'trojan', 'proxy']) {
|
||||||
|
for (const wave of [10, 25]) {
|
||||||
|
const def = ENEMIES[kind], m = spawned(id, kind, wave);
|
||||||
|
assert.equal(m.reward, Math.max(1, Math.round(def.reward * TD.rewardScale(wave) * d.reward)), id + ' ' + kind + ' reward, wave ' + wave);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const [e, n, h] = ['easy', 'normal', 'hard'].map((id) => spawned(id, 'rootkit', 10).reward);
|
||||||
|
assert.ok(e > n && n > h, `a boss pays ${e} / ${n} / ${h} credits on easy / normal / hard`);
|
||||||
|
// the credits really arrive when it dies
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const s = new Sim({ map: 'open', difficulty: id, gold: 0 });
|
||||||
|
s.spawnMonster({ k: 'rootkit', wave: 10 });
|
||||||
|
const m = s.monsters[0], want = m.reward;
|
||||||
|
s.damage(m, 1e9, null, true);
|
||||||
|
assert.equal(s.gold, want, id + ': the kill paid the packet\'s reward');
|
||||||
|
}
|
||||||
|
// the wave clear bonus is the same on every difficulty
|
||||||
|
const bonus = [];
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const s = new Sim({ map: 'open', difficulty: id, gold: 0 });
|
||||||
|
s.startWave(); s.spawnQ.length = 0;
|
||||||
|
s.tick(STEP);
|
||||||
|
bonus.push(s.gold);
|
||||||
|
}
|
||||||
|
assert.equal(new Set(bonus).size, 1, 'the clear bonus does not depend on the difficulty: ' + bonus);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a whole wave of the real game: the same packets come, with the difficulty\'s hit points', () => {
|
||||||
|
const hp = {};
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const s = new Sim({ map: 'open', difficulty: id });
|
||||||
|
s.cmd({ c: 'wave' });
|
||||||
|
for (let i = 0; i < 60 * 8 && s.spawnQ.length; i++) s.tick(STEP); // 8 s: the first group of pings is out
|
||||||
|
assert.ok(s.monsters.length > 0 || s.leaks > 0);
|
||||||
|
const m = s.monsters.find((x) => x.kind === 'ping') || s.monsters[0];
|
||||||
|
assert.ok(m, id + ' has a packet on the board');
|
||||||
|
hp[id] = m.maxhp;
|
||||||
|
assert.equal(m.maxhp, Math.round(ENEMIES[m.kind].hp * TD.hpScale(1) * DIFFICULTIES[id].hp));
|
||||||
|
}
|
||||||
|
assert.ok(hp.easy < hp.normal && hp.normal < hp.hard);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fullState carries the difficulty (additively), the snapshot keeps its shape, and both survive JSON', () => {
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const s = new Sim({ map: 'twin', difficulty: id });
|
||||||
|
const fs1 = s.fullState();
|
||||||
|
assert.equal(fs1.difficulty, id);
|
||||||
|
for (const k of ['map', 'rev', 'towers', 'winWave', 'maxLives']) assert.ok(k in fs1, 'the old field ' + k + ' is still there');
|
||||||
|
assert.equal(fs1.maxLives, s.maxLives);
|
||||||
|
assert.deepEqual(JSON.parse(JSON.stringify(fs1)), fs1);
|
||||||
|
assert.ok(!('difficulty' in s.snapshot()), 'the per-tick snapshot does not repeat it');
|
||||||
|
s.cmd({ c: 'wave' }); for (let i = 0; i < 200; i++) s.tick(STEP);
|
||||||
|
assert.equal(s.fullState().difficulty, id, 'it never changes during a game');
|
||||||
|
JSON.stringify(s.snapshot());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- Orbital Uplink price growth (the user's request: slightly dearer per unit owned)
|
||||||
|
test('Orbital Uplink: each one you own makes the next a little dearer than it used to (more than 25%, still modest), upgrades by the same factor', () => {
|
||||||
|
const up = TD.TOWERS.uplink;
|
||||||
|
assert.ok(up.priceGrowth > 1.25, 'the growth per Uplink owned went up from 25%');
|
||||||
|
assert.ok(up.priceGrowth <= 1.4, 'but it is a slight increase');
|
||||||
|
assert.ok(up.desc.includes(Math.round((up.priceGrowth - 1) * 100) + '%'), 'the description quotes the real percentage: ' + up.desc);
|
||||||
|
assert.ok(!/25%/.test(up.desc), 'and not the old one');
|
||||||
|
const base = up.levels[0].cost;
|
||||||
|
for (let n = 1; n <= 5; n++) {
|
||||||
|
const price = TD.priceFor('uplink', n), prev = TD.priceFor('uplink', n - 1);
|
||||||
|
assert.ok(price / prev > 1.25, 'Uplink number ' + (n + 1) + ' costs more than 25% over the one before (' + prev + ' -> ' + price + ')');
|
||||||
|
assert.ok(Math.abs(price - Math.round(base * Math.pow(up.priceGrowth, n) / 10) * 10) <= 10, 'it follows the growth rate');
|
||||||
|
}
|
||||||
|
// the buying price and the upgrade price rise by the SAME factor, in the sim as well as in the helpers
|
||||||
|
const s = new Sim({ map: 'open', gold: 1e7 });
|
||||||
|
const towers = [4, 8, 12].map((x) => s.towerById(s.place('uplink', x, 6).id));
|
||||||
|
towers.forEach((t, i) => {
|
||||||
|
assert.ok(Math.abs(t.pm - Math.pow(up.priceGrowth, i)) < 1e-9);
|
||||||
|
for (let lv = 1; lv < up.levels.length; lv++) {
|
||||||
|
const got = TD.upgradePrice('uplink', lv, t.pm), want = up.levels[lv].cost * Math.pow(up.priceGrowth, i);
|
||||||
|
assert.ok(Math.abs(got - want) <= 5 + 1e-9, `upgrade ${lv} of Uplink ${i + 1} costs ${got}, expected about ${want}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const buyRatio = TD.priceFor('uplink', 2) / TD.priceFor('uplink', 0), upRatio = TD.upgradePrice('uplink', 1, towers[2].pm) / TD.upgradePrice('uplink', 1, towers[0].pm);
|
||||||
|
assert.ok(Math.abs(buyRatio - upRatio) < 0.01, 'buying and upgrading get dearer by the same factor: ' + buyRatio + ' vs ' + upRatio);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- the server
|
||||||
|
const noop = () => {};
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
let pidN = 0;
|
||||||
|
const newPid = () => 'diffpid' + String(++pidN).padStart(6, '0');
|
||||||
|
async function until(fn, ms = 3000, label = 'condition') {
|
||||||
|
const end = Date.now() + ms;
|
||||||
|
for (;;) { const v = fn(); if (v) return v; if (Date.now() > end) throw new Error('timed out waiting for ' + label); await sleep(4); }
|
||||||
|
}
|
||||||
|
class Client {
|
||||||
|
constructor(url) {
|
||||||
|
this.msgs = []; this.pos = 0; this.closeInfo = null; this.opened = false;
|
||||||
|
const ws = this.ws = new WebSocket(url);
|
||||||
|
ws.on('open', () => { this.opened = true; });
|
||||||
|
ws.on('message', (d) => { this.msgs.push(JSON.parse(d.toString())); });
|
||||||
|
ws.on('close', (code) => { this.closeInfo = { code }; });
|
||||||
|
ws.on('error', noop);
|
||||||
|
}
|
||||||
|
async open() { await until(() => this.opened || this.closeInfo, 3000, 'open'); return this; }
|
||||||
|
send(o) { this.ws.send(JSON.stringify(o)); }
|
||||||
|
next(pred, ms = 3000, label = 'message') {
|
||||||
|
return until(() => { for (let i = this.pos; i < this.msgs.length; i++) if (pred(this.msgs[i])) { this.pos = i + 1; return this.msgs[i]; } return null; }, ms, label);
|
||||||
|
}
|
||||||
|
type(t) { return this.next((m) => m.t === t, 3000, t); }
|
||||||
|
async barrier() { const ts = Math.random(); this.send({ t: 'rtt', ts }); await this.next((m) => m.t === 'rtt' && m.ts === ts, 3000, 'barrier'); }
|
||||||
|
}
|
||||||
|
async function withServer(fn) {
|
||||||
|
const srv = await createServer({ port: 0, host: '127.0.0.1', log: noop, graceMs: 400, pingMs: 0 });
|
||||||
|
const clients = [];
|
||||||
|
const S = {
|
||||||
|
srv,
|
||||||
|
async join(extra) {
|
||||||
|
const c = new Client('ws://127.0.0.1:' + srv.port + '/ws'); clients.push(c);
|
||||||
|
await c.open();
|
||||||
|
c.send(Object.assign({ t: 'join', pid: newPid(), name: 'P' }, extra));
|
||||||
|
const r = await c.next((m) => m.t === 'joined' || m.t === 'error', 3000, 'joined');
|
||||||
|
return { c, r };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
try { return await fn(S); } finally { for (const c of clients) { try { c.ws.terminate(); } catch (e) { /* ignore */ } } await srv.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('server: create-room takes a difficulty (default normal) and tells everyone in the state', async () => {
|
||||||
|
await withServer(async (S) => {
|
||||||
|
const none = await S.join({});
|
||||||
|
assert.equal(none.r.state.difficulty, 'normal', 'no option: normal');
|
||||||
|
assert.equal(S.srv.rooms.get(none.r.room).sim.difficulty, 'normal');
|
||||||
|
const nul = await S.join({ difficulty: null });
|
||||||
|
assert.equal(nul.r.state.difficulty, 'normal', 'null is "not given"');
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const d = DIFFICULTIES[id];
|
||||||
|
const host = await S.join({ map: 'twin', difficulty: id });
|
||||||
|
assert.equal(host.r.t, 'joined', id);
|
||||||
|
assert.equal(host.r.state.difficulty, id);
|
||||||
|
assert.equal(host.r.state.map, 'twin', 'the map option is untouched');
|
||||||
|
assert.equal(host.r.snap.g, Math.round(TD.START_GOLD * d.gold), id + ' credits in the first snapshot');
|
||||||
|
assert.equal(host.r.snap.l, Math.max(1, Math.round(TD.START_LIVES * d.lives)), id + ' lives');
|
||||||
|
assert.equal(host.r.state.maxLives, host.r.snap.l);
|
||||||
|
assert.equal(S.srv.rooms.get(host.r.room).sim.difficulty, id);
|
||||||
|
// a joiner gets the room's difficulty in its own joined message
|
||||||
|
const guest = await S.join({ room: host.r.room });
|
||||||
|
assert.equal(guest.r.state.difficulty, id, id + ': the guest sees the host\'s choice');
|
||||||
|
assert.equal(guest.r.snap.g, host.r.snap.g);
|
||||||
|
// ... and in a sync
|
||||||
|
guest.c.send({ t: 'sync' });
|
||||||
|
assert.equal((await guest.c.type('state')).state.difficulty, id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('server: a bad difficulty is refused like a bad map (bad_difficulty, closed, no room left behind)', async () => {
|
||||||
|
await withServer(async (S) => {
|
||||||
|
for (const bad of NOT_DIFFICULTIES) {
|
||||||
|
const { c, r } = await S.join({ difficulty: bad });
|
||||||
|
assert.equal(r.t, 'error', JSON.stringify(bad));
|
||||||
|
assert.equal(r.code, 'bad_difficulty', JSON.stringify(bad));
|
||||||
|
assert.equal(typeof r.msg, 'string');
|
||||||
|
assert.ok((await until(() => c.closeInfo, 3000, 'close')).code >= 4000);
|
||||||
|
}
|
||||||
|
assert.equal(S.srv.rooms.size, 0, 'a refused create leaves no room');
|
||||||
|
const both = await S.join({ map: 'nope', difficulty: 'nope' });
|
||||||
|
assert.equal(both.r.code, 'bad_map', 'the map is checked first');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('server: only a creating join carries a difficulty; joining a room takes the room\'s', async () => {
|
||||||
|
await withServer(async (S) => {
|
||||||
|
const host = await S.join({ difficulty: 'hard' });
|
||||||
|
const guest = await S.join({ room: host.r.room, difficulty: 'easy' });
|
||||||
|
assert.equal(guest.r.t, 'joined');
|
||||||
|
assert.equal(guest.r.state.difficulty, 'hard');
|
||||||
|
assert.equal(S.srv.rooms.get(host.r.room).sim.difficulty, 'hard');
|
||||||
|
const odd = await S.join({ room: host.r.room, difficulty: 'nope' }); // (the room is full, but a bogus field must not matter first)
|
||||||
|
assert.notEqual(odd.r.code, 'bad_difficulty');
|
||||||
|
// a reconnect (same pid) gets the room's difficulty again
|
||||||
|
const pid = newPid();
|
||||||
|
const first = await S.join({ pid, difficulty: 'easy' });
|
||||||
|
first.c.ws.terminate();
|
||||||
|
await until(() => S.srv.rooms.get(first.r.room).players[0].conn === null, 2000, 'the socket is gone');
|
||||||
|
const back = await S.join({ pid, room: first.r.room });
|
||||||
|
assert.equal(back.r.resumed, true);
|
||||||
|
assert.equal(back.r.state.difficulty, 'easy');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('server: the host\'s newgame may carry a difficulty; none keeps the room\'s; a bad one is rejected and changes nothing', async () => {
|
||||||
|
await withServer(async (S) => {
|
||||||
|
const a = await S.join({ name: 'Alice', difficulty: 'easy' });
|
||||||
|
const b = await S.join({ name: 'Bob', room: a.r.room });
|
||||||
|
await a.c.next((m) => m.t === 'players' && m.players.length === 2, 3000, 'two players');
|
||||||
|
const room = S.srv.rooms.get(a.r.room);
|
||||||
|
a.c.send({ t: 'cmd', c: 'place', type: 'wall', x: 2, y: 2 });
|
||||||
|
await a.c.next((m) => m.t === 'snap' && m.rev === 1, 3000, 'a wall');
|
||||||
|
|
||||||
|
// a non-host cannot, whatever it asks for
|
||||||
|
b.c.send({ t: 'newgame', difficulty: 'hard' });
|
||||||
|
assert.deepEqual(await b.c.type('reject'), { t: 'reject', c: 'newgame', reason: 'not_host' });
|
||||||
|
assert.equal(room.sim.difficulty, 'easy');
|
||||||
|
|
||||||
|
// a bad value: rejected, the running game is untouched, nobody gets a new state
|
||||||
|
for (const bad of ['nope', 7, '__proto__', {}]) {
|
||||||
|
a.c.send({ t: 'newgame', difficulty: bad });
|
||||||
|
assert.deepEqual(await a.c.type('reject'), { t: 'reject', c: 'newgame', reason: 'bad_difficulty' }, JSON.stringify(bad));
|
||||||
|
}
|
||||||
|
a.c.send({ t: 'newgame', map: 'nope', difficulty: 'hard' });
|
||||||
|
assert.equal((await a.c.type('reject')).reason, 'bad_map', 'the map is checked first');
|
||||||
|
await a.c.barrier();
|
||||||
|
assert.equal(room.sim.difficulty, 'easy'); assert.equal(room.sim.rev, 1, 'the wall is still there');
|
||||||
|
assert.equal(a.c.msgs.filter((m) => m.t === 'state').length, 0);
|
||||||
|
|
||||||
|
// switch to hard: both players get the new state, with the table's credits and lives
|
||||||
|
const hard = DIFFICULTIES.hard;
|
||||||
|
a.c.send({ t: 'newgame', difficulty: 'hard' });
|
||||||
|
for (const c of [a.c, b.c]) {
|
||||||
|
const st = await c.type('state');
|
||||||
|
assert.equal(st.newgame, true);
|
||||||
|
assert.equal(st.state.difficulty, 'hard');
|
||||||
|
assert.equal(st.state.map, 'open', 'the map stays when only the difficulty is given');
|
||||||
|
assert.deepEqual(st.state.towers, []);
|
||||||
|
assert.equal(st.snap.g, Math.round(TD.START_GOLD * hard.gold));
|
||||||
|
assert.equal(st.snap.l, Math.max(1, Math.round(TD.START_LIVES * hard.lives)));
|
||||||
|
assert.equal(st.state.maxLives, st.snap.l);
|
||||||
|
}
|
||||||
|
assert.equal(room.sim.difficulty, 'hard');
|
||||||
|
|
||||||
|
// no difficulty (Play again): it stays hard; a map change alone keeps it too
|
||||||
|
a.c.send({ t: 'newgame' });
|
||||||
|
assert.equal((await b.c.type('state')).state.difficulty, 'hard');
|
||||||
|
a.c.send({ t: 'newgame', map: 'hub' });
|
||||||
|
const st = await b.c.type('state');
|
||||||
|
assert.equal(st.state.map, 'hub'); assert.equal(st.state.difficulty, 'hard');
|
||||||
|
a.c.send({ t: 'newgame', map: 'hub', difficulty: 'normal' });
|
||||||
|
assert.equal((await b.c.type('state')).state.difficulty, 'normal');
|
||||||
|
assert.equal(room.sim.gold, TD.START_GOLD);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('server: the hard packets really are tougher in a running room', async () => {
|
||||||
|
await withServer(async (S) => {
|
||||||
|
const out = {};
|
||||||
|
for (const id of ['easy', 'hard']) {
|
||||||
|
const host = await S.join({ difficulty: id });
|
||||||
|
host.c.send({ t: 'cmd', c: 'wave' });
|
||||||
|
const snap = await host.c.next((m) => m.t === 'snap' && m.mo.length > 0, 5000, 'a packet on the board');
|
||||||
|
out[id] = snap.mo[0][5]; // maxhp of the first packet
|
||||||
|
}
|
||||||
|
assert.ok(out.easy < out.hard, `maxhp ${out.easy} on easy, ${out.hard} on hard`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- the controllers (browser code, run in a vm with a fake socket)
|
||||||
|
const CTRL_SRC = fs.readFileSync(path.join(__dirname, '..', 'public', 'js', 'controllers.js'), 'utf8');
|
||||||
|
function controllers() {
|
||||||
|
const sockets = [];
|
||||||
|
class FakeWS {
|
||||||
|
constructor(url) { this.url = url; this.readyState = 0; this.sent = []; sockets.push(this); }
|
||||||
|
send(s) { this.sent.push(JSON.parse(s)); }
|
||||||
|
close() { this.readyState = 3; }
|
||||||
|
open() { this.readyState = 1; if (this.onopen) this.onopen(); }
|
||||||
|
recv(o) { if (this.onmessage) this.onmessage({ data: JSON.stringify(o) }); }
|
||||||
|
}
|
||||||
|
const sb = {
|
||||||
|
TD, console, URL, WebSocket: FakeWS, document: { hidden: false, addEventListener() {}, removeEventListener() {} },
|
||||||
|
performance: { now: () => 1000 }, location: { href: 'http://localhost/index.html' }, addEventListener() {}, removeEventListener() {},
|
||||||
|
setTimeout: () => 1, clearTimeout() {}, setInterval: () => 1, clearInterval() {},
|
||||||
|
};
|
||||||
|
sb.self = sb;
|
||||||
|
vm.runInNewContext(CTRL_SRC, sb, { filename: 'controllers.js' });
|
||||||
|
return { NW: sb.NW, sockets };
|
||||||
|
}
|
||||||
|
function joined(sim, extra) {
|
||||||
|
return Object.assign({
|
||||||
|
t: 'joined', room: 'ABCD', resumed: false, you: { pid: 'pidpidpid1', slot: 0, host: true },
|
||||||
|
players: [{ pid: 'pidpidpid1', slot: 0, name: 'A', host: true, online: true }], state: sim.fullState(), snap: sim.snapshot(), speed: 1, paused: false,
|
||||||
|
}, extra);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('LocalController: starts on the chosen difficulty, keeps it for "Play again", changes it when asked', () => {
|
||||||
|
const { NW } = controllers();
|
||||||
|
const dflt = new NW.LocalController({ map: 'open' });
|
||||||
|
assert.equal(dflt.difficulty, 'normal'); assert.equal(dflt.view.difficulty, 'normal');
|
||||||
|
assert.equal(dflt.view.gold, TD.START_GOLD);
|
||||||
|
assert.equal(new NW.LocalController({ map: 'open', difficulty: 'bogus' }).difficulty, 'normal');
|
||||||
|
for (const id of TD.DIFFICULTY_ORDER) {
|
||||||
|
const d = DIFFICULTIES[id], c = new NW.LocalController({ map: 'twin', difficulty: id });
|
||||||
|
assert.equal(c.sim.difficulty, id);
|
||||||
|
assert.equal(c.view.difficulty, id);
|
||||||
|
assert.equal(c.view.gold, Math.round(TD.START_GOLD * d.gold));
|
||||||
|
assert.equal(c.view.lives, Math.max(1, Math.round(TD.START_LIVES * d.lives)));
|
||||||
|
assert.equal(c.view.maxLives, c.view.lives);
|
||||||
|
c.sim.gold = 1; c.sim.lives = 1;
|
||||||
|
let fired = 0; c.on('newgame', () => fired++);
|
||||||
|
c.newGame(c.mapId); // Play again
|
||||||
|
assert.equal(fired, 1);
|
||||||
|
assert.equal(c.difficulty, id, id + ' survives Play again'); assert.equal(c.view.difficulty, id);
|
||||||
|
assert.equal(c.view.gold, Math.round(TD.START_GOLD * d.gold), 'a fresh game: the credits are back');
|
||||||
|
c.newGame('open', id);
|
||||||
|
assert.equal(c.sim.difficulty, id);
|
||||||
|
}
|
||||||
|
const c = new NW.LocalController({ map: 'open', difficulty: 'hard' });
|
||||||
|
c.newGame('open', 'easy');
|
||||||
|
assert.equal(c.sim.difficulty, 'easy'); assert.equal(c.view.difficulty, 'easy'); assert.equal(c.view.lives, Math.round(TD.START_LIVES * DIFFICULTIES.easy.lives));
|
||||||
|
c.newGame('open', 'nonsense');
|
||||||
|
assert.equal(c.sim.difficulty, 'normal', 'an unknown one is normal, like the sim says');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('RemoteController: a creating join asks for the difficulty, a joining one does not; the state decides what the view shows', () => {
|
||||||
|
const { NW, sockets } = controllers();
|
||||||
|
const create = new NW.RemoteController({ pid: 'pidpidpid1', name: 'A', room: null, map: 'hub', difficulty: 'hard', url: 'ws://x/ws' });
|
||||||
|
create.connect(); sockets[0].open();
|
||||||
|
assert.deepEqual(sockets[0].sent[0], { t: 'join', pid: 'pidpidpid1', name: 'A', map: 'hub', difficulty: 'hard' });
|
||||||
|
const defaulted = new NW.RemoteController({ pid: 'pidpidpid2', name: 'A', room: null, map: 'open', url: 'ws://x/ws' });
|
||||||
|
defaulted.connect(); sockets[1].open();
|
||||||
|
assert.equal(sockets[1].sent[0].difficulty, 'normal');
|
||||||
|
const join = new NW.RemoteController({ pid: 'pidpidpid3', name: 'B', room: 'ABCD', difficulty: 'hard', url: 'ws://x/ws' });
|
||||||
|
join.connect(); sockets[2].open();
|
||||||
|
assert.deepEqual(sockets[2].sent[0], { t: 'join', pid: 'pidpidpid3', name: 'B', room: 'ABCD' }, 'no map, no difficulty when joining');
|
||||||
|
|
||||||
|
// the server's state is the truth (the guest asked for nothing, the room is easy)
|
||||||
|
const sim = new TD.Sim({ map: 'open', difficulty: 'easy' });
|
||||||
|
sockets[2].recv(joined(sim));
|
||||||
|
assert.equal(join.difficulty, 'easy'); assert.equal(join.view.difficulty, 'easy');
|
||||||
|
assert.equal(join.maxLives, sim.maxLives);
|
||||||
|
// a new game on another difficulty arrives as a state message
|
||||||
|
const sim2 = new TD.Sim({ map: 'open', difficulty: 'hard' });
|
||||||
|
let newgames = 0; join.on('newgame', () => newgames++);
|
||||||
|
sockets[2].recv({ t: 'state', state: sim2.fullState(), snap: sim2.snapshot(), speed: 1, paused: false, newgame: true });
|
||||||
|
assert.equal(newgames, 1); assert.equal(join.view.difficulty, 'hard'); assert.equal(join.maxLives, sim2.maxLives);
|
||||||
|
// an older server sends no difficulty: normal
|
||||||
|
const old = sim.fullState(); delete old.difficulty;
|
||||||
|
sockets[2].recv({ t: 'state', state: old, snap: sim.snapshot(), speed: 1, paused: false });
|
||||||
|
assert.equal(join.view.difficulty, 'normal');
|
||||||
|
// a reconnect of the creator no longer carries the options (it has a room by then)
|
||||||
|
sockets[0].recv(joined(sim, { room: 'WXYZ' }));
|
||||||
|
assert.equal(create.room, 'WXYZ');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('RemoteController: newGame sends the difficulty only when one is given; bad_difficulty has a message', () => {
|
||||||
|
const { NW, sockets } = controllers();
|
||||||
|
const rc = new NW.RemoteController({ pid: 'pidpidpid1', name: 'A', room: 'ABCD', url: 'ws://x/ws' });
|
||||||
|
rc.connect(); sockets[0].open();
|
||||||
|
sockets[0].recv(joined(new TD.Sim({ map: 'open' })));
|
||||||
|
rc.newGame('hub');
|
||||||
|
rc.newGame('hub', 'hard');
|
||||||
|
const ng = sockets[0].sent.filter((m) => m.t === 'newgame');
|
||||||
|
assert.deepEqual(ng[0], { t: 'newgame', map: 'hub' }, 'no difficulty: the server keeps the room\'s');
|
||||||
|
assert.deepEqual(ng[1], { t: 'newgame', map: 'hub', difficulty: 'hard' });
|
||||||
|
const rc2 = new NW.RemoteController({ pid: 'pidpidpid5', name: 'A', room: null, url: 'ws://x/ws' });
|
||||||
|
let fatal = null; rc2.on('fatal', (f) => { fatal = f; });
|
||||||
|
rc2.connect(); sockets[1].open();
|
||||||
|
sockets[1].recv({ t: 'error', code: 'bad_difficulty', msg: 'unknown difficulty' });
|
||||||
|
assert.equal(fatal.code, 'bad_difficulty'); assert.match(fatal.msg, /difficulty/i);
|
||||||
|
});
|
||||||
|
|
@ -699,9 +699,10 @@ test('Load Balancer: cooldowns really elapse faster, so a boosted tower fires mo
|
||||||
a.s.tick(0.1); b.s.tick(0.1);
|
a.s.tick(0.1); b.s.tick(0.1);
|
||||||
assert.ok(Math.abs(a.t.cd - 0.9) < 1e-9);
|
assert.ok(Math.abs(a.t.cd - 0.9) < 1e-9);
|
||||||
assert.ok(Math.abs(b.t.cd - (1 - 0.1 * (1 + TOWERS.balancer.levels[0].boost))) < 1e-9, 'cooldown ran 15% faster');
|
assert.ok(Math.abs(b.t.cd - (1 - 0.1 * (1 + TOWERS.balancer.levels[0].boost))) < 1e-9, 'cooldown ran 15% faster');
|
||||||
const shots = (x) => { tick(x.s, 40); return x.s.drainEvents().filter((e) => e.e === 'shot' && e.k === 'ids').length; };
|
const secs = 100;
|
||||||
|
const shots = (x) => { tick(x.s, secs); return x.s.drainEvents().filter((e) => e.e === 'shot' && e.k === 'ids').length; };
|
||||||
const na = shots(a), nb = shots(b);
|
const na = shots(a), nb = shots(b);
|
||||||
assert.ok(na >= 25, 'baseline fires ~28 shots in 40 s: ' + na);
|
assert.ok(Math.abs(na - secs * TOWERS.ids.levels[0].rate) <= 3, 'an unboosted sniper fires about rate x seconds shots: ' + na);
|
||||||
assert.ok(nb > na * 1.1 && nb < na * 1.2, 'boosted ' + nb + ' vs ' + na);
|
assert.ok(nb > na * 1.1 && nb < na * 1.2, 'boosted ' + nb + ' vs ' + na);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -797,7 +798,7 @@ test('the new waves run end to end and the snapshot (incl. daemon, proxy, botnet
|
||||||
assert.equal(JSON.stringify(s.fullState()).includes('null'), false);
|
assert.equal(JSON.stringify(s.fullState()).includes('null'), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Orbital Uplink pricing: very expensive, and every one you own makes the next dearer', () => { // (25% per owned one, for buying and for upgrading)
|
test('Orbital Uplink pricing: very expensive, and every one you own makes the next dearer', () => { // (priceGrowth per owned one, for buying and for upgrading)
|
||||||
const base = TOWERS.uplink.levels[0].cost;
|
const base = TOWERS.uplink.levels[0].cost;
|
||||||
assert.ok(base >= 8 * TD.START_GOLD, 'the first Uplink costs many times the opening credits');
|
assert.ok(base >= 8 * TD.START_GOLD, 'the first Uplink costs many times the opening credits');
|
||||||
assert.ok(base >= 20 * TOWERS.ids.levels[0].cost, 'and a lot more than an IDS Sniper');
|
assert.ok(base >= 20 * TOWERS.ids.levels[0].cost, 'and a lot more than an IDS Sniper');
|
||||||
|
|
@ -806,7 +807,7 @@ test('Orbital Uplink pricing: very expensive, and every one you own makes the ne
|
||||||
assert.equal(TD.priceFor('uplink', [{ type: 'uplink' }, { type: 'filter' }, { type: 'uplink' }]), TD.priceFor('uplink', 2));
|
assert.equal(TD.priceFor('uplink', [{ type: 'uplink' }, { type: 'filter' }, { type: 'uplink' }]), TD.priceFor('uplink', 2));
|
||||||
assert.equal(TD.priceFor('filter', 50), TOWERS.filter.levels[0].cost, 'a Packet Filter never gets dearer');
|
assert.equal(TD.priceFor('filter', 50), TOWERS.filter.levels[0].cost, 'a Packet Filter never gets dearer');
|
||||||
assert.equal(TD.priceFor('wall', [{ type: 'wall' }, { type: 'wall' }]), TOWERS.wall.levels[0].cost);
|
assert.equal(TD.priceFor('wall', [{ type: 'wall' }, { type: 'wall' }]), TOWERS.wall.levels[0].cost);
|
||||||
for (let n = 1; n < 6; n++) assert.ok(TD.priceFor('uplink', n) >= 1.2 * TD.priceFor('uplink', n - 1), 'each Uplink is about 25% dearer than the one before');
|
for (let n = 1; n < 6; n++) assert.ok(TD.priceFor('uplink', n) >= 1.2 * TD.priceFor('uplink', n - 1), 'each Uplink is about priceGrowth dearer than the one before');
|
||||||
|
|
||||||
const s = new Sim({ map: 'open', gold: 1e6 });
|
const s = new Sim({ map: 'open', gold: 1e6 });
|
||||||
const ids = [];
|
const ids = [];
|
||||||
|
|
|
||||||
134
tools/bot.js
134
tools/bot.js
|
|
@ -12,9 +12,11 @@
|
||||||
* node tools/bot.js --maps open,twin,hub --strategies maze,nomaze,spam-filter,lazy --seeds 6 --max 30
|
* node tools/bot.js --maps open,twin,hub --strategies maze,nomaze,spam-filter,lazy --seeds 6 --max 30
|
||||||
* node tools/bot.js --sim /path/to/other/sim.js ... (or SIM_PATH=...) to measure another copy of the sim (baselines)
|
* node tools/bot.js --sim /path/to/other/sim.js ... (or SIM_PATH=...) to measure another copy of the sim (baselines)
|
||||||
* node tools/bot.js --json out.json --detail (raw results / per-game rows)
|
* node tools/bot.js --json out.json --detail (raw results / per-game rows)
|
||||||
|
* a strategy can name a game difficulty after '@' and the only maps it runs on after '#': --strategies maze,maze@easy#open,maze@hard#open+twin (default: normal)
|
||||||
*
|
*
|
||||||
* Strategies: maze | nomaze | spam-filter | spam-ids | spam-mortar | spam-arc | lazy
|
* Strategies: maze | nomaze | spam-filter | spam-ids | spam-mortar | spam-arc | lazy
|
||||||
* maze-no-<type> (ablation: the mixed maze build without one tower type, e.g. maze-no-ids)
|
* maze-no-<type> (ablation: the mixed maze build without one tower type, e.g. maze-no-ids)
|
||||||
|
* full (the mixed build plus Sandbox, Load Balancer and Orbital Uplink) | maze+<type> (the mixed build plus one of those)
|
||||||
* any of them can take overrides: "maze:share=0.6,S=1.2" (see DEFAULTS)
|
* any of them can take overrides: "maze:share=0.6,S=1.2" (see DEFAULTS)
|
||||||
*
|
*
|
||||||
* How the "mixed" build decides (it must adapt to whatever numbers are in the TOWERS / ENEMIES tables):
|
* How the "mixed" build decides (it must adapt to whatever numbers are in the TOWERS / ENEMIES tables):
|
||||||
|
|
@ -34,6 +36,7 @@ const path = require('path');
|
||||||
|
|
||||||
const DEFAULT_SIM = process.env.SIM_PATH || path.join(__dirname, '..', 'public', 'js', 'sim.js');
|
const DEFAULT_SIM = process.env.SIM_PATH || path.join(__dirname, '..', 'public', 'js', 'sim.js');
|
||||||
const ALL_TYPES = ['filter', 'ids', 'mortar', 'throttle', 'arc'];
|
const ALL_TYPES = ['filter', 'ids', 'mortar', 'throttle', 'arc'];
|
||||||
|
const EXTRA_TYPES = ['sandbox', 'balancer', 'uplink']; // bought only by the 'full' / 'maze+<type>' strategies (the older matrices never had them)
|
||||||
|
|
||||||
const DEFAULTS = {
|
const DEFAULTS = {
|
||||||
maze: true, // build wall lines
|
maze: true, // build wall lines
|
||||||
|
|
@ -62,6 +65,9 @@ const DEFAULTS = {
|
||||||
rampLen: 6, // ... over this many waves
|
rampLen: 6, // ... over this many waves
|
||||||
coreBias: 1.0, // prefer wall lines near the server (flyers end there too)
|
coreBias: 1.0, // prefer wall lines near the server (flyers end there too)
|
||||||
compact: 1.0, // bonus for wall lines two cells from another solid line
|
compact: 1.0, // bonus for wall lines two cells from another solid line
|
||||||
|
uplinkFrom: 0, // from this wave on, a bot that may buy the Orbital Uplink SAVES for it (stops buying anything else until it can pay); 0 = never saves
|
||||||
|
uplinkLevel: 2, // ... and for the upgrades of the Uplinks it owns, up to this level
|
||||||
|
uplinkMax: 1, // ... and for this many Uplinks
|
||||||
};
|
};
|
||||||
|
|
||||||
function parseStrategy(spec) {
|
function parseStrategy(spec) {
|
||||||
|
|
@ -79,6 +85,8 @@ function parseStrategy(spec) {
|
||||||
else if (name === 'nomaze') { s.maze = false; s.flat = true; }
|
else if (name === 'nomaze') { s.maze = false; s.flat = true; }
|
||||||
else if (name.startsWith('spam-')) { s.types = [name.slice(5)]; }
|
else if (name.startsWith('spam-')) { s.types = [name.slice(5)]; }
|
||||||
else if (name.startsWith('maze-no-')) { s.types = ALL_TYPES.filter((t) => t !== name.slice(8)); }
|
else if (name.startsWith('maze-no-')) { s.types = ALL_TYPES.filter((t) => t !== name.slice(8)); }
|
||||||
|
else if (name === 'full') { s.types = ALL_TYPES.concat(EXTRA_TYPES); s.uplinkFrom = 16; }
|
||||||
|
else if (name.startsWith('maze+')) { s.types = ALL_TYPES.concat([name.slice(5)]); if (name.slice(5) === 'uplink') s.uplinkFrom = 16; }
|
||||||
else if (name === 'lazy') { s.lazy = true; s.maze = false; s.waitClear = false; }
|
else if (name === 'lazy') { s.lazy = true; s.maze = false; s.waitClear = false; }
|
||||||
else throw new Error('unknown strategy ' + name);
|
else throw new Error('unknown strategy ' + name);
|
||||||
for (const k of Object.keys(over)) if (k !== 'name') s[k] = over[k];
|
for (const k of Object.keys(over)) if (k !== 'name') s[k] = over[k];
|
||||||
|
|
@ -98,6 +106,9 @@ function prng(seed) { // mulberry32
|
||||||
|
|
||||||
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
|
||||||
const perHit = (d, armor) => Math.max(d - armor, d * 0.25);
|
const perHit = (d, armor) => Math.max(d - armor, d * 0.25);
|
||||||
|
const isSlower = (type) => type === 'throttle' || type === 'sandbox';
|
||||||
|
// a Rate Limiter slows by `slow`; a Sandbox freezes for `stun` out of every `pulse` seconds, which holds a packet back by the same fraction
|
||||||
|
const slowOf = (sp) => (sp.type === 'sandbox' ? sp.st.stun / sp.st.pulse : sp.st.slow);
|
||||||
|
|
||||||
class Bot {
|
class Bot {
|
||||||
constructor(TD, sim, strat, rng, ctx) {
|
constructor(TD, sim, strat, rng, ctx) {
|
||||||
|
|
@ -172,11 +183,46 @@ class Bot {
|
||||||
this.specs = this.specsNow();
|
this.specs = this.specsNow();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inRange(sp, x, y, range) { const dx = sp.x - x, dy = sp.y - y; return dx * dx + dy * dy <= range * range; }
|
||||||
|
|
||||||
|
// caps after a Load Balancer of stats `st` stands at (x, y): the attack turrets it reaches fire faster (only where it beats their current boost)
|
||||||
|
boostCaps(baseCaps, perSpec, ents, slows, x, y, st) {
|
||||||
|
const nc = Float64Array.from(baseCaps);
|
||||||
|
this.specs.forEach((sp, si) => {
|
||||||
|
if (this.TD.TOWERS[sp.type].role !== 'attack' || sp.buff >= st.boost || !this.inRange(sp, x, y, st.range)) return;
|
||||||
|
const nsp = Object.assign({}, sp, { buff: st.boost });
|
||||||
|
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]) - perSpec[si][i];
|
||||||
|
});
|
||||||
|
return nc;
|
||||||
|
}
|
||||||
|
|
||||||
|
// free cells next to several attack turrets: the places a Load Balancer is worth a thought
|
||||||
|
balancerSites() {
|
||||||
|
const sim = this.sim, b = sim.board, res = sim.monsterCells().reserved, TD = this.TD;
|
||||||
|
const range = TD.TOWERS.balancer.levels[0].range;
|
||||||
|
const att = this.specs.filter((sp) => TD.TOWERS[sp.type].role === 'attack');
|
||||||
|
if (att.length < 2) return [];
|
||||||
|
const list = [];
|
||||||
|
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
|
||||||
|
const i = y * b.cols + x;
|
||||||
|
if (b.solid[i] || b.obst[i] || res.has(i) || b.isSpecial(x, y)) continue;
|
||||||
|
let n = 0;
|
||||||
|
for (const sp of att) if (this.inRange(sp, x + 0.5, y + 0.5, range)) n++;
|
||||||
|
if (n >= 2) list.push({ x, y, n });
|
||||||
|
}
|
||||||
|
list.sort((p, q) => q.n - p.n);
|
||||||
|
return list.slice(0, 8);
|
||||||
|
}
|
||||||
|
|
||||||
specsNow() {
|
specsNow() {
|
||||||
const out = [];
|
const out = [];
|
||||||
for (const t of this.sim.towers) {
|
for (const t of this.sim.towers) {
|
||||||
if (t.type === 'wall') continue;
|
if (t.type === 'wall') continue;
|
||||||
out.push({ id: t.id, type: t.type, level: t.level, x: t.x + 0.5, y: t.y + 0.5, st: this.TD.TOWERS[t.type].levels[t.level - 1] });
|
out.push({ id: t.id, type: t.type, level: t.level, x: t.x + 0.5, y: t.y + 0.5, st: this.TD.TOWERS[t.type].levels[t.level - 1], buff: 0 });
|
||||||
|
}
|
||||||
|
for (const b of out) { // Load Balancers: every attack turret takes the best boost in range (no stacking)
|
||||||
|
if (b.type !== 'balancer') continue;
|
||||||
|
for (const t of out) if (this.TD.TOWERS[t.type].role === 'attack' && t.buff < b.st.boost && this.inRange(t, b.x, b.y, b.st.range)) t.buff = b.st.boost;
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
@ -215,8 +261,8 @@ class Bot {
|
||||||
const K = this.kinds[ki], P = K.air ? this.a : G;
|
const K = this.kinds[ki], P = K.air ? this.a : G;
|
||||||
const arr = new Float64Array(P.n);
|
const arr = new Float64Array(P.n);
|
||||||
for (const sp of specs) {
|
for (const sp of specs) {
|
||||||
if (sp.type !== 'throttle') continue;
|
if (!isSlower(sp.type)) continue;
|
||||||
const r2 = sp.st.range * sp.st.range, eff = Math.min(0.6, sp.st.slow * (1 - K.slowRes));
|
const r2 = sp.st.range * sp.st.range, eff = Math.min(0.6, slowOf(sp) * (1 - K.slowRes));
|
||||||
for (let i = 0; i < P.n; i++) {
|
for (let i = 0; i < P.n; i++) {
|
||||||
const dx = P.x[i] - sp.x, dy = P.y[i] - sp.y;
|
const dx = P.x[i] - sp.x, dy = P.y[i] - sp.y;
|
||||||
if (dx * dx + dy * dy <= r2 && eff > arr[i]) arr[i] = eff;
|
if (dx * dx + dy * dy <= r2 && eff > arr[i]) arr[i] = eff;
|
||||||
|
|
@ -229,13 +275,15 @@ class Bot {
|
||||||
|
|
||||||
// damage one packet of entry e takes from tower spec sp over its whole walk (analytic model)
|
// damage one packet of entry e takes from tower spec sp over its whole walk (analytic model)
|
||||||
capSpec(sp, e, slow, G) {
|
capSpec(sp, e, slow, G) {
|
||||||
if (sp.type === 'throttle') return 0;
|
if (isSlower(sp.type) || sp.type === 'balancer') return 0;
|
||||||
const TD = this.TD, td = TD.TOWERS[sp.type], st = sp.st;
|
const TD = this.TD, td = TD.TOWERS[sp.type], st = sp.st;
|
||||||
if (!(st.dmg > 0)) return 0; // support / control towers (Load Balancer, Sandbox) deal no damage; the bot never builds them
|
if (!(st.dmg > 0)) return 0; // support / control towers (Load Balancer, Sandbox) deal no damage; the bot never builds them
|
||||||
if (e.air ? !td.air : !td.ground) return 0;
|
if (e.air ? !td.air : !td.ground) return 0;
|
||||||
const hit0 = Math.min(perHit(st.dmg, e.armor), e.h); // no credit for overkill
|
const hit0 = Math.min(sp.type === 'uplink' ? st.dmg : perHit(st.dmg, e.armor), e.h); // no credit for overkill (the Uplink ignores armour)
|
||||||
let dps = hit0 * st.rate, M = 1;
|
let dps = hit0 * st.rate * (1 + (sp.buff || 0)), M = 1;
|
||||||
if (sp.type === 'mortar') {
|
if (sp.type === 'uplink') {
|
||||||
|
M = clamp(1 + (2 * st.splash + 0.6 * st.range) / e.spacing, 1, Math.max(1, e.N)); // the beam pierces everything on its line, the blast hits the packets around the target
|
||||||
|
} else if (sp.type === 'mortar') {
|
||||||
dps *= 0.8;
|
dps *= 0.8;
|
||||||
M = clamp(1 + 2 * st.splash / e.spacing, 1, Math.max(1, e.N));
|
M = clamp(1 + 2 * st.splash / e.spacing, 1, Math.max(1, e.N));
|
||||||
} else if (sp.type === 'arc') {
|
} else if (sp.type === 'arc') {
|
||||||
|
|
@ -331,7 +379,7 @@ class Bot {
|
||||||
const opts = [];
|
const opts = [];
|
||||||
const consider = (o, newCaps) => {
|
const consider = (o, newCaps) => {
|
||||||
const dv = this.value(newCaps, ents) - baseV;
|
const dv = this.value(newCaps, ents) - baseV;
|
||||||
o.ratio = this.jit(dv / o.cost) * (this.typeBias[o.type] || 1) * (this.learned[o.type] || 1) * (o.kind === 'new' && this.sim.wave <= this.s.exploreUntil && (this.typeCount[o.type] || 0) < 2 ? this.s.explore : 1);
|
o.ratio = this.jit(dv / o.cost) * (this.typeBias[o.type] || 1) * (this.learned[o.type] || 1) * (o.kind === 'new' && ALL_TYPES.includes(o.type) && this.sim.wave <= this.s.exploreUntil && (this.typeCount[o.type] || 0) < 2 ? this.s.explore : 1);
|
||||||
o.dv = dv;
|
o.dv = dv;
|
||||||
opts.push(o);
|
opts.push(o);
|
||||||
};
|
};
|
||||||
|
|
@ -341,33 +389,37 @@ class Bot {
|
||||||
if (!lv || !this.s.types.includes(sp.type)) return;
|
if (!lv || !this.s.types.includes(sp.type)) return;
|
||||||
const nsp = Object.assign({}, sp, { st: lv, level: sp.level + 1 });
|
const nsp = Object.assign({}, sp, { st: lv, level: sp.level + 1 });
|
||||||
let nc;
|
let nc;
|
||||||
if (sp.type === 'throttle') {
|
if (isSlower(sp.type)) {
|
||||||
const specs2 = this.specs.map((q, j) => (j === si ? nsp : q));
|
const specs2 = this.specs.map((q, j) => (j === si ? nsp : q));
|
||||||
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
|
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
|
||||||
|
} else if (sp.type === 'balancer') {
|
||||||
|
nc = this.boostCaps(baseCaps, perSpec, ents, slows, sp.x, sp.y, lv);
|
||||||
} else {
|
} else {
|
||||||
nc = Float64Array.from(baseCaps);
|
nc = Float64Array.from(baseCaps);
|
||||||
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]) - perSpec[si][i];
|
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]) - perSpec[si][i];
|
||||||
}
|
}
|
||||||
consider({ kind: 'up', id: sp.id, type: sp.type, cost: lv.cost }, nc);
|
consider({ kind: 'up', id: sp.id, type: sp.type, cost: sim.upgradeCost(sim.towerById(sp.id)) }, nc);
|
||||||
});
|
});
|
||||||
// new towers
|
// new towers
|
||||||
const sites = this.sites();
|
const sites = this.sites();
|
||||||
this.typeCount = {};
|
this.typeCount = {};
|
||||||
for (const sp of this.specs) this.typeCount[sp.type] = (this.typeCount[sp.type] || 0) + 1;
|
for (const sp of this.specs) this.typeCount[sp.type] = (this.typeCount[sp.type] || 0) + 1;
|
||||||
for (const type of this.s.types) {
|
for (const type of this.s.types) {
|
||||||
const lv = TD.TOWERS[type].levels[0];
|
const lv = TD.TOWERS[type].levels[0], price = TD.priceFor(type, sim.towers);
|
||||||
const sl = type === 'throttle' ? sites.filter((q, ix) => ix % 3 === 0) : sites; // throttle evaluation is the expensive one
|
const sl = isSlower(type) ? sites.filter((q, ix) => ix % 3 === 0) : type === 'balancer' ? this.balancerSites() : sites; // slow-field evaluation is the expensive one
|
||||||
for (const site of sl) {
|
for (const site of sl) {
|
||||||
const nsp = { type, level: 1, x: site.x + 0.5, y: site.y + 0.5, st: lv };
|
const nsp = { type, level: 1, x: site.x + 0.5, y: site.y + 0.5, st: lv, buff: 0 };
|
||||||
let nc;
|
let nc;
|
||||||
if (type === 'throttle') {
|
if (isSlower(type)) {
|
||||||
const specs2 = this.specs.concat([nsp]);
|
const specs2 = this.specs.concat([nsp]);
|
||||||
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
|
nc = this.capsFor(specs2, ents, this.slowFieldsFor(specs2));
|
||||||
|
} else if (type === 'balancer') {
|
||||||
|
nc = this.boostCaps(baseCaps, perSpec, ents, slows, nsp.x, nsp.y, lv);
|
||||||
} else {
|
} else {
|
||||||
nc = Float64Array.from(baseCaps);
|
nc = Float64Array.from(baseCaps);
|
||||||
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]);
|
for (let i = 0; i < ents.length; i++) nc[i] += this.capSpec(nsp, ents[i], slows[ents[i].ki]);
|
||||||
}
|
}
|
||||||
consider({ kind: 'new', type, x: site.x, y: site.y, wall: site.wall, cost: lv.cost }, nc);
|
consider({ kind: 'new', type, x: site.x, y: site.y, wall: site.wall, cost: price }, nc);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return opts;
|
return opts;
|
||||||
|
|
@ -573,7 +625,7 @@ class Bot {
|
||||||
this.refresh();
|
this.refresh();
|
||||||
let sold = 0;
|
let sold = 0;
|
||||||
for (const sp of this.specs) {
|
for (const sp of this.specs) {
|
||||||
if (sp.level > 1) continue;
|
if (sp.level > 1 || sp.type === 'balancer') continue;
|
||||||
const r2 = sp.st.range * sp.st.range;
|
const r2 = sp.st.range * sp.st.range;
|
||||||
let hit = false;
|
let hit = false;
|
||||||
for (let i = 0; i < this.g.n && !hit; i++) { const dx = this.g.x[i] - sp.x, dy = this.g.y[i] - sp.y; if (dx * dx + dy * dy <= r2) hit = true; }
|
for (let i = 0; i < this.g.n && !hit; i++) { const dx = this.g.x[i] - sp.x, dy = this.g.y[i] - sp.y; if (dx * dx + dy * dy <= r2) hit = true; }
|
||||||
|
|
@ -647,9 +699,31 @@ class Bot {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The Orbital Uplink costs more than the bot ever has in hand (it spends as it earns), so a player who wants one has to save. From
|
||||||
|
// wave uplinkFrom the bot stops buying anything else until it can pay for the Uplink (then the best site by the surrogate) or the
|
||||||
|
// next Uplink upgrade. Returns true while it is saving (the caller skips every other purchase).
|
||||||
|
uplinkStep() {
|
||||||
|
const sim = this.sim, TD = this.TD;
|
||||||
|
if (!(this.s.uplinkFrom > 0) || !this.s.types.includes('uplink') || sim.wave < this.s.uplinkFrom || sim.lives < 0.5 * sim.maxLives) return false;
|
||||||
|
const ups = sim.towers.filter((t) => t.type === 'uplink');
|
||||||
|
let up = null, cost;
|
||||||
|
if (ups.length < this.s.uplinkMax) cost = TD.priceFor('uplink', sim.towers);
|
||||||
|
else {
|
||||||
|
up = ups.filter((t) => t.level < this.s.uplinkLevel).sort((a, b) => a.level - b.level)[0];
|
||||||
|
if (!up) return false;
|
||||||
|
cost = sim.upgradeCost(up);
|
||||||
|
}
|
||||||
|
if (sim.gold < cost) return true; // keep saving
|
||||||
|
if (up) { sim.cmd({ c: 'upgrade', id: up.id }); return false; }
|
||||||
|
const opts = (this.bestOption() || []).filter((o) => o.kind === 'new' && o.type === 'uplink' && !o.wall).sort((a, b) => b.dv - a.dv);
|
||||||
|
for (const o of opts.slice(0, 3)) if (this.exec(o)) return false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ one round of decisions
|
// ------------------------------------------------------------------ one round of decisions
|
||||||
think(maxActions) {
|
think(maxActions) {
|
||||||
if (this.s.lazy) { this.lazyThink(); return; }
|
if (this.s.lazy) { this.lazyThink(); return; }
|
||||||
|
if (this.uplinkStep()) return;
|
||||||
let n = 0;
|
let n = 0;
|
||||||
if (this.s.maze && this.sim.rev !== this.prunedRev) { this.prune(); this.prunedRev = this.sim.rev; }
|
if (this.s.maze && this.sim.rev !== this.prunedRev) { this.prune(); this.prunedRev = this.sim.rev; }
|
||||||
while (n++ < (maxActions || 40)) {
|
while (n++ < (maxActions || 40)) {
|
||||||
|
|
@ -670,6 +744,7 @@ function playGame(opts) {
|
||||||
const rng = prng(seed * 7919 + 13);
|
const rng = prng(seed * 7919 + 13);
|
||||||
const maxWave = opts.maxWave || 30;
|
const maxWave = opts.maxWave || 30;
|
||||||
const simOpts = { map: opts.map || 'open', events: false };
|
const simOpts = { map: opts.map || 'open', events: false };
|
||||||
|
if (opts.difficulty) simOpts.difficulty = opts.difficulty;
|
||||||
if (opts.startGold !== undefined) simOpts.gold = opts.startGold;
|
if (opts.startGold !== undefined) simOpts.gold = opts.startGold;
|
||||||
if (opts.lives !== undefined) simOpts.lives = opts.lives;
|
if (opts.lives !== undefined) simOpts.lives = opts.lives;
|
||||||
const sim = new TD.Sim(simOpts);
|
const sim = new TD.Sim(simOpts);
|
||||||
|
|
@ -792,7 +867,7 @@ function printTables(results, a) {
|
||||||
const maps = a.maps, strats = a.strategies;
|
const maps = a.maps, strats = a.strategies;
|
||||||
for (const map of maps) {
|
for (const map of maps) {
|
||||||
console.log('\n=== map ' + map + ' (' + a.seeds + ' seeds, up to wave ' + a.max + ') ===');
|
console.log('\n=== map ' + map + ' (' + a.seeds + ' seeds, up to wave ' + a.max + ') ===');
|
||||||
console.log(padr('strategy', 16) + pad('win', 6) + pad('surv', 7) + pad('min-max', 9) + pad('lives', 7) + pad('leaks', 7) + pad('gold@5', 8) + pad('gold@10', 8) + pad('gold@15', 8) + pad('gold@20', 8) + pad('gold@30', 8) + pad('rt@10', 7) + pad('rt@20', 7) + pad('rt@30', 7) + pad('twr@20', 7) + pad('walls', 6) + pad('actions', 8));
|
console.log(padr('strategy', 16) + pad('win', 6) + pad('surv', 7) + pad('min-max', 9) + pad('lives', 7) + pad('leaks', 7) + pad('gold@5', 8) + pad('gold@10', 8) + pad('gold@15', 8) + pad('gold@20', 8) + pad('gold@25', 8) + pad('gold@30', 8) + pad('rt@10', 7) + pad('rt@20', 7) + pad('rt@30', 7) + pad('twr@20', 7) + pad('walls', 6) + pad('actions', 8));
|
||||||
for (const st of strats) {
|
for (const st of strats) {
|
||||||
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
||||||
if (!rs.length) continue;
|
if (!rs.length) continue;
|
||||||
|
|
@ -800,11 +875,19 @@ function printTables(results, a) {
|
||||||
const g = (w, f) => { const v = rs.map((r) => logAt(r, w)).filter(Boolean).map(f); return v.length ? Math.round(mean(v)) : '-'; };
|
const g = (w, f) => { const v = rs.map((r) => logAt(r, w)).filter(Boolean).map(f); return v.length ? Math.round(mean(v)) : '-'; };
|
||||||
console.log(padr(st, 16) + pad(rs.filter((r) => r.result.won).length + '/' + rs.length, 6) + pad(mean(surv).toFixed(1), 7) + pad(Math.min(...surv) + '-' + Math.max(...surv), 9)
|
console.log(padr(st, 16) + pad(rs.filter((r) => r.result.won).length + '/' + rs.length, 6) + pad(mean(surv).toFixed(1), 7) + pad(Math.min(...surv) + '-' + Math.max(...surv), 9)
|
||||||
+ pad(mean(rs.map((r) => r.result.livesLeft)).toFixed(1), 7) + pad(mean(rs.map((r) => r.result.leaks)).toFixed(0), 7)
|
+ pad(mean(rs.map((r) => r.result.livesLeft)).toFixed(1), 7) + pad(mean(rs.map((r) => r.result.leaks)).toFixed(0), 7)
|
||||||
+ pad(g(5, (e) => e.gold), 8) + pad(g(10, (e) => e.gold), 8) + pad(g(15, (e) => e.gold), 8) + pad(g(20, (e) => e.gold), 8) + pad(g(30, (e) => e.gold), 8)
|
+ pad(g(5, (e) => e.gold), 8) + pad(g(10, (e) => e.gold), 8) + pad(g(15, (e) => e.gold), 8) + pad(g(20, (e) => e.gold), 8) + pad(g(25, (e) => e.gold), 8) + pad(g(30, (e) => e.gold), 8)
|
||||||
+ pad(g(10, (e) => e.routeLen), 7) + pad(g(20, (e) => e.routeLen), 7) + pad(g(30, (e) => e.routeLen), 7) + pad(g(20, (e) => e.towers), 7)
|
+ pad(g(10, (e) => e.routeLen), 7) + pad(g(20, (e) => e.routeLen), 7) + pad(g(30, (e) => e.routeLen), 7) + pad(g(20, (e) => e.towers), 7)
|
||||||
+ pad(Math.round(mean(rs.map((r) => r.result.wallsBuilt))), 6) + pad(Math.round(mean(rs.map((r) => r.result.actions))), 8));
|
+ pad(Math.round(mean(rs.map((r) => r.result.wallsBuilt))), 6) + pad(Math.round(mean(rs.map((r) => r.result.actions))), 8));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// credits the bot has been paid by wave N (gold in hand + everything invested), games that reached it only: the true size of the economy
|
||||||
|
console.log('\n--- credits seen (gold + invested) at waves 10 / 15 / 20 / 25 / 30, games that got that far ---');
|
||||||
|
for (const map of maps) for (const st of strats) {
|
||||||
|
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
||||||
|
if (!rs.length) continue;
|
||||||
|
const cs = [10, 15, 20, 25, 30].map((w) => { const v = rs.filter((r) => r.log.some((e) => e.wave >= w)).map((r) => logAt(r, w)).map((e) => e.gold + e.spentWalls + e.spentOther); return v.length ? Math.round(mean(v)) + ' (' + v.length + ')' : '-'; });
|
||||||
|
console.log(padr(map, 12) + padr(st, 16) + cs.map((c) => pad(c, 12)).join(''));
|
||||||
|
}
|
||||||
// where do games end?
|
// where do games end?
|
||||||
console.log('\n--- death waves (wave in which the game was lost; "W" = reached the end) ---');
|
console.log('\n--- death waves (wave in which the game was lost; "W" = reached the end) ---');
|
||||||
for (const map of maps) for (const st of strats) {
|
for (const map of maps) for (const st of strats) {
|
||||||
|
|
@ -815,7 +898,7 @@ function printTables(results, a) {
|
||||||
// tower mix of mixed builds
|
// tower mix of mixed builds
|
||||||
console.log('\n--- average final tower mix (maze strategies) ---');
|
console.log('\n--- average final tower mix (maze strategies) ---');
|
||||||
for (const map of maps) for (const st of strats) {
|
for (const map of maps) for (const st of strats) {
|
||||||
if (!/^maze/.test(st)) continue;
|
if (!/^(maze|full)/.test(st)) continue;
|
||||||
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
const rs = results.filter((r) => r.map === map && r.strategy === st);
|
||||||
if (!rs.length) continue;
|
if (!rs.length) continue;
|
||||||
const mix = {};
|
const mix = {};
|
||||||
|
|
@ -849,7 +932,16 @@ function printDetail(results) {
|
||||||
function main() {
|
function main() {
|
||||||
const a = parseArgs(process.argv);
|
const a = parseArgs(process.argv);
|
||||||
const jobs = [];
|
const jobs = [];
|
||||||
for (const map of a.maps) for (const strategy of a.strategies) for (let s = 0; s < a.seeds; s++) jobs.push({ map, strategy, seed: a.seedStart + s, maxWave: a.max, simPath: a.sim || undefined, startGold: a.startGold });
|
// a strategy may carry a game difficulty after '@' ("maze@hard") and a list of the only maps it runs on after '#' ("maze@hard#open+twin");
|
||||||
|
// the label of the rows keeps both
|
||||||
|
for (const map of a.maps) for (const label of a.strategies) {
|
||||||
|
const hash = label.indexOf('#');
|
||||||
|
if (hash >= 0 && label.slice(hash + 1).split('+').indexOf(map) < 0) continue;
|
||||||
|
const bare = hash < 0 ? label : label.slice(0, hash);
|
||||||
|
const at = bare.indexOf('@');
|
||||||
|
const strategy = at < 0 ? bare : bare.slice(0, at), difficulty = at < 0 ? undefined : bare.slice(at + 1);
|
||||||
|
for (let s = 0; s < a.seeds; s++) jobs.push({ map, strategy, label, difficulty, seed: a.seedStart + s, maxWave: a.max, simPath: a.sim || undefined, startGold: a.startGold });
|
||||||
|
}
|
||||||
const { fork } = require('child_process');
|
const { fork } = require('child_process');
|
||||||
const results = [];
|
const results = [];
|
||||||
let next = 0, running = 0, done = 0;
|
let next = 0, running = 0, done = 0;
|
||||||
|
|
@ -880,7 +972,7 @@ function main() {
|
||||||
|
|
||||||
if (require.main === module) {
|
if (require.main === module) {
|
||||||
if (process.argv.includes('--worker')) {
|
if (process.argv.includes('--worker')) {
|
||||||
process.on('message', (job) => { process.send(playGame(job)); });
|
process.on('message', (job) => { const r = playGame(job); r.strategy = job.label || r.strategy; process.send(r); });
|
||||||
} else main();
|
} else main();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue