Phase 3: trade/end-game client, bot simulator, first balance pass
Built: - Client: trade screen, world/end-game screen (landing sites, shipping, node build, final ranking), report sharing + alliance reports tab, alert describers for all notification types, error-code strings (en+nb) for every server CODE. - tools/bot.js (+ tools/bot/): 50 headless bots against the real server in-process with a fake clock; resource/unit conservation ledger, exit 1 on broken invariants. docs/BALANCE.md has method and every run behind a number. - Balance changes (evidence in docs/BALANCE.md): secondQueueCoreLevel 10 -> 3, TRANSPORT.capacityPerLink 500 -> 1000 (end game was shipping-limited in bot runs). - Server fixes: POST /reports/:id/share 500 without a pending reportCleanup; bounced link shipments were silent about cargo overflow. Tested: npm test 207/207 (new: bot determinism + invariants, client alerts/world/i18n over CODES, two regression tests that failed before their fix); openapi check up to date. Real-browser scratch runs (not in repo): WebSocket push shows an incoming-attack banner ~214 ms after launch, polling fallback ~52 s, 15 scripted flows, 71 screenshots. NOT tested: Playwright suite (e2e/ still empty), real devices/Safari, nginx proxy websockets, throttled networks, HTTP-level bot load. NOT claimed: balance. Bots are not humans; open balance items (loot waste, escrow refund clipping, no garrisons at landing sites, end game not scaling with world speed) are listed in docs/BALANCE.md. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
parent
d84b0c9d12
commit
931f59e11e
49 changed files with 4750 additions and 59 deletions
|
|
@ -98,7 +98,7 @@ notifications (`incoming`, `report`, `train_done`, `research_done`, `movement_re
|
||||||
| ----- | ------- |
|
| ----- | ------- |
|
||||||
| `POST /towns/:id/train {unit, count}` | queue a batch (201). Batches of one training building (NOC / Ops lab / Rollout depot) run in order, buildings in parallel; queue limit 8 per building (`queue_full`) |
|
| `POST /towns/:id/train {unit, count}` | queue a batch (201). Batches of one training building (NOC / Ops lab / Rollout depot) run in order, buildings in parallel; queue limit 8 per building (`queue_full`) |
|
||||||
| `POST /towns/:id/research {unit, stat}` | +5% `attack` or `defence` per level for one unit type, one research at a time per POP, level n needs a Research lab of level n + 2 |
|
| `POST /towns/:id/research {unit, stat}` | +5% `attack` or `defence` per level for one unit type, one research at a time per POP, level n needs a Research lab of level n + 2 |
|
||||||
| `POST /movements {fromTownId, type, toTownId \| x,y, units, ...}` | send `scan`, `raid`, `attack`, `takeover`, `reinforce`, `settle` (201). `type: transport` carries `cargo: {fiber, hardware, capital}` (Internet exchange: level = concurrent transports, 500 each). Extra fields: `target` (building for exploit kits), `wild` (two field types for a new POP), `confirmEndProtection` |
|
| `POST /movements {fromTownId, type, toTownId \| x,y, units, ...}` | send `scan`, `raid`, `attack`, `takeover`, `reinforce`, `settle` (201). `type: transport` carries `cargo: {fiber, hardware, capital}` (Internet exchange: level = concurrent transports, 1000 each, `D.TRANSPORT.capacityPerLink`). Extra fields: `target` (building for exploit kits), `wild` (two field types for a new POP), `confirmEndProtection` |
|
||||||
| `GET /movements` | your active movements (full detail, `recallableUntil`) and incoming ones from others: origin and ETA only, `type: "unknown"` |
|
| `GET /movements` | your active movements (full detail, `recallableUntil`) and incoming ones from others: origin and ETA only, `type: "unknown"` |
|
||||||
| `POST /movements/:id/recall` | turn an outbound movement around within the first 90 s (`recall_expired` after) |
|
| `POST /movements/:id/recall` | turn an outbound movement around within the first 90 s (`recall_expired` after) |
|
||||||
| `POST /towns/:id/withdraw {ownerTownId, units?}` | reinforcements in this POP go home (host kicks them out, or their owner calls them back) |
|
| `POST /towns/:id/withdraw {ownerTownId, units?}` | reinforcements in this POP go home (host kicks them out, or their owner calls them back) |
|
||||||
|
|
@ -121,7 +121,7 @@ Later stages append their routes here and to the route table.
|
||||||
|
|
||||||
## Trade, end game, shared reports (stage 5 rest, stage 7 start)
|
## Trade, end game, shared reports (stage 5 rest, stage 7 start)
|
||||||
|
|
||||||
**Internet exchange trade.** Offers "give X of A for Y of B within Z tiles". Amounts are whole numbers, each side 1..500 (one transport
|
**Internet exchange trade.** Offers "give X of A for Y of B within Z tiles". Amounts are whole numbers, each side 1..1000 (one transport
|
||||||
link), the two amounts differ by at most 1:2, the resources differ; `maxDistance` 1..300. Lists are newest first, `after` = id of the last
|
link), the two amounts differ by at most 1:2, the resources differ; `maxDistance` 1..300. Lists are newest first, `after` = id of the last
|
||||||
offer you have (older ones follow). `status`: `open`, `accepted`, `completed`, `cancelled`, `expired`, `void`.
|
offer you have (older ones follow). `status`: `open`, `accepted`, `completed`, `cancelled`, `expired`, `void`.
|
||||||
|
|
||||||
|
|
|
||||||
419
docs/BALANCE.md
Normal file
419
docs/BALANCE.md
Normal file
|
|
@ -0,0 +1,419 @@
|
||||||
|
# BALANCE
|
||||||
|
|
||||||
|
First evidence-based balance pass, driven by `tools/bot.js`. **Nothing here says the game is balanced.** It says what 50 scripted
|
||||||
|
players did to the real server code, what looked wrong, what was changed in `public/js/data.js` because of it, and what is still
|
||||||
|
unknown. The bots are not humans (sections 1 and 8).
|
||||||
|
|
||||||
|
**How to read the run labels.** A label like `m2-before-d30-s1` names an option set: default mix, "before" = `--set FORMULAS.secondQueueCoreLevel=10`
|
||||||
|
(and, for the end game, `--set TRANSPORT.capacityPerLink=500`), 30 days, seed 1. The reproducible thing is always the command; the JSON
|
||||||
|
outputs (1 to 2 MB each) are not committed. Every run cited here finished with `INVARIANTS OK`.
|
||||||
|
|
||||||
|
## 1. The harness
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node tools/bot.js --players 50 --days 14 --speed 1 --seed 1 # the run CLAUDE.md asks for
|
||||||
|
node tools/bot.js --players 50 --days 60 --seed 1 --sessions-per-day 2 # a casual player's pace
|
||||||
|
node tools/bot.js --players 50 --days 60 --seed 1 --set FORMULAS.secondQueueCoreLevel=10 # "before" of change B1
|
||||||
|
node tools/bot.js --help # every option
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Driver: the commands layer, not HTTP.** `createServer({ dbPath: ':memory:', clock: FakeClock, autoArm: false })` runs in-process
|
||||||
|
and the bots call `srv.commands.run(name, args)`, the function every REST route calls: same validation, same one-transaction
|
||||||
|
commands, same events and notifications. HTTP, JSON and scrypt are skipped, which is what makes 50 players x 14 days take about
|
||||||
|
3 s and 50 players x 170 days about 140 s on one core (about 3 000 to 5 000 commands per second, p95 command latency 0.1 to 0.5 ms).
|
||||||
|
A route-level bug (schema, auth, rate limit) is therefore not covered by the harness; `npm test` covers those.
|
||||||
|
- **Time:** a `FakeClock` is advanced from stop to stop (next bot sitting, next 2 h economy sample, next midnight), and
|
||||||
|
`scheduler.runDue()` settles every event that fell due in between, each at its own `due_at`, in order.
|
||||||
|
- **Bots** (`tools/bot/bots.js`): builder, raider, conqueror (raider that also takes POPs over), turtle, expander, trader,
|
||||||
|
alliancer (founds and recruits for an alliance). Default mix of 50: 11 builder, 7 raider, 3 conqueror, 6 turtle, 8 expander,
|
||||||
|
6 trader, 9 alliancer. They read the world through the server's own modules (own POPs, the map's towns, their reports) and use the
|
||||||
|
`rules.js` previews (`buildPlan`, `trainPlan`, `footprintGate`, `resolveBattle` ...) before sending a command. Intel about another
|
||||||
|
POP comes only from a real scan (and the scan can fail). They never write to the database.
|
||||||
|
- **Human cadence** (this matters more than anything else in the numbers): a bot plays 3 to 5 short sittings a day at seeded times
|
||||||
|
between 07:00 and 23:00 (a builder 4, a raider 5, a turtle 3 ...; `--sessions-per-day N` forces N for everyone). A sitting lasts
|
||||||
|
5 minutes (`--session-min`, the first one 20): when the build in progress finishes inside the sitting the bot is still there and
|
||||||
|
starts the next, so cheap early builds chain and expensive ones do not. `--always-on` (a sitting every 10 minutes) is the upper
|
||||||
|
bound of what attention can do.
|
||||||
|
- **Player skill:** fields are chosen to keep the production mix at what the bot spends (`--field-policy marginal`, default) or all
|
||||||
|
fields level together (`balanced`, a lower bound). A bot that has been raided trains defence up to 1.25 x the strongest attack
|
||||||
|
it saw, for 5 days (`--no-adapt` turns that off, an upper bound on how badly defenders can do). A bot that sees every store full
|
||||||
|
upgrades the Rack hall first. Several of these were bot bugs before they were fixed, and each moved the results: see section 7.
|
||||||
|
- **`--set PATH=VALUE`** changes `data.js` in place for one run and restores it afterwards. It reaches every value the code reads at call time
|
||||||
|
(all the ones used here); a primitive copied when a module is loaded, e.g. `ENDGAME.scanStrength` in `server/military/landing.js`, is
|
||||||
|
not overridable and the run would silently ignore it.
|
||||||
|
- **Determinism:** every decision comes from a generator seeded with (seed, bot, purpose). The same options give the same stats;
|
||||||
|
`test/bot-run.test.js` runs 12 players for 6 days twice and compares everything except wall-clock `perf`.
|
||||||
|
- **Debug hooks:** `BOT_DEBUG=1` prints the first command errors of each kind, `BOT_DEBUG_DRIFT=1` prints the conservation drift
|
||||||
|
at every economy sample (that is how server finding S1 was found).
|
||||||
|
|
||||||
|
### Invariants (the run exits 1 when one breaks)
|
||||||
|
|
||||||
|
| invariant | how it is checked |
|
||||||
|
|---|---|
|
||||||
|
| resources are conserved | `pools = sources + production - sinks`, per resource, at every midnight and at the end. Pools: POP stock, open trade escrow, cargo of movements that are out, landing-site stockpiles. **Production is exact**: a tap on `db.run` books the difference every `state.settle` writes (and drops it if the transaction rolls back). Sources: start stock of operators and founded POPs, the incumbent Hardware bonus. Sinks: build/train/research costs (command results), Backbone node levels, `cargoLost` in notifications (overflow at delivery), trade refunds clipped by the Rack hall cap (tap on the refund statement). Tolerance 0.5 per rounding event. |
|
||||||
|
| units are conserved | alive (home + stationed + on the road) = trained (`trainDone` events that ran) - lost (battle, scan, incumbent, landing reports, decommission notifications) - consumed (3 crews per founded POP, 1 M&A team per loyalty hit). Exact. |
|
||||||
|
| no negative stock | SQL scan of towns and landing sites. |
|
||||||
|
| no failed events | `events.status = 'failed'` and any server log line mentioning a failure. |
|
||||||
|
| no unexpected error codes | every refused command is counted by code; `validation_failed`, `internal_error` or a non-GameError throw fails the run. |
|
||||||
|
|
||||||
|
`test/bot-run.test.js` also proves the checks bite: it conjures Fiber, deletes units, makes a stock negative and inserts an event
|
||||||
|
without a handler, and asserts the run reports BROKEN each time.
|
||||||
|
|
||||||
|
## 2. The state before this pass (what the bots saw)
|
||||||
|
|
||||||
|
"Before" in every table below means the data as it was: `--set FORMULAS.secondQueueCoreLevel=10` on top of today's `data.js`
|
||||||
|
(that is the only economy number this pass changed, plus `TRANSPORT.capacityPerLink` for the end game, see section 3).
|
||||||
|
|
||||||
|
Default mix, 50 players, per-archetype cadence (3 to 5 sittings a day), speed 1, three seeds, 30 days (`m2-before-d30-s1..3`):
|
||||||
|
|
||||||
|
- Field level (mean over the capital's 18 fields) 10.3 on day 30; Core router 10 reached on day 27 (median); first expansion
|
||||||
|
(a second POP actually founded) on day 27.5; median footprint 7 200.
|
||||||
|
- **The footprint gate is not what holds expansion back.** 84 to 100 % of operators are over the 500 footprint of the first
|
||||||
|
extra POP from day 8 on (`over gate` column); the Rollout depot needs Core router 10, and three Rollout crews cost
|
||||||
|
1 200 / 900 / 900. A bot that beelines for it (the "expander") has Core router 10 on day ~13 and its first new POP on day ~16.
|
||||||
|
- **Build time is irrelevant, the number of builds you can start is not.** A level costs one to three hours of one resource's production
|
||||||
|
and takes 2 to 15 minutes to build. A player gets one build slot (two from Core router 10) and a 5-minute sitting, so what limits
|
||||||
|
progress is how many builds can be started per sitting. Queue utilisation (share of POP-samples with a build running) is 0 to 6 %
|
||||||
|
all game, and 28 % (14 days) to 32 % (30 days) of the production that the rates would give is lost to full stores.
|
||||||
|
- Everyone who plays at all gets there; the question is when. 2 sittings a day: field level 9.8 after 60 days; 4 a day: 18.4
|
||||||
|
(`node tools/bot.js --players 50 --days 60 --seed 1 --sessions-per-day 2|4 --set FORMULAS.secondQueueCoreLevel=10`); a 24/7 player is not much
|
||||||
|
faster than 8 a day (field level 15.3 against 14.9 after 30 days, `--always-on` against `--sessions-per-day 8`).
|
||||||
|
|
||||||
|
## 3. What was changed
|
||||||
|
|
||||||
|
### B1. Second build slot at Core router 3 (was 10)
|
||||||
|
|
||||||
|
| parameter | old | new | file |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `FORMULAS.secondQueueCoreLevel` | 10 | 3 | `public/js/data.js` |
|
||||||
|
|
||||||
|
Why: see above. The experiment that decided it (bots at 2 and 4 sittings a day, 50 players, seeds 1 and 2 averaged; "before" =
|
||||||
|
`--set FORMULAS.secondQueueCoreLevel=10`, "after" = the new default; command pattern
|
||||||
|
`node tools/bot.js --players 50 --days 60 --seed 1 --sessions-per-day 4 [--set FORMULAS.secondQueueCoreLevel=10]`):
|
||||||
|
|
||||||
|
**2 sittings a day, 60 days** (`--sessions-per-day 2 --days 60`, seeds 1+2):
|
||||||
|
|
||||||
|
| metric | before (second slot at Core 10) | after (Core 3) |
|
||||||
|
|---|---|---|
|
||||||
|
| day F>=10 | not reached | 39.0 |
|
||||||
|
| day F>=15 | not reached | not reached |
|
||||||
|
| day F>=18 | not reached | not reached |
|
||||||
|
| F at end | 9.8 | 13.9 |
|
||||||
|
| core10 day p50 | 53.9 | 35.7 |
|
||||||
|
| first expansion day p50 | 49.9 | 36.8 |
|
||||||
|
| footprint p50 | 13092 | 21607 |
|
||||||
|
| net worth (all) | 142818 | 365943 |
|
||||||
|
| storage waste % | 67.8 | 61.5 |
|
||||||
|
|
||||||
|
**4 sittings a day, 60 days** (`--sessions-per-day 4 --days 60`, seeds 1+2):
|
||||||
|
|
||||||
|
| metric | before (second slot at Core 10) | after (Core 3) |
|
||||||
|
|---|---|---|
|
||||||
|
| day F>=10 | 32.0 | 22.5 |
|
||||||
|
| day F>=15 | 47.0 | 37.0 |
|
||||||
|
| day F>=18 | 58.0 | 48.0 |
|
||||||
|
| F at end | 18.4 | 18.9 |
|
||||||
|
| core10 day p50 | 31.4 | 20.0 |
|
||||||
|
| first expansion day p50 | 29.6 | 18.7 |
|
||||||
|
| footprint p50 | 30849 | 42146 |
|
||||||
|
| net worth (all) | 1002649 | 1167173 |
|
||||||
|
| storage waste % | 53.9 | 67.2 |
|
||||||
|
|
||||||
|
(The 60-day waste rises because the economy saturates earlier: once every field is at its maximum the stores are full and the production has nowhere to go. At 14 days, before saturation, B1 halves the waste.)
|
||||||
|
|
||||||
|
**4 sittings a day, 14 days** (`--sessions-per-day 4 --days 14`, seeds 1+2):
|
||||||
|
|
||||||
|
| metric | before (second slot at Core 10) | after (Core 3) |
|
||||||
|
|---|---|---|
|
||||||
|
| F at end | 5.2 | 7.1 |
|
||||||
|
| core10 day p50 | not reached | 8.9 |
|
||||||
|
| first expansion day p50 | not reached | 10.8 |
|
||||||
|
| footprint p50 | 1473 | 1883 |
|
||||||
|
| net worth (all) | 35163 | 56845 |
|
||||||
|
| storage waste % | 37.0 | 16.4 |
|
||||||
|
|
||||||
|
Default mix, per-archetype cadence, seeds 1 to 3 (`node tools/bot.js --players 50 --days 30 --seed N [--set ...=10]`):
|
||||||
|
|
||||||
|
**30 days** (seeds 1 to 3):
|
||||||
|
|
||||||
|
| metric | before (second slot at Core 10) | after (Core 3) |
|
||||||
|
|---|---|---|
|
||||||
|
| day F>=10 | 29.7 | 21.7 |
|
||||||
|
| F at end | 10.3 | 13.2 |
|
||||||
|
| core10 day p50 | 27.0 | 16.7 |
|
||||||
|
| first expansion day p50 | 27.5 | 17.8 |
|
||||||
|
| footprint p50 | 7215 | 10329 |
|
||||||
|
| net worth (all) | 157200 | 307644 |
|
||||||
|
| net worth builder | 108835 | 295333 |
|
||||||
|
| net worth raider | 193321 | 277369 |
|
||||||
|
| raids | 253 | 189 |
|
||||||
|
| storage waste % | 31.8 | 26.0 |
|
||||||
|
|
||||||
|
**14 days** (seeds 1 to 3):
|
||||||
|
|
||||||
|
| metric | before (second slot at Core 10) | after (Core 3) |
|
||||||
|
|---|---|---|
|
||||||
|
| F at end | 5.5 | 7.3 |
|
||||||
|
| core10 day p50 | not reached | 9.0 |
|
||||||
|
| first expansion day p50 | not reached | 11.6 |
|
||||||
|
| footprint p50 | 1569 | 2045 |
|
||||||
|
| storage waste % | 28.1 | 13.2 |
|
||||||
|
|
||||||
|
World speed 2 and 3, 30 days, default mix, seeds 1 and 2 (`--speed 2|3`):
|
||||||
|
|
||||||
|
**Speed 2** (`--speed 2 --days 30`, seeds 1+2):
|
||||||
|
|
||||||
|
| metric | before (second slot at Core 10) | after (Core 3) |
|
||||||
|
|---|---|---|
|
||||||
|
| day F>=10 | 18.0 | 13.0 |
|
||||||
|
| day F>=15 | 28.0 | 23.0 |
|
||||||
|
| F at end | 16.2 | 18.0 |
|
||||||
|
| core10 day p50 | 15.9 | 10.1 |
|
||||||
|
| first expansion day p50 | 16.1 | 10.4 |
|
||||||
|
|
||||||
|
**Speed 3** (`--speed 3 --days 30`, seeds 1+2):
|
||||||
|
|
||||||
|
| metric | before (second slot at Core 10) | after (Core 3) |
|
||||||
|
|---|---|---|
|
||||||
|
| day F>=10 | 14.0 | 11.0 |
|
||||||
|
| day F>=15 | 21.0 | 18.0 |
|
||||||
|
| F at end | 18.6 | 18.9 |
|
||||||
|
| core10 day p50 | 11.5 | 8.1 |
|
||||||
|
| first expansion day p50 | 12.0 | 7.7 |
|
||||||
|
|
||||||
|
What it does not do: it changes nothing for a player who is always online (`--always-on`, 30 days: field level 15.3 before, 15.2 after, same day for Core router 10) and little at 8 sittings a day (field level 14.9 to 15.6); it helps most those who play 1 to 4 times a day (1 a day, 30 days: field level 3.8 to 4.6). A casual player is still behind a committed one (section 4, "attention"). Going further (slots
|
||||||
|
2/3/4/5 at Core router 2/4/7/10) was measured with a three-line hook in `rules.queueSlots` (`FORMULAS.extraQueueCores`, default
|
||||||
|
`[]`, so the committed behaviour is unchanged) and not adopted: slots 2/3/4/5 at Core 2/4/7/10 bring the 2-a-day player to level 18 on day 51 and everybody to saturation between day 40 and 51 (table in section 4). That removes most of the attention gap by speeding everybody up and leaves the committed player with nothing to build for ~60 days before the backbone opens, which is a pacing decision (how long should the economy last?) the bots cannot make.
|
||||||
|
|
||||||
|
Side effects worth knowing: builders now lose far less to raids (they are no longer slow targets, see "raiding" below), and the
|
||||||
|
first expansion comes ~10 days earlier. Both are consequences of the faster early game, not separate changes.
|
||||||
|
|
||||||
|
### B2. Transport capacity 1000 per link (was 500)
|
||||||
|
|
||||||
|
| parameter | old | new | file |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `TRANSPORT.capacityPerLink` | 500 | 1000 | `public/js/data.js` |
|
||||||
|
|
||||||
|
Why: the end game was **shipping-limited**, not production-limited. The Backbone node costs 7.2 M of each resource over 100 levels
|
||||||
|
(21.6 M units in all) and the only way to bring them to the site is by transport, 500 units per link per trip, links = Internet
|
||||||
|
exchange level, one trip per sitting per link. By day ~50 to 60 (4 sittings a day, with B1) a committed player's 18 fields are at their maximum;
|
||||||
|
one 18-member alliance then produces roughly 2.6 M units a day (a world average of 600 / 600 / 480 per POP and hour on ~165 POPs, a third of
|
||||||
|
them the alliance's), so production would cover the cost in about eight days, while the same
|
||||||
|
alliance shipped 150 to 220k units a day (18 members x ~5 links x ~4 sittings x 500 = 180k). The early levels are cheap (level 1 is
|
||||||
|
4 000 of each, level 89 is 193 000 of each, 580k for one level) so the stockpile covers them at once; from level ~60 on a single level costs more than
|
||||||
|
a day of shipping and the alliance waits for trucks, not for the 2 h x 1.025^L build.
|
||||||
|
|
||||||
|
"Before" = `--set TRANSPORT.capacityPerLink=500`, "after" = the new default; commands
|
||||||
|
`node tools/bot.js --players 50 --days 175 --seed 1 [--set TRANSPORT.capacityPerLink=500]` (speed 1) and
|
||||||
|
`--speed 3 --days 110` (a 3x world). Winner = the first alliance to finish node level 100.
|
||||||
|
|
||||||
|
| world | before: 500 per link | after (B2): 1000 per link | measured, not adopted: 2000 per link | measured, not adopted: 500 per link and `ENDGAME.costGrowth` 1.035 (3.9 M of each) |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| speed 1, seed 1, 175 days | no winner by day 175, best node level 89 (about 45 more days at its rate) | winner day 164 (64 days after the sites opened) | winner day 143 (43 days after the sites opened) | winner day 159 (59 days after the sites opened) |
|
||||||
|
| speed 1, seed 2, 190 days | no winner by day 190, best node level 97 (about 12 more days at its rate) | winner day 156 (55 days after the sites opened) | not run | not run |
|
||||||
|
| speed 1, seed 3, 190 days | no winner by day 190, best node level 88 (about 61 more days at its rate) | winner day 178 (78 days after the sites opened) | not run | not run |
|
||||||
|
| speed 3, seed 1, 110 days | no winner by day 110, best node level 79 (about 114 more days at its rate) | no winner by day 110, best node level 94 (about 22 more days at its rate) | winner day 84 (51 days after the sites opened) | no winner by day 110, best node level 94 (about 17 more days at its rate) |
|
||||||
|
| speed 3, seed 2, 110 days | no winner by day 110, best node level 84 (about 76 more days at its rate) | winner day 109 (76 days after the sites opened) | not run | not run |
|
||||||
|
|
||||||
|
Reading it: at 500 per link nobody finished within 175 to 190 days at speed 1 (levels 88, 89, 97; the extrapolations are 12 to 61 more
|
||||||
|
days at the rate the leading site was fed), so a 1x world would run to day ~200 to 250. At 1000 the winner arrives 55 to 78 days after
|
||||||
|
the sites open, which is 1.5 to 2.2 times the 36 days that building the 100 levels takes on its own, so shipping still matters but does not
|
||||||
|
decide everything. 2000 gives 43 days: shipping is then barely a constraint. Lowering the cost (`ENDGAME.costGrowth` 1.035) helps about as
|
||||||
|
much as 1000 per link at both speeds (59 days at 1x; best level 94 on day 110 at 3x, the same as 1000 per link). Either dial works; capacity
|
||||||
|
was taken because the cost curve was set on purpose ("far more than anything else", DECISIONS E5, and DESIGN.md quotes 7.2 M) while carrying
|
||||||
|
500 units per trip is a convenience limit nobody argued for, and because it also lifts bulk trade a little.
|
||||||
|
|
||||||
|
**Not solved by B2:** speed does not shorten the end game the way it shortens everything else. A 3x world opens its sites on day 33, but
|
||||||
|
its alliances still take 76 days (seed 2) after that, about as long as a 1x world, because shipping is per sitting, not per hour (and
|
||||||
|
at day 33 the members are at field level ~12 with fewer links). `capacityPerLink x world speed` in `rules.transportPlan` would
|
||||||
|
restore the scaling (a 10x world with a final push finished 8.5 days after opening, below) but the client reads the constant directly
|
||||||
|
(trade form limits, send dialog), so it was left to the owner of that code.
|
||||||
|
|
||||||
|
|
||||||
|
## 4. Found, not changed
|
||||||
|
|
||||||
|
Each item: what the runs show, the run to reproduce it, and why nothing was tuned.
|
||||||
|
|
||||||
|
### Attention is still the biggest lever (B1 narrows it, does not remove it)
|
||||||
|
|
||||||
|
Days until the average capital's mean field level reaches 10 / 15 / 18 (all 18 fields, mean over the 50 operators; 50 players, seed 1, 120
|
||||||
|
days, `node tools/bot.js --players 50 --days 120 --seed 1 --sessions-per-day N [--set FORMULAS.secondQueueCoreLevel=10]`):
|
||||||
|
|
||||||
|
| sittings a day | before: second slot at Core 10 | after (B1): second slot at Core 3 | not adopted: slots 2/3/4/5 at Core 2/4/7/10 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 2 | 62 / 91 / 113 | 39 / 67 / 85 | 26 / 40 / 51 |
|
||||||
|
| 4 | 32 / 47 / 58 | 22 / 37 / 48 | 18 / 29 / 41 |
|
||||||
|
| 8 | 20 / 31 / 46 | 18 / 29 / 43 | 17 / 27 / 40 |
|
||||||
|
|
||||||
|
A 2-sittings-a-day player takes about 1.8 times as long as a 4-a-day player to level 18, and 2.0 times as long as an
|
||||||
|
8-a-day player. That is a lot less than before B1 (2 a day: 113 days to level 18 against 58 at 4 a day) but it is not "a few minutes a
|
||||||
|
few times a day is enough": the casual player gets level 18 on day 85, two weeks before the backbone opens, the committed one
|
||||||
|
on day 48. More slots narrow it further (last column), at the price of pushing the committed player to saturation even sooner;
|
||||||
|
that is a pacing decision (how long should the economy last?) that the bots cannot make for you, so it is left open.
|
||||||
|
|
||||||
|
### Raiding: profitable per raid, not a winning strategy at equal attention
|
||||||
|
|
||||||
|
Every bot at 4 sittings a day, B1 config, 30 days, seeds 1 to 3 (`node tools/bot.js --players 50 --days 30 --seed N --sessions-per-day 4`;
|
||||||
|
net worth = everything spent on buildings, units and research plus the stock left):
|
||||||
|
|
||||||
|
| archetype | n | net worth, seeds 1 / 2 / 3 | field level (seed 1) | POPs (seed 1) | raids won / sent (seed 1) | times hit, mean over the archetype (seed 1) |
|
||||||
|
|---|---|---|---|---|---|---|
|
||||||
|
| builder | 11 | 302k / 301k / 297k | 13.7 | 3 | - | 2.5 |
|
||||||
|
| raider | 7 | 214k / 232k / 216k | 11.9 | 1 | 63/63 | 0.3 |
|
||||||
|
| conqueror | 3 | 309k / 246k / 284k | 12.7 | 3.67 | 43/43 | 4.3 |
|
||||||
|
| turtle | 6 | 156k / 157k / 154k | 10.4 | 1 | - | 0.0 |
|
||||||
|
| expander | 8 | 384k / 385k / 386k | 14.2 | 6 | - | 4.6 |
|
||||||
|
| trader | 6 | 206k / 212k / 231k | 12.1 | 3 | - | 5.2 |
|
||||||
|
| alliancer | 9 | 286k / 289k / 291k | 13 | 3 | - | 2.3 |
|
||||||
|
|
||||||
|
- Raids are won (100 % in all three seeds, attack/defence median 4 to 27: the raider only attacks what it beats by a wide margin
|
||||||
|
after a scan that succeeds 81 to 86 % of the time), they return about 2.7 to 3.2 times the value of the units lost, 106 to 153 raids
|
||||||
|
per run. Nobody younger than 4 days is raided (72 h protection and the bots prefer rich targets); 3 to 8 raids per run hit
|
||||||
|
operators of 4 to 7 days.
|
||||||
|
- But the raiders end 23 to 29 % behind the builders in net worth and (seed 1) 1.8 levels behind in field level: a 1.5-day army is not paid back within
|
||||||
|
a month, and the 15 to 27k of loot per raider (nominal; see the overflow note below) is much less than the army costs. Builders lose
|
||||||
|
2 to 4k each, about 1 % of their output. Turtles (two days of production in defence) were never hit (0 hits in all three 30-day runs, and in a 170-day run made with the
|
||||||
|
bot build before B1) and are 48 % behind builders: defence is cheap per point (a Honeypot is 0.42 defence per resource point against 0.27 attack
|
||||||
|
per point for a Script crew, before the Firewall) but a turtle pays for it every day.
|
||||||
|
- `--no-adapt` (nobody answers a raid with more defence): 137 and 213 raids instead of 106 and 153, builders hit 24 and 13 times
|
||||||
|
instead of 27 and 19; net worth within 3 % for everybody except raiders (+3 to +12 %) and conquerors (+3 to +7 %). The army cost, not the
|
||||||
|
defenders' reaction, is what keeps raiding in check here.
|
||||||
|
- Earlier in this pass raiders looked dominant (net worth 1.8 times a builder's). That was the old single build slot (builders were
|
||||||
|
slow and easy to hit, raids 253 against 189 per run) plus a cadence difference: with per-archetype cadence a raider plays 5 sittings and a builder 4.
|
||||||
|
After saturation (day ~50 at 4 sittings a day) net worth stops being comparable: everybody turns the surplus into units
|
||||||
|
(60-day runs `arch-d60-s1/2` show raiders ahead 1.5 to 1.6 times, which says nothing about raiding).
|
||||||
|
- Sensitivity, so the next pass knows the dials (per-archetype cadence, 30 days, seeds 1+2, B1 config; builder loot loss per
|
||||||
|
builder / raids per run / raider net worth against the untouched run):
|
||||||
|
`MILITARY.cacheMax 0.7 + cachePerLevel 0.14`: 4-6k, 181, -4 to -5 %; `cacheMax 0.8 + cachePerLevel 0.2`: 2-3k, 87 to 164, -8 to -11 %;
|
||||||
|
`MILITARY.raidLossFactor 0.8`: 4-6k, 142-158, -4 to -6 %; `script_crew carry 30, botnet 90`: 3k, 137-197, -7 to -12 %. Untouched:
|
||||||
|
10-11k, 188-198. None adopted: the untouched game is not dominant and bots scout better than most players will.
|
||||||
|
- **Loot is mostly wasted on arrival** (`m2-after-d30-s1`): loot is split evenly over Fiber, Hardware and Capital whatever the raider
|
||||||
|
needs, the raider's Hardware and Capital stores are usually full, and overflow at delivery is destroyed: over all deliveries of that run 77k Hardware,
|
||||||
|
14k Capital and 2k Fiber vanished against 251k looted in total. Real value of a raid is mostly its Fiber. A rule that weights
|
||||||
|
the split by free storage would double the effective loot; that is a design change, not a number.
|
||||||
|
|
||||||
|
### Takeover is expensive enough
|
||||||
|
|
||||||
|
A conqueror-heavy world (12 of 50 conquerors, 20 expanders, 18 builders, 4 sittings a day, 45 days, seeds 1 and 2: `cq-base-d45`,
|
||||||
|
`cq-base-d45-s2`):
|
||||||
|
|
||||||
|
| run | POPs in the world | taken over | takeover battles (one M&A team each) | conqueror: net worth / footprint / POPs | expander: net worth / footprint / POPs | builder: net worth / footprint / POPs |
|
||||||
|
|---|---|---|---|---|---|---|
|
||||||
|
| seed 1, M&A team 700/600/800 (as shipped) | 279 | 42 | 613 | 911k / 21k / 5.83 | 981k / 27k / 7.7 | 934k / 25k / 3.06 |
|
||||||
|
| seed 1, M&A team x3 (2100/1800/2400) | 254 | 4 | 266 | 905k / 21k / 3.25 | 975k / 27k / 7.95 | 934k / 25k / 3.11 |
|
||||||
|
| seed 2, as shipped | 288 | 46 | 657 | 1000k / 22k / 6.17 | 984k / 27k / 8 | 937k / 25k / 3 |
|
||||||
|
| seed 2, M&A x3 | 252 | 3 | 304 | 979k / 22k / 3.17 | 978k / 27k / 8 | 934k / 25k / 3 |
|
||||||
|
|
||||||
|
Taking over costs about 14 to 15 M&A teams per POP (loyalty 100, 15 to 30 per hit, +1 per hour back, the bots hit once per sitting),
|
||||||
|
about 30k of resources, and the 12 conquerors in that world end level with the expanders and builders in net worth (911 to 1 000k
|
||||||
|
against 975 to 984k and 934k) and behind them in footprint (21 to 22k against 27k and 25k): not dominant. Tripling the M&A price
|
||||||
|
(2 100 / 1 800 / 2 400) leaves 3 to 4 takeovers: the mechanic dies. So 700 / 600 / 800 sits in a narrow working window. Not tuned.
|
||||||
|
(Net worth is read near saturation here, hence the footprint column.)
|
||||||
|
|
||||||
|
### Trade works but is thin, and escrow loses resources
|
||||||
|
|
||||||
|
38 to 47 offers completed per 30 days in the standard runs (volume about 40k units), roughly half of all posted offers expire. Every
|
||||||
|
operator is short of Fiber (buildings cost Fiber : Hardware : Capital in a ratio of about 1 : 0.7 : 0.5, the 18 fields give 5 : 5 : 4
|
||||||
|
plus 4 substations), so the market has no natural counterparties and trade is mostly Hardware or Capital surplus for Fiber or each
|
||||||
|
other. Completed offers trade at 1.00 give/want (median). Not tuned: a thin market is an observation about this bot population, not a
|
||||||
|
number to move.
|
||||||
|
|
||||||
|
**Server finding S2 (not fixed):** the escrow of an offer that expires or is cancelled after the POP's store filled up again is
|
||||||
|
refunded only up to the Rack hall cap (`trade.refund`, decision R1). The harness books it: 36 refunds per 30-day run (all three seeds) lose
|
||||||
|
12 to 15k Hardware and Capital in total (`arch-d30-s1`: 3.3k Hardware, 11.2k Capital in 36 events), invisibly to the player.
|
||||||
|
DESIGN.md says nothing is lost in trade. Fix options: credit the clipped part back as a transport that waits, or let escrow refunds
|
||||||
|
exceed the cap the way the existing "stock above a lowered cap is kept" rule does for stock.
|
||||||
|
|
||||||
|
### Power binds early and then recedes
|
||||||
|
|
||||||
|
Share of POPs that carry units whose net power is below 3 per hour: 64 to 77 % on day 4, 52 to 56 % on day 8, about 30 % on day 12,
|
||||||
|
6 to 11 % from day 20 (`arch-d30-s1..3`). The bots size armies to net power, so no unit went offline in any standard run (0 `units_offline`
|
||||||
|
notifications, 0 decommissioned); that path is covered only by the unit tests. Units on the road draw power from nobody, so a raider that is
|
||||||
|
out frees headroom, trains more, and finds the POP over its output when the army returns: in a one-off probe (not part of the harness) 22 of 1 039 raiding sittings of a 20-day run found
|
||||||
|
the capital's units offline (transient, fixed by the next substation level). Not tuned.
|
||||||
|
|
||||||
|
### Everything else that looked fine, with numbers
|
||||||
|
|
||||||
|
- **Footprint gate vs reachable footprint:** the gate for the first extra POP (500) is passed on day ~8 by 84 to 100 % of operators; the
|
||||||
|
8th extra POP needs 21k and the median footprint is 10k on day 30 and 40k on day 60 (4 a day). The gate never binds before Core
|
||||||
|
router 10 and the crews do.
|
||||||
|
- **Incumbent sites:** 14 to 21 attacks per 30-day run (raiders and conquerors only), all won, +2 500 Hardware each (35 to 52k in total)
|
||||||
|
for units worth 1.4 to 1.6k lost per attack: farmable, not a runaway (defence grows 4 % a day, the bots' armies and travel time cap the
|
||||||
|
rate). Not tuned.
|
||||||
|
- **Storage:** with B1, 13 % (14 days) to 26 % (30 days) of the production the rates would give is lost to full stores, mostly Hardware and
|
||||||
|
Capital (28 to 30 % against 19 % Fiber), and from saturation on (day ~50 at 4 sittings) nearly all of it. Stores are meant to cap
|
||||||
|
the economy; the point is that a committed player has nothing left to spend on in the capital for ~50 days before the backbone
|
||||||
|
opens, except units and extra POPs. A pacing decision, not changed.
|
||||||
|
- **Beginner protection** (72 h): 0 raids against operators younger than 4 days in any run.
|
||||||
|
- **Rack hall cache** and **loyalty/takeover** behave as described above.
|
||||||
|
- **Performance:** 50 players x 60 days in 17 to 30 s (the higher figure with 16 runs in parallel), 200 players x 14 days (radius 100) in 14 s, p95 command latency 0.1 to 0.5 ms,
|
||||||
|
no failed event and no unexpected error code in any run listed here.
|
||||||
|
|
||||||
|
## 5. The end game
|
||||||
|
|
||||||
|
### What the bots do
|
||||||
|
|
||||||
|
When the world is at day `ENDGAME.openDay / speed` every alliance with at least 3 members plans (a shared in-memory plan, what an
|
||||||
|
alliance would agree in its chat): the site with the lowest static defence (a little weight on distance); ONE member with an Ops lab trains
|
||||||
|
Script crews to 1.12 times the site's defence at arrival and attacks with everything it has (an attack is one movement from one POP and is resolved
|
||||||
|
against the full static defence, so attacks cannot be added up); once the alliance holds a site every member ships its spare Fiber, Hardware and Capital
|
||||||
|
(`backboneShip`, up to its free links per sitting) and anyone starts the next level when the stockpile pays for it (`backboneBuild`).
|
||||||
|
`--endgame-step-min N` adds a final push: those members also act every N minutes after the sites opened.
|
||||||
|
|
||||||
|
### What the runs show
|
||||||
|
|
||||||
|
- **Capturing is not hard for a developed alliance.** In the 1x runs three alliances took a site within 0.1 to 2.5 days of the opening (the
|
||||||
|
first attack that was strong enough; 3 of 3 landing attacks won), in the 3x world six sites were held by six alliances after 14 won attacks (sites
|
||||||
|
change hands while the defence is still low). The static defence of a site at day 100 is 27k to 45k depending on the site (600 x 5.0 x 12 x a seeded +-25 %), i.e. an army of
|
||||||
|
700 to 1 150 Script crews before research, which the striker (the member with the best economy and an Ops lab) had within days.
|
||||||
|
- **Nothing is contested afterwards, and nothing can be.** The biggest army any single POP held at the end was 55 to 62k attack before research;
|
||||||
|
the defence of a built-up site was 200 to 240k at speed 1 (levels 89+), 370 to 440k at speed 3. Defence passes what one POP can send
|
||||||
|
at node level ~25 (weakest site) to ~40. That is E1 (no garrisons) showing up: after the opening days the race is shipping and node build
|
||||||
|
time, not war. The only interaction is the opening scramble (the 3x world saw 14 won attacks for 6 sites; the 1x worlds none after the
|
||||||
|
first three).
|
||||||
|
- **Is 7.2 M of each resource feasible or trivial?** Not infeasible, not trivial: with the capacity it was (500) the leading alliance (13 to 19 members) needed
|
||||||
|
more than 90 days after opening at 1x (extrapolated 100 to 150); with 1000, 55 to 78 days (seeds 1 to 3). Production is not the limit (previous section).
|
||||||
|
- **With attention it is fast.** A 10x world, seed 1, members of the alliances that chase the backbone online every 30 minutes after the
|
||||||
|
sites opened (`--speed 10 --days 24 --endgame-step-min 30`): the winner finished 13.8 days after opening with 500 per link and 8.5 days
|
||||||
|
with 1000 (85 world days; the node build time alone is 3.6 days at 10x). Without the final push (`--speed 10 --days 30`, 500 per link) the best
|
||||||
|
node was at level 58 nineteen days after opening. So the race is decided by who is online, as designed, and 1000 per link does not make it trivial
|
||||||
|
for people who are not.
|
||||||
|
- **Conservation holds through all of it**: shipments, bounces, stockpiles and Backbone levels are in the ledger; every run above finished
|
||||||
|
`INVARIANTS OK` (the first speed-1 runs of this pass were flagged only because the bots kept commanding an ended world; the harness now stops
|
||||||
|
and treats `world_ended` as expected).
|
||||||
|
|
||||||
|
|
||||||
|
## 6. Server findings
|
||||||
|
|
||||||
|
| # | finding | status |
|
||||||
|
|---|---|---|
|
||||||
|
| S1 | **Cargo above the Rack hall cap was destroyed silently on bounced shipments.** A shipment that comes home (landing site changed hands, POP gone) rides back on a `link` return leg; `events/return.js` sent no notification for link legs, so the overflow was invisible to the player and to any audit. The conservation ledger found it as 1 000 Hardware + 2 718 Capital of drift in the first speed-10 end-game run (`node tools/bot.js --players 50 --days 14 --seed 1 --speed 10 --endgame-step-min 30`; with the fix the same command shows no drift, and it reproduces the bug if the `carrying` condition in `return.js` is taken out). | **fixed** (`return.js` notifies when a link leg carries cargo), `test/bot-server-fixes.test.js` fails without the fix |
|
||||||
|
| S2 | Trade escrow refunds are clipped at the Rack hall cap and the loss is not reported (section 4). | open, design decision |
|
||||||
|
| S3 | `reports.id` is `INTEGER PRIMARY KEY` without `AUTOINCREMENT`; the 14-day cleanup can empty the table and SQLite then reuses low ids. A consumer that keeps "the last report id I saw" (the harness did, and silently missed every report after the first cleanup in a 170-day run) skips new reports. The API's own cursor (`GET /reports?after=` with `r.id < after`, newest first) is not hurt unless a client mixes old and new ids. Repro in five lines: insert three reports, `DELETE FROM reports`, insert one more: its id is 1 (the harness hit it in 170-day runs, where raids stop and every report expires). | open, low severity |
|
||||||
|
| S4 | Loot is split evenly over the three resources and destroyed on overflow (section 4). | open, design |
|
||||||
|
| S5 | `ensureSites` is lazy (E2): the first touch of a landing site writes `backbone_open`; the harness reads sites with `E.siteStates` and never triggers it. No bug, noted so nobody expects the push in a bot run. | known |
|
||||||
|
|
||||||
|
## 7. Bot bugs that moved the numbers (so nobody trusts an early number from this pass)
|
||||||
|
|
||||||
|
- Bots read reports with "id greater than the last id": after the first 14-day cleanup new reports were skipped and the unit ledger
|
||||||
|
drifted (phantom `script_crew -855`). Fixed with a (created_at, ids at that instant) cursor (S3).
|
||||||
|
- The wish list offered the field that was already being built, so a bot with two or more build slots could only ever have ONE field
|
||||||
|
upgrade running. That understated B1: before the fix the second slot at Core 3 looked like +25 % net worth for casual players, after
|
||||||
|
it 2.6 times (2 sittings a day, 60 days). Every table in this document was produced after that fix.
|
||||||
|
- Bots tried to send raids from POPs whose units were offline (676 refused commands in one 30-day run) and ran a fixed "balanced"
|
||||||
|
field policy that wasted Capital; both fixed (`--field-policy balanced` keeps the old one as a lower bound).
|
||||||
|
|
||||||
|
## 8. What is still unknown
|
||||||
|
|
||||||
|
- Bots are not humans. They never forget to log in, never panic, never coordinate beyond a shared in-memory plan, never mis-click, and play
|
||||||
|
the same sittings every day. They do not use reinforcement, recall, the shared report folder, messages, sitters, or night play. They
|
||||||
|
never choose a different capital or sell their stock off before an attack.
|
||||||
|
- No real players means no data on how many sittings a day people really play; the whole B1 argument rests on the 2-to-8 sittings-a-day
|
||||||
|
band that the CLAUDE.md pitch implies.
|
||||||
|
- Rural bonuses, wild slots and the Peering office size ladder were not examined. The offline/decommission power path never ran in a bot
|
||||||
|
run. The alliance war/peace states were exercised (NAP, confederation, war appear in the runs) but never made to matter in a fight.
|
||||||
|
- The end game was run with a single plan per alliance that nobody contests after the first days (section 5); a determined rival with
|
||||||
|
several armies cannot beat a built-up site (single-POP attack ceiling), so there is no data on what an actual fight for a site would look like.
|
||||||
|
- `--always-on` is an upper bound on attention, not a model of a person.
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -230,3 +230,25 @@ Accepted for now, written down so nobody is surprised:
|
||||||
the reviewer or ~70 fuzz seeds; a recovery sweeper is a stage-7 item.
|
the reviewer or ~70 fuzz seeds; a recovery sweeper is a stage-7 item.
|
||||||
- HTTP connections per IP are not capped (only WebSockets are); behind nginx Proxy Manager the per-IP request limiter applies.
|
- HTTP connections per IP are not capped (only WebSockets are); behind nginx Proxy Manager the per-IP request limiter applies.
|
||||||
- Tokens do not expire and there is no change-password route yet (revoke from Settings works).
|
- Tokens do not expire and there is no change-password route yet (revoke from Settings works).
|
||||||
|
|
||||||
|
## B1 — Second build slot at Core router 3, and slots are data (stage 7 balance pass, `docs/BALANCE.md`)
|
||||||
|
The bot harness (`tools/bot.js`) showed that progress is limited by how many builds a player can START per sitting, not by resources or
|
||||||
|
build time (builds take minutes, a level costs hours of production; with one slot a 5-minute sitting starts one or two). 2 sittings a day
|
||||||
|
needed 62 days for the capital's mean field level to reach 10, 4 a day 32. `FORMULAS.secondQueueCoreLevel` 10 -> 3 (data only) brings that to 39 and 22 days
|
||||||
|
and changes nothing for a player who is always online. `rules.queueSlots` now also reads `FORMULAS.extraQueueCores` (default `[]`: more
|
||||||
|
slots at the listed Core router levels; behaviour unchanged until someone fills it). That is a three-line extension of a formula, not a bug
|
||||||
|
fix, logged here because the rule was "formulas only if wrong": more slots (2/3/4/5 at Core 2/4/7/10) would remove most of the gap between
|
||||||
|
casual and committed players but saturate the committed ones six weeks before the backbone opens; left as a pacing decision.
|
||||||
|
|
||||||
|
## B2 — Transport capacity 1000 per link (was 500)
|
||||||
|
The end game is shipping-limited, not production-limited: 21.6 M units (7.2 M of each resource) in 500-unit trips. In three seeds with 50 bots
|
||||||
|
(4 to 5 sittings a day, alliances of 13 to 19) nobody finished level 100 by day 175 to 190 at speed 1 (levels 88 to 97); with 1000 per link one alliance
|
||||||
|
won in each seed, 55 to 78 days after the sites opened (node build time alone is 36 days). Raising `ENDGAME.costGrowth` to 1.035 or
|
||||||
|
the capacity to 2000 were measured and not taken (2000 leaves only the 36-day build floor as a constraint). Not solved: a 3x world takes about as
|
||||||
|
long after the sites open as a 1x world, because shipping is per sitting, not per hour; `capacityPerLink x world speed` would fix it but the
|
||||||
|
client reads the constant. See BALANCE.md section 5.
|
||||||
|
|
||||||
|
## B3 — A bounced shipment reports its overflow
|
||||||
|
`events/return.js` stayed silent for empty-carrier return legs AND for shipments that came home with cargo; cargo above the Rack hall cap is
|
||||||
|
dropped on arrival, so that loss was invisible. Link legs that carry cargo now send `movement_returned` with `cargoLost`
|
||||||
|
(`test/bot-server-fixes.test.js`). Found by the harness's conservation ledger (BALANCE.md section 6, S1).
|
||||||
|
|
|
||||||
|
|
@ -67,7 +67,7 @@ One build queue per POP. The **Core router** level shortens all build times. Lev
|
||||||
|
|
||||||
| Building | Role |
|
| Building | Role |
|
||||||
| --------------- | --------------------------------------------------------------------------------------------- |
|
| --------------- | --------------------------------------------------------------------------------------------- |
|
||||||
| Core router | Required for everything. Build time ÷ (1 + 0.04·L). Unlocks the second queue slot at 10. |
|
| Core router | Required for everything. Build time ÷ (1 + 0.04·L). Unlocks the second queue slot at 3 (was 10, BALANCE.md B1). |
|
||||||
| Rack hall | Storage cap for Fiber/Hardware/Capital: `cap(L) = 1000 * 1.22^(L-1)`. |
|
| Rack hall | Storage cap for Fiber/Hardware/Capital: `cap(L) = 1000 * 1.22^(L-1)`. |
|
||||||
| Battery bank | Power buffer: `buf(L) = 200 * 1.22^(L-1)` points. |
|
| Battery bank | Power buffer: `buf(L) = 200 * 1.22^(L-1)` points. |
|
||||||
| Firewall | Defence multiplier `1 + 0.03·L`. DDoS rigs reduce it during attacks. |
|
| Firewall | Defence multiplier `1 + 0.03·L`. DDoS rigs reduce it during attacks. |
|
||||||
|
|
@ -159,11 +159,11 @@ A new POP starts at level 0 everything and 1 h of resources. Takeover requires t
|
||||||
|
|
||||||
The Internet exchange lists offers "give X of A for Y of B, max distance Z". Ratio bounded 1:2 to stop
|
The Internet exchange lists offers "give X of A for Y of B, max distance Z". Ratio bounded 1:2 to stop
|
||||||
pump-feeding. Accepting an offer spawns two transport movements. Direct transports to own POPs or to any player
|
pump-feeding. Accepting an offer spawns two transport movements. Direct transports to own POPs or to any player
|
||||||
(e.g. alliance support) use the same links. Transport links: level of the exchange, capacity 500 each.
|
(e.g. alliance support) use the same links. Transport links: level of the exchange, capacity 1000 each (500 before BALANCE.md B2).
|
||||||
|
|
||||||
**Clarified (what the server does).**
|
**Clarified (what the server does).**
|
||||||
- An offer is "give `giveAmount` of `giveRes` for `wantAmount` of `wantRes`, within `maxDistance` tiles", posted from one POP that has
|
- An offer is "give `giveAmount` of `giveRes` for `wantAmount` of `wantRes`, within `maxDistance` tiles", posted from one POP that has
|
||||||
an Internet exchange. Each side must fit ONE transport link (1..500) and the two amounts differ by at most 1:2:
|
an Internet exchange. Each side must fit ONE transport link (1..1000) and the two amounts differ by at most 1:2:
|
||||||
`give <= 2 x want` and `want <= 2 x give` (count-based, the resources are not weighted). The resources must differ.
|
`give <= 2 x want` and `want <= 2 x give` (count-based, the resources are not weighted). The resources must differ.
|
||||||
- The offered amount is **escrowed**: it leaves the POP when the offer is posted. Cancelling or expiry (48 h / world speed) credits it back
|
- The offered amount is **escrowed**: it leaves the POP when the offer is posted. Cancelling or expiry (48 h / world speed) credits it back
|
||||||
to the POP without the Rack hall cap (an amount above the cap is kept, it only stops growing), so nothing is created or lost.
|
to the POP without the Rack hall cap (an amount above the cap is kept, it only stops growing), so nothing is created or lost.
|
||||||
|
|
@ -204,7 +204,7 @@ stays with the site. Landing sites cannot be settled, only taken.
|
||||||
home otherwise). A full attack with attack > defence wins: the attacker's alliance holds the site. No loot, the site loses nothing, the
|
home otherwise). A full attack with attack > defence wins: the attacker's alliance holds the site. No loot, the site loses nothing, the
|
||||||
survivors drive home. Level, stockpile and a running build stay with the site. A holder that disbands leaves the site to the incumbent
|
survivors drive home. Level, stockpile and a running build stay with the site. A holder that disbands leaves the site to the incumbent
|
||||||
(level kept).
|
(level kept).
|
||||||
- **Feeding the node:** members of the holder alliance send resources by transport (`POST /backbone/:id/ship`, same links, 500 per link, 12
|
- **Feeding the node:** members of the holder alliance send resources by transport (`POST /backbone/:id/ship`, same links, 1000 per link, 12
|
||||||
tiles/h). On arrival they join the stockpile if the sender's alliance still holds the site, otherwise they ride home. A ledger records
|
tiles/h). On arrival they join the stockpile if the sender's alliance still holds the site, otherwise they ride home. A ledger records
|
||||||
who sent what.
|
who sent what.
|
||||||
- **Building:** level L (1..100) costs `4000 x 1.045^(L-1)` of each resource (level 100: 312 301; about 7.2 million of each in total) and
|
- **Building:** level L (1..100) costs `4000 x 1.045^(L-1)` of each resource (level 100: 312 301; about 7.2 million of each in total) and
|
||||||
|
|
@ -251,7 +251,7 @@ computed from `serverTime`.
|
||||||
or attacked, never raided or taken over, and never fight back.
|
or attacked, never raided or taken over, and never fight back.
|
||||||
- **Power:** when the battery is empty and net power is negative, all units in that POP are offline; after 24 h / speed the most
|
- **Power:** when the battery is empty and net power is negative, all units in that POP are offline; after 24 h / speed the most
|
||||||
expensive are decommissioned until the draw fits.
|
expensive are decommissioned until the draw fits.
|
||||||
- **Transport:** 12 tiles/h, 500 per link, links = Internet exchange level; a link is busy until the empty carriers are back.
|
- **Transport:** 12 tiles/h, 1000 per link, links = Internet exchange level; a link is busy until the empty carriers are back.
|
||||||
- **Protection and recall:** see S3-4 and S3-7 in DECISIONS.md; the recall window is 90 s of real time (not divided by world speed).
|
- **Protection and recall:** see S3-4 and S3-7 in DECISIONS.md; the recall window is 90 s of real time (not divided by world speed).
|
||||||
|
|
||||||
## Open questions
|
## Open questions
|
||||||
|
|
|
||||||
69
docs/NEXT.md
69
docs/NEXT.md
|
|
@ -20,7 +20,7 @@ Not done:
|
||||||
- Marketplace / Internet exchange: DONE on the server, see "Trade, end game, gaps" below.
|
- Marketplace / Internet exchange: DONE on the server, see "Trade, end game, gaps" below.
|
||||||
- Shared report folder and "see each other's incoming": DONE on the server (below). The pact effect "no attacks inside a NAP/confederation"
|
- Shared report folder and "see each other's incoming": DONE on the server (below). The pact effect "no attacks inside a NAP/confederation"
|
||||||
is enforced by the military stage (`pactBlocks`).
|
is enforced by the military stage (`pactBlocks`).
|
||||||
- No web client; WebSocket push (stage 6) now exists server-side, see "Stage 6" below.
|
- Web client: see the client sections below; WebSocket push (stage 6) exists server-side and in the client.
|
||||||
- Message retention/cleanup of old rows, alliance rename/description, mass-mail abuse reporting, sitter accounts.
|
- Message retention/cleanup of old rows, alliance rename/description, mass-mail abuse reporting, sitter accounts.
|
||||||
- Rankings are not cached; battle rankings stay empty until the military stage writes `operator_stats`.
|
- Rankings are not cached; battle rankings stay empty until the military stage writes `operator_stats`.
|
||||||
- Not run: Playwright, load, or any bot balance run; the social numbers in `SOCIAL` (limits, TTLs, role table) are first guesses.
|
- Not run: Playwright, load, or any bot balance run; the social numbers in `SOCIAL` (limits, TTLs, role table) are first guesses.
|
||||||
|
|
@ -41,7 +41,7 @@ its protections, offline units and decommission, restart catch-up from a reopene
|
||||||
recall, research, reports/cursor/retention, API smoke over HTTP). Fake clock, in-memory DB, port 0; no Playwright.
|
recall, research, reports/cursor/retention, API smoke over HTTP). Fake clock, in-memory DB, port 0; no Playwright.
|
||||||
Not done / not claimed:
|
Not done / not claimed:
|
||||||
- **Nothing is balanced.** All unit stats, costs, research curves, incumbent defence and the 50-unit-scale combat numbers are first guesses;
|
- **Nothing is balanced.** All unit stats, costs, research curves, incumbent defence and the 50-unit-scale combat numbers are first guesses;
|
||||||
there was no bot run (`tools/bot.js` does not exist yet). Do not cite any of them as tuned.
|
there was no bot run when this was written (`tools/bot.js` exists now: see "Stage 7" below and BALANCE.md; most of these numbers are still untuned). Do not cite any of them as tuned.
|
||||||
- Training cannot be cancelled; no sitter, no night protection. (Report sharing and allied incoming: done, see below.)
|
- Training cannot be cancelled; no sitter, no night protection. (Report sharing and allied incoming: done, see below.)
|
||||||
- Units in transit draw no power from anyone; an operator cannot choose a new capital POP (no command); a captured POP keeps its footprint.
|
- Units in transit draw no power from anyone; an operator cannot choose a new capital POP (no command); a captured POP keeps its footprint.
|
||||||
- Backbone landing sites and the Backbone node: see "Trade, end game, gaps" below.
|
- Backbone landing sites and the Backbone node: see "Trade, end game, gaps" below.
|
||||||
|
|
@ -133,6 +133,47 @@ Not done / not claimed:
|
||||||
- Close 4401 stops the socket but does not itself send the player to login: that happens on the next REST 401 (`api` `unauthorized`).
|
- Close 4401 stops the socket but does not itself send the player to login: that happens on the next REST 401 (`api` `unauthorized`).
|
||||||
- `ready.serverTime` is not used for the clock offset (no round-trip estimate on the socket); REST responses keep doing that.
|
- `ready.serverTime` is not used for the clock offset (no round-trip estimate on the socket); REST responses keep doing that.
|
||||||
|
|
||||||
|
## Client: trade, end game, alerts (public/)
|
||||||
|
Built (More group; strings in `strings/{trade,world,alerts}.js`, en + nb):
|
||||||
|
- **Exchange** (`screens/trade.js`): tabs Offers / New / Mine / Send. Offers: filters give / want / POP, reach pills, "Take" sheet with a POP chooser
|
||||||
|
from `acceptableFrom` (distance, transport time, stock, free links, why a POP is greyed out). New: live check with `rules.tradeTermsCheck` (1:2 band,
|
||||||
|
1000 per link, distance), stock and free-link checks, the exchange level a taker needs, escrow/expiry rules in words. Mine: status chips, poster/acceptor
|
||||||
|
role, expiry countdown, cancel. Send: direct transport through the send dialog (`App.openSend({ type: 'transport' })`; `milcore.moveOptions` got a
|
||||||
|
`transportOnly` flag so a rival's POP can be the target) plus links in use per exchange POP. No exchange: empty state with the requirement (Core router 4).
|
||||||
|
- **Backbone race / ended world** (`screens/world.js`, `endcore.js`, `cargo-ui.js`): phase banner (countdown to the landing sites, leading alliance, winner,
|
||||||
|
ended), the 7 sites with holder / level / build progress / stockpile, Manage sheet for your alliance's sites (build next level, ship resources, ledger),
|
||||||
|
scan/attack through the send dialog (`milcore.moveOptions` landing branch), final ranking tabs after the end. Whole-client ended mode: `App.worldEnded()`,
|
||||||
|
pill in the top bar, card on the POP screen, action buttons (primary/danger/`[data-act]`, not `[data-keep]`) disabled by a MutationObserver; a stale page
|
||||||
|
learns it from a `world_ended` error (via `App.errMsg`), the `world_ended` push or `/me`.
|
||||||
|
- **Map**: landing sites drawn as a diamond with a level ring (gold = incumbent, cyan = yours, magenta = rival alliance), legend row, tile sheet (holder, level,
|
||||||
|
Backbone race button, send). **Reports**: `landing` type, scans of landing sites, share to alliance, Alliance tab (folder), remove from folder; shared reports
|
||||||
|
are told from nobody's side. **Movements**: shipments to a site are labelled; `alliedIncoming` was already there and never counts in the red badge.
|
||||||
|
- **Alerts** (`alertkinds.js`, pure): every notification type the server writes (found by a test that greps `server/`) has a describer; includes trade_*,
|
||||||
|
backbone_*, world_ended, alliance_*, diplomacy_*, message kinds.
|
||||||
|
- Tests: `test/client-world.test.js` (endcore, moveOptions, string coverage, no HTML sinks, every public script parses), `test/client-alerts.test.js`,
|
||||||
|
`test/client-i18n.test.js` now iterates `CODES` of `server/errors.js`. 203 tests green.
|
||||||
|
- Looked at in headless Chromium against the real server (real clock, in-memory DB; scratch scripts, not in the repo): screenshot sweep of every new screen on phone
|
||||||
|
portrait, phone landscape and desktop (en, plus nb for trade/world) in three world states (day 62, day 100+ with held sites, ended); scripted flows with DB
|
||||||
|
assertions (take an offer, post with live validation, cancel, transport to a rival by coordinates, ship, build, scan/attack dialog, tap a site on the map, share
|
||||||
|
and unshare a report, alerts feed, a stale page hitting `world_ended`).
|
||||||
|
- **Push, end to end in real browsers**: Alice raids Bob; Bob's page (real login, WebSocket open) showed the incoming banner, red Moves badge and toast 214 ms
|
||||||
|
after the launch with no reload; the banner went away and the Reports badge rose when the raid arrived. With `WebSocket` undefined, and with a socket that is
|
||||||
|
closed at once (reconnect loop, 7 attempts in the run), the same raid showed up after about 52 s through the REST poll (15 s tick, 45 s gap): worst case about a
|
||||||
|
minute. Confederate Carol gets no push for `alliedIncoming` (known server gap): it shows when the Moves screen is opened or the poll runs, and never in her badge.
|
||||||
|
Found and fixed in the client: `report` pushes now also refetch movements (the incoming banner used to linger up to a few seconds after the arrival).
|
||||||
|
Not done / not claimed:
|
||||||
|
- Not run: real devices, Safari, a socket behind nginx Proxy Manager, throttled networks, the Playwright suite (`e2e/` is still empty), long lists (offers > 25 per
|
||||||
|
filter paged only up to what the sweep seeded).
|
||||||
|
- Ended-world locking is a DOM sweep, not per-button wiring: a new primary/danger button that is NOT a game command must carry `data-keep`. Messages, ranking and
|
||||||
|
settings screens are exempt by selector. Open send/trade sheets that were opened before the end stay usable until the next DOM change or a refused command.
|
||||||
|
- Trade: no order book or price history, no notification for new offers in reach, offers are listed per page of 25 with a cursor only. The landing-site manage sheet
|
||||||
|
does not poll while open (it reloads after your own actions and when the site screen refreshes). Ledger shows the top 15 contributors.
|
||||||
|
- Site numbers are `index + 1` ("Landing site 1..7"), not a name from the server. `backbone_open` is only pushed on first touch (server E2): the countdown flips
|
||||||
|
by the client clock at `opensAt`, the sites appear after the next status fetch.
|
||||||
|
- A transport to a rival's POP is a gift that warns its owner (`incoming`, type hidden); the UI says so, but nothing stops a griefing stream of them.
|
||||||
|
- Server bug found and fixed (tiny): `POST /reports/:id/share` threw a 500 when no `reportCleanup` event was pending (`ensureCleanup` needs `ctx.enqueue`);
|
||||||
|
`reportShare` now wraps its ctx with `ctxOf`, regression test `test/report-share-cleanup.test.js` (failed before).
|
||||||
|
|
||||||
## Stage 6 (server half): WebSocket push
|
## Stage 6 (server half): WebSocket push
|
||||||
Built: `/ws` on the game's HTTP server (`server/push.js` transport, `server/pushHooks.js` routing), contract in `docs/PROTOCOL.md`.
|
Built: `/ws` on the game's HTTP server (`server/push.js` transport, `server/pushHooks.js` routing), contract in `docs/PROTOCOL.md`.
|
||||||
Auth as first message (`ready` / close 4401), Origin check (`net.originAllowed`), per-IP cap `MAX_CONN_PER_IP` (HTTP 429), 1 KB frames,
|
Auth as first message (`ready` / close 4401), Origin check (`net.originAllowed`), per-IP cap `MAX_CONN_PER_IP` (HTTP 429), 1 KB frames,
|
||||||
|
|
@ -173,7 +214,7 @@ Built and tested (`test/trade-*.test.js`, `test/endgame-*.test.js`; fake clock,
|
||||||
Not done / not claimed:
|
Not done / not claimed:
|
||||||
- **Nothing here is balanced.** Defence multiplier 12 (+3% per level), node cost 4000 x 1.045^(L-1) (about 7.2 M of each resource in total),
|
- **Nothing here is balanced.** Defence multiplier 12 (+3% per level), node cost 4000 x 1.045^(L-1) (about 7.2 M of each resource in total),
|
||||||
node time 2 h x 1.025^(L-1) (about 36 world days), 48 h offer ttl, 10 tiles of reach per exchange level, 500-per-side offers: first guesses,
|
node time 2 h x 1.025^(L-1) (about 36 world days), 48 h offer ttl, 10 tiles of reach per exchange level, 500-per-side offers: first guesses,
|
||||||
no bot run (`tools/bot.js` still does not exist). Whether an alliance can actually ship 7 M of everything in time is unknown.
|
no bot run when written (now there is one: BALANCE.md section 5 says an 18-member alliance needs 55 to 78 days after the sites open with 1000 per link, and does not finish in 175 days with 500).
|
||||||
- **No garrison at landing sites** (E1): defence is static, holders cannot station units. If the first world shows the race is decided by who
|
- **No garrison at landing sites** (E1): defence is static, holders cannot station units. If the first world shows the race is decided by who
|
||||||
hits first, the next step is a small `site_units` table with reinforce-to-site and defenders in `landing.js`.
|
hits first, the next step is a small `site_units` table with reinforce-to-site and defenders in `landing.js`.
|
||||||
- No `backbone_open` push at the moment the sites appear unless something touches a site first (E2); clients see the phase by polling status.
|
- No `backbone_open` push at the moment the sites appear unless something touches a site first (E2); clients see the phase by polling status.
|
||||||
|
|
@ -182,9 +223,25 @@ Not done / not claimed:
|
||||||
- Ended worlds: movements still `out` and queued builds are left as they were (events cancelled, E3); there is no admin "end world now" or
|
- Ended worlds: movements still `out` and queued builds are left as they were (events cancelled, E3); there is no admin "end world now" or
|
||||||
"reset" yet (stage 7 world lifecycle: the `worldEnd` event can be enqueued by hand); several winners are impossible by design.
|
"reset" yet (stage 7 world lifecycle: the `worldEnd` event can be enqueued by hand); several winners are impossible by design.
|
||||||
- The ranking snapshot is the same numbers as `/rankings`, computed once; `/rankings/*` after the end still compute live from the frozen state.
|
- The ranking snapshot is the same numbers as `/rankings`, computed once; `/rankings/*` after the end still compute live from the frozen state.
|
||||||
- Client: nothing in `public/` was touched. New notification types (`trade_*`, `backbone_*`, `world_ended`), the `landing` report type, the
|
- Client for all of this: see "Client: trade, end game, alerts" above.
|
||||||
`backbone` map special / tile, `world_ended` and the new error codes (`trade_ratio`, `offer_closed`, `own_offer`, `trade_out_of_range`,
|
|
||||||
`world_ended`, `backbone_closed`) need strings and screens.
|
## Stage 7 (first part): bot harness and first balance pass
|
||||||
|
Built: `tools/bot.js` (+ `tools/bot/*`): N headless bots (builder, raider, conqueror, turtle, expander, trader, alliancer; a coordinated alliance
|
||||||
|
plays the end game) against the real server in-process (`createServer` with an in-memory DB and a FakeClock, bots drive `srv.commands.run`, no
|
||||||
|
HTTP), 50 players x 14 days in ~3 s, x 170 days in ~140 s. Per-day economy, progression, combat, trade, alliance, end game, performance and
|
||||||
|
error tables; `--json`, `--set PATH=VALUE` data overrides, `--sessions-per-day`, `--always-on`, `--speed`, `--strategy-mix`. Exit code 1 when an
|
||||||
|
invariant breaks: exact resource conservation (production measured at every settle, sinks from command results and notifications), exact unit
|
||||||
|
conservation, no negative stock, no failed events, no unexpected error codes. `docs/BALANCE.md` has the method, every run behind a number, what
|
||||||
|
was tuned and what was not.
|
||||||
|
Tuned (each with before/after runs in BALANCE.md): second build slot at Core router 3 (was 10), transport capacity 1000 per link (was 500).
|
||||||
|
Server fix found by the harness: bounced shipments reported no overflow (`events/return.js`).
|
||||||
|
Tests: `test/bot-run.test.js` (12 players x 6 days twice, identical stats, invariants, the checks catch tampering, a fast world reaches the end game),
|
||||||
|
`test/bot-server-fixes.test.js`.
|
||||||
|
Not done / not claimed: **the game is not balanced**; the bots are not humans (no reinforcement, recall, messages, sitters; fixed sittings). Open
|
||||||
|
items from the pass: a 3x world's end game is as long as a 1x world's (shipping is per sitting; `capacityPerLink x speed` needs the client to stop
|
||||||
|
reading the constant); trade escrow refunds are clipped at the Rack hall cap silently; raid loot is split evenly over resources and destroyed on overflow;
|
||||||
|
the capital runs out of things to build ~50 days before the backbone opens at 4 sittings a day; a built-up landing site is out of reach of any
|
||||||
|
single-POP army (no garrisons, E1), so there is no fight for a site after the first days.
|
||||||
|
|
||||||
## Not done
|
## Not done
|
||||||
- Everything else. See CLAUDE.md "Working in stages".
|
- Everything else. See CLAUDE.md "Working in stages".
|
||||||
|
|
|
||||||
|
|
@ -511,3 +511,95 @@ select { width: 100%; }
|
||||||
.mil-train .cost { padding: 3px 8px; }
|
.mil-train .cost { padding: 3px 8px; }
|
||||||
.mil-train .cost svg.ic { width: 15px; height: 15px; }
|
.mil-train .cost svg.ic { width: 15px; height: 15px; }
|
||||||
.mil-train .pill { max-width: none; }
|
.mil-train .pill { max-width: none; }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------- Internet exchange (trd-), end game (wld-), ended world */
|
||||||
|
.trd-page, .wld-page { gap: 10px; }
|
||||||
|
.trd-tabs .seg-btn { min-width: 0; padding: 0 4px; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.trd-body { display: grid; gap: 12px; align-content: start; min-width: 0; }
|
||||||
|
.trd-filters { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 10px; }
|
||||||
|
.trd-filters .field:nth-child(3) { grid-column: 1 / -1; }
|
||||||
|
.trd-reach { margin: 0 0 10px; }
|
||||||
|
.trd-list { gap: 8px; }
|
||||||
|
.trd-offer { display: grid; grid-template-columns: 38px minmax(0, 1fr); gap: 8px 10px; align-items: start; }
|
||||||
|
.trd-offer .row-main { gap: 6px; }
|
||||||
|
.trd-offer .row-sub { white-space: normal; overflow-wrap: anywhere; }
|
||||||
|
.trd-offer > .btn { grid-column: 1 / -1; min-height: 44px; }
|
||||||
|
.trd-terms { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 10px; }
|
||||||
|
.trd-term { display: grid; gap: 3px; min-width: 0; align-content: start; }
|
||||||
|
.trd-lbl { font-size: 11px; color: var(--dimmer); text-transform: uppercase; letter-spacing: .08em; }
|
||||||
|
.trd-terms .cost { width: max-content; max-width: 100%; }
|
||||||
|
.trd-chips { margin-bottom: 2px; }
|
||||||
|
.trd-need { display: grid; gap: 10px; }
|
||||||
|
.trd-need .card-head { margin-bottom: 0; }
|
||||||
|
.trd-pops { display: grid; gap: 8px; }
|
||||||
|
.trd-pop { display: flex; align-items: flex-start; gap: 10px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; min-height: 56px; }
|
||||||
|
.trd-pop:has(input:checked) { border-color: var(--cyan); background: #0c1f33; }
|
||||||
|
.trd-pop.off { opacity: .65; }
|
||||||
|
.trd-pop input { width: 22px; height: 22px; flex: none; margin-top: 2px; accent-color: var(--cyan); }
|
||||||
|
.trd-form .field { margin-bottom: 8px; }
|
||||||
|
.trd-form .sub { margin-top: 10px; }
|
||||||
|
.trd-form .field-hint, .trd-form > .dimmer { display: block; margin-top: 2px; }
|
||||||
|
.trd-page .card .detail-desc { margin-bottom: 8px; }
|
||||||
|
.trd-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 8px; align-items: center; }
|
||||||
|
.trd-pair select, .trd-pair input.mil-num { min-height: 46px; }
|
||||||
|
.trd-pair .btn.small { min-height: 46px; }
|
||||||
|
.trd-msgs { display: grid; gap: 4px; margin-top: 8px; }
|
||||||
|
.trd-msgs:empty { display: none; }
|
||||||
|
.trd-note { display: grid; gap: 4px; margin-top: 4px; }
|
||||||
|
.trd-links .mil-row { align-items: flex-start; }
|
||||||
|
.trd-links .bar { margin-top: 6px; --c: var(--cyan); }
|
||||||
|
.trd-empty { display: grid; gap: 8px; }
|
||||||
|
|
||||||
|
.wld-banner { display: flex; gap: 14px; align-items: center; border-color: var(--line2); }
|
||||||
|
.wld-banner .row-main { gap: 6px; }
|
||||||
|
.wld-banner h2 { font-size: 18px; line-height: 1.25; text-transform: none; letter-spacing: 0; color: var(--text); overflow-wrap: anywhere; }
|
||||||
|
.wld-trophy { width: 52px; height: 52px; flex: none; display: grid; place-items: center; border-radius: 16px; background: var(--panel3); color: var(--cyan); }
|
||||||
|
.wld-trophy svg.ic { width: 30px; height: 30px; }
|
||||||
|
.wld-banner.open { border-color: color-mix(in srgb, var(--cyan) 55%, var(--line2)); }
|
||||||
|
.wld-banner.won, .wld-banner.ended { border-color: #6b5a1f; background: rgba(43, 34, 8, .55); }
|
||||||
|
.wld-banner.won .wld-trophy, .wld-banner.ended .wld-trophy { color: var(--amber); background: #3a2d08; }
|
||||||
|
.wld-count { font-size: 26px; color: var(--cyan); line-height: 1.1; }
|
||||||
|
.wld-cd { font-variant-numeric: tabular-nums; }
|
||||||
|
.wld-bar { height: 8px; margin-top: 4px; --c: var(--dim); }
|
||||||
|
.wld-bar.mine { --c: var(--cyan); } .wld-bar.rival { --c: var(--amber); } .wld-bar.incumbent { --c: var(--violet); } .wld-bar.build { --c: var(--amber); height: 6px; }
|
||||||
|
.wld-sub { margin-top: 4px; }
|
||||||
|
.wld-sites { display: grid; gap: 10px; grid-template-columns: minmax(0, 1fr); }
|
||||||
|
@media (min-width: 900px) { .wld-sites { grid-template-columns: repeat(2, minmax(0, 1fr)); } .wld-page { max-width: 980px; } }
|
||||||
|
.wld-site { display: grid; gap: 8px; align-content: start; }
|
||||||
|
.wld-site.mine { border-color: color-mix(in srgb, var(--cyan) 65%, var(--line)); background: rgba(10, 30, 50, .85); }
|
||||||
|
.wld-site.rival { border-color: #6b5a1f; }
|
||||||
|
.wld-site.flash { animation: wld-flash 1.6s ease-out 1; }
|
||||||
|
@keyframes wld-flash { 0% { box-shadow: 0 0 0 3px var(--amber); } 100% { box-shadow: 0 0 0 0 transparent; } }
|
||||||
|
.wld-site-head { display: flex; align-items: center; gap: 10px; }
|
||||||
|
.wld-site-head .row-main { min-width: 0; }
|
||||||
|
.wld-site .row-sub { white-space: normal; }
|
||||||
|
.wld-holder { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.wld-level { display: grid; gap: 2px; }
|
||||||
|
.wld-building { display: grid; gap: 2px; }
|
||||||
|
.wld-acts { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||||
|
.wld-how { padding-left: 20px; display: grid; gap: 6px; color: var(--dim); font-size: 14px; }
|
||||||
|
.wld-sec { display: grid; gap: 8px; margin-top: 6px; }
|
||||||
|
.wld-manage .costs { margin: 2px 0; }
|
||||||
|
.wld-results { display: grid; gap: 8px; }
|
||||||
|
.wld-results .card-head { margin-bottom: 0; }
|
||||||
|
.wld-ranks { display: grid; gap: 6px; }
|
||||||
|
.wld-rank { display: flex; align-items: center; gap: 10px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 52px; }
|
||||||
|
.wld-rank .row-main { min-width: 0; }
|
||||||
|
.wld-rank .row-sub { white-space: normal; overflow-wrap: anywhere; }
|
||||||
|
.wld-rank.you { border-color: var(--cyan); background: #0c1f33; }
|
||||||
|
.wld-rank.win { border-color: #6b5a1f; background: rgba(43, 34, 8, .55); }
|
||||||
|
.wld-rank.win svg.ic { color: var(--amber); }
|
||||||
|
.wld-ended-card { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; border-color: #6b5a1f; background: rgba(43, 34, 8, .6); }
|
||||||
|
.wld-ended-card .row-main { flex: 1 1 200px; min-width: 0; }
|
||||||
|
.wld-ended-card > .btn { flex: none; }
|
||||||
|
.wld-ended-card .row-ic { color: var(--amber); }
|
||||||
|
.lg.backbone { background: #2b2208; border: 2px solid #f5c542; transform: rotate(45deg) scale(.85); }
|
||||||
|
|
||||||
|
.ended-pill { margin-left: auto; background: #2b2208; color: var(--amber); border: 1px solid #6b5a1f; cursor: pointer; min-height: 30px; }
|
||||||
|
html[data-ended] #app { box-shadow: inset 0 3px 0 #6b5a1f; }
|
||||||
|
button[data-ended-lock] { cursor: not-allowed; }
|
||||||
|
|
||||||
|
.rep-tabs { margin-bottom: 0; }
|
||||||
|
.rep-tabs .seg-btn { min-height: 42px; font-size: 14px; }
|
||||||
|
.rep-verdict.neutral { background: var(--panel2); color: var(--dim); border: 1px solid var(--line2); }
|
||||||
|
.rep-share { display: grid; gap: 8px; border-top: 1px solid var(--line); padding-top: 12px; margin-top: 4px; }
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@
|
||||||
<header id="topbar">
|
<header id="topbar">
|
||||||
<div class="brand"><span class="brand-mark" aria-hidden="true"></span><span id="title">UPSTREAM</span></div>
|
<div class="brand"><span class="brand-mark" aria-hidden="true"></span><span id="title">UPSTREAM</span></div>
|
||||||
<span id="netstate" class="netstate" role="status" aria-live="polite" hidden></span>
|
<span id="netstate" class="netstate" role="status" aria-live="polite" hidden></span>
|
||||||
|
<button id="world-pill" class="netstate ended-pill" type="button" data-keep hidden></button>
|
||||||
</header>
|
</header>
|
||||||
<section id="hud" class="hud" aria-label="Resources" hidden></section>
|
<section id="hud" class="hud" aria-label="Resources" hidden></section>
|
||||||
<main id="view"></main>
|
<main id="view"></main>
|
||||||
|
|
@ -35,13 +36,18 @@
|
||||||
<script src="js/i18n.js" defer></script>
|
<script src="js/i18n.js" defer></script>
|
||||||
<script src="js/strings/military.js" defer></script>
|
<script src="js/strings/military.js" defer></script>
|
||||||
<script src="js/strings/social.js" defer></script>
|
<script src="js/strings/social.js" defer></script>
|
||||||
|
<script src="js/strings/alerts.js" defer></script>
|
||||||
|
<script src="js/strings/trade.js" defer></script>
|
||||||
|
<script src="js/strings/world.js" defer></script>
|
||||||
<script src="js/api.js" defer></script>
|
<script src="js/api.js" defer></script>
|
||||||
<script src="js/ui.js" defer></script>
|
<script src="js/ui.js" defer></script>
|
||||||
<script src="js/social.js" defer></script>
|
<script src="js/social.js" defer></script>
|
||||||
<script src="js/render.js" defer></script>
|
<script src="js/render.js" defer></script>
|
||||||
<script src="js/milcore.js" defer></script>
|
<script src="js/milcore.js" defer></script>
|
||||||
|
<script src="js/endcore.js" defer></script>
|
||||||
<script src="js/main.js" defer></script>
|
<script src="js/main.js" defer></script>
|
||||||
<script src="js/milstate.js" defer></script>
|
<script src="js/milstate.js" defer></script>
|
||||||
|
<script src="js/alertkinds.js" defer></script>
|
||||||
<script src="js/ws.js" defer></script>
|
<script src="js/ws.js" defer></script>
|
||||||
<script src="js/screens/auth.js" defer></script>
|
<script src="js/screens/auth.js" defer></script>
|
||||||
<script src="js/screens/pop.js" defer></script>
|
<script src="js/screens/pop.js" defer></script>
|
||||||
|
|
@ -57,5 +63,8 @@
|
||||||
<script src="js/screens/alliance.js" defer></script>
|
<script src="js/screens/alliance.js" defer></script>
|
||||||
<script src="js/screens/messages.js" defer></script>
|
<script src="js/screens/messages.js" defer></script>
|
||||||
<script src="js/screens/rankings.js" defer></script>
|
<script src="js/screens/rankings.js" defer></script>
|
||||||
|
<script src="js/screens/cargo-ui.js" defer></script>
|
||||||
|
<script src="js/screens/trade.js" defer></script>
|
||||||
|
<script src="js/screens/world.js" defer></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
77
public/js/alertkinds.js
Normal file
77
public/js/alertkinds.js
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* What the Alerts feed shows for the notification types of trade, the end game, the world and the social screens
|
||||||
|
* (alliances, diplomacy, messages). Pure: no DOM, no App. make(ctx) returns { type: (notification, payload) -> { icon, title,
|
||||||
|
* detail, go, params } } and test/client-alerts.test.js feeds it payloads in the shapes the server writes. In the browser the
|
||||||
|
* bottom of this file registers the describers in App.alertKinds (the military ones live in milstate.js, build_done in
|
||||||
|
* screens/alerts.js). Unknown payload fields never throw: a describer falls back to something readable.
|
||||||
|
*
|
||||||
|
* ctx = { t(key, vars), num(n), resName(res), townName(id) -> string | null, clockTime(ms), dayTime(ms) }
|
||||||
|
*/
|
||||||
|
(function (root, factory) {
|
||||||
|
if (typeof module === 'object' && module.exports) module.exports = { make: factory };
|
||||||
|
else {
|
||||||
|
root.UpstreamAlertKinds = { make: factory };
|
||||||
|
if (root.App && root.UpstreamI18n) {
|
||||||
|
const App = root.App, mil = () => App.mil;
|
||||||
|
const kinds = factory({
|
||||||
|
t: (k, v) => App.t(k, v), num: (n) => App.fmt.num(n), resName: (r) => App.resName(r),
|
||||||
|
townName: (id) => (mil() ? mil().townName(id) : null), clockTime: (ms) => mil().clockTime(ms), dayTime: (ms) => mil().dayTime(ms),
|
||||||
|
});
|
||||||
|
for (const k of Object.keys(kinds)) if (!App.alertKinds[k]) App.alertKinds[k] = kinds[k];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}(typeof self !== 'undefined' ? self : this, function make(c) {
|
||||||
|
const t = c.t;
|
||||||
|
const RES = ['fiber', 'hardware', 'capital'];
|
||||||
|
const amt = (a) => (a && a.resource ? c.num(a.amount) + ' ' + c.resName(a.resource) : '');
|
||||||
|
const cargoText = (cargo) => RES.filter((r) => cargo && cargo[r] > 0).map((r) => c.num(cargo[r]) + ' ' + c.resName(r)).join(', ');
|
||||||
|
const town = (id) => c.townName(id) || '#' + id;
|
||||||
|
const tag = (o) => (o ? (o.tag ? '[' + o.tag + ']' : (o.name || '')) : '');
|
||||||
|
const site = (p) => (Number.isInteger(p.index) ? p.index + 1 : '?');
|
||||||
|
const known = (prefix, key) => { const k = prefix + key; const s = t(k); return s === k ? String(key) : s; };
|
||||||
|
const there = (p) => (p.x !== undefined ? t('alerts.at', { x: p.x, y: p.y }) : '');
|
||||||
|
const worldGo = (p) => ({ go: 'world', params: p && Number.isInteger(p.index) ? { site: p.index } : null });
|
||||||
|
|
||||||
|
return {
|
||||||
|
// ---- trade
|
||||||
|
trade_accepted: (n, p) => ({ icon: 'swap', title: t('alerts.trade_accepted', { give: amt(p.give), want: amt(p.want) }), detail: t('alerts.build_done.in', { town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }),
|
||||||
|
trade_completed: (n, p) => ({ icon: 'swap', title: t('alerts.trade_completed', { give: amt(p.give), want: amt(p.want) }), detail: '', go: 'trade', params: { tab: 'mine' } }),
|
||||||
|
trade_expired: (n, p) => ({ icon: 'clock', title: t('alerts.trade_expired'), detail: t('alerts.trade_expired.back', { what: amt(p.returned), town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }),
|
||||||
|
trade_void: (n, p) => ({ icon: 'alert', title: t('alerts.trade_void'), detail: t('alerts.build_done.in', { town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }),
|
||||||
|
|
||||||
|
// ---- end game
|
||||||
|
backbone_open: (n, p) => Object.assign({ icon: 'b-backbone_node', title: t('alerts.backbone_open'), detail: t('alerts.backbone_open.n', { n: (p.sites || []).length || 7 }) }, worldGo(null)),
|
||||||
|
backbone_taken: (n, p) => Object.assign({ icon: 'flag', title: t('alerts.backbone_taken', { n: site(p) }), detail: [t('alerts.level', { n: p.level || 0 }), p.from ? t('alerts.backbone_taken.from', { tag: tag(p.from) }) : t('alerts.backbone_taken.incumbent'), there(p)].filter(Boolean).join(' · ') }, worldGo(p)),
|
||||||
|
backbone_lost: (n, p) => Object.assign({ icon: 'alert', title: t('alerts.backbone_lost', { n: site(p), tag: tag(p.by) }), detail: [t('alerts.level', { n: p.level || 0 }), there(p)].filter(Boolean).join(' · ') }, worldGo(p)),
|
||||||
|
backbone_level: (n, p) => Object.assign({ icon: 'b-backbone_node', title: t('alerts.backbone_level', { n: site(p), level: p.level }), detail: '' }, worldGo(p)),
|
||||||
|
backbone_delivered: (n, p) => ({ icon: 'box', title: t('alerts.backbone_delivered'), detail: cargoText(p.cargo), go: 'world', params: null }),
|
||||||
|
backbone_ship_bounced: (n, p) => ({ icon: 'alert', title: t('alerts.backbone_ship_bounced'), detail: cargoText(p.cargo), go: 'movements', params: null }),
|
||||||
|
backbone_won: (n, p) => ({ icon: 'trophy', title: t('alerts.backbone_won', { name: p.name || tag(p) }), detail: p.endsAt ? t('alerts.backbone_won.ends', { time: c.dayTime(p.endsAt) }) : '', go: 'world', params: null }),
|
||||||
|
world_ended: (n, p) => ({ icon: 'trophy', title: t('alerts.world_ended'), detail: p.winner && p.winner.name ? t('alerts.world_ended.winner', { name: p.winner.name }) : t('alerts.world_ended.nowinner'), go: 'world', params: null }),
|
||||||
|
|
||||||
|
// ---- alliance
|
||||||
|
alliance_invite: (n, p) => ({ icon: 'users', title: t('alerts.alliance_invite', { name: p.name || tag(p) }), detail: t('alerts.alliance_invite.by', { name: p.by || '?' }), go: 'alliance', params: null }),
|
||||||
|
alliance_invite_declined: (n, p) => ({ icon: 'users', title: t('alerts.alliance_invite_declined', { name: p.by || '?' }), detail: '', go: 'alliance', params: null }),
|
||||||
|
alliance_member_joined: (n, p) => ({ icon: 'users', title: t('alerts.alliance_member_joined', { name: p.name || '?' }), detail: '', go: 'alliance', params: null }),
|
||||||
|
alliance_member_left: (n, p) => ({ icon: 'users', title: t(p.kicked ? 'alerts.alliance_member_kicked' : 'alerts.alliance_member_left', { name: p.name || '?' }), detail: '', go: 'alliance', params: null }),
|
||||||
|
alliance_kicked: (n, p) => ({ icon: 'alert', title: t('alerts.alliance_kicked', { name: p.name || tag(p) }), detail: '', go: 'alliance', params: null }),
|
||||||
|
alliance_role: (n, p) => ({ icon: 'users', title: t('alerts.alliance_role', { role: known('soc.role.', p.role) }), detail: p.from ? t('alerts.alliance_role.was', { role: known('soc.role.', p.from) }) : '', go: 'alliance', params: null }),
|
||||||
|
alliance_leader: (n, p) => ({ icon: 'users', title: t('alerts.alliance_leader', { name: p.name || '?' }), detail: p.from ? t('alerts.alliance_leader.from', { name: p.from }) : '', go: 'alliance', params: null }),
|
||||||
|
alliance_disbanded: (n, p) => ({ icon: 'alert', title: t('alerts.alliance_disbanded', { name: p.name || tag(p) }), detail: '', go: 'alliance', params: null }),
|
||||||
|
|
||||||
|
// ---- diplomacy (diplomacy_changed has two payload shapes: { other: {tag,..} } and, when an alliance was disbanded, { otherTag, reason })
|
||||||
|
diplomacy_proposal: (n, p) => ({ icon: 'handshake', title: t('alerts.diplomacy_proposal', { tag: tag(p.from), state: known('soc.state.', p.state) }), detail: p.expiresAt ? t('alerts.diplomacy_proposal.until', { time: c.dayTime(p.expiresAt) }) : '', go: 'alliance', params: null }),
|
||||||
|
diplomacy_declined: (n, p) => ({ icon: 'handshake', title: t('alerts.diplomacy_declined', { tag: tag(p.by), state: known('soc.state.', p.state) }), detail: '', go: 'alliance', params: null }),
|
||||||
|
diplomacy_changed: (n, p) => ({
|
||||||
|
icon: 'handshake', title: t('alerts.diplomacy_changed', { tag: p.other ? tag(p.other) : (p.otherTag ? '[' + p.otherTag + ']' : '?'), to: known('soc.state.', p.to) }),
|
||||||
|
detail: [p.from ? t('alerts.diplomacy_changed.was', { state: known('soc.state.', p.from) }) : '', p.reason === 'disbanded' ? t('alerts.diplomacy_changed.disbanded') : ''].filter(Boolean).join(' · '), go: 'alliance', params: null,
|
||||||
|
}),
|
||||||
|
diplomacy_cancel_pending: (n, p) => ({ icon: 'clock', title: t('alerts.diplomacy_cancel_pending', { tag: tag(p.other), state: known('soc.state.', p.from) }), detail: p.effectiveAt ? t('alerts.diplomacy_cancel_pending.at', { time: c.dayTime(p.effectiveAt) }) : '', go: 'alliance', params: null }),
|
||||||
|
diplomacy_cancel_revoked: (n, p) => ({ icon: 'handshake', title: t('alerts.diplomacy_cancel_revoked', { tag: tag(p.other), state: known('soc.state.', p.state) }), detail: '', go: 'alliance', params: null }),
|
||||||
|
|
||||||
|
// ---- messages
|
||||||
|
message: (n, p) => ({ icon: 'mail', title: t('alerts.message', { name: p.from && p.from.name ? p.from.name : '?' }), detail: '', go: 'messages', params: null }),
|
||||||
|
alliance_message: (n, p) => ({ icon: 'mail', title: t('alerts.alliance_message', { name: typeof p.from === 'string' ? p.from : '?' }), detail: p.tag ? '[' + p.tag + ']' : '', go: 'messages', params: null }),
|
||||||
|
};
|
||||||
|
}));
|
||||||
|
|
@ -36,7 +36,8 @@
|
||||||
footprintNeedExp: 1.8,
|
footprintNeedExp: 1.8,
|
||||||
loyaltyRegenPerHour: 1,
|
loyaltyRegenPerHour: 1,
|
||||||
loyaltyMax: 100,
|
loyaltyMax: 100,
|
||||||
secondQueueCoreLevel: 10, // Core router level that opens the second build slot
|
secondQueueCoreLevel: 3, // Core router level that opens the second build slot (was 10; docs/BALANCE.md B1)
|
||||||
|
extraQueueCores: [], // Core router levels that each open one more build slot (after the second)
|
||||||
minBuildMs: 5000,
|
minBuildMs: 5000,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -215,7 +216,8 @@
|
||||||
};
|
};
|
||||||
|
|
||||||
// Resource transport between POPs (trade is built on it): `links` concurrent transports = Internet exchange level.
|
// Resource transport between POPs (trade is built on it): `links` concurrent transports = Internet exchange level.
|
||||||
const TRANSPORT = { building: 'internet_exchange', speed: 12, capacityPerLink: 500 };
|
// capacityPerLink was 500; 1000 since docs/BALANCE.md B2 (the end game was shipping-limited: 21.6 M units in 500-unit trips).
|
||||||
|
const TRANSPORT = { building: 'internet_exchange', speed: 12, capacityPerLink: 1000 };
|
||||||
|
|
||||||
// Which unit roles may go on which movement type.
|
// Which unit roles may go on which movement type.
|
||||||
const MOVE_ROLES = {
|
const MOVE_ROLES = {
|
||||||
|
|
|
||||||
87
public/js/endcore.js
Normal file
87
public/js/endcore.js
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Pure helpers of the end game screen (no DOM, no storage, no clock): who leads the race, how far a node build is, what a build
|
||||||
|
* still lacks, what a holder may do. Loads as a browser script (window.UpstreamEnd) and as a Node module (test/client-world.test.js).
|
||||||
|
* The SERVER decides everything (GET /worlds/:id/status, GET /backbone/:id); this only avoids doomed taps and explains the greyed-out ones.
|
||||||
|
*
|
||||||
|
* A site is the `LandingSite` of docs/openapi.json: { id | null, index, x, y, holder: { allianceId, tag, name } | null, takenBy, takenAt,
|
||||||
|
* level, maxLevel, progress, pool: { fiber, hardware, capital }, build: { toLevel, startedAt, dueAt } | null, next: { toLevel, cost, durationMs } | null }.
|
||||||
|
*/
|
||||||
|
(function (root, factory) {
|
||||||
|
if (typeof module === 'object' && module.exports) module.exports = factory(require('./data.js'));
|
||||||
|
else root.UpstreamEnd = factory(root.UpstreamData);
|
||||||
|
}(typeof self !== 'undefined' ? self : this, function (D) {
|
||||||
|
const RES = D.RESOURCES;
|
||||||
|
|
||||||
|
// The alliance furthest in the race: highest node level on any of its sites; ties by more sites held, then the earlier takeover.
|
||||||
|
// -> { allianceId, tag, name, level, sites, siteIndex } | null (nobody holds a site)
|
||||||
|
function leading(sites) {
|
||||||
|
const by = new Map();
|
||||||
|
for (const s of sites || []) {
|
||||||
|
if (!s.holder) continue;
|
||||||
|
const k = s.holder.allianceId;
|
||||||
|
const c = by.get(k) || { allianceId: k, tag: s.holder.tag, name: s.holder.name, level: -1, sites: 0, siteIndex: null, at: Infinity };
|
||||||
|
c.sites++;
|
||||||
|
if (s.level > c.level) { c.level = s.level; c.siteIndex = s.index; }
|
||||||
|
c.at = Math.min(c.at, s.takenAt || Infinity);
|
||||||
|
by.set(k, c);
|
||||||
|
}
|
||||||
|
const all = Array.from(by.values());
|
||||||
|
if (!all.length) return null;
|
||||||
|
all.sort((a, b) => b.level - a.level || b.sites - a.sites || a.at - b.at || a.allianceId - b.allianceId);
|
||||||
|
const w = all[0];
|
||||||
|
return { allianceId: w.allianceId, tag: w.tag, name: w.name, level: w.level, sites: w.sites, siteIndex: w.siteIndex };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Progress 0..1 of the node level being built, or null when nothing is being built.
|
||||||
|
function buildProgress(site, now) {
|
||||||
|
const b = site && site.build;
|
||||||
|
if (!b) return null;
|
||||||
|
return Math.max(0, Math.min(1, (now - b.startedAt) / Math.max(1, b.dueAt - b.startedAt)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the stockpile lacks for `cost`: { res: missing } (empty object = enough).
|
||||||
|
function missing(cost, pool) {
|
||||||
|
const out = {};
|
||||||
|
for (const r of RES) {
|
||||||
|
const lack = ((cost && cost[r]) || 0) - ((pool && pool[r]) || 0);
|
||||||
|
if (lack > 0) out[r] = lack;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Who holds the site, seen from `allianceId`: 'mine' | 'rival' | 'incumbent'.
|
||||||
|
function holderKind(site, allianceId) {
|
||||||
|
if (!site.holder) return 'incumbent';
|
||||||
|
return allianceId && site.holder.allianceId === allianceId ? 'mine' : 'rival';
|
||||||
|
}
|
||||||
|
|
||||||
|
// May the node be built now? -> { ok, reason } with reason in: ended, forbidden, max_level, already_queued, not_enough_resources.
|
||||||
|
// `you` = the `you` block of GET /backbone/:id.
|
||||||
|
function buildCheck(site, you, ended) {
|
||||||
|
if (ended) return { ok: false, reason: 'ended' };
|
||||||
|
if (!you || !you.holder || !you.canBuild) return { ok: false, reason: 'forbidden' };
|
||||||
|
if (!site.next) return { ok: false, reason: 'max_level' };
|
||||||
|
if (site.build) return { ok: false, reason: 'already_queued' };
|
||||||
|
if (Object.keys(missing(site.next.cost, site.pool)).length) return { ok: false, reason: 'not_enough_resources' };
|
||||||
|
return { ok: true, reason: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The phase as the clock sees it: the status says 'running' until it is refetched, but the sites open at opensAt.
|
||||||
|
function phaseNow(status, now) {
|
||||||
|
if (!status) return 'running';
|
||||||
|
if (status.phase === 'ended') return 'ended';
|
||||||
|
if (status.phase === 'running' && now >= status.opensAt) return 'backbone_open';
|
||||||
|
return status.phase;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Share of the way to the opening day, 0..1.
|
||||||
|
const openProgress = (status) => (status && status.openDay ? Math.max(0, Math.min(1, status.ageDays / status.openDay)) : 0);
|
||||||
|
|
||||||
|
const sumCargo = (c) => Object.keys(c || {}).reduce((s, k) => s + (c[k] || 0), 0);
|
||||||
|
|
||||||
|
// Rows of a final ranking list for display: the first `n` (a snapshot holds the top 100).
|
||||||
|
const topRows = (list, n) => (list || []).slice(0, n);
|
||||||
|
|
||||||
|
return { leading, buildProgress, missing, holderKind, buildCheck, phaseNow, openProgress, sumCargo, topRows };
|
||||||
|
}));
|
||||||
|
|
@ -59,6 +59,7 @@
|
||||||
};
|
};
|
||||||
App.errMsg = (err) => {
|
App.errMsg = (err) => {
|
||||||
const code = err && err.code;
|
const code = err && err.code;
|
||||||
|
if (code === 'world_ended' && App.markWorldEnded) App.markWorldEnded(); // every screen shows its errors through here
|
||||||
if (code && Object.prototype.hasOwnProperty.call(I.strings.en, 'err.' + code)) return App.t('err.' + code);
|
if (code && Object.prototype.hasOwnProperty.call(I.strings.en, 'err.' + code)) return App.t('err.' + code);
|
||||||
return (err && err.message) || App.t('err.unknown');
|
return (err && err.message) || App.t('err.unknown');
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,8 @@
|
||||||
* What can be sent to a tile. c = {
|
* What can be sent to a tile. c = {
|
||||||
* tile: GET /map/tile response,
|
* tile: GET /map/tile response,
|
||||||
* home: units at the sending POP, transport: { links, active } of the sending POP,
|
* home: units at the sending POP, transport: { links, active } of the sending POP,
|
||||||
* allianceId: my alliance id or null, crews: number of rollout crews at home
|
* allianceId: my alliance id or null, crews: number of rollout crews at home,
|
||||||
|
* transportOnly: the dialog was opened for a transport (trade screen): a POP, anybody's, offers only the transport
|
||||||
* } -> [{ type, ok, reason }] (reason is a code the sheet turns into text; null when ok)
|
* } -> [{ type, ok, reason }] (reason is a code the sheet turns into text; null when ok)
|
||||||
* Hidden (not even greyed): types that make no sense for this kind of tile. Pact rules (NAP, confederation) are not
|
* Hidden (not even greyed): types that make no sense for this kind of tile. Pact rules (NAP, confederation) are not
|
||||||
* known to the client: the server refuses those and the sheet shows its message.
|
* known to the client: the server refuses those and the sheet shows its message.
|
||||||
|
|
@ -42,6 +43,14 @@
|
||||||
if (!t) return out;
|
if (!t) return out;
|
||||||
const has = (type) => unitsForType(type, home).length > 0;
|
const has = (type) => unitsForType(type, home).length > 0;
|
||||||
const add = (type, ok, reason) => out.push({ type, ok: !!ok, reason: ok ? null : reason });
|
const add = (type, ok, reason) => out.push({ type, ok: !!ok, reason: ok ? null : reason });
|
||||||
|
const linksFree = () => {
|
||||||
|
const links = (c.transport && c.transport.links) || 0, active = (c.transport && c.transport.active) || 0;
|
||||||
|
return { ok: links > active, reason: links === 0 ? 'no_link' : 'links_busy' };
|
||||||
|
};
|
||||||
|
if (c.transportOnly) { // resources may go to any POP, a rival's too (the server warns its owner of the arrival)
|
||||||
|
if (t.town) { const l = linksFree(); add('transport', l.ok, l.reason); }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
if (t.town) {
|
if (t.town) {
|
||||||
if (t.town.mine) {
|
if (t.town.mine) {
|
||||||
add('reinforce', has('reinforce'), 'no_units');
|
add('reinforce', has('reinforce'), 'no_units');
|
||||||
|
|
@ -60,6 +69,14 @@
|
||||||
} else if (t.type === 'incumbent') {
|
} else if (t.type === 'incumbent') {
|
||||||
add('scan', has('scan'), 'no_units');
|
add('scan', has('scan'), 'no_units');
|
||||||
add('attack', has('attack'), 'no_units');
|
add('attack', has('attack'), 'no_units');
|
||||||
|
} else if (t.type === 'backbone') {
|
||||||
|
// End game landing site: scan or attack, nothing else. Attacking needs an alliance and a site that is not your own
|
||||||
|
// alliance's (pacts are the server's call: its answer is shown by the dialog).
|
||||||
|
const b = t.backbone || {};
|
||||||
|
add('scan', has('scan'), 'no_units');
|
||||||
|
if (!c.allianceId) add('attack', false, 'no_alliance');
|
||||||
|
else if (b.mine) add('attack', false, 'own_site');
|
||||||
|
else add('attack', has('attack'), 'no_units');
|
||||||
} else if (t.type === 'land') {
|
} else if (t.type === 'land') {
|
||||||
const s = t.settle || {};
|
const s = t.settle || {};
|
||||||
if (!s.possible) add('settle', false, 'settle:' + (s.code || 'invalid_target'));
|
if (!s.possible) add('settle', false, 'settle:' + (s.code || 'invalid_target'));
|
||||||
|
|
|
||||||
|
|
@ -125,6 +125,7 @@
|
||||||
if (!op) return;
|
if (!op) return;
|
||||||
const before = townSig(st.towns);
|
const before = townSig(st.towns);
|
||||||
st.operators = me.operators; st.operator = op; st.world = op.world; st.towns = op.towns;
|
st.operators = me.operators; st.operator = op; st.world = op.world; st.towns = op.towns;
|
||||||
|
if (App.checkWorld) App.checkWorld(); // the world may have ended while we were away
|
||||||
let gone = false;
|
let gone = false;
|
||||||
if (!st.towns.some((t) => t.id === st.townId)) {
|
if (!st.towns.some((t) => t.id === st.townId)) {
|
||||||
const pick = st.towns.find((t) => t.isCapital) || st.towns[0] || null;
|
const pick = st.towns.find((t) => t.isCapital) || st.towns[0] || null;
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@
|
||||||
* source.isOwn(town) -> bool
|
* source.isOwn(town) -> bool
|
||||||
* source.movements() -> [{ from: {x,y}, to: {x,y}, kind: 'out' | 'in' | 'ret' | 'ally', p: 0..1 }] optional: lines with a marker at progress p
|
* source.movements() -> [{ from: {x,y}, to: {x,y}, kind: 'out' | 'in' | 'ret' | 'ally', p: 0..1 }] optional: lines with a marker at progress p
|
||||||
* source.threatened(town) -> bool optional: an incoming movement is heading for this own POP (red ring)
|
* source.threatened(town) -> bool optional: an incoming movement is heading for this own POP (red ring)
|
||||||
|
* source.myAllianceId() -> id | null optional: colours the end game landing sites (specials of type 'backbone')
|
||||||
* onTap(x, y) a finger lift / click that was not a drag or a pinch (act on lift)
|
* onTap(x, y) a finger lift / click that was not a drag or a pinch (act on lift)
|
||||||
* onMoveEnd(view) debounced after the camera stopped; view = { x0, y0, x1, y1, cx, cy, zoom }
|
* onMoveEnd(view) debounced after the camera stopped; view = { x0, y0, x1, y1, cx, cy, zoom }
|
||||||
*
|
*
|
||||||
|
|
@ -19,6 +20,7 @@
|
||||||
const COLORS = {
|
const COLORS = {
|
||||||
void: '#04070e', land: '#0d1626', land2: '#0f192b', grid: 'rgba(120,160,220,0.10)', grid10: 'rgba(120,160,220,0.22)', border: 'rgba(77,227,255,0.55)',
|
void: '#04070e', land: '#0d1626', land2: '#0f192b', grid: 'rgba(120,160,220,0.10)', grid10: 'rgba(120,160,220,0.22)', border: 'rgba(77,227,255,0.55)',
|
||||||
fiber: '#4de3ff', hardware: '#ff9f5a', capital: '#5be08f', incumbent: '#b06cff', incumbentFill: '#241338',
|
fiber: '#4de3ff', hardware: '#ff9f5a', capital: '#5be08f', incumbent: '#b06cff', incumbentFill: '#241338',
|
||||||
|
backbone: '#f5c542', backboneFill: '#2b2208', rivalSite: '#ff6bd6',
|
||||||
own: '#4de3ff', ownFill: '#0f4b63', select: '#ffd24d', text: '#e4f0ff', halo: 'rgba(4,7,14,0.9)', reach: 'rgba(77,227,255,0.35)',
|
own: '#4de3ff', ownFill: '#0f4b63', select: '#ffd24d', text: '#e4f0ff', halo: 'rgba(4,7,14,0.9)', reach: 'rgba(77,227,255,0.35)',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -278,6 +280,7 @@
|
||||||
this.src.forEachSpecial(v.x0, v.y0, v.x1, v.y1, (sp) => {
|
this.src.forEachSpecial(v.x0, v.y0, v.x1, v.y1, (sp) => {
|
||||||
const s = this.toScreen(sp.x, sp.y);
|
const s = this.toScreen(sp.x, sp.y);
|
||||||
if (sp.type === 'rural') this._rural(s.x, s.y, sp.bonus);
|
if (sp.type === 'rural') this._rural(s.x, s.y, sp.bonus);
|
||||||
|
else if (sp.type === 'backbone') this._backbone(s.x, s.y, sp);
|
||||||
else this._incumbent(s.x, s.y);
|
else this._incumbent(s.x, s.y);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -336,6 +339,41 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// End game landing site: a diamond with a ring that fills with the node level; gold = nobody's (the incumbent's), cyan = your
|
||||||
|
// alliance, a rival hue = another alliance. Clearly not an incumbent square and not a POP hexagon.
|
||||||
|
_backbone(x, y, sp) {
|
||||||
|
const { ctx, zoom: z } = this;
|
||||||
|
if (x < -40 || y < -40 || x > this.w + 40 || y > this.h + 40) return;
|
||||||
|
const site = sp.site || {};
|
||||||
|
const mine = !!(this.src.myAllianceId && site.holder && site.holder.allianceId === this.src.myAllianceId());
|
||||||
|
const col = !site.holder ? COLORS.backbone : mine ? COLORS.own : COLORS.rivalSite;
|
||||||
|
const r = Math.max(4, z * 0.46);
|
||||||
|
ctx.save();
|
||||||
|
ctx.shadowColor = col; ctx.shadowBlur = Math.min(18, 4 + z * 0.3);
|
||||||
|
ctx.beginPath(); ctx.moveTo(x, y - r); ctx.lineTo(x + r, y); ctx.lineTo(x, y + r); ctx.lineTo(x - r, y); ctx.closePath();
|
||||||
|
ctx.fillStyle = COLORS.backboneFill; ctx.fill();
|
||||||
|
ctx.restore();
|
||||||
|
ctx.beginPath(); ctx.moveTo(x, y - r); ctx.lineTo(x + r, y); ctx.lineTo(x, y + r); ctx.lineTo(x - r, y); ctx.closePath();
|
||||||
|
ctx.strokeStyle = col; ctx.lineWidth = Math.max(1.5, z * 0.09); ctx.stroke();
|
||||||
|
if (z >= 7) {
|
||||||
|
const rr = r * 1.45, frac = site.maxLevel ? Math.max(0, Math.min(1, (site.level || 0) / site.maxLevel)) : 0;
|
||||||
|
ctx.lineWidth = Math.max(2, z * 0.1); ctx.lineCap = 'round';
|
||||||
|
ctx.strokeStyle = 'rgba(160,180,220,0.22)'; ctx.beginPath(); ctx.arc(x, y, rr, 0, Math.PI * 2); ctx.stroke();
|
||||||
|
if (frac > 0) { ctx.strokeStyle = col; ctx.beginPath(); ctx.arc(x, y, rr, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * frac); ctx.stroke(); }
|
||||||
|
}
|
||||||
|
if (z >= 14) { // a lightning bolt: the backbone
|
||||||
|
ctx.fillStyle = col; ctx.beginPath();
|
||||||
|
ctx.moveTo(x + r * 0.12, y - r * 0.55); ctx.lineTo(x - r * 0.3, y + r * 0.08); ctx.lineTo(x - r * 0.02, y + r * 0.08);
|
||||||
|
ctx.lineTo(x - r * 0.14, y + r * 0.55); ctx.lineTo(x + r * 0.3, y - r * 0.1); ctx.lineTo(x + r * 0.02, y - r * 0.1); ctx.closePath(); ctx.fill();
|
||||||
|
}
|
||||||
|
if (z >= 18) {
|
||||||
|
ctx.font = '700 ' + Math.round(clamp(z * 0.3, 10, 13)) + 'px system-ui, sans-serif';
|
||||||
|
ctx.textAlign = 'center'; ctx.textBaseline = 'top'; ctx.lineWidth = 3; ctx.lineJoin = 'round'; ctx.strokeStyle = COLORS.halo;
|
||||||
|
const label = (site.index !== undefined ? 'S' + (site.index + 1) : '') + (site.holder ? ' [' + site.holder.tag + ']' : '') + ' L' + (site.level || 0);
|
||||||
|
ctx.strokeText(label, x, y + r * 1.45 + 4); ctx.fillStyle = col; ctx.fillText(label, x, y + r * 1.45 + 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
_hex(x, y, rad) {
|
_hex(x, y, rad) {
|
||||||
const { ctx } = this;
|
const { ctx } = this;
|
||||||
ctx.beginPath();
|
ctx.beginPath();
|
||||||
|
|
|
||||||
|
|
@ -204,7 +204,14 @@
|
||||||
return Math.max(F.minBuildMs, Math.round(secs * 1000));
|
return Math.max(F.minBuildMs, Math.round(secs * 1000));
|
||||||
}
|
}
|
||||||
|
|
||||||
function queueSlots(town) { return coreLevel(town) >= F.secondQueueCoreLevel ? 2 : 1; }
|
// Build slots (builds running at once): 1, one more from Core router F.secondQueueCoreLevel, and one more at each level listed
|
||||||
|
// in F.extraQueueCores (data, default none).
|
||||||
|
function queueSlots(town) {
|
||||||
|
const core = coreLevel(town);
|
||||||
|
let n = core >= F.secondQueueCoreLevel ? 2 : 1;
|
||||||
|
for (const lv of F.extraQueueCores || []) if (core >= lv) n += 1;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
function storageCap(town) {
|
function storageCap(town) {
|
||||||
const r = town.buildings.rack_hall;
|
const r = town.buildings.rack_hall;
|
||||||
|
|
|
||||||
40
public/js/screens/cargo-ui.js
Normal file
40
public/js/screens/cargo-ui.js
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Cargo pickers shared by the trade and end game screens (window.CargoUI): one slider + stepper + number box per resource.
|
||||||
|
* The server decides everything (capacity per link, stock, links); this only keeps the numbers inside what the POP holds.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
const { h } = UI;
|
||||||
|
const D = UpstreamData;
|
||||||
|
const num = (n) => App.fmt.num(n);
|
||||||
|
|
||||||
|
// One row: label, "/ have", slider, -/+ buttons, number box, "all". onChange(v) gets the clamped integer.
|
||||||
|
function pickRow(label, have, cur, onChange, sub) {
|
||||||
|
have = Math.max(0, Math.floor(have));
|
||||||
|
const range = h('input', { type: 'range', min: '0', max: String(have), step: '1', value: String(cur), 'aria-label': label });
|
||||||
|
const numIn = h('input', { type: 'number', inputmode: 'numeric', min: '0', max: String(have), value: String(cur), class: 'mil-num', 'aria-label': label });
|
||||||
|
const set = (v) => { v = Math.max(0, Math.min(have, Math.floor(Number(v)) || 0)); range.value = String(v); numIn.value = String(v); onChange(v); };
|
||||||
|
range.addEventListener('input', () => set(range.value));
|
||||||
|
numIn.addEventListener('input', () => set(numIn.value));
|
||||||
|
return h('div', { class: 'mil-pick' },
|
||||||
|
h('div', { class: 'row' }, h('span', null, h('b', { text: label }), h('span', { class: 'dimmer', text: ' / ' + num(have) })), sub || null),
|
||||||
|
h('div', { class: 'pick-ctl' },
|
||||||
|
h('button', { class: 'btn small', type: 'button', 'aria-label': '-1', onclick: () => set(Number(numIn.value) - 1) }, '−'),
|
||||||
|
range,
|
||||||
|
h('button', { class: 'btn small', type: 'button', 'aria-label': '+1', onclick: () => set(Number(numIn.value) + 1) }, '+'),
|
||||||
|
numIn,
|
||||||
|
h('button', { class: 'btn small', type: 'button', onclick: () => set(have) }, App.t('send.all'))));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pickers for fiber / hardware / capital writing into `cargo` ({res: n}, zero entries removed). have = { fiber, hardware, capital }.
|
||||||
|
function cargoPickers(cargo, have, onChange) {
|
||||||
|
return D.RESOURCES.map((r) => pickRow(App.resName(r), Math.floor(have[r] || 0), cargo[r] || 0, (v) => {
|
||||||
|
if (v > 0) cargo[r] = v; else delete cargo[r];
|
||||||
|
if (onChange) onChange();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
const cargoTotal = (cargo) => Object.keys(cargo).reduce((s, k) => s + (cargo[k] || 0), 0);
|
||||||
|
|
||||||
|
window.CargoUI = { pickRow, cargoPickers, cargoTotal };
|
||||||
|
}());
|
||||||
|
|
@ -35,7 +35,7 @@
|
||||||
];
|
];
|
||||||
const actions = [];
|
const actions = [];
|
||||||
if (crews >= D.EXPANSION.crews) {
|
if (crews >= D.EXPANSION.crews) {
|
||||||
actions.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { App.go('map', { x: t.x, y: t.y, zoom: 24 }); toast(App.t('exp.pick'), 'ok'); } }, icon('flag'), App.t('exp.found')));
|
actions.push(h('button', { class: 'btn primary wide', type: 'button', 'data-keep': '', onclick: () => { App.go('map', { x: t.x, y: t.y, zoom: 24 }); toast(App.t('exp.pick'), 'ok'); } }, icon('flag'), App.t('exp.found')));
|
||||||
} else {
|
} else {
|
||||||
actions.push(h('p', { class: 'row-sub wrap', text: canTrain ? App.t('exp.needCrews', { n: D.EXPANSION.crews - crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) : App.t('exp.needDepot') }));
|
actions.push(h('p', { class: 'row-sub wrap', text: canTrain ? App.t('exp.needCrews', { n: D.EXPANSION.crews - crews, unit: mil().unitName(D.EXPANSION.settleUnit) }) : App.t('exp.needDepot') }));
|
||||||
if (canTrain) actions.push(h('button', { class: 'btn wide', type: 'button', onclick: () => App.go('units') }, icon('units'), App.t('exp.train')));
|
if (canTrain) actions.push(h('button', { class: 'btn wide', type: 'button', onclick: () => App.go('units') }, icon('units'), App.t('exp.train')));
|
||||||
|
|
|
||||||
|
|
@ -115,6 +115,7 @@
|
||||||
isOwn: (t) => t.owner.id === ownOperatorId(),
|
isOwn: (t) => t.owner.id === ownOperatorId(),
|
||||||
movements: () => moveLines(),
|
movements: () => moveLines(),
|
||||||
threatened: (t) => App.mil.moves.incoming.some((m) => m.to && m.to.townId === t.id),
|
threatened: (t) => App.mil.moves.incoming.some((m) => m.to && m.to.townId === t.id),
|
||||||
|
myAllianceId: () => (App.state.operator ? App.state.operator.allianceId : null),
|
||||||
};
|
};
|
||||||
view = new MapRender.MapView(canvas, source, {
|
view = new MapRender.MapView(canvas, source, {
|
||||||
onTap: onTap,
|
onTap: onTap,
|
||||||
|
|
@ -152,6 +153,7 @@
|
||||||
legendEl.appendChild(item('rival', App.t('map.legend.rival')));
|
legendEl.appendChild(item('rival', App.t('map.legend.rival')));
|
||||||
legendEl.appendChild(item('rural', App.t('map.legend.rural')));
|
legendEl.appendChild(item('rural', App.t('map.legend.rural')));
|
||||||
legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent')));
|
legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent')));
|
||||||
|
legendEl.appendChild(item('backbone', App.t('map.legend.backbone')));
|
||||||
legendEl.appendChild(item('mv-out', App.t('map.legend.out')));
|
legendEl.appendChild(item('mv-out', App.t('map.legend.out')));
|
||||||
legendEl.appendChild(item('mv-in', App.t('map.legend.in')));
|
legendEl.appendChild(item('mv-in', App.t('map.legend.in')));
|
||||||
}
|
}
|
||||||
|
|
@ -187,22 +189,31 @@
|
||||||
body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus))));
|
body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus))));
|
||||||
} else if (special && special.type === 'incumbent') {
|
} else if (special && special.type === 'incumbent') {
|
||||||
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') }));
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') }));
|
||||||
|
} else if (special && special.type === 'backbone') {
|
||||||
|
const site = special.site || {};
|
||||||
|
const mine = !!(site.holder && site.holder.allianceId && site.holder.allianceId === (App.state.operator && App.state.operator.allianceId));
|
||||||
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.backbone', { max: site.maxLevel || UpstreamData.ENDGAME.maxLevel }) }));
|
||||||
|
body.push(h('div', { class: 'pill-row' },
|
||||||
|
site.holder ? h('span', { class: 'pill' + (mine ? ' accent' : '') }, '[' + site.holder.tag + '] ' + site.holder.name) : h('span', { class: 'pill dim', text: App.t('wld.incumbent') }),
|
||||||
|
h('span', { class: 'pill', text: App.t('wld.level', { n: site.level || 0, max: site.maxLevel || UpstreamData.ENDGAME.maxLevel }) })));
|
||||||
|
body.push(h('div', { class: 'bar wld-bar ' + (mine ? 'mine' : site.holder ? 'rival' : 'incumbent'), 'aria-hidden': 'true' }, (() => { const i = h('i'); i.style.setProperty('--p', String(site.maxLevel ? (site.level || 0) / site.maxLevel : 0)); return i; })()));
|
||||||
|
body.push(h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { closeSheet(); App.go('world', { site: site.index }); } }, icon('b-backbone_node'), App.t('map.info.openWorld')));
|
||||||
} else if (!known) {
|
} else if (!known) {
|
||||||
body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') }));
|
body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') }));
|
||||||
} else {
|
} else {
|
||||||
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
|
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
|
||||||
}
|
}
|
||||||
body.push(row('', App.t('map.info.coords', { x, y })));
|
body.push(row('', App.t('map.info.coords', { x, y })));
|
||||||
if (App.openSend && App.state.towns.length && (town || (special && special.type === 'incumbent') || (!special && known))) {
|
if (App.openSend && App.state.towns.length && (town || (special && (special.type === 'incumbent' || (special.type === 'backbone' && !(special.site && special.site.holder && special.site.holder.allianceId === (App.state.operator && App.state.operator.allianceId))))) || (!special && known))) {
|
||||||
body.push(h('button', { class: 'btn wide' + (town && town.owner.id === ownOperatorId() ? '' : ' primary'), type: 'button', onclick: () => App.openSend({ x, y }) }, icon('target'), App.t('send.open')));
|
body.push(h('button', { class: 'btn wide' + (town && town.owner.id === ownOperatorId() ? '' : ' primary'), type: 'button', onclick: () => App.openSend({ x, y }) }, icon('target'), App.t('send.open')));
|
||||||
}
|
}
|
||||||
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));
|
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));
|
||||||
if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) {
|
if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) {
|
||||||
body.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
|
body.push(h('button', { class: 'btn primary wide', type: 'button', 'data-keep': '', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
|
||||||
}
|
}
|
||||||
const title = town ? town.name : App.t('tile.' + type);
|
const title = town ? town.name : (type === 'backbone' && special.site && Number.isInteger(special.site.index) ? App.t('wld.site', { n: special.site.index + 1 }) : App.t('tile.' + type));
|
||||||
infoSheet = openSheet({
|
infoSheet = openSheet({
|
||||||
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
|
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : type === 'backbone' ? 'b-backbone_node' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
|
||||||
closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body),
|
closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body),
|
||||||
onClose: () => { if (view) view.setSelected(null); infoSheet = null; },
|
onClose: () => { if (view) view.setSelected(null); infoSheet = null; },
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -32,10 +32,11 @@
|
||||||
if (m.units && Mil.sumUnits(m.units) > 0) sub.push(h('span', { class: 'row-sub wrap', text: mil().unitsText(m.units) }));
|
if (m.units && Mil.sumUnits(m.units) > 0) sub.push(h('span', { class: 'row-sub wrap', text: mil().unitsText(m.units) }));
|
||||||
if (m.cargo && Object.keys(m.cargo).some((r) => m.cargo[r] > 0)) sub.push(mil().resChips(m.cargo));
|
if (m.cargo && Object.keys(m.cargo).some((r) => m.cargo[r] > 0)) sub.push(mil().resChips(m.cargo));
|
||||||
if (m.target) sub.push(h('span', { class: 'row-sub wrap', text: App.t('mov.target', { name: App.buildingName(m.target) }) }));
|
if (m.target) sub.push(h('span', { class: 'row-sub wrap', text: App.t('mov.target', { name: App.buildingName(m.target) }) }));
|
||||||
|
if (m.siteId) sub.push(h('span', { class: 'row-sub wrap', text: App.t('mov.siteShipment') })); // a shipment to a backbone landing site (POST /backbone/:id/ship)
|
||||||
const recallable = m.recallableUntil && m.recallableUntil > now;
|
const recallable = m.recallableUntil && m.recallableUntil > now;
|
||||||
const bar = h('i');
|
const bar = h('i');
|
||||||
const row = h('li', { class: 'mil-row out type-' + type, dataset: { id: m.id } },
|
const row = h('li', { class: 'mil-row out type-' + type, dataset: { id: m.id } },
|
||||||
h('span', { class: 'row-ic' }, icon(Mil.TYPE_ICON[type] || 'move')),
|
h('span', { class: 'row-ic' }, icon(m.siteId ? 'b-backbone_node' : (Mil.TYPE_ICON[type] || 'move'))),
|
||||||
h('span', { class: 'row-main' },
|
h('span', { class: 'row-main' },
|
||||||
h('span', { class: 'row-title' }, h('b', { text: mil().typeLabel(type) })),
|
h('span', { class: 'row-title' }, h('b', { text: mil().typeLabel(type) })),
|
||||||
h('span', { class: 'row-sub wrap' }, mil().endLink(m.from), h('span', { class: 'arrow', 'aria-hidden': 'true' }, icon('move')), mil().endLink(m.to)),
|
h('span', { class: 'row-sub wrap' }, mil().endLink(m.from), h('span', { class: 'arrow', 'aria-hidden': 'true' }, icon('move')), mil().endLink(m.to)),
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,11 @@
|
||||||
'use strict';
|
'use strict';
|
||||||
/*
|
/*
|
||||||
* Reports: newest first, cursor-paginated (GET /reports?after=<last id>), unread highlighted, a detail sheet per report
|
* Reports: newest first, cursor-paginated (GET /reports?after=<last id>), unread highlighted, a detail sheet per report
|
||||||
* (GET /reports/:id, then POST /reports/:id/read). Detail layouts exist for battle (raid/attack/takeover), scan,
|
* (GET /reports/:id, then POST /reports/:id/read). Detail layouts exist for battle (raid/attack/takeover), landing (an attack on a backbone
|
||||||
* scan_detected, incumbent, settle, reinforce and movement_failed; coordinates are links that jump to the map.
|
* landing site), scan (also of a landing site), scan_detected, incumbent, settle, reinforce and movement_failed; coordinates are links that
|
||||||
* `data` differs by report type AND by the recipient's role (attacker / defender / reinforcer / sender / target).
|
* jump to the map. `data` differs by report type AND by the recipient's role (attacker / defender / reinforcer / sender / target).
|
||||||
|
* Alliance folder: a report can be shared with your alliance (POST /reports/:id/share) and the "Alliance" tab lists the folder
|
||||||
|
* (GET /alliances/:id/reports). Shared reports have no recipient role and no read flag: they are told from nobody's side ("attacker won").
|
||||||
*/
|
*/
|
||||||
(function () {
|
(function () {
|
||||||
const { h, clear, icon, toast, openSheet } = UI;
|
const { h, clear, icon, toast, openSheet } = UI;
|
||||||
|
|
@ -14,6 +16,11 @@
|
||||||
const PAGE = 25;
|
const PAGE = 25;
|
||||||
|
|
||||||
let box, listEl, moreBtn, statusEl, items = [], next = null, loading = false, visible = false, offAgo = null;
|
let box, listEl, moreBtn, statusEl, items = [], next = null, loading = false, visible = false, offAgo = null;
|
||||||
|
let tabsEl, markBtn, mode = 'mine'; // 'mine' | 'alliance' (the shared folder)
|
||||||
|
const folder = { items: [], next: null, loaded: false };
|
||||||
|
const allianceId = () => (App.state.operator ? App.state.operator.allianceId : null);
|
||||||
|
const curItems = () => (mode === 'alliance' ? folder.items : items);
|
||||||
|
const curNext = () => (mode === 'alliance' ? folder.next : next);
|
||||||
|
|
||||||
// ------------------------------------------------------------------ list rows
|
// ------------------------------------------------------------------ list rows
|
||||||
const nameOf = (o) => (o && o.name) || '?';
|
const nameOf = (o) => (o && o.name) || '?';
|
||||||
|
|
@ -22,16 +29,26 @@
|
||||||
// { icon, title, sub, tone } for the list
|
// { icon, title, sub, tone } for the list
|
||||||
function describe(it) {
|
function describe(it) {
|
||||||
const s = it.summary || {};
|
const s = it.summary || {};
|
||||||
|
const sharedItem = !it.role; // alliance folder: nobody's side
|
||||||
switch (it.type) {
|
switch (it.type) {
|
||||||
case 'raid': case 'attack': case 'takeover': {
|
case 'raid': case 'attack': case 'takeover': {
|
||||||
|
if (sharedItem) {
|
||||||
|
return { icon: Mil.TYPE_ICON[it.type], title: mil().reportTypeLabel(it.type) + ': ' + townOf(s.target), sub: App.t('rep.vs', { a: nameOf(s.attacker), d: nameOf(s.defender) }) + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: 'neutral', badge: App.t(s.outcome === 'attacker_won' ? 'rep.attackerWon' : 'rep.defenderWon') };
|
||||||
|
}
|
||||||
const res = Mil.perspective(it.role, s.outcome);
|
const res = Mil.perspective(it.role, s.outcome);
|
||||||
const mine = it.role === 'attacker';
|
const mine = it.role === 'attacker';
|
||||||
const title = mil().reportTypeLabel(it.type) + ': ' + townOf(s.target);
|
const title = mil().reportTypeLabel(it.type) + ': ' + townOf(s.target);
|
||||||
const sub = mine ? App.t('rep.sub.you_vs', { name: nameOf(s.defender) }) : App.t('rep.sub.by', { name: nameOf(s.attacker) });
|
const sub = mine ? App.t('rep.sub.you_vs', { name: nameOf(s.defender) }) : App.t('rep.sub.by', { name: nameOf(s.attacker) });
|
||||||
return { icon: Mil.TYPE_ICON[it.type], title, sub: sub + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: res === 'victory' ? 'good' : 'bad', badge: App.t('rep.' + res) };
|
return { icon: Mil.TYPE_ICON[it.type], title, sub: sub + (s.captured ? ' · ' + App.t('rep.captured') : ''), tone: res === 'victory' ? 'good' : 'bad', badge: App.t('rep.' + res) };
|
||||||
}
|
}
|
||||||
|
case 'landing': {
|
||||||
|
const site = s.site || {};
|
||||||
|
const taken = !!s.taken;
|
||||||
|
const res = sharedItem ? null : Mil.perspective(it.role, s.outcome);
|
||||||
|
return { icon: 'b-backbone_node', title: App.t('rep.landing.title', { n: Number.isInteger(site.index) ? site.index + 1 : '?' }), sub: sharedItem ? App.t('rep.by', { name: nameOf(s.attacker) }) + ' · ' + (taken ? App.t('rep.landing.taken') : App.t('rep.landing.held')) : (taken ? App.t('rep.landing.taken') : App.t('rep.landing.held')), tone: res === null ? 'neutral' : (res === 'victory' ? 'good' : 'bad'), badge: res === null ? null : App.t('rep.' + res) };
|
||||||
|
}
|
||||||
case 'scan': {
|
case 'scan': {
|
||||||
const where = s.target ? townOf(s.target) : (s.site ? s.site.x + ', ' + s.site.y : '?');
|
const where = s.target ? townOf(s.target) : (s.site ? (s.site.type === 'backbone' ? App.t('wld.site', { n: s.site.index + 1 }) : s.site.x + ', ' + s.site.y) : '?');
|
||||||
return { icon: 'eye', title: App.t('rep.scan.title', { where }), sub: s.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed'), tone: s.success ? 'good' : 'bad' };
|
return { icon: 'eye', title: App.t('rep.scan.title', { where }), sub: s.success ? App.t('rep.scan.ok') : App.t('rep.scan.failed'), tone: s.success ? 'good' : 'bad' };
|
||||||
}
|
}
|
||||||
case 'scan_detected':
|
case 'scan_detected':
|
||||||
|
|
@ -58,23 +75,49 @@
|
||||||
|
|
||||||
function row(it) {
|
function row(it) {
|
||||||
const d = describe(it);
|
const d = describe(it);
|
||||||
return h('li', null, h('button', { class: 'alert rep tone-' + d.tone + (it.read ? '' : ' new'), type: 'button', dataset: { id: String(it.id) }, onclick: () => openReport(it.id) },
|
const unread = it.read === false; // shared items have no read flag
|
||||||
|
const shared = mode === 'alliance';
|
||||||
|
return h('li', null, h('button', { class: 'alert rep tone-' + d.tone + (unread ? ' new' : ''), type: 'button', dataset: { id: String(it.id) }, onclick: () => openReport(it.id, shared) },
|
||||||
h('span', { class: 'row-ic' }, icon(d.icon)),
|
h('span', { class: 'row-ic' }, icon(d.icon)),
|
||||||
h('span', { class: 'row-main' },
|
h('span', { class: 'row-main' },
|
||||||
h('span', { class: 'row-title' }, h('b', { text: d.title }), d.badge ? h('span', { class: 'pill ' + (d.tone === 'good' ? 'green' : 'amber'), text: d.badge }) : null, it.read ? null : h('span', { class: 'pill accent', text: App.t('alerts.new') })),
|
h('span', { class: 'row-title' }, h('b', { text: d.title }), d.badge ? h('span', { class: 'pill ' + (d.tone === 'good' ? 'green' : 'amber'), text: d.badge }) : null, unread ? h('span', { class: 'pill accent', text: App.t('alerts.new') }) : null),
|
||||||
d.sub ? h('span', { class: 'row-sub', text: d.sub }) : null),
|
d.sub ? h('span', { class: 'row-sub', text: d.sub }) : null,
|
||||||
|
shared && it.sharedBy ? h('span', { class: 'row-sub', text: App.t('rep.sharedBy', { name: it.sharedBy.name }) }) : null),
|
||||||
h('span', { class: 'when mono', dataset: { at: String(it.createdAt) }, text: App.fmt.ago(App.now() - it.createdAt) })));
|
h('span', { class: 'when mono', dataset: { at: String(it.createdAt) }, text: App.fmt.ago(App.now() - it.createdAt) })));
|
||||||
}
|
}
|
||||||
|
|
||||||
function draw() {
|
function draw() {
|
||||||
clear(listEl);
|
clear(listEl);
|
||||||
if (!items.length) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: loading ? App.t('common.loading') : App.t('rep.empty') }))); }
|
const list = curItems();
|
||||||
for (const it of items) listEl.appendChild(row(it));
|
if (mode === 'alliance' && !allianceId()) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: App.t('rep.folder.none') }))); moreBtn.hidden = true; return; }
|
||||||
moreBtn.hidden = next === null;
|
if (!list.length) { listEl.appendChild(h('li', null, h('p', { class: 'empty pad', text: loading || (mode === 'alliance' && !folder.loaded) ? App.t('common.loading') : App.t(mode === 'alliance' ? 'rep.folder.empty' : 'rep.empty') }))); }
|
||||||
|
for (const it of list) listEl.appendChild(row(it));
|
||||||
|
moreBtn.hidden = curNext() === null;
|
||||||
|
if (markBtn) markBtn.hidden = mode === 'alliance';
|
||||||
|
drawTabs();
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawTabs() {
|
||||||
|
if (!tabsEl) return;
|
||||||
|
tabsEl.hidden = !allianceId();
|
||||||
|
clear(tabsEl);
|
||||||
|
for (const k of ['mine', 'alliance']) tabsEl.appendChild(h('button', { class: 'seg-btn', type: 'button', dataset: { tab: k }, 'aria-pressed': String(mode === k), onclick: () => { mode = k; draw(); load(false); } }, App.t(k === 'mine' ? 'rep.tab.mine' : 'rep.tab.alliance')));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function load(more) {
|
async function load(more) {
|
||||||
if (loading) return;
|
if (loading) return;
|
||||||
|
if (mode === 'alliance') {
|
||||||
|
if (!allianceId()) { draw(); return; }
|
||||||
|
loading = true; statusEl.hidden = true;
|
||||||
|
try {
|
||||||
|
const r = await App.api.get('/alliances/' + allianceId() + '/reports', { limit: PAGE, after: more ? folder.next : undefined });
|
||||||
|
folder.items = more ? folder.items.concat(r.items.filter((x) => !folder.items.some((y) => y.id === x.id))) : r.items;
|
||||||
|
folder.next = r.next; folder.loaded = true;
|
||||||
|
} catch (e) { statusEl.textContent = e.code === 'forbidden' ? App.t('rep.folder.forbidden') : App.errMsg(e); statusEl.hidden = false; folder.loaded = true; }
|
||||||
|
finally { loading = false; }
|
||||||
|
draw();
|
||||||
|
return;
|
||||||
|
}
|
||||||
loading = true; statusEl.hidden = true;
|
loading = true; statusEl.hidden = true;
|
||||||
try {
|
try {
|
||||||
const r = await App.api.get('/reports', { limit: PAGE, after: more ? next : undefined });
|
const r = await App.api.get('/reports', { limit: PAGE, after: more ? next : undefined });
|
||||||
|
|
@ -118,6 +161,7 @@
|
||||||
town ? mil().endLink(town) : null));
|
town ? mil().endLink(town) : null));
|
||||||
|
|
||||||
function verdict(role, outcome) {
|
function verdict(role, outcome) {
|
||||||
|
if (!role) return h('div', { class: 'rep-verdict neutral' }, icon('report'), h('b', { text: App.t(outcome === 'attacker_won' ? 'rep.attackerWon' : 'rep.defenderWon') })); // shared: nobody's side
|
||||||
const res = Mil.perspective(role, outcome);
|
const res = Mil.perspective(role, outcome);
|
||||||
return h('div', { class: 'rep-verdict ' + res }, icon(res === 'victory' ? 'check' : 'alert'), h('b', { text: App.t('rep.' + res) }));
|
return h('div', { class: 'rep-verdict ' + res }, icon(res === 'victory' ? 'check' : 'alert'), h('b', { text: App.t('rep.' + res) }));
|
||||||
}
|
}
|
||||||
|
|
@ -165,6 +209,14 @@
|
||||||
out.push(sec(App.t('rep.scanners'), unitsTable(d.scanners && d.scanners.sent, d.scanners && d.scanners.lost, d.scanners && d.scanners.survivors)));
|
out.push(sec(App.t('rep.scanners'), unitsTable(d.scanners && d.scanners.sent, d.scanners && d.scanners.lost, d.scanners && d.scanners.survivors)));
|
||||||
const intel = d.intel;
|
const intel = d.intel;
|
||||||
if (!intel) { out.push(h('p', { class: 'reason', text: App.t('rep.scan.noIntel') })); return out; }
|
if (!intel) { out.push(h('p', { class: 'reason', text: App.t('rep.scan.noIntel') })); return out; }
|
||||||
|
if (d.site && d.site.type === 'backbone') { // end game landing site: the static defence is the number to beat
|
||||||
|
out.push(sec(App.t('rep.intel'),
|
||||||
|
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
|
||||||
|
kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: intel.level || 0, max: D.ENDGAME.maxLevel }) })),
|
||||||
|
kv(App.t('rep.landing.holder'), h('span', { text: intel.holder ? '[' + intel.holder.tag + '] ' + intel.holder.name : App.t('wld.incumbent') })),
|
||||||
|
intel.build ? kv(App.t('wld.building', { n: intel.build.toLevel }), h('span', { text: mil().dayTime(intel.build.dueAt) })) : null));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
if (d.site) { // incumbent site
|
if (d.site) { // incumbent site
|
||||||
out.push(sec(App.t('rep.intel'),
|
out.push(sec(App.t('rep.intel'),
|
||||||
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
|
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
|
||||||
|
|
@ -198,7 +250,7 @@
|
||||||
|
|
||||||
function incumbentBody(r) {
|
function incumbentBody(r) {
|
||||||
const d = r.data, out = [];
|
const d = r.data, out = [];
|
||||||
out.push(verdict('attacker', d.outcome));
|
out.push(verdict(r.role ? 'attacker' : null, d.outcome));
|
||||||
out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
|
out.push(kv(App.t('rep.site'), mil().coordLink(d.site.x, d.site.y)));
|
||||||
if (d.origin) out.push(kv(App.t('rep.from'), mil().endLink(d.origin)));
|
if (d.origin) out.push(kv(App.t('rep.from'), mil().endLink(d.origin)));
|
||||||
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(d.power.attack) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(d.power.defence) }))));
|
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(d.power.attack) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(d.power.defence) }))));
|
||||||
|
|
@ -207,12 +259,30 @@
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function landingBody(r) {
|
||||||
|
const d = r.data, out = [];
|
||||||
|
const site = d.site || {};
|
||||||
|
out.push(verdict(r.role, d.outcome));
|
||||||
|
out.push(h('p', { class: 'row-sub', text: App.t('rep.arrived', { t: mil().dayTime(d.arrivedAt) }) }));
|
||||||
|
out.push(kv(App.t('rep.site'), h('span', { class: 'rep-party' }, h('b', { text: Number.isInteger(site.index) ? App.t('wld.site', { n: site.index + 1 }) : '?' }), mil().coordLink(site.x, site.y))));
|
||||||
|
out.push(kv(App.t('rep.landing.holder'), h('span', { text: site.holder ? '[' + site.holder.tag + '] ' + site.holder.name : App.t('wld.incumbent') })));
|
||||||
|
out.push(kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: site.level || 0, max: D.ENDGAME.maxLevel }) })));
|
||||||
|
out.push(d.taken ? h('p', { class: 'good', text: App.t('rep.landing.takenLine', { tag: d.attacker && d.attacker.alliance ? '[' + d.attacker.alliance.tag + '] ' + d.attacker.alliance.name : '?' }) }) : h('p', { class: 'row-sub wrap', text: App.t('rep.landing.heldLine') }));
|
||||||
|
out.push(party(App.t('rep.attacker'), d.attacker.operator, d.origin));
|
||||||
|
const p = d.power || {};
|
||||||
|
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(p.attack || 0) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(p.defence || 0) }))));
|
||||||
|
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
|
||||||
|
out.push(h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { UI.closeSheet(); App.go('world', Number.isInteger(site.index) ? { site: site.index } : null); } }, icon('b-backbone_node'), App.t('map.info.openWorld')));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
function settleBody(r, ctl) {
|
function settleBody(r, ctl) {
|
||||||
const d = r.data, out = [];
|
const d = r.data, out = [];
|
||||||
out.push(h('div', { class: 'rep-verdict victory' }, icon('flag'), h('b', { text: App.t('rep.settle.title', { name: d.town.name }) })));
|
out.push(h('div', { class: 'rep-verdict victory' }, icon('flag'), h('b', { text: App.t('rep.settle.title', { name: d.town.name }) })));
|
||||||
out.push(kv(App.t('rep.site'), mil().coordLink(d.town.x, d.town.y)));
|
out.push(kv(App.t('rep.site'), mil().coordLink(d.town.x, d.town.y)));
|
||||||
out.push(kv(App.t('rep.settle.wild'), h('span', { text: (d.wild || []).map((w) => App.buildingName(w)).join(', ') })));
|
out.push(kv(App.t('rep.settle.wild'), h('span', { text: (d.wild || []).map((w) => App.buildingName(w)).join(', ') })));
|
||||||
out.push(h('button', { class: 'btn primary wide', type: 'button', onclick: async () => {
|
if (r.shared) return out;
|
||||||
|
out.push(h('button', { class: 'btn primary wide', type: 'button', 'data-keep': '', onclick: async () => {
|
||||||
ctl.close();
|
ctl.close();
|
||||||
try { await App.refreshTowns(); } catch (e) { /* the POP list may be stale; setTown below copes */ }
|
try { await App.refreshTowns(); } catch (e) { /* the POP list may be stale; setTown below copes */ }
|
||||||
App.setTown(d.town.id); App.go('pop');
|
App.setTown(d.town.id); App.go('pop');
|
||||||
|
|
@ -245,6 +315,7 @@
|
||||||
function bodyFor(r, ctl) {
|
function bodyFor(r, ctl) {
|
||||||
switch (r.type) {
|
switch (r.type) {
|
||||||
case 'raid': case 'attack': case 'takeover': return combatBody(r);
|
case 'raid': case 'attack': case 'takeover': return combatBody(r);
|
||||||
|
case 'landing': return landingBody(r);
|
||||||
case 'scan': return scanBody(r);
|
case 'scan': return scanBody(r);
|
||||||
case 'scan_detected': return detectedBody(r);
|
case 'scan_detected': return detectedBody(r);
|
||||||
case 'incumbent': return incumbentBody(r);
|
case 'incumbent': return incumbentBody(r);
|
||||||
|
|
@ -256,19 +327,53 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ detail sheet
|
// ------------------------------------------------------------------ detail sheet
|
||||||
async function openReport(id) {
|
function shareRow(r) {
|
||||||
|
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
const btn = h('button', { class: 'btn', type: 'button', 'data-act': '' }, icon('users'), App.t('rep.share'));
|
||||||
|
btn.addEventListener('click', async () => {
|
||||||
|
btn.disabled = true; msg.hidden = true;
|
||||||
|
try {
|
||||||
|
const res = await App.api.post('/reports/' + r.id + '/share', {}, { intent: 'report-share:' + r.id });
|
||||||
|
toast(App.t(res.changed === false ? 'rep.share.already' : 'rep.share.done'), 'ok');
|
||||||
|
folder.loaded = false;
|
||||||
|
} catch (e) {
|
||||||
|
msg.textContent = e.code === 'forbidden' ? App.t('rep.share.forbidden') : App.errMsg(e); msg.hidden = false; btn.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return h('div', { class: 'rep-share' }, h('p', { class: 'row-sub wrap', text: App.t('rep.share.hint') }), btn, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
function unshareRow(r, ctl) {
|
||||||
|
const msg = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
const btn = h('button', { class: 'btn danger', type: 'button' }, icon('x'), App.t('rep.unshare'));
|
||||||
|
btn.addEventListener('click', async () => {
|
||||||
|
btn.disabled = true; msg.hidden = true;
|
||||||
|
try {
|
||||||
|
await App.api.del('/reports/' + r.id + '/share');
|
||||||
|
toast(App.t('rep.unshare.done'), 'ok');
|
||||||
|
folder.items = folder.items.filter((x) => x.id !== r.id);
|
||||||
|
ctl.close(); if (visible) draw();
|
||||||
|
} catch (e) { msg.textContent = e.code === 'forbidden' ? App.t('rep.unshare.forbidden') : App.errMsg(e); msg.hidden = false; btn.disabled = false; }
|
||||||
|
});
|
||||||
|
return h('div', { class: 'rep-share' }, btn, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openReport(id, shared) {
|
||||||
const body = h('div', { class: 'detail rep-detail' }, h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' })));
|
const body = h('div', { class: 'detail rep-detail' }, h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' })));
|
||||||
const ctl = openSheet({ title: App.t('screen.reports'), icon: 'report', closeLabel: App.t('common.close'), body });
|
const ctl = openSheet({ title: App.t('screen.reports'), icon: 'report', closeLabel: App.t('common.close'), body });
|
||||||
try {
|
try {
|
||||||
const res = await App.api.get('/reports/' + id);
|
const res = await App.api.get(shared ? '/alliances/' + allianceId() + '/reports/' + id : '/reports/' + id);
|
||||||
const r = res.report;
|
const r = res.report;
|
||||||
|
r.shared = !!shared;
|
||||||
ctl.setTitle(mil().reportTypeLabel(r.type));
|
ctl.setTitle(mil().reportTypeLabel(r.type));
|
||||||
clear(body);
|
clear(body);
|
||||||
body.appendChild(h('p', { class: 'row-sub', text: mil().dayTime(r.createdAt) + ' · ' + App.t('rep.role.' + r.role) + ' · ' + App.t('rep.expires', { t: mil().dayTime(r.expiresAt) }) }));
|
body.appendChild(h('p', { class: 'row-sub', text: mil().dayTime(r.createdAt) + ' · ' + (shared ? App.t('rep.sharedBy', { name: r.sharedBy ? r.sharedBy.name : '?' }) : App.t('rep.role.' + r.role)) + ' · ' + App.t('rep.expires', { t: mil().dayTime(r.expiresAt) }) }));
|
||||||
let parts;
|
let parts;
|
||||||
try { parts = bodyFor(r, ctl); } catch (e) { parts = genericBody(r); }
|
try { parts = bodyFor(r, ctl); } catch (e) { parts = genericBody(r); }
|
||||||
for (const p of parts.flat(2)) if (p) body.appendChild(p);
|
for (const p of parts.flat(2)) if (p) body.appendChild(p);
|
||||||
if (!r.read) {
|
if (shared) body.appendChild(unshareRow(r, ctl));
|
||||||
|
else if (allianceId()) body.appendChild(shareRow(r));
|
||||||
|
if (!shared && !r.read) {
|
||||||
App.api.post('/reports/' + id + '/read', {}).then(() => {
|
App.api.post('/reports/' + id + '/read', {}).then(() => {
|
||||||
const it = items.find((x) => x.id === id); if (it) it.read = true;
|
const it = items.find((x) => x.id === id); if (it) it.read = true;
|
||||||
if (visible) draw();
|
if (visible) draw();
|
||||||
|
|
@ -289,22 +394,26 @@
|
||||||
listEl = h('ul', { class: 'alert-list' });
|
listEl = h('ul', { class: 'alert-list' });
|
||||||
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
moreBtn = h('button', { class: 'btn wide', type: 'button', hidden: true, onclick: () => load(true) }, App.t('rep.older'));
|
moreBtn = h('button', { class: 'btn wide', type: 'button', hidden: true, onclick: () => load(true) }, App.t('rep.older'));
|
||||||
|
tabsEl = h('div', { class: 'seg rep-tabs', role: 'group', hidden: true });
|
||||||
|
markBtn = h('button', { class: 'btn small', type: 'button', onclick: markAll }, icon('check'), App.t('rep.markAll'));
|
||||||
box.appendChild(h('div', { class: 'page' },
|
box.appendChild(h('div', { class: 'page' },
|
||||||
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.reports') }),
|
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.reports') }),
|
||||||
h('div', { class: 'head-actions' },
|
h('div', { class: 'head-actions' }, markBtn,
|
||||||
h('button', { class: 'btn small', type: 'button', onclick: markAll }, icon('check'), App.t('rep.markAll')),
|
|
||||||
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load(false) }, icon('refresh')))),
|
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load(false) }, icon('refresh')))),
|
||||||
statusEl, listEl, moreBtn));
|
tabsEl, statusEl, listEl, moreBtn));
|
||||||
App.on('session', () => { items = []; next = null; });
|
App.on('session', () => { items = []; next = null; folder.items = []; folder.next = null; folder.loaded = false; mode = 'mine'; });
|
||||||
App.on('report', () => { if (visible) load(false); });
|
App.on('report', () => { if (visible) load(false); });
|
||||||
},
|
},
|
||||||
onShow(params) {
|
onShow(params) {
|
||||||
visible = true;
|
visible = true;
|
||||||
box.querySelector('h1').textContent = App.t('screen.reports');
|
box.querySelector('h1').textContent = App.t('screen.reports');
|
||||||
moreBtn.textContent = App.t('rep.older');
|
moreBtn.textContent = App.t('rep.older');
|
||||||
|
markBtn.lastChild.textContent = App.t('rep.markAll');
|
||||||
|
if (params && params.tab === 'alliance' && allianceId()) mode = 'alliance';
|
||||||
|
if (mode === 'alliance' && !allianceId()) mode = 'mine';
|
||||||
draw();
|
draw();
|
||||||
load(false);
|
load(false);
|
||||||
if (params && params.open) openReport(Number(params.open));
|
if (params && params.open) openReport(Number(params.open), false);
|
||||||
if (offAgo) offAgo();
|
if (offAgo) offAgo();
|
||||||
offAgo = App.onTick(() => {
|
offAgo = App.onTick(() => {
|
||||||
const now = App.now();
|
const now = App.now();
|
||||||
|
|
|
||||||
|
|
@ -84,7 +84,7 @@
|
||||||
|
|
||||||
function computeOptions() {
|
function computeOptions() {
|
||||||
const m = st.from.td.military;
|
const m = st.from.td.military;
|
||||||
st.options = Mil.moveOptions({ tile: st.tile, home: m.units.home, transport: m.transport, allianceId: op() ? op().allianceId : null, crews: m.units.home[D.EXPANSION.settleUnit] || 0 });
|
st.options = Mil.moveOptions({ tile: st.tile, home: m.units.home, transport: m.transport, allianceId: op() ? op().allianceId : null, crews: m.units.home[D.EXPANSION.settleUnit] || 0, transportOnly: opts.type === 'transport' });
|
||||||
const want = st.type && st.options.some((o) => o.type === st.type) ? st.type : (opts.type && st.options.some((o) => o.type === opts.type && o.ok) ? opts.type : null);
|
const want = st.type && st.options.some((o) => o.type === st.type) ? st.type : (opts.type && st.options.some((o) => o.type === opts.type && o.ok) ? opts.type : null);
|
||||||
const first = st.options.find((o) => o.ok);
|
const first = st.options.find((o) => o.ok);
|
||||||
setType(want || (first ? first.type : (st.options[0] ? st.options[0].type : null)), true);
|
setType(want || (first ? first.type : (st.options[0] ? st.options[0].type : null)), true);
|
||||||
|
|
@ -126,8 +126,14 @@
|
||||||
if (t.town.owner && t.town.owner.protected) pills.push(h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')));
|
if (t.town.owner && t.town.owner.protected) pills.push(h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')));
|
||||||
}
|
}
|
||||||
if (t.type === 'rural' && t.bonus) pills.push(h('span', { class: 'pill res-' + t.bonus }, icon(t.bonus), App.resName(t.bonus)));
|
if (t.type === 'rural' && t.bonus) pills.push(h('span', { class: 'pill res-' + t.bonus }, icon(t.bonus), App.resName(t.bonus)));
|
||||||
|
const bb = t.type === 'backbone' ? (t.backbone || {}) : null; // end game landing site
|
||||||
|
if (bb) {
|
||||||
|
if (bb.holder) pills.push(h('span', { class: 'pill' + (bb.mine ? ' accent' : '') }, '[' + bb.holder.tag + '] ' + bb.holder.name));
|
||||||
|
else pills.push(h('span', { class: 'pill dim', text: App.t('wld.incumbent') }));
|
||||||
|
pills.push(h('span', { class: 'pill', text: App.t('wld.level', { n: bb.level || 0, max: bb.maxLevel || D.ENDGAME.maxLevel }) }));
|
||||||
|
}
|
||||||
secTarget.appendChild(h('div', { class: 'send-target' },
|
secTarget.appendChild(h('div', { class: 'send-target' },
|
||||||
h('div', { class: 'row' }, h('b', { text: t.town ? t.town.name : App.t('tile.' + t.type) }), mil().coordLink(t.x, t.y)),
|
h('div', { class: 'row' }, h('b', { text: t.town ? t.town.name : (bb && Number.isInteger(bb.index) ? App.t('wld.site', { n: bb.index + 1 }) : App.t('tile.' + t.type)) }), mil().coordLink(t.x, t.y)),
|
||||||
t.town && t.town.owner ? h('p', { class: 'row-sub wrap', text: t.town.owner.name + ' · ' + UpstreamI18n.fmtAs(t.town.owner.asNumber) }) : null,
|
t.town && t.town.owner ? h('p', { class: 'row-sub wrap', text: t.town.owner.name + ' · ' + UpstreamI18n.fmtAs(t.town.owner.asNumber) }) : null,
|
||||||
h('div', { class: 'pill-row' }, pills)));
|
h('div', { class: 'pill-row' }, pills)));
|
||||||
}
|
}
|
||||||
|
|
@ -283,6 +289,8 @@
|
||||||
h('span', { class: 'field-hint', text: App.t('send.siege.hint', { n: D.MILITARY.kitsMin }) })));
|
h('span', { class: 'field-hint', text: App.t('send.siege.hint', { n: D.MILITARY.kitsMin }) })));
|
||||||
}
|
}
|
||||||
if (type === 'takeover') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.takeover.hint') }));
|
if (type === 'takeover') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.takeover.hint') }));
|
||||||
|
if (st.tile.type === 'backbone' && (type === 'attack' || type === 'scan')) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.landing.hint', { mult: D.ENDGAME.defenceMult }) }));
|
||||||
|
if (type === 'transport' && st.tile.town && !st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.transport.rival') }));
|
||||||
if (type === 'raid') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.raid.hint') }));
|
if (type === 'raid') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.raid.hint') }));
|
||||||
if (type === 'scan') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.scan.hint') }));
|
if (type === 'scan') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.scan.hint') }));
|
||||||
if (type === 'reinforce' && st.tile.town && st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.reinforce.own') }));
|
if (type === 'reinforce' && st.tile.town && st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.reinforce.own') }));
|
||||||
|
|
|
||||||
503
public/js/screens/trade.js
Normal file
503
public/js/screens/trade.js
Normal file
|
|
@ -0,0 +1,503 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Internet exchange: trade offers and direct transports (More > Exchange). Four tabs:
|
||||||
|
* offers open offers of other operators that one of your exchanges can reach (GET /trade/offers), filters for what they give / want,
|
||||||
|
* "Take" opens a sheet with the POPs that may accept (acceptableFrom) and what each one would pay
|
||||||
|
* new post an offer (POST /trade/offers): terms checked live with rules.tradeTermsCheck (1:2 band, per-link capacity, distance)
|
||||||
|
* mine offers you posted or took (GET /trade/offers/mine), cancel (DELETE), expiry countdowns
|
||||||
|
* send direct transport to one of your POPs or to any POP by coordinates (the send dialog in transport mode) + the links in use
|
||||||
|
* Needs an Internet exchange (level 1+). Without one every tab but "mine" shows what is required. The server re-validates everything and
|
||||||
|
* its error codes are translated; player-controlled strings (operator and POP names) are set with textContent only.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
const { h, clear, icon, toast, openSheet } = UI;
|
||||||
|
const R = UpstreamRules;
|
||||||
|
const D = UpstreamData;
|
||||||
|
const T = D.TRADE;
|
||||||
|
const mil = () => App.mil;
|
||||||
|
const num = (n) => App.fmt.num(n);
|
||||||
|
const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
|
||||||
|
const EXCH = D.TRANSPORT.building;
|
||||||
|
const TABS = ['offers', 'new', 'mine', 'send'];
|
||||||
|
const PAGE = 25;
|
||||||
|
|
||||||
|
let box, tabsEl, bodyEl, visible = false, offTick = null;
|
||||||
|
let tab = 'offers', gen = 0;
|
||||||
|
const S = {
|
||||||
|
levels: null, // [{ townId, level, reach }] of my POPs with an exchange, from GET /trade/offers
|
||||||
|
filter: { give: '', want: '', townId: 0 },
|
||||||
|
offers: { items: [], next: null, loaded: false, loading: false, err: null },
|
||||||
|
mine: { items: [], next: null, loaded: false, loading: false, err: null, status: '' },
|
||||||
|
form: null, // the "new offer" draft, kept while you switch tabs
|
||||||
|
send: { fromId: 0, x: '', y: '' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const townName = (id) => mil().townName(id) || '#' + id;
|
||||||
|
const speed = () => (App.state.world ? App.state.world.speed : 1);
|
||||||
|
const hasExchange = () => !!(S.levels && S.levels.length);
|
||||||
|
const levelOf = (townId) => { const l = (S.levels || []).find((x) => x.townId === townId); return l ? l.level : 0; };
|
||||||
|
const chip = (res, amount, signed) => h('span', { class: 'cost ' + res }, icon(res), h('b', { text: (signed || '') + num(amount) }), h('small', { text: App.resName(res) }));
|
||||||
|
const amountChip = (a, signed) => chip(a.resource, a.amount, signed);
|
||||||
|
const sel = (opts, value, onchange, label) => h('select', { 'aria-label': label, onchange: (e) => onchange(e.target.value) }, opts.map((o) => h('option', { value: o.value, selected: String(o.value) === String(value), text: o.text })));
|
||||||
|
const resOptions = (any) => (any ? [{ value: '', text: App.t('trd.any') }] : []).concat(D.RESOURCES.map((r) => ({ value: r, text: App.resName(r) })));
|
||||||
|
|
||||||
|
function errText(e) {
|
||||||
|
const d = e.details || {};
|
||||||
|
if (e.code === 'trade_out_of_range') return App.t('trd.err.range', { d: App.fmt.dec(d.distance || 0), max: d.maxDistance || 0, reach: d.reach || 0 });
|
||||||
|
if (e.code === 'trade_ratio') return App.t('trd.err.ratio', { n: T.ratioMax });
|
||||||
|
if (e.code === 'capacity_exceeded') return App.t('trd.err.cap', { n: D.TRANSPORT.capacityPerLink });
|
||||||
|
return App.errMsg(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ POP info (stock + links), cached for a few seconds
|
||||||
|
const infos = new Map();
|
||||||
|
async function townInfo(id, force) {
|
||||||
|
const c = infos.get(id);
|
||||||
|
if (!force && c && Date.now() - c.at < 8000) return c;
|
||||||
|
const x = await mil().loadTown(id);
|
||||||
|
const rec = { at: Date.now(), id, td: x.town, rt: App.rulesTownFrom(x.town, x.serverTime) };
|
||||||
|
infos.set(id, rec);
|
||||||
|
return rec;
|
||||||
|
}
|
||||||
|
const stock = (rec) => R.resourcesAt(rec.rt, App.now()).amounts;
|
||||||
|
const linkState = (rec) => { const t = rec.td.military.transport; return { links: t.links, active: t.active, free: Math.max(0, t.links - t.active) }; };
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ loading
|
||||||
|
async function loadLevels() {
|
||||||
|
const r = await App.api.get('/trade/offers', { limit: 1 });
|
||||||
|
S.levels = r.exchangeLevels || [];
|
||||||
|
if (S.filter.townId && !levelOf(S.filter.townId)) S.filter.townId = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadOffers(more) {
|
||||||
|
const o = S.offers;
|
||||||
|
if (o.loading) return;
|
||||||
|
o.loading = true; o.err = null;
|
||||||
|
try {
|
||||||
|
const q = { limit: PAGE };
|
||||||
|
if (S.filter.give) q.give = S.filter.give;
|
||||||
|
if (S.filter.want) q.want = S.filter.want;
|
||||||
|
if (S.filter.townId) q.townId = S.filter.townId;
|
||||||
|
if (more && o.next) q.after = o.next;
|
||||||
|
const r = await App.api.get('/trade/offers', q);
|
||||||
|
o.items = more ? o.items.concat(r.items.filter((x) => !o.items.some((y) => y.id === x.id))) : r.items;
|
||||||
|
o.next = r.next; o.loaded = true;
|
||||||
|
if (!S.filter.townId) S.levels = r.exchangeLevels || [];
|
||||||
|
} catch (e) { o.err = e; } finally {
|
||||||
|
o.loading = false;
|
||||||
|
if (visible && tab === 'offers') drawBody();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadMine(more) {
|
||||||
|
const m = S.mine;
|
||||||
|
if (m.loading) return;
|
||||||
|
m.loading = true; m.err = null;
|
||||||
|
try {
|
||||||
|
const q = { limit: PAGE };
|
||||||
|
if (m.status) q.status = m.status;
|
||||||
|
if (more && m.next) q.after = m.next;
|
||||||
|
const r = await App.api.get('/trade/offers/mine', q);
|
||||||
|
m.items = more ? m.items.concat(r.items.filter((x) => !m.items.some((y) => y.id === x.id))) : r.items;
|
||||||
|
m.next = r.next; m.loaded = true;
|
||||||
|
} catch (e) { m.err = e; } finally {
|
||||||
|
m.loading = false;
|
||||||
|
if (visible && tab === 'mine') drawBody();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function reloadAll() {
|
||||||
|
infos.clear();
|
||||||
|
loadLevels().catch(() => {}).then(() => { if (visible) drawBody(); });
|
||||||
|
loadOffers(false); loadMine(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ pieces
|
||||||
|
function needExchange() {
|
||||||
|
const req = (D.BUILDINGS[EXCH].requires || []).map((r) => App.t('trd.need.req', { building: App.buildingName(r.type), level: r.level })).join(' ');
|
||||||
|
return h('section', { class: 'card trd-need' },
|
||||||
|
h('div', { class: 'card-head' }, h('h2', null, icon('b-' + EXCH), App.t('trd.need.title'))),
|
||||||
|
h('p', { class: 'detail-desc', text: App.t('trd.need.body', { n: T.reachPerLevel, cap: D.TRANSPORT.capacityPerLink }) }),
|
||||||
|
h('p', { class: 'row-sub wrap', text: req }),
|
||||||
|
h('button', { class: 'btn primary wide', type: 'button', onclick: () => App.go('pop') }, icon('pop'), App.t('trd.need.go')));
|
||||||
|
}
|
||||||
|
|
||||||
|
function reachPills() {
|
||||||
|
return h('div', { class: 'pill-row trd-reach' }, (S.levels || []).map((l) => h('span', { class: 'pill', title: App.t('trd.reach.title') },
|
||||||
|
icon('b-' + EXCH), townName(l.townId) + ' · ' + App.t('trd.reach', { lv: l.level, n: l.reach }))));
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusPill(status) {
|
||||||
|
const cls = { open: 'accent', accepted: 'amber', completed: 'green' }[status] || 'dim';
|
||||||
|
return h('span', { class: 'pill ' + cls, text: App.t('trd.status.' + status) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ tab: offers
|
||||||
|
function drawOffers(into) {
|
||||||
|
const o = S.offers;
|
||||||
|
if (!hasExchange()) { into.appendChild(needExchange()); return; }
|
||||||
|
const filters = h('div', { class: 'trd-filters' },
|
||||||
|
h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.f.give') }), sel(resOptions(true), S.filter.give, (v) => { S.filter.give = v; loadOffers(false); }, App.t('trd.f.give'))),
|
||||||
|
h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.f.want') }), sel(resOptions(true), S.filter.want, (v) => { S.filter.want = v; loadOffers(false); }, App.t('trd.f.want'))),
|
||||||
|
S.levels.length > 1 ? h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.f.from') }),
|
||||||
|
sel([{ value: 0, text: App.t('trd.f.allPops') }].concat(S.levels.map((l) => ({ value: l.townId, text: townName(l.townId) }))), S.filter.townId, (v) => { S.filter.townId = Number(v); loadOffers(false); }, App.t('trd.f.from'))) : null);
|
||||||
|
into.appendChild(h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', null, icon('swap'), App.t('trd.offers.head'))), reachPills(), filters));
|
||||||
|
if (o.err) into.appendChild(h('div', { class: 'soc-err' }, h('p', { class: 'form-error', role: 'alert', text: errText(o.err) }), h('button', { class: 'btn small', type: 'button', onclick: () => loadOffers(false) }, icon('refresh'), App.t('common.retry'))));
|
||||||
|
if (!o.loaded) { into.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
|
||||||
|
if (!o.items.length) {
|
||||||
|
into.appendChild(h('div', { class: 'card trd-empty' }, h('p', { class: 'empty', text: S.filter.give || S.filter.want ? App.t('trd.offers.emptyFiltered') : App.t('trd.offers.empty') }),
|
||||||
|
h('button', { class: 'btn wide', type: 'button', onclick: () => setTab('new') }, icon('plus'), App.t('trd.offers.post'))));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
into.appendChild(h('ul', { class: 'mil-list trd-list' }, o.items.map(openRow)));
|
||||||
|
if (o.next) into.appendChild(h('button', { class: 'btn wide', type: 'button', disabled: o.loading, onclick: () => loadOffers(true) }, App.t('trd.more')));
|
||||||
|
}
|
||||||
|
|
||||||
|
function terms(get, pay) {
|
||||||
|
return h('div', { class: 'trd-terms' },
|
||||||
|
h('div', { class: 'trd-term' }, h('span', { class: 'trd-lbl', text: App.t('trd.get') }), amountChip(get)),
|
||||||
|
h('div', { class: 'trd-term' }, h('span', { class: 'trd-lbl', text: App.t('trd.pay') }), amountChip(pay)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function openRow(o) {
|
||||||
|
const near = o.acceptableFrom && o.acceptableFrom.length ? Math.min.apply(null, o.acceptableFrom.map((a) => a.distance)) : null;
|
||||||
|
return h('li', { class: 'mil-row trd-offer', dataset: { id: String(o.id) } },
|
||||||
|
h('span', { class: 'row-ic' }, icon('swap')),
|
||||||
|
h('span', { class: 'row-main' },
|
||||||
|
terms(o.give, o.want),
|
||||||
|
h('span', { class: 'row-sub wrap' }, h('span', { text: o.operator.name + (o.townName ? ' · ' + o.townName : '') + ' ' }), o.x !== null && o.x !== undefined ? mil().coordLink(o.x, o.y) : null,
|
||||||
|
near !== null ? h('span', { text: ' · ' + App.t('trd.away', { d: App.fmt.dec(near) }) }) : null),
|
||||||
|
h('span', { class: 'row-sub wrap' }, App.t('trd.maxDist', { n: o.maxDistance }) + ' · ' + App.t('trd.expiresIn') + ' ', mil().countdown(o.expiresAt))),
|
||||||
|
h('button', { class: 'btn small primary', type: 'button', onclick: () => openAccept(o) }, App.t('trd.take')));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The accept sheet: which of my POPs takes the offer.
|
||||||
|
async function openAccept(o) {
|
||||||
|
const body = h('div', { class: 'detail trd-accept' });
|
||||||
|
const sheet = openSheet({ title: App.t('trd.accept.title'), icon: 'swap', closeLabel: App.t('common.close'), body });
|
||||||
|
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
|
||||||
|
const list = h('div', { class: 'trd-pops' }, h('p', { class: 'empty', text: App.t('common.loading') }));
|
||||||
|
const errEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
const go = h('button', { class: 'btn primary wide', type: 'button', disabled: true }, icon('check'), App.t('trd.accept.go'));
|
||||||
|
body.appendChild(h('div', null, kv(App.t('trd.get'), amountChip(o.give)), kv(App.t('trd.pay'), amountChip(o.want)),
|
||||||
|
kv(App.t('trd.from'), h('span', null, o.operator.name + (o.townName ? ' · ' + o.townName : ''))), kv(App.t('trd.expiresIn'), mil().countdown(o.expiresAt))));
|
||||||
|
body.appendChild(h('h3', { class: 'sub', text: App.t('trd.accept.with') }));
|
||||||
|
body.appendChild(list); body.appendChild(errEl); body.appendChild(h('div', { class: 'send-foot' }, go));
|
||||||
|
let chosen = 0, busy = false, intent = 'trade-accept:' + o.id + ':' + nonce();
|
||||||
|
try {
|
||||||
|
const cands = (o.acceptableFrom || []).slice().sort((a, b) => a.distance - b.distance);
|
||||||
|
const recs = await Promise.all(cands.map((c) => townInfo(c.townId, true).catch(() => null)));
|
||||||
|
clear(list);
|
||||||
|
if (!cands.length) list.appendChild(h('p', { class: 'reason', text: App.t('trd.accept.nopop') }));
|
||||||
|
cands.forEach((c, i) => {
|
||||||
|
const rec = recs[i];
|
||||||
|
let why = '';
|
||||||
|
if (!rec) why = App.t('err.unknown');
|
||||||
|
else {
|
||||||
|
const have = stock(rec)[o.want.resource], ls = linkState(rec);
|
||||||
|
if (have + 1e-6 < o.want.amount) why = App.t('trd.accept.short', { res: App.resName(o.want.resource), have: num(have) });
|
||||||
|
else if (!ls.free) why = App.t('trd.accept.nolink');
|
||||||
|
}
|
||||||
|
const radio = h('input', { type: 'radio', name: 'trd-pop', value: String(c.townId), disabled: !!why, onchange: () => { chosen = c.townId; go.disabled = busy; } });
|
||||||
|
list.appendChild(h('label', { class: 'trd-pop' + (why ? ' off' : '') }, radio,
|
||||||
|
h('span', { class: 'row-main' },
|
||||||
|
h('b', { text: townName(c.townId) }),
|
||||||
|
h('span', { class: 'row-sub wrap', text: App.t('trd.away', { d: App.fmt.dec(c.distance) }) + ' · ' + App.t('trd.latency', { t: App.fmt.dur(R.transportMs(c.distance, speed())) }) + (rec ? ' · ' + App.t('trd.have', { n: num(stock(rec)[o.want.resource]), res: App.resName(o.want.resource) }) : '') }),
|
||||||
|
why ? h('span', { class: 'reason', text: why }) : null)));
|
||||||
|
if (!why && !chosen) { radio.checked = true; chosen = c.townId; go.disabled = false; }
|
||||||
|
});
|
||||||
|
} catch (e) { clear(list); list.appendChild(h('p', { class: 'form-error', text: errText(e) })); }
|
||||||
|
go.addEventListener('click', async () => {
|
||||||
|
if (!chosen || busy) return;
|
||||||
|
busy = true; go.disabled = true; errEl.hidden = true;
|
||||||
|
try {
|
||||||
|
const r = await App.api.post('/trade/offers/' + o.id + '/accept', { townId: chosen }, { intent: intent });
|
||||||
|
toast(App.t('trd.accept.done', { t: App.fmt.dur(r.arriveAt - App.now()) }), 'ok');
|
||||||
|
sheet.close();
|
||||||
|
infos.clear();
|
||||||
|
App.refreshTown().catch(() => {}); App.refreshMovements().catch(() => {});
|
||||||
|
loadOffers(false); loadMine(false);
|
||||||
|
} catch (e) {
|
||||||
|
busy = false; go.disabled = false;
|
||||||
|
errEl.textContent = errText(e); errEl.hidden = false;
|
||||||
|
if (e.code === 'offer_closed' || e.code === 'not_found') { loadOffers(false); go.disabled = true; }
|
||||||
|
intent = 'trade-accept:' + o.id + ':' + nonce();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ tab: new offer
|
||||||
|
function newForm() {
|
||||||
|
if (S.form) return S.form;
|
||||||
|
const first = (S.levels || [])[0];
|
||||||
|
S.form = { townId: first ? first.townId : 0, giveRes: 'fiber', giveAmount: 100, wantRes: 'hardware', wantAmount: 100, maxDistance: null, touchedDist: false, nonce: nonce() };
|
||||||
|
return S.form;
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawNew(into) {
|
||||||
|
if (!hasExchange()) { into.appendChild(needExchange()); return; }
|
||||||
|
const F = newForm();
|
||||||
|
if (!levelOf(F.townId)) F.townId = S.levels[0].townId;
|
||||||
|
const defaultDist = () => Math.min(T.maxDistance, Math.max(1, (S.levels.find((l) => l.townId === F.townId) || { reach: 10 }).reach));
|
||||||
|
if (F.maxDistance === null) F.maxDistance = defaultDist();
|
||||||
|
let rec = null;
|
||||||
|
|
||||||
|
const msgs = h('div', { class: 'trd-msgs', role: 'status' });
|
||||||
|
const note = h('div', { class: 'trd-note' });
|
||||||
|
const bandEl = h('p', { class: 'field-hint' });
|
||||||
|
const stockEl = h('span', { class: 'dimmer' });
|
||||||
|
const submit = h('button', { class: 'btn primary wide', type: 'button', onclick: () => post() }, icon('swap'), App.t('trd.new.go'));
|
||||||
|
const errEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
const numField = (key, label, min, max) => {
|
||||||
|
const input = h('input', { type: 'number', inputmode: 'numeric', class: 'mil-num', min: String(min), max: String(max), value: F[key] === null ? '' : String(F[key]), 'aria-label': label });
|
||||||
|
input.addEventListener('input', () => { F[key] = input.value === '' ? 0 : Math.floor(Number(input.value)) || 0; if (key === 'maxDistance') F.touchedDist = true; refresh(); });
|
||||||
|
return input;
|
||||||
|
};
|
||||||
|
const giveIn = numField('giveAmount', App.t('trd.new.giveAmount'), 1, D.TRANSPORT.capacityPerLink);
|
||||||
|
const wantIn = numField('wantAmount', App.t('trd.new.wantAmount'), 1, D.TRANSPORT.capacityPerLink);
|
||||||
|
const distIn = numField('maxDistance', App.t('trd.new.maxDist'), 1, T.maxDistance);
|
||||||
|
const maxBtn = h('button', { class: 'btn small', type: 'button', onclick: () => { const have = rec ? Math.floor(stock(rec)[F.giveRes]) : 0; F.giveAmount = Math.max(1, Math.min(D.TRANSPORT.capacityPerLink, have)); giveIn.value = String(F.giveAmount); refresh(); } }, App.t('send.all'));
|
||||||
|
const matchBtn = h('button', { class: 'btn small', type: 'button', onclick: () => { F.wantAmount = F.giveAmount; wantIn.value = String(F.wantAmount); refresh(); } }, App.t('trd.new.match'));
|
||||||
|
|
||||||
|
function validate() {
|
||||||
|
const out = [];
|
||||||
|
const chk = R.tradeTermsCheck({ giveRes: F.giveRes, giveAmount: F.giveAmount, wantRes: F.wantRes, wantAmount: F.wantAmount, maxDistance: F.maxDistance });
|
||||||
|
if (!chk.ok) {
|
||||||
|
if (chk.code === 'trade_ratio') out.push(App.t('trd.err.ratio', { n: T.ratioMax }));
|
||||||
|
else if (chk.code === 'capacity_exceeded') out.push(App.t('trd.err.cap', { n: D.TRANSPORT.capacityPerLink }));
|
||||||
|
else out.push(App.t('trd.v.' + ((chk.errors && chk.errors[0] && chk.errors[0].path) || 'terms')));
|
||||||
|
}
|
||||||
|
if (rec) {
|
||||||
|
const have = stock(rec)[F.giveRes];
|
||||||
|
if (have + 1e-6 < F.giveAmount) out.push(App.t('trd.v.have', { res: App.resName(F.giveRes), have: num(have) }));
|
||||||
|
if (!linkState(rec).free) out.push(App.t('trd.v.links'));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function refresh() {
|
||||||
|
const lv = levelOf(F.townId), reach = (S.levels.find((l) => l.townId === F.townId) || {}).reach || 0;
|
||||||
|
const problems = validate();
|
||||||
|
clear(msgs);
|
||||||
|
for (const p of problems) msgs.appendChild(h('p', { class: 'reason', text: p }));
|
||||||
|
submit.disabled = problems.length > 0 || !rec;
|
||||||
|
if (F.giveAmount >= 1) {
|
||||||
|
const lo = Math.max(1, Math.ceil(F.giveAmount / T.ratioMax)), hi = Math.min(D.TRANSPORT.capacityPerLink, F.giveAmount * T.ratioMax);
|
||||||
|
bandEl.textContent = App.t('trd.new.band', { lo: num(lo), hi: num(hi) });
|
||||||
|
} else bandEl.textContent = '';
|
||||||
|
stockEl.textContent = rec ? App.t('trd.have', { n: num(stock(rec)[F.giveRes]), res: App.resName(F.giveRes) }) : '';
|
||||||
|
clear(note);
|
||||||
|
const need = Math.max(1, Math.ceil((F.maxDistance || 1) / T.reachPerLevel));
|
||||||
|
note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.level', { lv, reach, need, d: F.maxDistance || 0 }) }));
|
||||||
|
note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.rules', { cap: D.TRANSPORT.capacityPerLink, n: T.ratioMax, ttl: App.fmt.dur(T.ttlHours * D.HOUR_MS / speed()) }) }));
|
||||||
|
if (rec) { const ls = linkState(rec); note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.links', { free: ls.free, links: ls.links }) })); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRec() {
|
||||||
|
rec = null; refresh();
|
||||||
|
try { rec = await townInfo(F.townId); } catch (e) { rec = null; }
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function post() {
|
||||||
|
if (submit.disabled) return;
|
||||||
|
submit.disabled = true; errEl.hidden = true;
|
||||||
|
try {
|
||||||
|
await App.api.post('/trade/offers', { townId: F.townId, giveRes: F.giveRes, giveAmount: F.giveAmount, wantRes: F.wantRes, wantAmount: F.wantAmount, maxDistance: F.maxDistance }, { intent: 'trade-offer:' + F.nonce });
|
||||||
|
F.nonce = nonce();
|
||||||
|
toast(App.t('trd.new.done'), 'ok');
|
||||||
|
infos.clear();
|
||||||
|
App.refreshTown().catch(() => {});
|
||||||
|
S.mine.status = ''; loadMine(false);
|
||||||
|
setTab('mine');
|
||||||
|
} catch (e) {
|
||||||
|
errEl.textContent = errText(e); errEl.hidden = false;
|
||||||
|
if (e.code !== 'network_error') F.nonce = nonce();
|
||||||
|
loadRec();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const otherRes = (r) => D.RESOURCES.find((x) => x !== r);
|
||||||
|
const giveResSel = sel(resOptions(false), F.giveRes, (v) => { F.giveRes = v; if (F.wantRes === v) { F.wantRes = otherRes(v); wantResSel.value = F.wantRes; } refresh(); }, App.t('trd.new.giveRes'));
|
||||||
|
const wantResSel = sel(resOptions(false), F.wantRes, (v) => { F.wantRes = v; if (F.giveRes === v) { F.giveRes = otherRes(v); giveResSel.value = F.giveRes; } refresh(); }, App.t('trd.new.wantRes'));
|
||||||
|
const popField = S.levels.length > 1
|
||||||
|
? h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.new.pop') }),
|
||||||
|
sel(S.levels.map((l) => ({ value: l.townId, text: townName(l.townId) + ' · ' + App.t('trd.reach', { lv: l.level, n: l.reach }) })), F.townId, (v) => { F.townId = Number(v); if (!F.touchedDist) { F.maxDistance = defaultDist(); distIn.value = String(F.maxDistance); } loadRec(); }, App.t('trd.new.pop')))
|
||||||
|
: h('p', { class: 'row-sub wrap', text: townName(F.townId) });
|
||||||
|
into.appendChild(h('section', { class: 'card trd-form' },
|
||||||
|
h('div', { class: 'card-head' }, h('h2', null, icon('plus'), App.t('trd.new.head'))),
|
||||||
|
popField,
|
||||||
|
h('h3', { class: 'sub', text: App.t('trd.new.give') }),
|
||||||
|
h('div', { class: 'trd-pair' }, giveResSel, giveIn, maxBtn),
|
||||||
|
stockEl,
|
||||||
|
h('h3', { class: 'sub', text: App.t('trd.new.want') }),
|
||||||
|
h('div', { class: 'trd-pair' }, wantResSel, wantIn, matchBtn),
|
||||||
|
bandEl,
|
||||||
|
h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('trd.new.maxDist') }), distIn, h('span', { class: 'field-hint', text: App.t('trd.new.maxDistHint', { max: T.maxDistance }) })),
|
||||||
|
note, msgs, errEl, h('div', { class: 'send-foot' }, submit)));
|
||||||
|
loadRec();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ tab: mine
|
||||||
|
function mineRow(o) {
|
||||||
|
const poster = o.role === 'poster';
|
||||||
|
const get = poster ? o.want : o.give, pay = poster ? o.give : o.want;
|
||||||
|
const open = o.status === 'open';
|
||||||
|
const cancel = open && poster ? h('button', { class: 'btn small danger', type: 'button', onclick: (ev) => cancelOffer(o, ev.currentTarget) }, icon('x'), App.t('trd.cancel')) : null;
|
||||||
|
return h('li', { class: 'mil-row trd-offer', dataset: { id: String(o.id), status: o.status } },
|
||||||
|
h('span', { class: 'row-ic' }, icon('swap')),
|
||||||
|
h('span', { class: 'row-main' },
|
||||||
|
h('span', { class: 'row-title' }, h('b', { text: App.t('trd.role.' + o.role) }), statusPill(o.status)),
|
||||||
|
terms(get, pay),
|
||||||
|
h('span', { class: 'row-sub wrap' }, o.townName ? h('span', { text: o.townName + ' ' }) : null, o.x !== null && o.x !== undefined ? mil().coordLink(o.x, o.y) : null, h('span', { text: ' · ' + App.t('trd.maxDist', { n: o.maxDistance }) })),
|
||||||
|
open ? h('span', { class: 'row-sub wrap' }, App.t('trd.expiresIn') + ' ', mil().countdown(o.expiresAt)) : null,
|
||||||
|
o.status === 'accepted' ? h('span', { class: 'row-sub wrap', text: App.t('trd.settles') }) : null,
|
||||||
|
o.status === 'void' ? h('span', { class: 'row-sub wrap', text: App.t('trd.voidHint') }) : null,
|
||||||
|
h('span', { class: 'row-sub', text: App.fmt.ago(App.now() - (o.closedAt || o.acceptedAt || o.createdAt)) })),
|
||||||
|
cancel);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cancelOffer(o, btn) {
|
||||||
|
btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const r = await App.api.del('/trade/offers/' + o.id, { intent: 'trade-cancel:' + o.id });
|
||||||
|
toast(App.t('trd.cancelled', { what: r.returned ? num(r.returned.amount) + ' ' + App.resName(r.returned.resource) : '' }), 'ok');
|
||||||
|
infos.clear();
|
||||||
|
App.refreshTown().catch(() => {});
|
||||||
|
loadMine(false); loadOffers(false);
|
||||||
|
} catch (e) {
|
||||||
|
toast(errText(e), 'error');
|
||||||
|
if (e.code === 'offer_closed') loadMine(false);
|
||||||
|
btn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawMine(into) {
|
||||||
|
const m = S.mine;
|
||||||
|
const chips = ['', 'open', 'accepted', 'completed'].map((s) => h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(m.status === s), onclick: () => { m.status = s; m.loaded = false; drawBody(); loadMine(false); } }, App.t(s ? 'trd.status.' + s : 'trd.status.all')));
|
||||||
|
into.appendChild(h('div', { class: 'soc-subtabs trd-chips' }, chips));
|
||||||
|
if (m.err) into.appendChild(h('p', { class: 'form-error', role: 'alert', text: errText(m.err) }));
|
||||||
|
if (!m.loaded) { into.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
|
||||||
|
if (!m.items.length) { into.appendChild(h('p', { class: 'empty pad', text: App.t('trd.mine.empty') })); return; }
|
||||||
|
into.appendChild(h('ul', { class: 'mil-list trd-list' }, m.items.map(mineRow)));
|
||||||
|
if (m.next) into.appendChild(h('button', { class: 'btn wide', type: 'button', disabled: m.loading, onclick: () => loadMine(true) }, App.t('trd.more')));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ tab: direct transport + links in use
|
||||||
|
function drawSend(into) {
|
||||||
|
if (!hasExchange()) { into.appendChild(needExchange()); return; }
|
||||||
|
const sd = S.send;
|
||||||
|
if (!levelOf(sd.fromId)) sd.fromId = S.levels[0].townId;
|
||||||
|
const own = App.state.towns;
|
||||||
|
const xin = h('input', { type: 'number', inputmode: 'numeric', class: 'mil-num', 'aria-label': 'x', placeholder: 'x', value: String(sd.x) });
|
||||||
|
const yin = h('input', { type: 'number', inputmode: 'numeric', class: 'mil-num', 'aria-label': 'y', placeholder: 'y', value: String(sd.y) });
|
||||||
|
xin.addEventListener('input', () => { sd.x = xin.value; }); yin.addEventListener('input', () => { sd.y = yin.value; });
|
||||||
|
const open = (x, y) => { if (App.openSend) App.openSend({ x, y, fromTownId: sd.fromId, type: 'transport' }); };
|
||||||
|
const lookup = () => { if (xin.value === '' || yin.value === '') return; open(Math.round(Number(xin.value)), Math.round(Number(yin.value))); };
|
||||||
|
into.appendChild(h('section', { class: 'card' },
|
||||||
|
h('div', { class: 'card-head' }, h('h2', null, icon('box'), App.t('trd.send.head'))),
|
||||||
|
h('p', { class: 'detail-desc', text: App.t('trd.send.body', { n: D.TRANSPORT.capacityPerLink }) }),
|
||||||
|
S.levels.length > 1 ? h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
|
||||||
|
sel(S.levels.map((l) => ({ value: l.townId, text: townName(l.townId) })), sd.fromId, (v) => { sd.fromId = Number(v); }, App.t('send.from'))) : h('p', { class: 'row-sub', text: App.t('send.from') + ': ' + townName(sd.fromId) }),
|
||||||
|
h('h3', { class: 'sub', text: App.t('trd.send.own') }),
|
||||||
|
own.filter((t) => t.id !== sd.fromId).length ? h('div', { class: 'chips' }, own.filter((t) => t.id !== sd.fromId).map((t) => h('button', { class: 'chip-btn', type: 'button', onclick: () => open(t.x, t.y) }, t.name))) : h('p', { class: 'row-sub', text: App.t('trd.send.noOwn') }),
|
||||||
|
h('h3', { class: 'sub', text: App.t('trd.send.coords') }),
|
||||||
|
h('div', { class: 'send-coords' }, h('span', { class: 'mono', text: 'x' }), xin, h('span', { class: 'mono', text: 'y' }), yin, h('button', { class: 'btn small primary', type: 'button', onclick: lookup }, icon('locate'), App.t('send.lookup'))),
|
||||||
|
h('p', { class: 'row-sub wrap', text: App.t('trd.send.warn') })));
|
||||||
|
// links in use
|
||||||
|
const wrap = h('section', { class: 'card trd-links' }, h('div', { class: 'card-head' }, h('h2', null, icon('b-' + EXCH), App.t('trd.links.head'))), h('p', { class: 'empty', text: App.t('common.loading') }));
|
||||||
|
into.appendChild(wrap);
|
||||||
|
const my = gen;
|
||||||
|
Promise.all(S.levels.map((l) => townInfo(l.townId, true).catch(() => null))).then((recs) => {
|
||||||
|
if (my !== gen || tab !== 'send' || !wrap.isConnected) return;
|
||||||
|
clear(wrap);
|
||||||
|
wrap.appendChild(h('div', { class: 'card-head' }, h('h2', null, icon('b-' + EXCH), App.t('trd.links.head'))));
|
||||||
|
const rows = h('ul', { class: 'mil-list' });
|
||||||
|
S.levels.forEach((l, i) => {
|
||||||
|
const rec = recs[i]; if (!rec) return;
|
||||||
|
const ls = linkState(rec);
|
||||||
|
const bar = h('span', { class: 'bar', 'aria-hidden': 'true' }, h('i'));
|
||||||
|
bar.firstChild.style.setProperty('--p', String(ls.links ? ls.active / ls.links : 0));
|
||||||
|
rows.appendChild(h('li', { class: 'mil-row' }, h('span', { class: 'row-ic' }, icon('swap')),
|
||||||
|
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: townName(l.townId) })),
|
||||||
|
h('span', { class: 'row-sub wrap', text: App.t('trd.links.used', { a: ls.active, n: ls.links, free: ls.free, cap: num(rec.td.military.transport.capacityPerLink) }) }), bar)));
|
||||||
|
});
|
||||||
|
wrap.appendChild(rows);
|
||||||
|
wrap.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.links.hint') }));
|
||||||
|
const tx = (mil().moves.outgoing || []).filter((m) => m.type === 'transport');
|
||||||
|
if (tx.length) {
|
||||||
|
wrap.appendChild(h('h3', { class: 'sub', text: App.t('trd.links.active') }));
|
||||||
|
wrap.appendChild(h('ul', { class: 'mil-list' }, tx.map((m) => h('li', { class: 'mil-row' }, h('span', { class: 'row-ic' }, icon('box')),
|
||||||
|
h('span', { class: 'row-main' }, h('span', { class: 'row-sub wrap' }, mil().endLink(m.from), h('span', { class: 'arrow', 'aria-hidden': 'true' }, icon('move')), mil().endLink(m.to)), mil().resChips(m.cargo)),
|
||||||
|
h('span', { class: 'mil-when' }, mil().countdown(m.arriveAt))))));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ screen
|
||||||
|
function drawTabs() {
|
||||||
|
clear(tabsEl);
|
||||||
|
for (const k of TABS) {
|
||||||
|
tabsEl.appendChild(h('button', { class: 'seg-btn', type: 'button', dataset: { tab: k }, 'aria-pressed': String(tab === k), onclick: () => setTab(k) }, App.t('trd.tab.' + k)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawBody() {
|
||||||
|
if (!bodyEl) return;
|
||||||
|
const top = box.scrollTop;
|
||||||
|
clear(bodyEl);
|
||||||
|
if (tab === 'offers') drawOffers(bodyEl);
|
||||||
|
else if (tab === 'new') drawNew(bodyEl);
|
||||||
|
else if (tab === 'mine') drawMine(bodyEl);
|
||||||
|
else drawSend(bodyEl);
|
||||||
|
box.scrollTop = top;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTab(k) {
|
||||||
|
if (!TABS.includes(k)) k = 'offers';
|
||||||
|
tab = k; gen++;
|
||||||
|
drawTabs(); drawBody();
|
||||||
|
if (k === 'offers' && !S.offers.loaded) loadOffers(false);
|
||||||
|
if (k === 'mine') loadMine(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
App.registerScreen({
|
||||||
|
id: 'trade', titleKey: 'screen.trade', navKey: 'nav.trade', icon: 'swap', hud: false, navGroup: 'more',
|
||||||
|
render(container) {
|
||||||
|
box = container;
|
||||||
|
tabsEl = h('div', { class: 'seg trd-tabs', role: 'group', 'aria-label': App.t('screen.trade') });
|
||||||
|
bodyEl = h('div', { class: 'trd-body' });
|
||||||
|
box.appendChild(h('div', { class: 'page trd-page' },
|
||||||
|
h('div', { class: 'card-head page-head' }, h('h1', { id: 'trd-h', text: App.t('screen.trade') }),
|
||||||
|
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => reloadAll() }, icon('refresh'))),
|
||||||
|
tabsEl, bodyEl));
|
||||||
|
App.on('session', () => { S.levels = null; S.offers = { items: [], next: null, loaded: false, loading: false, err: null }; S.mine = { items: [], next: null, loaded: false, loading: false, err: null, status: '' }; S.form = null; infos.clear(); });
|
||||||
|
App.on('movements', () => { if (visible && tab === 'send') drawBody(); });
|
||||||
|
App.api.on('push', (msg) => {
|
||||||
|
if (!visible || !msg || msg.type !== 'notification' || !/^trade_/.test(msg.kind || '')) return;
|
||||||
|
infos.clear(); loadMine(false); loadOffers(false);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onShow(params) {
|
||||||
|
visible = true;
|
||||||
|
document.getElementById('trd-h').textContent = App.t('screen.trade');
|
||||||
|
const want = params && params.tab && TABS.includes(params.tab) ? params.tab : tab;
|
||||||
|
S.form = S.form && S.form.townId && !levelOf(S.form.townId) && S.levels ? null : S.form;
|
||||||
|
tab = want; gen++;
|
||||||
|
drawTabs(); drawBody();
|
||||||
|
loadLevels().catch(() => {}).then(() => { if (visible) { drawBody(); } });
|
||||||
|
loadOffers(false); loadMine(false);
|
||||||
|
if (offTick) offTick();
|
||||||
|
let last = 0;
|
||||||
|
offTick = App.onTick((now) => {
|
||||||
|
if (now - last < 4000) return;
|
||||||
|
last = now;
|
||||||
|
const stale = (list) => list.some((o) => o.status === 'open' && o.expiresAt < now - 1500);
|
||||||
|
if ((tab === 'offers' && stale(S.offers.items.map((o) => Object.assign({ status: 'open' }, o)))) && !S.offers.loading) loadOffers(false);
|
||||||
|
if (tab === 'mine' && stale(S.mine.items) && !S.mine.loading) loadMine(false);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onHide() { visible = false; gen++; if (offTick) offTick(); offTick = null; },
|
||||||
|
onLang() { drawTabs(); document.getElementById('trd-h').textContent = App.t('screen.trade'); drawBody(); },
|
||||||
|
});
|
||||||
|
}());
|
||||||
412
public/js/screens/world.js
Normal file
412
public/js/screens/world.js
Normal file
|
|
@ -0,0 +1,412 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* The end game: the Backbone race (More > Backbone) and the read-only state of an ended world.
|
||||||
|
*
|
||||||
|
* Screen: GET /worlds/:id/status -> phase (running | backbone_open | ended), a countdown to the day the 7 landing sites appear, the sites with
|
||||||
|
* holder / node level / build progress, the leading alliance, the winner banner; when the world has ended GET /worlds/:id/results -> final ranking.
|
||||||
|
* Sites your alliance holds open a "manage" sheet (GET /backbone/:id): the stockpile, build the next node level (POST /backbone/:id/build), ship
|
||||||
|
* resources from a POP (POST /backbone/:id/ship, a transport) and the contribution ledger. Other sites: scan or attack through the send dialog.
|
||||||
|
*
|
||||||
|
* Also here (loaded at start-up, whether or not the screen is ever opened): the ended-world mode of the whole client. Once the world has ended
|
||||||
|
* (`/me` says so, the `world_ended` notification arrives, or any command answers `world_ended`) the page gets `data-ended`, a pill in the top bar,
|
||||||
|
* a card on the POP screen, and every action button (primary / danger buttons, `[data-act]`) is disabled with an explanation. Reading, messages and
|
||||||
|
* navigation keep working; the server refuses everything else with `world_ended` anyway, so this only makes that graceful.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
const { h, clear, icon, toast, openSheet } = UI;
|
||||||
|
const R = UpstreamRules;
|
||||||
|
const D = UpstreamData;
|
||||||
|
const E = UpstreamEnd;
|
||||||
|
const mil = () => App.mil;
|
||||||
|
const num = (n) => App.fmt.num(n);
|
||||||
|
const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
|
||||||
|
const worldId = () => (App.state.world ? App.state.world.id : 0);
|
||||||
|
const myAllianceId = () => (App.state.operator ? App.state.operator.allianceId : null);
|
||||||
|
const speed = () => (App.state.world ? App.state.world.speed : 1);
|
||||||
|
|
||||||
|
// ================================================================== ended-world mode (whole client)
|
||||||
|
let lockObserver = null, lockQueued = false;
|
||||||
|
const LOCK_SEL = 'button.btn.primary, button.btn.danger, button[data-act]';
|
||||||
|
const LOCK_SKIP = '.screen-auth, .screen-settings, .screen-messages, .screen-rankings, .soc-composer, .boot, [data-keep]';
|
||||||
|
|
||||||
|
function lockButtons() {
|
||||||
|
lockQueued = false;
|
||||||
|
if (!App.worldEnded()) return;
|
||||||
|
const msg = App.t('ended.locked');
|
||||||
|
for (const b of document.querySelectorAll(LOCK_SEL)) {
|
||||||
|
if (b.disabled || b.closest(LOCK_SKIP) || b.hasAttribute('data-keep')) continue;
|
||||||
|
b.disabled = true; b.dataset.endedLock = '1'; b.title = msg;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function unlockButtons() {
|
||||||
|
for (const b of document.querySelectorAll('[data-ended-lock]')) { b.disabled = false; delete b.dataset.endedLock; b.removeAttribute('title'); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyEnded() {
|
||||||
|
const on = App.worldEnded() && !!App.state.user;
|
||||||
|
document.documentElement.toggleAttribute('data-ended', on);
|
||||||
|
const pill = document.getElementById('world-pill');
|
||||||
|
if (pill) { pill.hidden = !on; pill.textContent = App.t('ended.pill'); pill.title = App.t('ended.body'); }
|
||||||
|
if (on && !lockObserver) {
|
||||||
|
lockObserver = new MutationObserver(() => { if (!lockQueued) { lockQueued = true; requestAnimationFrame(lockButtons); } });
|
||||||
|
lockObserver.observe(document.body, { childList: true, subtree: true });
|
||||||
|
} else if (!on && lockObserver) { lockObserver.disconnect(); lockObserver = null; unlockButtons(); }
|
||||||
|
if (on) lockButtons();
|
||||||
|
for (const el of document.querySelectorAll('.wld-ended-card')) fillEndedCard(el);
|
||||||
|
}
|
||||||
|
|
||||||
|
App.worldEnded = () => !!(App.state.world && App.state.world.status === 'ended');
|
||||||
|
// Something told us the world has ended (a refused command, the notification, the status fetch).
|
||||||
|
App.markWorldEnded = () => {
|
||||||
|
if (!App.state.world) return;
|
||||||
|
const was = App.worldEnded();
|
||||||
|
App.state.world.status = 'ended';
|
||||||
|
applyEnded();
|
||||||
|
if (!was) App.emit('worldended', App.state.world);
|
||||||
|
};
|
||||||
|
App.checkWorld = () => applyEnded();
|
||||||
|
App.on('session', () => applyEnded());
|
||||||
|
App.on('lang', () => applyEnded());
|
||||||
|
App.on('towns', () => applyEnded());
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
const pill = document.getElementById('world-pill');
|
||||||
|
if (pill) pill.addEventListener('click', () => App.go('world'));
|
||||||
|
});
|
||||||
|
|
||||||
|
function fillEndedCard(el) {
|
||||||
|
clear(el);
|
||||||
|
el.hidden = !App.worldEnded();
|
||||||
|
if (el.hidden) return;
|
||||||
|
el.appendChild(h('div', { class: 'row-ic' }, icon('trophy')));
|
||||||
|
el.appendChild(h('div', { class: 'row-main' }, h('b', { text: App.t('ended.title') }), h('span', { class: 'row-sub wrap', text: App.t('ended.body') })));
|
||||||
|
el.appendChild(h('button', { class: 'btn small', type: 'button', 'data-keep': '', onclick: () => App.go('world') }, App.t('ended.see')));
|
||||||
|
}
|
||||||
|
App.popSections.push({
|
||||||
|
slot: 'top',
|
||||||
|
render() { const el = h('section', { class: 'card wld-ended-card', role: 'status' }); fillEndedCard(el); return el; },
|
||||||
|
});
|
||||||
|
|
||||||
|
// ================================================================== the screen
|
||||||
|
let box, bodyEl, visible = false, offTick = null, gen = 0, focusSite = null;
|
||||||
|
const W = { status: null, results: null, err: null, loading: false, at: 0, rankTab: 'operators', rankN: 20, resErr: null };
|
||||||
|
|
||||||
|
const siteTitle = (s) => App.t('wld.site', { n: s.index + 1 });
|
||||||
|
const tagPill = (hd) => h('span', { class: 'pill wld-holder', title: hd.name }, '[' + hd.tag + '] ' + hd.name);
|
||||||
|
const kv = (k, v) => h('div', { class: 'kv' }, h('span', { class: 'k', text: k }), h('span', { class: 'v' }, v));
|
||||||
|
const costChips = (cost, pool) => h('div', { class: 'costs' }, D.RESOURCES.map((r) => {
|
||||||
|
const short = pool && (pool[r] || 0) < (cost[r] || 0);
|
||||||
|
return h('span', { class: 'cost ' + r + (short ? ' short' : '') }, icon(r), h('b', { text: num(cost[r] || 0) }));
|
||||||
|
}));
|
||||||
|
const bar = (p, cls) => { const i = h('i'); i.style.setProperty('--p', String(Math.max(0, Math.min(1, p)))); return h('span', { class: 'bar wld-bar ' + (cls || ''), 'aria-hidden': 'true' }, i); };
|
||||||
|
const cd = (ms) => h('b', { class: 'mono wld-cd', dataset: { until: String(ms) }, text: App.fmt.dur(ms - App.now(), 3) });
|
||||||
|
|
||||||
|
async function loadStatus() {
|
||||||
|
if (W.loading || !worldId()) return;
|
||||||
|
W.loading = true;
|
||||||
|
const my = gen;
|
||||||
|
try {
|
||||||
|
const st = await App.api.get('/worlds/' + worldId() + '/status');
|
||||||
|
W.status = st; W.err = null; W.at = Date.now();
|
||||||
|
if (st.phase === 'ended' || st.status === 'ended') {
|
||||||
|
App.markWorldEnded();
|
||||||
|
try { const r = await App.api.get('/worlds/' + worldId() + '/results'); W.results = r.available ? r : null; W.resErr = null; } catch (e) { W.resErr = e; }
|
||||||
|
}
|
||||||
|
} catch (e) { W.err = e; } finally {
|
||||||
|
W.loading = false;
|
||||||
|
if (my === gen && visible) draw();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function phaseCard() {
|
||||||
|
const st = W.status;
|
||||||
|
const now = App.now();
|
||||||
|
const phase = E.phaseNow(st, now);
|
||||||
|
const lead = E.leading(st.sites);
|
||||||
|
if (phase === 'ended') {
|
||||||
|
const w = st.winner;
|
||||||
|
return h('section', { class: 'card wld-banner ended' },
|
||||||
|
h('div', { class: 'wld-trophy' }, icon('trophy')),
|
||||||
|
h('div', { class: 'row-main' },
|
||||||
|
h('h2', { text: w && w.name ? App.t('wld.won', { name: w.name }) : App.t('wld.endedNoWinner') }),
|
||||||
|
w && w.tag ? h('p', { class: 'row-sub wrap', text: '[' + w.tag + ']' + (w.wonAt ? ' · ' + App.t('wld.wonAt', { t: mil().dayTime(w.wonAt) }) : '') }) : null,
|
||||||
|
h('p', { class: 'row-sub wrap', text: App.t('wld.endedAt', { t: st.endedAt ? mil().dayTime(st.endedAt) : '' }) + ' ' + App.t('ended.body') })));
|
||||||
|
}
|
||||||
|
if (st.winner) {
|
||||||
|
return h('section', { class: 'card wld-banner won' },
|
||||||
|
h('div', { class: 'wld-trophy' }, icon('trophy')),
|
||||||
|
h('div', { class: 'row-main' },
|
||||||
|
h('h2', { text: App.t('wld.won', { name: st.winner.name }) }),
|
||||||
|
h('p', { class: 'row-sub wrap' }, App.t('wld.endsIn') + ' ', st.endsAt ? cd(st.endsAt) : null),
|
||||||
|
h('p', { class: 'row-sub wrap', text: App.t('wld.winnerKeep') })));
|
||||||
|
}
|
||||||
|
if (phase === 'backbone_open') {
|
||||||
|
return h('section', { class: 'card wld-banner open' },
|
||||||
|
h('div', { class: 'wld-trophy' }, icon('b-backbone_node')),
|
||||||
|
h('div', { class: 'row-main' },
|
||||||
|
h('h2', { text: App.t('wld.open') }),
|
||||||
|
lead ? h('p', { class: 'row-sub wrap', text: App.t('wld.leading', { tag: lead.tag, name: lead.name, n: lead.siteIndex + 1, level: lead.level, max: D.ENDGAME.maxLevel }) })
|
||||||
|
: h('p', { class: 'row-sub wrap', text: App.t('wld.noLeader') }),
|
||||||
|
h('p', { class: 'row-sub wrap', text: App.t('wld.goal', { max: D.ENDGAME.maxLevel }) })));
|
||||||
|
}
|
||||||
|
return h('section', { class: 'card wld-banner' },
|
||||||
|
h('div', { class: 'wld-trophy' }, icon('b-backbone_node')),
|
||||||
|
h('div', { class: 'row-main' },
|
||||||
|
h('h2', { text: App.t('wld.opensIn') }),
|
||||||
|
h('p', { class: 'wld-count' }, cd(st.opensAt)),
|
||||||
|
bar(E.openProgress(st)),
|
||||||
|
h('p', { class: 'row-sub wrap', text: App.t('wld.day', { day: App.fmt.dec(st.ageDays), open: st.openDay }) })));
|
||||||
|
}
|
||||||
|
|
||||||
|
function howCard() {
|
||||||
|
return h('section', { class: 'card' },
|
||||||
|
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('wld.how.head'))),
|
||||||
|
h('ol', { class: 'wld-how' },
|
||||||
|
h('li', { text: App.t('wld.how.1', { n: D.ENDGAME.sites, day: D.ENDGAME.openDay }) }),
|
||||||
|
h('li', { text: App.t('wld.how.2') }),
|
||||||
|
h('li', { text: App.t('wld.how.3', { max: D.ENDGAME.maxLevel }) }),
|
||||||
|
h('li', { text: App.t('wld.how.4', { d: D.ENDGAME.graceDays }) })));
|
||||||
|
}
|
||||||
|
|
||||||
|
function siteCard(s) {
|
||||||
|
const kind = E.holderKind(s, myAllianceId());
|
||||||
|
const ended = App.worldEnded();
|
||||||
|
const now = App.now();
|
||||||
|
const prog = E.buildProgress(s, now);
|
||||||
|
const kids = [
|
||||||
|
h('div', { class: 'wld-site-head' },
|
||||||
|
h('span', { class: 'row-ic' }, icon(kind === 'mine' ? 'flag' : 'b-backbone_node')),
|
||||||
|
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: siteTitle(s) }), mil().coordLink(s.x, s.y)),
|
||||||
|
h('span', { class: 'row-sub wrap' }, s.holder ? [tagPill(s.holder), kind === 'mine' ? h('span', { class: 'pill accent', text: App.t('wld.yours') }) : null] : h('span', { class: 'pill dim', text: App.t('wld.incumbent') }),
|
||||||
|
s.takenBy ? h('span', { text: ' ' + App.t('wld.takenBy', { name: s.takenBy.name }) }) : null))),
|
||||||
|
h('div', { class: 'wld-level' }, h('b', { class: 'mono', text: App.t('wld.level', { n: s.level, max: s.maxLevel }) }), bar(s.progress, kind)),
|
||||||
|
];
|
||||||
|
if (s.build && !ended) { // a running build is frozen when the world ends: do not show a countdown that never finishes
|
||||||
|
const b = bar(prog || 0, 'build'); b.dataset.build = String(s.index);
|
||||||
|
kids.push(h('div', { class: 'wld-building' }, h('span', { class: 'row-sub wrap' }, App.t('wld.building', { n: s.build.toLevel }) + ' ', cd(s.build.dueAt)), b));
|
||||||
|
}
|
||||||
|
if (s.holder && s.id) kids.push(h('div', { class: 'row-sub wrap' }, App.t('wld.stock') + ' ', mil().resChips(s.pool)));
|
||||||
|
const acts = [];
|
||||||
|
if (kind === 'mine' && s.id) acts.push(h('button', { class: 'btn small primary', type: 'button', disabled: ended, onclick: () => openManage(s) }, icon('up'), App.t('wld.manage')));
|
||||||
|
if (kind !== 'mine' && App.openSend && App.state.towns.length) acts.push(h('button', { class: 'btn small primary', type: 'button', disabled: ended, onclick: () => App.openSend({ x: s.x, y: s.y }) }, icon('target'), App.t('wld.attack')));
|
||||||
|
acts.push(h('button', { class: 'btn small', type: 'button', onclick: () => App.go('map', { x: s.x, y: s.y, zoom: 40 }) }, icon('map'), App.t('wld.onMap')));
|
||||||
|
kids.push(h('div', { class: 'wld-acts' }, acts));
|
||||||
|
return h('li', { class: 'card wld-site ' + kind, dataset: { index: String(s.index) } }, kids);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resultsCard() {
|
||||||
|
const r = W.results;
|
||||||
|
if (W.resErr) return h('p', { class: 'form-error', role: 'alert', text: App.errMsg(W.resErr) });
|
||||||
|
if (!r || !r.results) return null;
|
||||||
|
const res = r.results;
|
||||||
|
const tabs = ['operators', 'alliances', 'attackers', 'defenders'];
|
||||||
|
const list = res[W.rankTab] || [];
|
||||||
|
const me = App.state.operator ? App.state.operator.id : 0;
|
||||||
|
const row = (x) => {
|
||||||
|
let name, sub, val;
|
||||||
|
if (W.rankTab === 'alliances') { name = x.name; sub = '[' + x.tag + '] ' + App.t('soc.rank.members', { n: x.members }) + ' · ' + App.t('soc.rank.pops', { n: x.towns }); val = App.fmt.dec(x.footprint); }
|
||||||
|
else if (W.rankTab === 'operators') { name = x.name; sub = (x.allianceTag ? '[' + x.allianceTag + '] ' : '') + App.t('soc.rank.pops', { n: x.towns }); val = App.fmt.dec(x.footprint); }
|
||||||
|
else { name = x.name; sub = x.allianceTag ? '[' + x.allianceTag + ']' : ''; val = num(W.rankTab === 'attackers' ? x.attackPoints : x.defensePoints); }
|
||||||
|
const you = (W.rankTab !== 'alliances' && x.operatorId === me) || (W.rankTab === 'alliances' && x.allianceId === myAllianceId());
|
||||||
|
const win = W.rankTab === 'alliances' && r.winner && x.allianceId === r.winner.allianceId;
|
||||||
|
return h('li', { class: 'wld-rank' + (you ? ' you' : '') + (win ? ' win' : '') },
|
||||||
|
h('span', { class: 'soc-rk mono', text: '#' + x.rank }),
|
||||||
|
h('span', { class: 'row-main' }, h('b', { text: name }), sub ? h('span', { class: 'row-sub', text: sub }) : null),
|
||||||
|
win ? icon('trophy') : null,
|
||||||
|
h('b', { class: 'mono', text: val }));
|
||||||
|
};
|
||||||
|
const shown = E.topRows(list, W.rankN);
|
||||||
|
return h('section', { class: 'card wld-results' },
|
||||||
|
h('div', { class: 'card-head' }, h('h2', null, icon('trophy'), App.t('wld.results'))),
|
||||||
|
h('div', { class: 'soc-subtabs' }, tabs.map((k) => h('button', { class: 'chip-btn', type: 'button', 'data-keep': '', 'aria-pressed': String(W.rankTab === k), onclick: () => { W.rankTab = k; W.rankN = 20; draw(); } }, App.t('wld.rank.' + k)))),
|
||||||
|
shown.length ? h('ul', { class: 'wld-ranks' }, shown.map(row)) : h('p', { class: 'empty', text: App.t('wld.rank.empty') }),
|
||||||
|
list.length > shown.length ? h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { W.rankN += 20; draw(); } }, App.t('trd.more')) : null,
|
||||||
|
res.totals ? h('p', { class: 'row-sub', text: App.t('wld.rank.totals', { o: res.totals.operators, a: res.totals.alliances }) }) : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
if (!bodyEl) return;
|
||||||
|
const top = box.scrollTop;
|
||||||
|
clear(bodyEl);
|
||||||
|
if (W.err && !W.status) {
|
||||||
|
bodyEl.appendChild(h('div', { class: 'soc-err' }, h('p', { class: 'form-error', role: 'alert', text: App.errMsg(W.err) }), h('button', { class: 'btn small', type: 'button', onclick: () => loadStatus() }, icon('refresh'), App.t('common.retry'))));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!W.status) { bodyEl.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
|
||||||
|
const st = W.status;
|
||||||
|
bodyEl.appendChild(phaseCard());
|
||||||
|
const phase = E.phaseNow(st, App.now());
|
||||||
|
if (phase === 'running') bodyEl.appendChild(howCard());
|
||||||
|
if (st.sites.length) {
|
||||||
|
bodyEl.appendChild(h('h3', { class: 'sub wld-sub', text: App.t('wld.sites') }));
|
||||||
|
bodyEl.appendChild(h('ul', { class: 'wld-sites' }, st.sites.map(siteCard)));
|
||||||
|
} else if (phase === 'backbone_open') {
|
||||||
|
bodyEl.appendChild(h('p', { class: 'empty', text: App.t('wld.noSites') }));
|
||||||
|
}
|
||||||
|
if (phase === 'ended') { const rc = resultsCard(); if (rc) bodyEl.appendChild(rc); }
|
||||||
|
box.scrollTop = top;
|
||||||
|
if (focusSite !== null) {
|
||||||
|
const el = bodyEl.querySelector('[data-index="' + focusSite + '"]');
|
||||||
|
focusSite = null;
|
||||||
|
if (el) { el.scrollIntoView({ block: 'center' }); el.classList.add('flash'); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the manage sheet of a site your alliance holds
|
||||||
|
async function openManage(site0) {
|
||||||
|
const body = h('div', { class: 'detail wld-manage' }, h('p', { class: 'empty', text: App.t('common.loading') }));
|
||||||
|
const sheet = openSheet({ title: siteTitle(site0), icon: 'b-backbone_node', closeLabel: App.t('common.close'), body });
|
||||||
|
let data = null, pops = null;
|
||||||
|
const sh = { fromId: 0, cargo: {}, nonce: nonce() };
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
const [d, p] = await Promise.all([
|
||||||
|
App.api.get('/backbone/' + site0.id),
|
||||||
|
pops ? Promise.resolve(pops) : Promise.all(App.state.towns.map((t) => mil().loadTown(t.id).then((x) => ({ id: t.id, name: t.name, x: t.x, y: t.y, td: x.town, rt: App.rulesTownFrom(x.town, x.serverTime) })).catch(() => null))),
|
||||||
|
]);
|
||||||
|
data = d; pops = p.filter(Boolean);
|
||||||
|
if (!pops.some((q) => q.id === sh.fromId)) { sh.fromId = (pops.find((q) => q.td.military.transport.links > 0) || pops[0] || { id: 0 }).id; sh.cargo = {}; }
|
||||||
|
drawManage();
|
||||||
|
} catch (e) {
|
||||||
|
clear(body);
|
||||||
|
body.appendChild(h('p', { class: 'form-error', role: 'alert', text: App.errMsg(e) }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function drawManage() {
|
||||||
|
clear(body);
|
||||||
|
const s = data.site, you = data.you;
|
||||||
|
sheet.setTitle(siteTitle(s));
|
||||||
|
if (!you.holder) { body.appendChild(h('p', { class: 'reason', text: App.t('wld.lost') })); }
|
||||||
|
body.appendChild(h('div', null, kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: s.level, max: s.maxLevel }) }))));
|
||||||
|
body.appendChild(bar(s.progress, 'mine'));
|
||||||
|
body.appendChild(h('div', null,
|
||||||
|
kv(App.t('wld.stock'), mil().resChips(s.pool)),
|
||||||
|
kv(App.t('wld.coords'), mil().coordLink(s.x, s.y))));
|
||||||
|
|
||||||
|
// ---- build the next node level
|
||||||
|
const chk = E.buildCheck(s, you, App.worldEnded());
|
||||||
|
const buildErr = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
const sec = h('section', { class: 'wld-sec' }, h('h3', { class: 'sub', text: App.t('wld.build.head') }));
|
||||||
|
if (s.build) sec.appendChild(h('div', { class: 'detail-queue' }, h('b', { text: App.t('wld.building', { n: s.build.toLevel }) }), h('span', null, cd(s.build.dueAt)), bar(E.buildProgress(s, App.now()) || 0, 'build')));
|
||||||
|
if (s.next && !s.build) {
|
||||||
|
sec.appendChild(h('p', { class: 'row-sub wrap', text: App.t('wld.build.next', { n: s.next.toLevel, t: App.fmt.dur(s.next.durationMs) }) }));
|
||||||
|
sec.appendChild(costChips(s.next.cost, s.pool));
|
||||||
|
const lack = E.missing(s.next.cost, s.pool);
|
||||||
|
if (Object.keys(lack).length) sec.appendChild(h('p', { class: 'reason', text: App.t('wld.build.lack', { what: D.RESOURCES.filter((r) => lack[r]).map((r) => num(lack[r]) + ' ' + App.resName(r)).join(', ') }) }));
|
||||||
|
} else if (!s.next) sec.appendChild(h('p', { class: 'good', text: App.t('wld.build.max') }));
|
||||||
|
const btn = h('button', { class: 'btn primary wide', type: 'button', disabled: !chk.ok, onclick: async () => {
|
||||||
|
btn.disabled = true; buildErr.hidden = true;
|
||||||
|
try {
|
||||||
|
const r = await App.api.post('/backbone/' + s.id + '/build', {}, { intent: 'bb-build:' + s.id + ':' + (s.next ? s.next.toLevel : 0) });
|
||||||
|
toast(App.t('wld.build.started', { n: r.toLevel, t: App.fmt.dur(r.dueAt - App.now()) }), 'ok');
|
||||||
|
await Promise.all([load(), loadStatus()]);
|
||||||
|
} catch (e) { buildErr.textContent = App.errMsg(e); buildErr.hidden = false; btn.disabled = false; load(); }
|
||||||
|
} }, icon('up'), s.next ? App.t('wld.build.go', { n: s.build ? s.build.toLevel : s.next.toLevel }) : App.t('wld.build.max'));
|
||||||
|
sec.appendChild(buildErr);
|
||||||
|
if (chk.reason && chk.reason !== 'not_enough_resources' && chk.reason !== 'max_level' && chk.reason !== 'already_queued') sec.appendChild(h('p', { class: 'reason', text: App.t('wld.build.why.' + chk.reason) }));
|
||||||
|
sec.appendChild(btn);
|
||||||
|
body.appendChild(sec);
|
||||||
|
|
||||||
|
// ---- ship resources
|
||||||
|
const ship = h('section', { class: 'wld-sec' }, h('h3', { class: 'sub', text: App.t('wld.ship.head') }));
|
||||||
|
const cur = pops.find((q) => q.id === sh.fromId);
|
||||||
|
if (!you.canShip) ship.appendChild(h('p', { class: 'reason', text: App.t('wld.ship.no') }));
|
||||||
|
else if (!cur) ship.appendChild(h('p', { class: 'empty', text: App.t('pop.noTown') }));
|
||||||
|
else {
|
||||||
|
const tr = cur.td.military.transport, free = Math.max(0, tr.links - tr.active), cap = tr.capacityPerLink;
|
||||||
|
const prev = h('div', { class: 'send-preview' });
|
||||||
|
const shipErr = h('p', { class: 'form-error', role: 'alert', hidden: true });
|
||||||
|
const go = h('button', { class: 'btn primary wide', type: 'button' }, icon('box'), App.t('wld.ship.go'));
|
||||||
|
const refresh = () => {
|
||||||
|
const total = CargoUI.cargoTotal(sh.cargo);
|
||||||
|
clear(prev);
|
||||||
|
const dist = R.distance(cur.x, cur.y, s.x, s.y);
|
||||||
|
prev.appendChild(kv(App.t('wld.ship.cargo'), h('b', { class: 'mono' + (total > cap ? ' bad' : ''), text: num(total) + ' / ' + num(cap) })));
|
||||||
|
prev.appendChild(kv(App.t('send.distance'), h('span', { class: 'mono', text: App.fmt.dec(dist) + ' ' + App.t('common.tiles') })));
|
||||||
|
prev.appendChild(kv(App.t('send.latency'), h('span', { class: 'mono', text: App.fmt.dur(R.transportMs(dist, speed())) })));
|
||||||
|
prev.appendChild(kv(App.t('trd.links.head'), h('span', { class: 'mono', text: free + ' / ' + tr.links })));
|
||||||
|
go.disabled = total < 1 || total > cap || !free;
|
||||||
|
};
|
||||||
|
if (pops.length > 1) ship.appendChild(h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
|
||||||
|
h('select', { onchange: (e) => { sh.fromId = Number(e.target.value); sh.cargo = {}; drawManage(); } }, pops.map((q) => h('option', { value: q.id, selected: q.id === sh.fromId, text: q.name })))));
|
||||||
|
ship.appendChild(h('p', { class: 'row-sub wrap', text: App.t('wld.ship.hint', { n: num(cap) }) }));
|
||||||
|
if (!tr.links) ship.appendChild(h('p', { class: 'reason', text: App.t('err.no_transport_link') }));
|
||||||
|
const have = R.resourcesAt(cur.rt, App.now()).amounts;
|
||||||
|
for (const row of CargoUI.cargoPickers(sh.cargo, have, refresh)) ship.appendChild(row);
|
||||||
|
ship.appendChild(prev); ship.appendChild(shipErr); ship.appendChild(go);
|
||||||
|
go.addEventListener('click', async () => {
|
||||||
|
go.disabled = true; shipErr.hidden = true;
|
||||||
|
try {
|
||||||
|
await App.api.post('/backbone/' + s.id + '/ship', { fromTownId: sh.fromId, cargo: Object.assign({}, sh.cargo) }, { intent: 'bb-ship:' + sh.nonce });
|
||||||
|
sh.nonce = nonce(); sh.cargo = {}; pops = null;
|
||||||
|
toast(App.t('wld.ship.done'), 'ok');
|
||||||
|
App.refreshTown().catch(() => {}); App.refreshMovements().catch(() => {});
|
||||||
|
await load();
|
||||||
|
} catch (e) { shipErr.textContent = App.errMsg(e); shipErr.hidden = false; if (e.code !== 'network_error') sh.nonce = nonce(); refresh(); }
|
||||||
|
});
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
body.appendChild(ship);
|
||||||
|
|
||||||
|
// ---- ledger
|
||||||
|
const ledger = (data.contributions || []).filter((c) => c.fiber || c.hardware || c.capital);
|
||||||
|
if (ledger.length) {
|
||||||
|
body.appendChild(h('section', { class: 'wld-sec' }, h('h3', { class: 'sub', text: App.t('wld.ledger') }),
|
||||||
|
h('ul', { class: 'mil-list' }, ledger.slice(0, 15).map((c) => h('li', { class: 'mil-row' },
|
||||||
|
h('span', { class: 'row-main' }, h('b', { text: c.name }), mil().resChips({ fiber: c.fiber, hardware: c.hardware, capital: c.capital }))))),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- ticks: countdown texts, build bars, phase flips
|
||||||
|
function tick(now) {
|
||||||
|
if (!box) return;
|
||||||
|
for (const el of bodyEl.querySelectorAll('.wld-cd')) {
|
||||||
|
const s = App.fmt.dur(Number(el.dataset.until) - now, 3);
|
||||||
|
if (el.textContent !== s) el.textContent = s;
|
||||||
|
}
|
||||||
|
for (const el of bodyEl.querySelectorAll('[data-build]')) {
|
||||||
|
const site = W.status && W.status.sites.find((x) => String(x.index) === el.dataset.build);
|
||||||
|
const p = site ? E.buildProgress(site, now) : null;
|
||||||
|
if (p !== null) el.firstChild.style.setProperty('--p', String(p));
|
||||||
|
}
|
||||||
|
if (W.status && !W.loading) {
|
||||||
|
const flip = W.status.phase === 'running' && now >= W.status.opensAt + 800;
|
||||||
|
const due = W.status.sites.some((s) => s.build && s.build.dueAt < now - 1500) || (W.status.winner && W.status.endsAt && W.status.phase !== 'ended' && now > W.status.endsAt + 1500);
|
||||||
|
if ((flip || due) && Date.now() - W.at > 4000) loadStatus();
|
||||||
|
else if (Date.now() - W.at > 60000) loadStatus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
App.registerScreen({
|
||||||
|
id: 'world', titleKey: 'screen.world', navKey: 'nav.world', icon: 'b-backbone_node', hud: false, navGroup: 'more',
|
||||||
|
render(container) {
|
||||||
|
box = container;
|
||||||
|
bodyEl = h('div', { class: 'wld-body' });
|
||||||
|
box.appendChild(h('div', { class: 'page wld-page' },
|
||||||
|
h('div', { class: 'card-head page-head' }, h('h1', { id: 'wld-h', text: App.t('screen.world') }),
|
||||||
|
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), 'data-keep': '', onclick: () => loadStatus() }, icon('refresh'))),
|
||||||
|
bodyEl));
|
||||||
|
App.on('session', () => { W.status = null; W.results = null; W.err = null; });
|
||||||
|
App.api.on('push', (msg) => {
|
||||||
|
if (!msg || msg.type !== 'notification' || !App.state.user) return;
|
||||||
|
if (msg.kind === 'world_ended') { App.markWorldEnded(); App.refreshTowns().catch(() => {}); }
|
||||||
|
if (/^(backbone_|world_ended)/.test(msg.kind || '')) { if (visible) loadStatus(); else W.at = 0; }
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onShow(params) {
|
||||||
|
visible = true; gen++;
|
||||||
|
document.getElementById('wld-h').textContent = App.t('screen.world');
|
||||||
|
if (params && Number.isInteger(params.site)) focusSite = params.site;
|
||||||
|
draw();
|
||||||
|
loadStatus();
|
||||||
|
if (offTick) offTick();
|
||||||
|
offTick = App.onTick(tick);
|
||||||
|
},
|
||||||
|
onHide() { visible = false; gen++; if (offTick) offTick(); offTick = null; },
|
||||||
|
onLang() { document.getElementById('wld-h').textContent = App.t('screen.world'); draw(); },
|
||||||
|
});
|
||||||
|
}());
|
||||||
82
public/js/strings/alerts.js
Normal file
82
public/js/strings/alerts.js
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
'use strict';
|
||||||
|
/* Strings of the Alerts feed for the notification types of trade, the end game, alliances, diplomacy and messages (js/alertkinds.js), en + nb. */
|
||||||
|
(function (root, factory) {
|
||||||
|
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
|
||||||
|
else factory(root.UpstreamI18n);
|
||||||
|
}(typeof self !== 'undefined' ? self : this, function (I) {
|
||||||
|
I.extend({
|
||||||
|
en: {
|
||||||
|
'alerts.level': 'level {n}', 'alerts.at': 'at {x}, {y}',
|
||||||
|
// trade
|
||||||
|
'alerts.trade_accepted': 'Your offer was taken: {give} for {want}',
|
||||||
|
'alerts.trade_completed': 'Trade settled: {give} for {want}',
|
||||||
|
'alerts.trade_expired': 'An offer of yours expired',
|
||||||
|
'alerts.trade_expired.back': '{what} is back in {town}',
|
||||||
|
'alerts.trade_void': 'An offer was voided: the POP changed hands',
|
||||||
|
// end game
|
||||||
|
'alerts.backbone_open': 'The backbone landing sites are open',
|
||||||
|
'alerts.backbone_open.n': '{n} landing sites are up for grabs. Scan one, then take it.',
|
||||||
|
'alerts.backbone_taken': 'Your alliance took landing site {n}',
|
||||||
|
'alerts.backbone_taken.from': 'from {tag}', 'alerts.backbone_taken.incumbent': 'from the incumbent',
|
||||||
|
'alerts.backbone_lost': 'Landing site {n} was taken by {tag}',
|
||||||
|
'alerts.backbone_level': 'Backbone node on site {n} reached level {level}',
|
||||||
|
'alerts.backbone_delivered': 'Your shipment reached the landing site',
|
||||||
|
'alerts.backbone_ship_bounced': 'A shipment was turned back: the site changed hands',
|
||||||
|
'alerts.backbone_won': '{name} completed the Backbone',
|
||||||
|
'alerts.backbone_won.ends': 'The world ends {time}',
|
||||||
|
'alerts.world_ended': 'The world has ended',
|
||||||
|
'alerts.world_ended.winner': 'Winner: {name}', 'alerts.world_ended.nowinner': 'It can still be read, nothing can be changed.',
|
||||||
|
// alliance
|
||||||
|
'alerts.alliance_invite': 'You were invited to {name}', 'alerts.alliance_invite.by': 'by {name}',
|
||||||
|
'alerts.alliance_invite_declined': '{name} declined your invitation',
|
||||||
|
'alerts.alliance_member_joined': '{name} joined the alliance',
|
||||||
|
'alerts.alliance_member_left': '{name} left the alliance', 'alerts.alliance_member_kicked': '{name} was removed from the alliance',
|
||||||
|
'alerts.alliance_kicked': 'You were removed from {name}',
|
||||||
|
'alerts.alliance_role': 'Your role is now {role}', 'alerts.alliance_role.was': 'was {role}',
|
||||||
|
'alerts.alliance_leader': '{name} is the new leader', 'alerts.alliance_leader.from': 'handed over by {name}',
|
||||||
|
'alerts.alliance_disbanded': '{name} was disbanded',
|
||||||
|
// diplomacy
|
||||||
|
'alerts.diplomacy_proposal': '{tag} proposes: {state}', 'alerts.diplomacy_proposal.until': 'answer by {time}',
|
||||||
|
'alerts.diplomacy_declined': '{tag} declined: {state}',
|
||||||
|
'alerts.diplomacy_changed': 'Relation with {tag} is now {to}', 'alerts.diplomacy_changed.was': 'was {state}', 'alerts.diplomacy_changed.disbanded': 'their alliance was disbanded',
|
||||||
|
'alerts.diplomacy_cancel_pending': 'The {state} with {tag} is ending', 'alerts.diplomacy_cancel_pending.at': 'effective {time}',
|
||||||
|
'alerts.diplomacy_cancel_revoked': 'Ending the {state} with {tag} was called off',
|
||||||
|
// messages
|
||||||
|
'alerts.message': 'Message from {name}', 'alerts.alliance_message': 'Alliance message from {name}',
|
||||||
|
},
|
||||||
|
nb: {
|
||||||
|
'alerts.level': 'nivå {n}', 'alerts.at': 'ved {x}, {y}',
|
||||||
|
'alerts.trade_accepted': 'Tilbudet ditt ble tatt: {give} for {want}',
|
||||||
|
'alerts.trade_completed': 'Handel gjennomført: {give} for {want}',
|
||||||
|
'alerts.trade_expired': 'Et tilbud fra deg gikk ut',
|
||||||
|
'alerts.trade_expired.back': '{what} er tilbake i {town}',
|
||||||
|
'alerts.trade_void': 'Et tilbud ble ugyldig: POP-en skiftet eier',
|
||||||
|
'alerts.backbone_open': 'Ryggradens landingspunkter er åpne',
|
||||||
|
'alerts.backbone_open.n': '{n} landingspunkter kan tas. Skann ett, og ta det.',
|
||||||
|
'alerts.backbone_taken': 'Alliansen din tok landingspunkt {n}',
|
||||||
|
'alerts.backbone_taken.from': 'fra {tag}', 'alerts.backbone_taken.incumbent': 'fra inkumbenten',
|
||||||
|
'alerts.backbone_lost': 'Landingspunkt {n} ble tatt av {tag}',
|
||||||
|
'alerts.backbone_level': 'Ryggradsnoden på punkt {n} nådde nivå {level}',
|
||||||
|
'alerts.backbone_delivered': 'Forsendelsen din nådde landingspunktet',
|
||||||
|
'alerts.backbone_ship_bounced': 'En forsendelse ble snudd: punktet skiftet eier',
|
||||||
|
'alerts.backbone_won': '{name} fullførte Ryggraden',
|
||||||
|
'alerts.backbone_won.ends': 'Verdenen slutter {time}',
|
||||||
|
'alerts.world_ended': 'Verdenen er slutt',
|
||||||
|
'alerts.world_ended.winner': 'Vinner: {name}', 'alerts.world_ended.nowinner': 'Den kan fortsatt leses, men ingenting kan endres.',
|
||||||
|
'alerts.alliance_invite': 'Du ble invitert til {name}', 'alerts.alliance_invite.by': 'av {name}',
|
||||||
|
'alerts.alliance_invite_declined': '{name} avslo invitasjonen din',
|
||||||
|
'alerts.alliance_member_joined': '{name} ble med i alliansen',
|
||||||
|
'alerts.alliance_member_left': '{name} forlot alliansen', 'alerts.alliance_member_kicked': '{name} ble fjernet fra alliansen',
|
||||||
|
'alerts.alliance_kicked': 'Du ble fjernet fra {name}',
|
||||||
|
'alerts.alliance_role': 'Rollen din er nå {role}', 'alerts.alliance_role.was': 'var {role}',
|
||||||
|
'alerts.alliance_leader': '{name} er ny leder', 'alerts.alliance_leader.from': 'overlatt av {name}',
|
||||||
|
'alerts.alliance_disbanded': '{name} ble oppløst',
|
||||||
|
'alerts.diplomacy_proposal': '{tag} foreslår: {state}', 'alerts.diplomacy_proposal.until': 'svar innen {time}',
|
||||||
|
'alerts.diplomacy_declined': '{tag} avslo: {state}',
|
||||||
|
'alerts.diplomacy_changed': 'Forholdet til {tag} er nå {to}', 'alerts.diplomacy_changed.was': 'var {state}', 'alerts.diplomacy_changed.disbanded': 'alliansen deres ble oppløst',
|
||||||
|
'alerts.diplomacy_cancel_pending': '{state} med {tag} avsluttes', 'alerts.diplomacy_cancel_pending.at': 'gjelder fra {time}',
|
||||||
|
'alerts.diplomacy_cancel_revoked': 'Avslutningen av {state} med {tag} ble avlyst',
|
||||||
|
'alerts.message': 'Melding fra {name}', 'alerts.alliance_message': 'Alliansemelding fra {name}',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}));
|
||||||
105
public/js/strings/trade.js
Normal file
105
public/js/strings/trade.js
Normal file
|
|
@ -0,0 +1,105 @@
|
||||||
|
'use strict';
|
||||||
|
/* Strings of the Internet exchange screen (offers, new offer, mine, direct transport, links) and its error codes, en + nb. */
|
||||||
|
(function (root, factory) {
|
||||||
|
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
|
||||||
|
else factory(root.UpstreamI18n);
|
||||||
|
}(typeof self !== 'undefined' ? self : this, function (I) {
|
||||||
|
I.extend({
|
||||||
|
en: {
|
||||||
|
'nav.trade': 'Trade', 'screen.trade': 'Internet exchange',
|
||||||
|
'trd.tab.offers': 'Offers', 'trd.tab.new': 'New', 'trd.tab.mine': 'Mine', 'trd.tab.send': 'Send',
|
||||||
|
'trd.any': 'Any', 'trd.more': 'Load more',
|
||||||
|
'trd.status.all': 'All', 'trd.status.open': 'Open', 'trd.status.accepted': 'Taken', 'trd.status.completed': 'Settled',
|
||||||
|
'trd.status.cancelled': 'Cancelled', 'trd.status.expired': 'Expired', 'trd.status.void': 'Void',
|
||||||
|
'trd.role.poster': 'You posted', 'trd.role.acceptor': 'You took',
|
||||||
|
|
||||||
|
'trd.need.title': 'You need an Internet exchange',
|
||||||
|
'trd.need.body': 'Trading runs over the Internet exchange. Its level is the number of transports that can run at once, each level reaches {n} tiles, and one link carries up to {cap}.',
|
||||||
|
'trd.need.req': 'You can build it once {building} is level {level}.', 'trd.need.go': 'Open POP',
|
||||||
|
'trd.reach': 'level {lv} · reach {n} tiles', 'trd.reach.title': 'How far this exchange sees and trades',
|
||||||
|
|
||||||
|
'trd.offers.head': 'Open offers in reach', 'trd.offers.empty': 'No open offers in reach. Post one of your own: somebody nearby has a surplus.',
|
||||||
|
'trd.offers.emptyFiltered': 'No offers match that filter.', 'trd.offers.post': 'Post an offer',
|
||||||
|
'trd.f.give': 'They give', 'trd.f.want': 'They want', 'trd.f.from': 'Trade from', 'trd.f.allPops': 'All my POPs',
|
||||||
|
'trd.get': 'You get', 'trd.pay': 'You pay', 'trd.from': 'From', 'trd.away': '{d} tiles away', 'trd.maxDist': 'max {n} tiles',
|
||||||
|
'trd.expiresIn': 'expires in', 'trd.take': 'Take', 'trd.have': 'In stock: {n} {res}', 'trd.latency': 'transport takes {t}',
|
||||||
|
|
||||||
|
'trd.accept.title': 'Take this offer', 'trd.accept.go': 'Take offer', 'trd.accept.with': 'Pay from which POP?',
|
||||||
|
'trd.accept.nopop': 'None of your POPs can take this offer any more.', 'trd.accept.short': 'Only {have} {res} here', 'trd.accept.nolink': 'No free transport link',
|
||||||
|
'trd.accept.done': 'Deal. Both transports are on their way and land in {t}.',
|
||||||
|
|
||||||
|
'trd.new.head': 'Post an offer', 'trd.new.pop': 'From POP', 'trd.new.give': 'You give', 'trd.new.want': 'You want in return',
|
||||||
|
'trd.new.giveRes': 'Resource you give', 'trd.new.wantRes': 'Resource you want', 'trd.new.giveAmount': 'Amount you give', 'trd.new.wantAmount': 'Amount you want',
|
||||||
|
'trd.new.match': 'Match', 'trd.new.band': 'Fair range for what you ask: {lo} to {hi}.',
|
||||||
|
'trd.new.maxDist': 'Max distance (tiles)', 'trd.new.maxDistHint': 'Only POPs this close can take it. 1 to {max}.',
|
||||||
|
'trd.new.level': 'Posting needs an Internet exchange of level 1 or higher: this POP has level {lv} (reach {reach} tiles). A taker needs level {need} to trade across {d} tiles.',
|
||||||
|
'trd.new.rules': 'Each side fits one transport link, at most {cap}, and the two amounts may differ by at most 1:{n}. What you give is held in escrow and one link is reserved until somebody takes the offer, you cancel it, or it expires after {ttl}.',
|
||||||
|
'trd.new.links': 'Free transport links here: {free} of {links}.', 'trd.new.go': 'Post offer', 'trd.new.done': 'Offer posted. The goods wait in escrow.',
|
||||||
|
'trd.v.giveRes': 'Pick a resource to give.', 'trd.v.wantRes': 'Give and want must be different resources.', 'trd.v.giveAmount': 'Give at least 1.',
|
||||||
|
'trd.v.wantAmount': 'Ask for at least 1.', 'trd.v.maxDistance': 'Max distance must be a whole number of tiles.', 'trd.v.terms': 'Check the terms.',
|
||||||
|
'trd.v.have': 'You only have {have} {res} here.', 'trd.v.links': 'No free transport link at this POP: all are busy or reserved by open offers.',
|
||||||
|
|
||||||
|
'trd.cancel': 'Cancel', 'trd.cancelled': 'Offer cancelled. {what} is back in the POP.', 'trd.settles': 'Settles when both transports have landed.',
|
||||||
|
'trd.voidHint': 'The POP changed hands, the goods went with it.', 'trd.mine.empty': 'No offers yet.',
|
||||||
|
|
||||||
|
'trd.send.head': 'Send resources', 'trd.send.body': 'A direct transport carries up to {n} per link, no strings attached. Pick one of your POPs, or type the coordinates of any POP.',
|
||||||
|
'trd.send.own': 'To one of your POPs', 'trd.send.noOwn': 'You have no other POP yet.', 'trd.send.coords': 'To any POP by coordinates',
|
||||||
|
'trd.send.warn': 'The owner of a POP that is not yours sees an incoming movement (type hidden) until the cargo lands.',
|
||||||
|
'trd.links.head': 'Transport links', 'trd.links.used': '{a} of {n} links in use, {free} free · {cap} per link',
|
||||||
|
'trd.links.hint': 'An open offer holds one link. A transport holds one until it lands and the empty carriers are back.', 'trd.links.active': 'On the road',
|
||||||
|
|
||||||
|
'trd.err.range': 'That POP is {d} tiles away. The offer reaches {max} tiles and your exchange reaches {reach}.',
|
||||||
|
'trd.err.ratio': 'The two amounts may differ by at most 1:{n}.', 'trd.err.cap': 'Each side must fit one transport link: at most {n}.',
|
||||||
|
'err.trade_ratio': 'The two amounts may differ by at most 1:2.', 'err.offer_closed': 'That offer is not open any more.', 'err.own_offer': 'You cannot take your own offer.',
|
||||||
|
'err.trade_out_of_range': 'That POP is too far from the offer: its max distance or your exchange reach is exceeded.',
|
||||||
|
},
|
||||||
|
nb: {
|
||||||
|
'nav.trade': 'Handel', 'screen.trade': 'Internettknutepunkt',
|
||||||
|
'trd.tab.offers': 'Tilbud', 'trd.tab.new': 'Nytt', 'trd.tab.mine': 'Mine', 'trd.tab.send': 'Send',
|
||||||
|
'trd.any': 'Alle', 'trd.more': 'Last flere',
|
||||||
|
'trd.status.all': 'Alle', 'trd.status.open': 'Åpne', 'trd.status.accepted': 'Tatt', 'trd.status.completed': 'Gjort opp',
|
||||||
|
'trd.status.cancelled': 'Trukket', 'trd.status.expired': 'Utløpt', 'trd.status.void': 'Ugyldig',
|
||||||
|
'trd.role.poster': 'Du la ut', 'trd.role.acceptor': 'Du tok',
|
||||||
|
|
||||||
|
'trd.need.title': 'Du trenger et Internettknutepunkt',
|
||||||
|
'trd.need.body': 'Handel går over Internettknutepunktet. Nivået er antall transporter som kan gå samtidig, hvert nivå rekker {n} felt, og én lenke bærer opptil {cap}.',
|
||||||
|
'trd.need.req': 'Du kan bygge det når {building} er på nivå {level}.', 'trd.need.go': 'Åpne POP',
|
||||||
|
'trd.reach': 'nivå {lv} · rekkevidde {n} felt', 'trd.reach.title': 'Hvor langt dette knutepunktet ser og handler',
|
||||||
|
|
||||||
|
'trd.offers.head': 'Åpne tilbud innen rekkevidde', 'trd.offers.empty': 'Ingen åpne tilbud innen rekkevidde. Legg ut ett selv: noen i nærheten har overskudd.',
|
||||||
|
'trd.offers.emptyFiltered': 'Ingen tilbud passer det filteret.', 'trd.offers.post': 'Legg ut et tilbud',
|
||||||
|
'trd.f.give': 'De gir', 'trd.f.want': 'De vil ha', 'trd.f.from': 'Handle fra', 'trd.f.allPops': 'Alle POP-ene mine',
|
||||||
|
'trd.get': 'Du får', 'trd.pay': 'Du betaler', 'trd.from': 'Fra', 'trd.away': '{d} felt unna', 'trd.maxDist': 'maks {n} felt',
|
||||||
|
'trd.expiresIn': 'utløper om', 'trd.take': 'Ta', 'trd.have': 'På lager: {n} {res}', 'trd.latency': 'transporten tar {t}',
|
||||||
|
|
||||||
|
'trd.accept.title': 'Ta dette tilbudet', 'trd.accept.go': 'Ta tilbudet', 'trd.accept.with': 'Betale fra hvilken POP?',
|
||||||
|
'trd.accept.nopop': 'Ingen av POP-ene dine kan ta dette tilbudet lenger.', 'trd.accept.short': 'Bare {have} {res} her', 'trd.accept.nolink': 'Ingen ledig transportlenke',
|
||||||
|
'trd.accept.done': 'Avtale. Begge transportene er på vei og lander om {t}.',
|
||||||
|
|
||||||
|
'trd.new.head': 'Legg ut et tilbud', 'trd.new.pop': 'Fra POP', 'trd.new.give': 'Du gir', 'trd.new.want': 'Du vil ha til gjengjeld',
|
||||||
|
'trd.new.giveRes': 'Ressurs du gir', 'trd.new.wantRes': 'Ressurs du vil ha', 'trd.new.giveAmount': 'Mengde du gir', 'trd.new.wantAmount': 'Mengde du vil ha',
|
||||||
|
'trd.new.match': 'Likt', 'trd.new.band': 'Rimelig område for det du ber om: {lo} til {hi}.',
|
||||||
|
'trd.new.maxDist': 'Maks avstand (felt)', 'trd.new.maxDistHint': 'Bare POP-er så nær kan ta det. 1 til {max}.',
|
||||||
|
'trd.new.level': 'Å legge ut krever et Internettknutepunkt på nivå 1 eller høyere: denne POP-en har nivå {lv} (rekkevidde {reach} felt). Den som tar det trenger nivå {need} for å handle over {d} felt.',
|
||||||
|
'trd.new.rules': 'Hver side må rommes av én transportlenke, maks {cap}, og de to mengdene kan avvike med høyst 1:{n}. Det du gir holdes i depot og én lenke reserveres til noen tar tilbudet, du trekker det, eller det utløper etter {ttl}.',
|
||||||
|
'trd.new.links': 'Ledige transportlenker her: {free} av {links}.', 'trd.new.go': 'Legg ut tilbud', 'trd.new.done': 'Tilbudet er lagt ut. Varene venter i depot.',
|
||||||
|
'trd.v.giveRes': 'Velg en ressurs å gi.', 'trd.v.wantRes': 'Du må gi og ønske ulike ressurser.', 'trd.v.giveAmount': 'Gi minst 1.',
|
||||||
|
'trd.v.wantAmount': 'Be om minst 1.', 'trd.v.maxDistance': 'Maks avstand må være et helt antall felt.', 'trd.v.terms': 'Sjekk vilkårene.',
|
||||||
|
'trd.v.have': 'Du har bare {have} {res} her.', 'trd.v.links': 'Ingen ledig transportlenke i denne POP-en: alle er opptatt eller reservert av åpne tilbud.',
|
||||||
|
|
||||||
|
'trd.cancel': 'Trekk', 'trd.cancelled': 'Tilbudet er trukket. {what} er tilbake i POP-en.', 'trd.settles': 'Gjøres opp når begge transportene har landet.',
|
||||||
|
'trd.voidHint': 'POP-en skiftet eier, og varene fulgte med.', 'trd.mine.empty': 'Ingen tilbud ennå.',
|
||||||
|
|
||||||
|
'trd.send.head': 'Send ressurser', 'trd.send.body': 'En direkte transport bærer opptil {n} per lenke, uten betingelser. Velg en av POP-ene dine, eller skriv koordinatene til en hvilken som helst POP.',
|
||||||
|
'trd.send.own': 'Til en av POP-ene dine', 'trd.send.noOwn': 'Du har ingen annen POP ennå.', 'trd.send.coords': 'Til en hvilken som helst POP med koordinater',
|
||||||
|
'trd.send.warn': 'Eieren av en POP som ikke er din ser en innkommende bevegelse (type skjult) til lasten lander.',
|
||||||
|
'trd.links.head': 'Transportlenker', 'trd.links.used': '{a} av {n} lenker i bruk, {free} ledige · {cap} per lenke',
|
||||||
|
'trd.links.hint': 'Et åpent tilbud holder én lenke. En transport holder én til den har landet og de tomme bærerne er tilbake.', 'trd.links.active': 'På veien',
|
||||||
|
|
||||||
|
'trd.err.range': 'Den POP-en er {d} felt unna. Tilbudet rekker {max} felt og knutepunktet ditt rekker {reach}.',
|
||||||
|
'trd.err.ratio': 'De to mengdene kan avvike med høyst 1:{n}.', 'trd.err.cap': 'Hver side må rommes av én transportlenke: høyst {n}.',
|
||||||
|
'err.trade_ratio': 'De to mengdene kan avvike med høyst 1:2.', 'err.offer_closed': 'Det tilbudet er ikke åpent lenger.', 'err.own_offer': 'Du kan ikke ta ditt eget tilbud.',
|
||||||
|
'err.trade_out_of_range': 'Den POP-en er for langt unna tilbudet: maks avstand eller knutepunktets rekkevidde er overskredet.',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}));
|
||||||
116
public/js/strings/world.js
Normal file
116
public/js/strings/world.js
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
'use strict';
|
||||||
|
/* Strings of the end game: the Backbone race screen, the ended-world mode, landing sites on the map / send dialog / reports,
|
||||||
|
* the shared report folder, and the world_ended / backbone_closed error codes, en + nb. */
|
||||||
|
(function (root, factory) {
|
||||||
|
if (typeof module === 'object' && module.exports) factory(require('../i18n.js'));
|
||||||
|
else factory(root.UpstreamI18n);
|
||||||
|
}(typeof self !== 'undefined' ? self : this, function (I) {
|
||||||
|
I.extend({
|
||||||
|
en: {
|
||||||
|
'nav.world': 'Backbone', 'screen.world': 'The Backbone race',
|
||||||
|
'ended.locked': 'This world has ended. Everything is read-only now.', 'ended.pill': 'World ended', 'ended.title': 'This world has ended',
|
||||||
|
'ended.body': 'You can still read everything and message people, but nothing can be built, sent or traded any more.', 'ended.see': 'Final standings',
|
||||||
|
|
||||||
|
'wld.site': 'Landing site {n}', 'wld.yours': 'Your alliance', 'wld.incumbent': 'Incumbent', 'wld.takenBy': 'taken by {name}',
|
||||||
|
'wld.level': 'Level {n} / {max}', 'wld.levelShort': 'Node level', 'wld.building': 'Building level {n}', 'wld.stock': 'Stockpile', 'wld.coords': 'Position',
|
||||||
|
'wld.manage': 'Manage', 'wld.attack': 'Scan or attack', 'wld.onMap': 'On map', 'wld.sites': 'Landing sites',
|
||||||
|
'wld.noSites': 'The sites are open but none is listed yet. Refresh in a moment.',
|
||||||
|
'wld.won': '{name} won the world', 'wld.endedNoWinner': 'The world has ended', 'wld.wonAt': 'finished {t}', 'wld.endedAt': 'Ended {t}.',
|
||||||
|
'wld.endsIn': 'The world ends in', 'wld.winnerKeep': 'The race is decided. Until the end you can still fight for the ranking.',
|
||||||
|
'wld.open': 'The landing sites are open', 'wld.leading': 'Leading: [{tag}] {name}, site {n}, node level {level} of {max}',
|
||||||
|
'wld.noLeader': 'Nobody holds a landing site yet. The first alliance to scan one and take it starts the race.',
|
||||||
|
'wld.goal': 'Build the Backbone node to level {max} first and your alliance wins the world.',
|
||||||
|
'wld.opensIn': 'The landing sites appear in', 'wld.day': 'World day {day} of {open}',
|
||||||
|
'wld.how.head': 'How the world ends',
|
||||||
|
'wld.how.1': '{n} backbone landing sites appear on the map on world day {day}.',
|
||||||
|
'wld.how.2': 'An alliance takes a site by beating its static defence: scan it first, then attack. Holders cannot garrison a site, they can only grow the node, which also makes it harder to take.',
|
||||||
|
'wld.how.3': 'The holders ship Fiber, Hardware and Capital to their site and build the Backbone node level by level up to {max}. The first node at level {max} wins.',
|
||||||
|
'wld.how.4': 'The world closes {d} world days after the winning level lands. After that it is read-only.',
|
||||||
|
'wld.lost': 'Your alliance no longer holds this site.',
|
||||||
|
'wld.build.head': 'Backbone node', 'wld.build.next': 'Next: level {n}, takes {t}', 'wld.build.lack': 'The stockpile lacks {what}.', 'wld.build.max': 'Fully built',
|
||||||
|
'wld.build.started': 'Level {n} is building, done in {t}.', 'wld.build.go': 'Build level {n}',
|
||||||
|
'wld.build.why.ended': 'The world has ended.', 'wld.build.why.forbidden': 'Your role may not build the node.',
|
||||||
|
'wld.ship.head': 'Ship resources', 'wld.ship.no': 'Only members of the holding alliance can ship.', 'wld.ship.go': 'Ship', 'wld.ship.cargo': 'Cargo',
|
||||||
|
'wld.ship.hint': 'A shipment is a transport: up to {n} per link. It lands in the stockpile, or rides home if the site has changed hands on the way.',
|
||||||
|
'wld.ship.done': 'Shipment on its way.', 'wld.ledger': 'Who shipped what',
|
||||||
|
'wld.results': 'Final standings', 'wld.rank.operators': 'Operators', 'wld.rank.alliances': 'Alliances', 'wld.rank.attackers': 'Attackers', 'wld.rank.defenders': 'Defenders',
|
||||||
|
'wld.rank.empty': 'Nobody on this list.', 'wld.rank.totals': '{o} operators in {a} alliances',
|
||||||
|
|
||||||
|
'tile.backbone': 'Backbone landing site', 'map.legend.backbone': 'Landing site', 'map.info.openWorld': 'Backbone race',
|
||||||
|
'map.info.backbone': 'A backbone landing site. The first alliance to build the node here to level {max} wins the world.',
|
||||||
|
'send.landing.hint': 'A landing site has no garrison: only its static defence counts (a scan shows the number, about {mult} times an incumbent site). Winning makes your alliance the holder.',
|
||||||
|
'send.transport.rival': 'This is a POP you do not own: the cargo is a gift, and its owner sees an incoming movement until it lands. For a trade use the Internet exchange.',
|
||||||
|
'send.reason.no_alliance': 'only alliance members can attack a landing site', 'send.reason.own_site': 'your alliance already holds this site',
|
||||||
|
'send.invalid.no_alliance': 'Join an alliance first.', 'send.invalid.own_site': 'Your alliance holds that site.',
|
||||||
|
'send.invalid.landing_scan_or_attack_only': 'Landing sites can only be scanned or attacked.', 'send.invalid.backbone_site': 'A landing site cannot be settled.',
|
||||||
|
'mov.siteShipment': 'Shipment to a landing site',
|
||||||
|
|
||||||
|
'report.type.landing': 'Landing site attack',
|
||||||
|
'rep.vs': '{a} vs {d}', 'rep.by': 'By {name}', 'rep.attackerWon': 'Attacker won', 'rep.defenderWon': 'Defender won',
|
||||||
|
'rep.landing.title': 'Landing site {n}', 'rep.landing.taken': 'Site taken', 'rep.landing.held': 'Site held', 'rep.landing.holder': 'Holder',
|
||||||
|
'rep.landing.takenLine': '{tag} took the site.', 'rep.landing.heldLine': 'The defence held. The site did not change hands.',
|
||||||
|
'rep.tab.mine': 'My reports', 'rep.tab.alliance': 'Alliance', 'rep.sharedBy': 'shared by {name}',
|
||||||
|
'rep.folder.none': 'Join an alliance to use the shared folder.', 'rep.folder.empty': 'Nothing shared yet. Open a report and share it with the alliance.',
|
||||||
|
'rep.folder.forbidden': 'Your role may not read the shared folder.',
|
||||||
|
'rep.share': 'Share with alliance', 'rep.share.hint': 'Put this report in the alliance folder. It is kept for another 14 days from now.',
|
||||||
|
'rep.share.done': 'Shared with the alliance.', 'rep.share.already': 'Already in the alliance folder.', 'rep.share.forbidden': 'Your role may not share reports.',
|
||||||
|
'rep.unshare': 'Remove from folder', 'rep.unshare.done': 'Removed from the folder.', 'rep.unshare.forbidden': 'Only the person who shared it, or a leader or officer, may remove it.',
|
||||||
|
|
||||||
|
'err.world_ended': 'This world has ended. It can still be read, but nothing can be changed.',
|
||||||
|
'err.backbone_closed': 'The backbone landing sites have not appeared yet.',
|
||||||
|
},
|
||||||
|
nb: {
|
||||||
|
'nav.world': 'Ryggrad', 'screen.world': 'Ryggradskappløpet',
|
||||||
|
'ended.locked': 'Denne verdenen er slutt. Alt er skrivebeskyttet nå.', 'ended.pill': 'Verdenen er slutt', 'ended.title': 'Denne verdenen er slutt',
|
||||||
|
'ended.body': 'Du kan fortsatt lese alt og sende meldinger, men ingenting kan bygges, sendes eller handles lenger.', 'ended.see': 'Sluttresultat',
|
||||||
|
|
||||||
|
'wld.site': 'Landingspunkt {n}', 'wld.yours': 'Din allianse', 'wld.incumbent': 'Inkumbent', 'wld.takenBy': 'tatt av {name}',
|
||||||
|
'wld.level': 'Nivå {n} / {max}', 'wld.levelShort': 'Nodenivå', 'wld.building': 'Bygger nivå {n}', 'wld.stock': 'Lager', 'wld.coords': 'Posisjon',
|
||||||
|
'wld.manage': 'Styr', 'wld.attack': 'Skann eller angrip', 'wld.onMap': 'På kartet', 'wld.sites': 'Landingspunkter',
|
||||||
|
'wld.noSites': 'Punktene er åpne, men ingen er listet ennå. Oppdater om et øyeblikk.',
|
||||||
|
'wld.won': '{name} vant verdenen', 'wld.endedNoWinner': 'Verdenen er slutt', 'wld.wonAt': 'ferdig {t}', 'wld.endedAt': 'Sluttet {t}.',
|
||||||
|
'wld.endsIn': 'Verdenen slutter om', 'wld.winnerKeep': 'Kappløpet er avgjort. Fram til slutten kan du fortsatt kjempe om rangeringen.',
|
||||||
|
'wld.open': 'Landingspunktene er åpne', 'wld.leading': 'Leder: [{tag}] {name}, punkt {n}, nodenivå {level} av {max}',
|
||||||
|
'wld.noLeader': 'Ingen holder et landingspunkt ennå. Første allianse som skanner ett og tar det starter kappløpet.',
|
||||||
|
'wld.goal': 'Bygg Ryggradsnoden til nivå {max} først, så vinner alliansen din verdenen.',
|
||||||
|
'wld.opensIn': 'Landingspunktene dukker opp om', 'wld.day': 'Verdensdag {day} av {open}',
|
||||||
|
'wld.how.head': 'Slik slutter verdenen',
|
||||||
|
'wld.how.1': '{n} landingspunkter for ryggraden dukker opp på kartet på verdensdag {day}.',
|
||||||
|
'wld.how.2': 'En allianse tar et punkt ved å slå det statiske forsvaret: skann det først, så angrip. Eierne kan ikke stasjonere enheter der, bare bygge noden, som også gjør det vanskeligere å ta.',
|
||||||
|
'wld.how.3': 'Eierne sender Fiber, Maskinvare og Kapital til punktet sitt og bygger Ryggradsnoden nivå for nivå opp til {max}. Første node på nivå {max} vinner.',
|
||||||
|
'wld.how.4': 'Verdenen stenger {d} verdensdager etter at vinnernivået er bygget. Etter det er den skrivebeskyttet.',
|
||||||
|
'wld.lost': 'Alliansen din holder ikke dette punktet lenger.',
|
||||||
|
'wld.build.head': 'Ryggradsnode', 'wld.build.next': 'Neste: nivå {n}, tar {t}', 'wld.build.lack': 'Lageret mangler {what}.', 'wld.build.max': 'Ferdigbygd',
|
||||||
|
'wld.build.started': 'Nivå {n} bygges, ferdig om {t}.', 'wld.build.go': 'Bygg nivå {n}',
|
||||||
|
'wld.build.why.ended': 'Verdenen er slutt.', 'wld.build.why.forbidden': 'Rollen din kan ikke bygge noden.',
|
||||||
|
'wld.ship.head': 'Send ressurser', 'wld.ship.no': 'Bare medlemmer av eieralliansen kan sende.', 'wld.ship.go': 'Send', 'wld.ship.cargo': 'Last',
|
||||||
|
'wld.ship.hint': 'En forsendelse er en transport: opptil {n} per lenke. Den lander på lageret, eller drar hjem hvis punktet har skiftet eier underveis.',
|
||||||
|
'wld.ship.done': 'Forsendelsen er på vei.', 'wld.ledger': 'Hvem sendte hva',
|
||||||
|
'wld.results': 'Sluttresultat', 'wld.rank.operators': 'Operatører', 'wld.rank.alliances': 'Allianser', 'wld.rank.attackers': 'Angripere', 'wld.rank.defenders': 'Forsvarere',
|
||||||
|
'wld.rank.empty': 'Ingen på denne listen.', 'wld.rank.totals': '{o} operatører i {a} allianser',
|
||||||
|
|
||||||
|
'tile.backbone': 'Landingspunkt for ryggraden', 'map.legend.backbone': 'Landingspunkt', 'map.info.openWorld': 'Ryggradskappløpet',
|
||||||
|
'map.info.backbone': 'Et landingspunkt for ryggraden. Første allianse som bygger noden her til nivå {max} vinner verdenen.',
|
||||||
|
'send.landing.hint': 'Et landingspunkt har ingen garnison: bare det statiske forsvaret teller (en skanning viser tallet, omtrent {mult} ganger et inkumbentpunkt). Seier gjør alliansen din til eier.',
|
||||||
|
'send.transport.rival': 'Dette er en POP du ikke eier: lasten er en gave, og eieren ser en innkommende bevegelse til den lander. For handel, bruk Internettknutepunktet.',
|
||||||
|
'send.reason.no_alliance': 'bare alliansemedlemmer kan angripe et landingspunkt', 'send.reason.own_site': 'alliansen din holder allerede dette punktet',
|
||||||
|
'send.invalid.no_alliance': 'Bli med i en allianse først.', 'send.invalid.own_site': 'Alliansen din holder det punktet.',
|
||||||
|
'send.invalid.landing_scan_or_attack_only': 'Landingspunkter kan bare skannes eller angripes.', 'send.invalid.backbone_site': 'Et landingspunkt kan ikke bosettes.',
|
||||||
|
'mov.siteShipment': 'Forsendelse til et landingspunkt',
|
||||||
|
|
||||||
|
'report.type.landing': 'Angrep på landingspunkt',
|
||||||
|
'rep.vs': '{a} mot {d}', 'rep.by': 'Av {name}', 'rep.attackerWon': 'Angriper vant', 'rep.defenderWon': 'Forsvarer vant',
|
||||||
|
'rep.landing.title': 'Landingspunkt {n}', 'rep.landing.taken': 'Punktet ble tatt', 'rep.landing.held': 'Punktet holdt', 'rep.landing.holder': 'Eier',
|
||||||
|
'rep.landing.takenLine': '{tag} tok punktet.', 'rep.landing.heldLine': 'Forsvaret holdt. Punktet skiftet ikke eier.',
|
||||||
|
'rep.tab.mine': 'Mine rapporter', 'rep.tab.alliance': 'Allianse', 'rep.sharedBy': 'delt av {name}',
|
||||||
|
'rep.folder.none': 'Bli med i en allianse for å bruke den delte mappen.', 'rep.folder.empty': 'Ingenting delt ennå. Åpne en rapport og del den med alliansen.',
|
||||||
|
'rep.folder.forbidden': 'Rollen din kan ikke lese den delte mappen.',
|
||||||
|
'rep.share': 'Del med alliansen', 'rep.share.hint': 'Legg denne rapporten i alliansemappen. Den lagres i 14 dager til fra nå.',
|
||||||
|
'rep.share.done': 'Delt med alliansen.', 'rep.share.already': 'Ligger allerede i alliansemappen.', 'rep.share.forbidden': 'Rollen din kan ikke dele rapporter.',
|
||||||
|
'rep.unshare': 'Fjern fra mappen', 'rep.unshare.done': 'Fjernet fra mappen.', 'rep.unshare.forbidden': 'Bare den som delte den, eller en leder eller offiser, kan fjerne den.',
|
||||||
|
|
||||||
|
'err.world_ended': 'Denne verdenen er slutt. Den kan fortsatt leses, men ingenting kan endres.',
|
||||||
|
'err.backbone_closed': 'Landingspunktene for ryggraden har ikke dukket opp ennå.',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
|
@ -131,6 +131,7 @@
|
||||||
case 'report':
|
case 'report':
|
||||||
App.refreshReportsUnread().catch(() => {});
|
App.refreshReportsUnread().catch(() => {});
|
||||||
debounce('towns', () => App.refreshTowns().catch(() => {}), 500); // a settle / takeover report changes the POP list
|
debounce('towns', () => App.refreshTowns().catch(() => {}), 500); // a settle / takeover report changes the POP list
|
||||||
|
debounce('moves', () => App.refreshMovements().catch(() => {}), 300); // the movement that made the report is over: the incoming banner must go
|
||||||
App.emit('report', msg);
|
App.emit('report', msg);
|
||||||
break;
|
break;
|
||||||
case 'notification':
|
case 'notification':
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ const D = require('../../public/js/data.js');
|
||||||
const { GameError } = require('../errors');
|
const { GameError } = require('../errors');
|
||||||
const A = require('../alliances');
|
const A = require('../alliances');
|
||||||
const { ensureCleanup } = require('../military/reports');
|
const { ensureCleanup } = require('../military/reports');
|
||||||
|
const ctxOf = require('../military/ctx');
|
||||||
|
|
||||||
function context(db, userId, reportId) {
|
function context(db, userId, reportId) {
|
||||||
const rep = db.get(`SELECT r.id, r.world_id, r.expires_at FROM reports r JOIN report_recipients rr ON rr.report_id = r.id AND rr.user_id = ? WHERE r.id = ?`, userId, reportId);
|
const rep = db.get(`SELECT r.id, r.world_id, r.expires_at FROM reports r JOIN report_recipients rr ON rr.report_id = r.id AND rr.user_id = ? WHERE r.id = ?`, userId, reportId);
|
||||||
|
|
@ -23,7 +24,8 @@ function context(db, userId, reportId) {
|
||||||
return { rep, op, member: m };
|
return { rep, op, member: m };
|
||||||
}
|
}
|
||||||
|
|
||||||
function reportShare(ctx, { userId, reportId }) {
|
function reportShare(ctx0, { userId, reportId }) {
|
||||||
|
const ctx = ctxOf(ctx0); // ensureCleanup enqueues: a plain command ctx has no enqueue (was a 500 when no cleanup event was pending)
|
||||||
const { db, now } = ctx;
|
const { db, now } = ctx;
|
||||||
const { rep, op, member } = context(db, userId, reportId);
|
const { rep, op, member } = context(db, userId, reportId);
|
||||||
if (!R.allianceCan(member.role, 'shareReport')) throw new GameError('forbidden', { need: 'shareReport', role: member.role });
|
if (!R.allianceCan(member.role, 'shareReport')) throw new GameError('forbidden', { need: 'shareReport', role: member.role });
|
||||||
|
|
|
||||||
|
|
@ -24,5 +24,7 @@ module.exports = function ret(ctx, ev) {
|
||||||
U.addHome(db, town.id, mv.units);
|
U.addHome(db, town.id, mv.units);
|
||||||
const lost = addCargo(db, town, mv.cargo);
|
const lost = addCargo(db, town, mv.cargo);
|
||||||
P.reschedule(ctx, town.id, ev.dueAt);
|
P.reschedule(ctx, town.id, ev.dueAt);
|
||||||
if (uid && !mv.extra.link) ctx.notify(uid, mv.worldId, 'movement_returned', { movementId: mv.id, townId: town.id, units: mv.units, cargo: mv.cargo, cargoLost: lost });
|
// Empty carriers coming home (extra.link) are silent; a bounced shipment that carries cargo is not: its overflow is reported.
|
||||||
|
const carrying = D.RESOURCES.some((r) => mv.cargo && mv.cargo[r] > 0);
|
||||||
|
if (uid && (!mv.extra.link || carrying)) ctx.notify(uid, mv.worldId, 'movement_returned', { movementId: mv.id, townId: town.id, units: mv.units, cargo: mv.cargo, cargoLost: lost });
|
||||||
};
|
};
|
||||||
|
|
|
||||||
75
test/bot-run.test.js
Normal file
75
test/bot-run.test.js
Normal file
|
|
@ -0,0 +1,75 @@
|
||||||
|
'use strict';
|
||||||
|
/* tools/bot.js: short deterministic runs of the bot harness against the real server. Asserts the invariants (conservation of
|
||||||
|
* resources and units, no negative stock, no failed events, no unexpected error codes), that the same seed gives identical stats
|
||||||
|
* (wall-clock `perf` excepted), that the harness parses its options, and that the data.js override mechanism restores what it
|
||||||
|
* changed. Keep it fast: it is part of `npm test`. */
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const { runBot, parseArgs, applyOverrides } = require('../tools/bot.js');
|
||||||
|
const D = require('../public/js/data.js');
|
||||||
|
|
||||||
|
const strip = (s) => { const c = JSON.parse(JSON.stringify(s)); delete c.perf; return c; };
|
||||||
|
|
||||||
|
test('bot run: invariants hold and the same seed gives identical stats', async () => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
const a = await runBot({ players: 12, days: 6, seed: 7 }); // long enough for scans, raids and battle losses
|
||||||
|
const b = await runBot({ players: 12, days: 6, seed: 7 });
|
||||||
|
assert.equal(a.invariants.ok, true, JSON.stringify(a.invariants).slice(0, 800));
|
||||||
|
assert.equal(a.invariants.resources.ok, true);
|
||||||
|
assert.equal(a.invariants.units.ok, true);
|
||||||
|
assert.equal(a.invariants.negativeStock.ok, true);
|
||||||
|
assert.equal(a.invariants.failedEvents.n, 0);
|
||||||
|
assert.equal(a.invariants.unexpectedErrors.n, 0);
|
||||||
|
assert.deepStrictEqual(strip(a), strip(b), 'same options and seed, different stats');
|
||||||
|
assert.ok(a.perf.commands > 50 && a.botLogs.builds > 20 && a.botLogs.trains > 0, 'the bots built and trained');
|
||||||
|
assert.ok(a.days.length === 6 && a.meta.players === 12);
|
||||||
|
assert.ok(a.combat.scans.n > 0, 'and scouted (the military paths ran, so determinism covers them)');
|
||||||
|
const c = await runBot({ players: 12, days: 6, seed: 8 });
|
||||||
|
assert.notDeepStrictEqual(strip(a).days, strip(c).days, 'a different seed should change the world');
|
||||||
|
assert.ok(Date.now() - t0 < 15000, 'the harness must stay fast (took ' + (Date.now() - t0) + ' ms)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bot run: a fast world reaches the landing sites, an alliance takes one and ships; conservation holds with backbone sinks', async () => {
|
||||||
|
// 20 bots, 12 sittings a day, a world at speed 15: day 100 of world time is day 6.7; takes ~5 s
|
||||||
|
const s = await runBot({ players: 20, days: 8, speed: 15, seed: 3, sessionsPerDay: 12, endgameStepMin: 60 });
|
||||||
|
assert.equal(s.invariants.ok, true, JSON.stringify(s.invariants).slice(0, 800));
|
||||||
|
assert.equal(s.endgame.open, true, 'age 120 world days: the sites are open');
|
||||||
|
assert.ok(s.endgame.strikes >= 1 && s.combat.landing.taken >= 1, 'an alliance took a landing site');
|
||||||
|
assert.ok(s.endgame.shipments > 0 && s.endgame.bestLevel >= 1, 'and its members shipped enough for Backbone node levels');
|
||||||
|
assert.ok(s.endgame.sites.some((x) => x.holder && x.contributors >= 1));
|
||||||
|
assert.equal(s.invariants.resources.final.fiber.backbone > 0, true, 'the ledger booked the node levels as a sink');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bot options: parsing, overrides and restore', () => {
|
||||||
|
const o = parseArgs(['--players', '12', '--days', '5', '--speed', '2', '--seed', '9', '--set', 'FORMULAS.costGrowth=1.3', '--set', 'UNITS.script_crew.cost.fiber=70', '--always-on']);
|
||||||
|
assert.equal(o.players, 12); assert.equal(o.speed, 2); assert.equal(o.seed, 9); assert.equal(o.alwaysOn, true); assert.equal(o.set.length, 2);
|
||||||
|
assert.throws(() => parseArgs(['--nope']), /unknown option/);
|
||||||
|
assert.throws(() => parseArgs(['--players']), /missing value/);
|
||||||
|
const before = [D.FORMULAS.costGrowth, D.UNITS.script_crew.cost.fiber];
|
||||||
|
const restore = applyOverrides(o.set);
|
||||||
|
assert.equal(D.FORMULAS.costGrowth, 1.3);
|
||||||
|
assert.equal(D.UNITS.script_crew.cost.fiber, 70);
|
||||||
|
restore();
|
||||||
|
assert.deepEqual([D.FORMULAS.costGrowth, D.UNITS.script_crew.cost.fiber], before);
|
||||||
|
assert.throws(() => applyOverrides(['FORMULAS.nope=1']), /no such path/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bot invariants catch tampering: created resources, vanished units, negative stock and failed events', async () => {
|
||||||
|
// tamper on the last day boundary: the final checkpoint follows at the same instant, nothing settles the damage away
|
||||||
|
const tamper = (fn, o) => runBot(Object.assign({ players: 6, days: 3, seed: 2, onDay: (sim, day) => { if (day === (o && o.days || 3)) fn(sim.db); } }, o));
|
||||||
|
const a = await tamper((db) => db.run('UPDATE towns SET fiber = fiber + 500 WHERE id = 1'));
|
||||||
|
assert.equal(a.invariants.ok, false);
|
||||||
|
assert.equal(a.invariants.resources.ok, false, 'conjured Fiber must show as drift');
|
||||||
|
assert.ok(a.invariants.resources.worstDrift >= 400);
|
||||||
|
let vanished = null;
|
||||||
|
const b = await tamper((db) => { const u = db.get('SELECT town_id, unit, count FROM town_units ORDER BY count DESC LIMIT 1'); if (u) { vanished = u; db.run('DELETE FROM town_units WHERE town_id = ? AND unit = ?', u.town_id, u.unit); } }, { players: 12, days: 6 });
|
||||||
|
assert.ok(vanished, 'the bots trained some units by day 6');
|
||||||
|
assert.equal(b.invariants.units.ok, false, 'units that vanish must show as drift');
|
||||||
|
assert.equal(b.invariants.ok, false);
|
||||||
|
const c = await tamper((db) => db.run('UPDATE towns SET hardware = -5 WHERE id = 2'));
|
||||||
|
assert.equal(c.invariants.negativeStock.ok, false);
|
||||||
|
assert.equal(c.invariants.ok, false);
|
||||||
|
const d = await tamper((db) => db.run("INSERT INTO events (world_id, due_at, type, payload, status, created_at) VALUES (1, 0, 'nope', '{}', 'pending', 0)"));
|
||||||
|
assert.ok(d.invariants.failedEvents.n >= 1, 'an event without a handler fails and is counted');
|
||||||
|
assert.equal(d.invariants.ok, false);
|
||||||
|
});
|
||||||
47
test/bot-server-fixes.test.js
Normal file
47
test/bot-server-fixes.test.js
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
'use strict';
|
||||||
|
/* Small server fixes found by the bot harness (tools/bot.js), each with the test that failed before the fix. */
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const T = require('./military-helpers');
|
||||||
|
const M = require('../server/military/movements');
|
||||||
|
const { R, D } = T;
|
||||||
|
|
||||||
|
// The conservation ledger of the harness found it: a shipment that comes home (a landing site changed hands, a POP vanished) rides
|
||||||
|
// back on a `link` return leg. Cargo above the Rack hall cap is dropped on arrival, but the return handler stayed silent for link
|
||||||
|
// legs, so the loss was invisible to the player and to every audit that sums the `cargoLost` notifications.
|
||||||
|
test('a bounced shipment that does not fit the Rack hall reports the overflow (link return legs with cargo are no longer silent)', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const a = T.addOperator(h, 'alice', { infra: { rack_hall: 1 } });
|
||||||
|
const cap = R.storageCap(require('../server/state').loadTown(h.db, a.townId));
|
||||||
|
h.db.run('UPDATE towns SET fiber = ?, hardware = 0, capital = 0 WHERE id = ?', cap - 100, a.townId);
|
||||||
|
const row = T.town(h, a.townId);
|
||||||
|
const ctx = h.ctx();
|
||||||
|
M.launchReturn(ctx, { worldId: h.worldId, ownerId: a.opId, fromTownId: null, at: { x: row.x + 5, y: row.y }, to: row, units: {}, cargo: { fiber: 400 }, arriveAt: h.clock.now() + 60 * 1000, parentId: null, extra: { link: 1 } });
|
||||||
|
h.advance(2 * 60 * 1000);
|
||||||
|
const n = T.notes(h, a.userId, 'movement_returned');
|
||||||
|
assert.equal(n.length, 1, 'the bounced shipment is announced');
|
||||||
|
assert.ok(Math.abs(n[0].cargoLost.fiber - 300) <= 2, 'and says how much did not fit (400 sent, 100 of room, a minute of production on top): ' + n[0].cargoLost.fiber);
|
||||||
|
assert.ok(Math.abs(T.town(h, a.townId).fiber - cap) < 1e-6, 'the store is full, not above the cap');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty carriers coming home on a link leg stay silent (no notification spam)', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const a = T.addOperator(h, 'alice');
|
||||||
|
const row = T.town(h, a.townId);
|
||||||
|
M.launchReturn(h.ctx(), { worldId: h.worldId, ownerId: a.opId, fromTownId: null, at: { x: row.x + 5, y: row.y }, to: row, units: {}, cargo: {}, arriveAt: h.clock.now() + 60 * 1000, parentId: null, extra: { link: 1 } });
|
||||||
|
h.advance(2 * 60 * 1000);
|
||||||
|
assert.equal(T.notes(h, a.userId, 'movement_returned').length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Balance pass B1 (docs/BALANCE.md): the second build slot opens at Core router 3; FORMULAS.extraQueueCores (default none) can open more.
|
||||||
|
test('build slots follow the Core router: one, a second from FORMULAS.secondQueueCoreLevel, more from FORMULAS.extraQueueCores', () => {
|
||||||
|
const F = D.FORMULAS;
|
||||||
|
const at = (core) => R.queueSlots({ buildings: { core_router: { type: 'core_router', level: core } } });
|
||||||
|
assert.equal(F.secondQueueCoreLevel, 3, 'the tuned value (B1)');
|
||||||
|
assert.deepEqual([0, 1, 2, 3, 10, 20].map(at), [1, 1, 1, 2, 2, 2], 'default: two slots from the second-slot level, no extra ones');
|
||||||
|
const saved = F.extraQueueCores;
|
||||||
|
try {
|
||||||
|
F.extraQueueCores = [6, 10];
|
||||||
|
assert.deepEqual([2, 3, 5, 6, 9, 10, 20].map(at), [1, 2, 2, 3, 3, 4, 4]);
|
||||||
|
} finally { F.extraQueueCores = saved; }
|
||||||
|
});
|
||||||
114
test/client-alerts.test.js
Normal file
114
test/client-alerts.test.js
Normal file
|
|
@ -0,0 +1,114 @@
|
||||||
|
'use strict';
|
||||||
|
/* The Alerts feed: every notification type the server writes has a describer, and each describer turns the real payload shapes
|
||||||
|
* into a readable title (no raw keys, no "undefined", no "[object Object]"). The browser files cannot be loaded here, so the pure
|
||||||
|
* describers (public/js/alertkinds.js) are run directly and the others are found by reading the sources. */
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const I = require('../public/js/i18n.js');
|
||||||
|
for (const f of fs.readdirSync(path.join(__dirname, '..', 'public', 'js', 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f);
|
||||||
|
const AK = require('../public/js/alertkinds.js');
|
||||||
|
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.js') ? [path.join(dir, e.name)] : []));
|
||||||
|
|
||||||
|
// every notification type the server writes: notify(uid, worldId, 'type', ...), A.notifyAlliance(ctx, id, 'type', ...), notifyWorld(...)
|
||||||
|
function serverTypes() {
|
||||||
|
const out = new Set();
|
||||||
|
for (const f of walk(path.join(ROOT, 'server'))) {
|
||||||
|
const src = fs.readFileSync(f, 'utf8');
|
||||||
|
for (const m of src.matchAll(/\bnotify(?:Alliance|Operator|World)?\(([^'`\n]*?)'([a-z_]+)'/g)) out.add(m[2]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lang = { en: 'en', nb: 'nb' };
|
||||||
|
function ctxFor(l) {
|
||||||
|
return {
|
||||||
|
t: (k, v) => I.t(l, k, v), num: (n) => I.fmtNum(l, n), resName: (r) => I.t(l, 'res.' + r),
|
||||||
|
townName: (id) => (id === 1 ? 'Home POP' : null), clockTime: () => '12:00', dayTime: () => '1 Jan, 12:00',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const T = { resource: 'fiber', amount: 400 }, W = { resource: 'hardware', amount: 300 };
|
||||||
|
const alliance = { id: 7, tag: 'NSP', name: 'North Sea Peering' };
|
||||||
|
// payloads in the shapes the server writes them (grep the notify calls)
|
||||||
|
const SAMPLES = {
|
||||||
|
trade_accepted: { offerId: 3, townId: 1, byTownId: 2, give: T, want: W },
|
||||||
|
trade_completed: { offerId: 3, give: T, want: W },
|
||||||
|
trade_expired: { offerId: 3, townId: 1, returned: T },
|
||||||
|
trade_void: { offerId: 3, townId: 1 },
|
||||||
|
backbone_open: { sites: [{ siteId: 1, index: 0, x: 3, y: 4 }, { siteId: 2, index: 1, x: 5, y: 6 }] },
|
||||||
|
backbone_taken: { siteId: 1, index: 2, x: 10, y: -4, level: 12, by: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' }, from: { allianceId: 8, tag: 'FTC', name: 'Fjord' } },
|
||||||
|
backbone_lost: { siteId: 1, index: 2, x: 10, y: -4, level: 12, by: { allianceId: 8, tag: 'FTC', name: 'Fjord' }, from: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' } },
|
||||||
|
backbone_level: { siteId: 1, index: 2, level: 20 },
|
||||||
|
backbone_delivered: { movementId: 5, siteId: 1, cargo: { fiber: 500, hardware: 0, capital: 120 } },
|
||||||
|
backbone_ship_bounced: { movementId: 5, siteId: 1, cargo: { fiber: 500 } },
|
||||||
|
backbone_won: { allianceId: 7, name: 'North Sea Peering', tag: 'NSP', siteId: 1, endsAt: 1767225600000 },
|
||||||
|
world_ended: { winner: { allianceId: 7, name: 'North Sea Peering', tag: 'NSP', siteId: 1, wonAt: 1 }, endedAt: 1767225600000 },
|
||||||
|
alliance_invite: { inviteId: 1, allianceId: 7, tag: 'NSP', name: 'North Sea Peering', by: 'Alice', expiresAt: 1767225600000 },
|
||||||
|
alliance_invite_declined: { inviteId: 1, allianceId: 7, by: 'Bob' },
|
||||||
|
alliance_member_joined: { allianceId: 7, operatorId: 3, name: 'Bob' },
|
||||||
|
alliance_member_left: { allianceId: 7, operatorId: 3, name: 'Bob', kicked: false },
|
||||||
|
alliance_kicked: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' },
|
||||||
|
alliance_role: { allianceId: 7, tag: 'NSP', from: 'member', role: 'officer' },
|
||||||
|
alliance_leader: { allianceId: 7, operatorId: 3, name: 'Bob', from: 'Alice' },
|
||||||
|
alliance_disbanded: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering', reason: 'disbanded' },
|
||||||
|
diplomacy_proposal: { proposalId: 1, from: alliance, state: 'nap', expiresAt: 1767225600000 },
|
||||||
|
diplomacy_declined: { proposalId: 1, by: alliance, state: 'nap' },
|
||||||
|
diplomacy_changed: { allianceId: 8, other: alliance, from: 'neutral', to: 'war' },
|
||||||
|
diplomacy_cancel_pending: { allianceId: 8, other: alliance, from: 'nap', to: 'neutral', effectiveAt: 1767225600000, startedBy: 7 },
|
||||||
|
diplomacy_cancel_revoked: { allianceId: 8, other: alliance, state: 'nap' },
|
||||||
|
message: { messageId: 4, from: { operatorId: 3, name: 'Bob' } },
|
||||||
|
alliance_message: { messageId: 4, allianceId: 7, tag: 'NSP', from: 'Alice' },
|
||||||
|
};
|
||||||
|
const KNOWN_ELSEWHERE = new Set(['build_done']); // screens/alerts.js
|
||||||
|
|
||||||
|
test('every notification type the server writes has a describer (alertkinds.js, milstate.js or alerts.js)', () => {
|
||||||
|
const have = new Set(Object.keys(AK.make(ctxFor('en'))));
|
||||||
|
const mil = fs.readFileSync(path.join(ROOT, 'public', 'js', 'milstate.js'), 'utf8');
|
||||||
|
for (const m of mil.matchAll(/\bkinds\.([a-z_]+) =/g)) have.add(m[1]);
|
||||||
|
for (const k of KNOWN_ELSEWHERE) have.add(k);
|
||||||
|
const types = serverTypes();
|
||||||
|
assert.ok(types.size >= 40, 'the notify calls were found (' + types.size + ')');
|
||||||
|
const missing = Array.from(types).filter((t) => !have.has(t)).sort();
|
||||||
|
assert.deepStrictEqual(missing, [], 'notification types without an Alerts describer (they would read "Event: <type>")');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('each new describer renders its server payload as readable text in en and nb, with an icon and a jump target', () => {
|
||||||
|
const icons = new Set(fs.readFileSync(path.join(ROOT, 'public', 'icons', 'sprite.svg'), 'utf8').match(/id="i-([a-z_-]+)"/g).map((s) => s.slice(6, -1)));
|
||||||
|
for (const l of Object.keys(lang)) {
|
||||||
|
const kinds = AK.make(ctxFor(l));
|
||||||
|
for (const [type, p] of Object.entries(SAMPLES)) {
|
||||||
|
assert.ok(kinds[type], 'describer for ' + type);
|
||||||
|
const d = kinds[type]({ id: 1, type, payload: p, createdAt: 0 }, p);
|
||||||
|
const text = d.title + ' | ' + d.detail;
|
||||||
|
assert.ok(d.title && d.title.length > 3, l + ' ' + type + ' has a title');
|
||||||
|
assert.ok(!/undefined|\[object|NaN|\{\w+\}|alerts\./.test(text), l + ' ' + type + ' looks raw: ' + text);
|
||||||
|
assert.ok(icons.has(d.icon), type + ' icon ' + d.icon + ' exists in the sprite');
|
||||||
|
assert.ok(typeof d.go === 'string', type + ' jumps somewhere');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('describers survive an empty payload (a newer server field never breaks the feed)', () => {
|
||||||
|
const kinds = AK.make(ctxFor('en'));
|
||||||
|
for (const type of Object.keys(SAMPLES)) assert.doesNotThrow(() => kinds[type]({ id: 1, type, payload: {} }, {}), type);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('diplomacy_changed has two payload shapes and both read well', () => {
|
||||||
|
const k = AK.make(ctxFor('en')).diplomacy_changed;
|
||||||
|
assert.match(k({}, { allianceId: 8, other: alliance, from: 'nap', to: 'neutral' }).title, /\[NSP\].*Neutral/);
|
||||||
|
const d = k({}, { allianceId: 8, otherId: 7, otherTag: 'NSP', from: 'war', to: 'neutral', reason: 'disbanded' });
|
||||||
|
assert.match(d.title, /\[NSP\]/);
|
||||||
|
assert.match(d.detail, /disbanded/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('backbone alerts jump to the world screen, to the right site when the payload has one', () => {
|
||||||
|
const k = AK.make(ctxFor('en'));
|
||||||
|
assert.deepStrictEqual([k.backbone_taken({}, SAMPLES.backbone_taken).go, k.backbone_taken({}, SAMPLES.backbone_taken).params], ['world', { site: 2 }]);
|
||||||
|
assert.strictEqual(k.backbone_won({}, SAMPLES.backbone_won).go, 'world');
|
||||||
|
assert.strictEqual(k.trade_accepted({}, SAMPLES.trade_accepted).go, 'trade');
|
||||||
|
assert.deepStrictEqual(k.trade_accepted({}, SAMPLES.trade_accepted).params, { tab: 'mine' });
|
||||||
|
});
|
||||||
|
|
@ -28,12 +28,15 @@ test('every building, resource and tile type has a player-facing name in both la
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('every error code the client can meet is translated', () => {
|
test('every error code the server can send is translated in en and nb (iterates server/errors.js CODES)', () => {
|
||||||
// codes the current screens can see (auth, build, cancel, rename, map, notifications, tokens) + client-side ones
|
const { CODES } = require('../server/errors');
|
||||||
const codes = ['bad_request', 'validation_failed', 'unauthorized', 'invalid_credentials', 'forbidden', 'not_found', 'conflict', 'request_in_progress',
|
// client-side codes (api.js ApiError) come on top of the server's table
|
||||||
'idempotency_key_reuse', 'payload_too_large', 'rate_limited', 'internal_error', 'signup_closed', 'username_taken', 'world_full', 'unknown_building',
|
const codes = Object.keys(CODES).concat(['network_error', 'unknown']);
|
||||||
'not_buildable', 'max_level', 'requirements_not_met', 'already_queued', 'queue_full', 'not_enough_resources', 'network_error', 'unknown', 'method_not_allowed'];
|
assert.ok(codes.length > 50, 'the CODES table was read');
|
||||||
for (const l of I.LANGS) for (const c of codes) assert.ok(I.strings[l]['err.' + c], l + ' err.' + c);
|
for (const l of I.LANGS) {
|
||||||
|
const missing = codes.filter((c) => !I.strings[l]['err.' + c]);
|
||||||
|
assert.deepStrictEqual(missing, [], l + ' is missing err.<code> translations');
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
test('t() fills placeholders, falls back to en then to the key', () => {
|
test('t() fills placeholders, falls back to en then to the key', () => {
|
||||||
|
|
|
||||||
159
test/client-world.test.js
Normal file
159
test/client-world.test.js
Normal file
|
|
@ -0,0 +1,159 @@
|
||||||
|
'use strict';
|
||||||
|
/* Client side of the end game and trade: pure helpers (endcore.js), the send-dialog options for landing sites and transports (milcore.js),
|
||||||
|
* string coverage of the new screens, and no HTML injection sinks. Browser behaviour was looked at in headless Chromium, not here. */
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const I = require('../public/js/i18n.js');
|
||||||
|
const D = require('../public/js/data.js');
|
||||||
|
const E = require('../public/js/endcore.js');
|
||||||
|
const M = require('../public/js/milcore.js');
|
||||||
|
for (const f of fs.readdirSync(path.join(__dirname, '..', 'public', 'js', 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f);
|
||||||
|
|
||||||
|
const ROOT = path.join(__dirname, '..', 'public', 'js');
|
||||||
|
const site = (o) => Object.assign({ id: 1, index: 0, x: 1, y: 2, holder: null, takenBy: null, takenAt: null, level: 0, maxLevel: 100, progress: 0, pool: { fiber: 0, hardware: 0, capital: 0 }, build: null, next: { toLevel: 1, cost: { fiber: 100, hardware: 100, capital: 100 }, durationMs: 1000 } }, o || {});
|
||||||
|
const holder = (id, tag) => ({ allianceId: id, tag, name: 'Alliance ' + tag });
|
||||||
|
|
||||||
|
test('leading: highest node level, then more sites, then the earlier takeover', () => {
|
||||||
|
assert.strictEqual(E.leading([]), null);
|
||||||
|
assert.strictEqual(E.leading([site(), site({ index: 1 })]), null, 'nobody holds a site');
|
||||||
|
const a = site({ index: 0, holder: holder(1, 'AAA'), level: 10, takenAt: 500 });
|
||||||
|
const b = site({ index: 1, holder: holder(2, 'BBB'), level: 12, takenAt: 900 });
|
||||||
|
assert.strictEqual(E.leading([a, b]).tag, 'BBB');
|
||||||
|
assert.strictEqual(E.leading([a, b]).siteIndex, 1);
|
||||||
|
const a2 = site({ index: 2, holder: holder(1, 'AAA'), level: 12, takenAt: 700 });
|
||||||
|
assert.strictEqual(E.leading([a, b, a2]).tag, 'AAA', 'same level: two sites beat one');
|
||||||
|
assert.strictEqual(E.leading([a, b, a2]).sites, 2);
|
||||||
|
const c = site({ index: 3, holder: holder(3, 'CCC'), level: 12, takenAt: 100 });
|
||||||
|
assert.strictEqual(E.leading([b, c]).tag, 'CCC', 'same level and sites: the earlier takeover');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildProgress, missing and holderKind', () => {
|
||||||
|
assert.strictEqual(E.buildProgress(site(), 5), null);
|
||||||
|
const s = site({ build: { toLevel: 2, startedAt: 1000, dueAt: 3000 } });
|
||||||
|
assert.strictEqual(E.buildProgress(s, 2000), 0.5);
|
||||||
|
assert.strictEqual(E.buildProgress(s, 9000), 1);
|
||||||
|
assert.strictEqual(E.buildProgress(s, 0), 0);
|
||||||
|
assert.deepStrictEqual(E.missing({ fiber: 100, hardware: 50, capital: 0 }, { fiber: 40, hardware: 50, capital: 9 }), { fiber: 60 });
|
||||||
|
assert.deepStrictEqual(E.missing({ fiber: 1 }, null), { fiber: 1 });
|
||||||
|
assert.strictEqual(E.holderKind(site(), 5), 'incumbent');
|
||||||
|
assert.strictEqual(E.holderKind(site({ holder: holder(5, 'X') }), 5), 'mine');
|
||||||
|
assert.strictEqual(E.holderKind(site({ holder: holder(6, 'Y') }), 5), 'rival');
|
||||||
|
assert.strictEqual(E.holderKind(site({ holder: holder(5, 'X') }), null), 'rival');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buildCheck explains why the node cannot be built, in the order the server checks it', () => {
|
||||||
|
const rich = { fiber: 1e6, hardware: 1e6, capital: 1e6 };
|
||||||
|
const ok = site({ pool: rich });
|
||||||
|
const you = { holder: true, canBuild: true, canShip: true, canAttack: false };
|
||||||
|
assert.deepStrictEqual(E.buildCheck(ok, you, false), { ok: true, reason: null });
|
||||||
|
assert.strictEqual(E.buildCheck(ok, you, true).reason, 'ended');
|
||||||
|
assert.strictEqual(E.buildCheck(ok, { holder: true, canBuild: false }, false).reason, 'forbidden');
|
||||||
|
assert.strictEqual(E.buildCheck(ok, { holder: false, canBuild: false }, false).reason, 'forbidden');
|
||||||
|
assert.strictEqual(E.buildCheck(site({ pool: rich, next: null, level: 100 }), you, false).reason, 'max_level');
|
||||||
|
assert.strictEqual(E.buildCheck(site({ pool: rich, build: { toLevel: 2, startedAt: 0, dueAt: 9 } }), you, false).reason, 'already_queued');
|
||||||
|
assert.strictEqual(E.buildCheck(site(), you, false).reason, 'not_enough_resources');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('phaseNow flips to backbone_open at opensAt even before the status is refetched; ended wins', () => {
|
||||||
|
const st = { phase: 'running', opensAt: 1000, ageDays: 40, openDay: 100 };
|
||||||
|
assert.strictEqual(E.phaseNow(st, 999), 'running');
|
||||||
|
assert.strictEqual(E.phaseNow(st, 1000), 'backbone_open');
|
||||||
|
assert.strictEqual(E.phaseNow({ phase: 'ended', opensAt: 1 }, 0), 'ended');
|
||||||
|
assert.strictEqual(E.phaseNow(null, 0), 'running');
|
||||||
|
assert.strictEqual(E.openProgress(st), 0.4);
|
||||||
|
assert.strictEqual(E.openProgress({ ageDays: 500, openDay: 100 }), 1);
|
||||||
|
assert.strictEqual(E.sumCargo({ fiber: 3, capital: 4 }), 7);
|
||||||
|
assert.strictEqual(E.topRows([1, 2, 3], 2).length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('moveOptions on a landing site: scan, attack (needs an alliance, not your own site)', () => {
|
||||||
|
const tile = (b) => ({ type: 'backbone', backbone: Object.assign({ siteId: 1, index: 0, mine: false, canAttack: true }, b) });
|
||||||
|
const home = { port_scanner: 2, script_crew: 10 };
|
||||||
|
const types = (o) => o.map((x) => x.type + (x.ok ? '' : '!'));
|
||||||
|
assert.deepStrictEqual(types(M.moveOptions({ tile: tile(), home, allianceId: 5 })), ['scan', 'attack']);
|
||||||
|
const noAll = M.moveOptions({ tile: tile(), home, allianceId: null });
|
||||||
|
assert.deepStrictEqual(types(noAll), ['scan', 'attack!']);
|
||||||
|
assert.strictEqual(noAll[1].reason, 'no_alliance');
|
||||||
|
const own = M.moveOptions({ tile: tile({ mine: true }), home, allianceId: 5 });
|
||||||
|
assert.strictEqual(own[1].reason, 'own_site');
|
||||||
|
assert.deepStrictEqual(types(M.moveOptions({ tile: tile(), home: {}, allianceId: 5 })), ['scan!', 'attack!']);
|
||||||
|
assert.ok(!M.moveOptions({ tile: tile(), home, allianceId: 5 }).some((o) => ['raid', 'takeover', 'settle', 'reinforce', 'transport'].includes(o.type)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('moveOptions transportOnly: any POP takes a transport (a rival\'s too), nothing else is offered, links decide ok', () => {
|
||||||
|
const rival = { type: 'pop', town: { id: 9, mine: false, owner: { id: 2, protected: true } } };
|
||||||
|
const mine = { type: 'pop', town: { id: 3, mine: true, owner: { id: 1 } } };
|
||||||
|
const home = { script_crew: 10, port_scanner: 3 };
|
||||||
|
const o = M.moveOptions({ tile: rival, home, transport: { links: 2, active: 1 }, transportOnly: true });
|
||||||
|
assert.deepStrictEqual(o, [{ type: 'transport', ok: true, reason: null }]);
|
||||||
|
assert.strictEqual(M.moveOptions({ tile: rival, home, transport: { links: 2, active: 2 }, transportOnly: true })[0].reason, 'links_busy');
|
||||||
|
assert.strictEqual(M.moveOptions({ tile: mine, home, transport: { links: 0, active: 0 }, transportOnly: true })[0].reason, 'no_link');
|
||||||
|
assert.deepStrictEqual(M.moveOptions({ tile: { type: 'land', settle: { possible: true } }, home, transportOnly: true }), [], 'empty land takes no transport');
|
||||||
|
// without the flag a rival POP still gets the hostile types only
|
||||||
|
assert.ok(!M.moveOptions({ tile: rival, home, transport: { links: 2, active: 0 } }).some((x) => x.type === 'transport'));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ strings of the new screens
|
||||||
|
const files = ['screens/trade.js', 'screens/world.js', 'screens/cargo-ui.js', 'screens/reports.js', 'screens/map.js', 'screens/send.js', 'screens/movements.js', 'alertkinds.js'];
|
||||||
|
const SRC = files.map((f) => fs.readFileSync(path.join(ROOT, f), 'utf8')).join('\n');
|
||||||
|
|
||||||
|
test('every static string key the trade / world / report / map / send screens use exists in en and nb', () => {
|
||||||
|
const used = new Set();
|
||||||
|
for (const m of SRC.matchAll(/\b(?:App\.)?t\('([a-zA-Z0-9_.]+)'/g)) if (!m[1].endsWith('.')) used.add(m[1]);
|
||||||
|
for (const m of SRC.matchAll(/\bt\([^()']*\? '([a-z0-9_]+\.[a-zA-Z0-9_.]+)' : '([a-z0-9_]+\.[a-zA-Z0-9_.]+)'/g)) { used.add(m[1]); used.add(m[2]); }
|
||||||
|
assert.ok(used.size > 150, 'found the keys (' + used.size + ')');
|
||||||
|
const missing = [];
|
||||||
|
for (const l of I.LANGS) for (const k of used) if (!I.strings[l][k]) missing.push(l + ' ' + k);
|
||||||
|
assert.deepStrictEqual(missing, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dynamic string keys: tabs, statuses, roles, validation codes, ranking tabs, build refusals, send reasons', () => {
|
||||||
|
const want = ['trd.tab.offers', 'trd.tab.new', 'trd.tab.mine', 'trd.tab.send', 'trd.role.poster', 'trd.role.acceptor', 'wld.rank.operators', 'wld.rank.alliances', 'wld.rank.attackers', 'wld.rank.defenders',
|
||||||
|
'wld.build.why.ended', 'wld.build.why.forbidden', 'send.reason.no_alliance', 'send.reason.own_site', 'send.invalid.no_alliance', 'send.invalid.own_site', 'send.invalid.landing_scan_or_attack_only',
|
||||||
|
'tile.backbone', 'report.type.landing', 'rep.attackerWon', 'rep.defenderWon', 'rep.tab.mine', 'rep.tab.alliance', 'rep.folder.empty', 'rep.share.done', 'rep.share.already', 'nav.trade', 'nav.world', 'screen.trade', 'screen.world']
|
||||||
|
.concat(['all', 'open', 'accepted', 'completed', 'cancelled', 'expired', 'void'].map((s) => 'trd.status.' + s))
|
||||||
|
.concat(['giveRes', 'wantRes', 'giveAmount', 'wantAmount', 'maxDistance', 'terms'].map((s) => 'trd.v.' + s));
|
||||||
|
for (const l of I.LANGS) for (const k of want) assert.ok(I.strings[l][k], l + ' ' + k);
|
||||||
|
// trade_terms paths the rules can report all have a message
|
||||||
|
const R = require('../public/js/rules.js');
|
||||||
|
for (const bad of [{ giveRes: 'x' }, { wantRes: 'x' }, { wantRes: 'fiber' }, { giveAmount: 0 }, { wantAmount: 0 }, { maxDistance: 0 }]) {
|
||||||
|
const r = R.tradeTermsCheck(Object.assign({ giveRes: 'fiber', giveAmount: 100, wantRes: 'hardware', wantAmount: 100, maxDistance: 30 }, bad));
|
||||||
|
assert.ok(!r.ok);
|
||||||
|
assert.ok(I.strings.en['trd.v.' + r.errors[0].path], 'message for ' + r.errors[0].path);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the new screens put no player-controlled text through HTML sinks', () => {
|
||||||
|
const code = SRC.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '');
|
||||||
|
assert.ok(!/innerHTML|insertAdjacentHTML|outerHTML|document\.write/.test(code), 'no HTML injection sinks');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every screen file of the new screens is loaded by index.html, strings before screens', () => {
|
||||||
|
const html = fs.readFileSync(path.join(__dirname, '..', 'public', 'index.html'), 'utf8');
|
||||||
|
const order = (f) => html.indexOf('js/' + f + '"');
|
||||||
|
for (const f of ['strings/alerts.js', 'strings/trade.js', 'strings/world.js', 'endcore.js', 'alertkinds.js', 'screens/cargo-ui.js', 'screens/trade.js', 'screens/world.js']) assert.ok(order(f) > 0, f + ' is in index.html');
|
||||||
|
assert.ok(order('strings/world.js') < order('main.js'), 'strings before the shell');
|
||||||
|
assert.ok(order('endcore.js') < order('screens/world.js'));
|
||||||
|
assert.ok(order('milstate.js') < order('alertkinds.js') && order('main.js') < order('alertkinds.js'), 'alert kinds need App and App.mil');
|
||||||
|
assert.ok(order('screens/cargo-ui.js') < order('screens/trade.js') && order('screens/cargo-ui.js') < order('screens/world.js'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('icons used by the new screens exist in the sprite', () => {
|
||||||
|
const sprite = fs.readFileSync(path.join(__dirname, '..', 'public', 'icons', 'sprite.svg'), 'utf8');
|
||||||
|
const have = new Set((sprite.match(/id="i-([a-z_-]+)"/g) || []).map((s) => s.slice(6, -1)));
|
||||||
|
const used = new Set();
|
||||||
|
for (const f of ['screens/trade.js', 'screens/world.js']) for (const m of fs.readFileSync(path.join(ROOT, f), 'utf8').matchAll(/\bicon\('([a-z_-]+)'/g)) used.add(m[1]);
|
||||||
|
used.delete('b-'); // icon('b-' + building): the building icons
|
||||||
|
used.add('b-' + D.TRANSPORT.building);
|
||||||
|
for (const i of used) assert.ok(have.has(i), 'icon ' + i);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every browser script under public/js parses (a syntax error in one file kills every screen after it)', () => {
|
||||||
|
const vm = require('vm');
|
||||||
|
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.js') ? [path.join(dir, e.name)] : []));
|
||||||
|
const files = walk(ROOT);
|
||||||
|
assert.ok(files.length > 30, 'found the scripts (' + files.length + ')');
|
||||||
|
for (const f of files) assert.doesNotThrow(() => new vm.Script(fs.readFileSync(f, 'utf8'), { filename: f }), f);
|
||||||
|
});
|
||||||
|
|
@ -177,7 +177,7 @@ test('shipping: members feed the stockpile by transport; strangers cannot; a shi
|
||||||
|
|
||||||
assert.equal(err(() => h.run('backboneShip', { userId: b.userId, siteId: site.id, fromTownId: b.townId, cargo: { fiber: 100 } })).code, 'forbidden');
|
assert.equal(err(() => h.run('backboneShip', { userId: b.userId, siteId: site.id, fromTownId: b.townId, cargo: { fiber: 100 } })).code, 'forbidden');
|
||||||
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 100 } })).code, 'not_found', "not your POP");
|
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a.townId, cargo: { fiber: 100 } })).code, 'not_found', "not your POP");
|
||||||
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: 501 } })).code, 'capacity_exceeded');
|
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: site.id, fromTownId: a2.townId, cargo: { fiber: D.TRANSPORT.capacityPerLink + 1 } })).code, 'capacity_exceeded');
|
||||||
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: 9999, fromTownId: a2.townId, cargo: { fiber: 5 } })).code, 'not_found');
|
assert.equal(err(() => h.run('backboneShip', { userId: a2.userId, siteId: 9999, fromTownId: a2.townId, cargo: { fiber: 5 } })).code, 'not_found');
|
||||||
|
|
||||||
const before = stock(a2.townId);
|
const before = stock(a2.townId);
|
||||||
|
|
|
||||||
|
|
@ -13,9 +13,9 @@ test('transport: capacity and links come from the Internet exchange; cargo arriv
|
||||||
const seen = [];
|
const seen = [];
|
||||||
M.hooks.transportArrived.push((ctx, mv, r) => seen.push({ id: mv.id, added: r.added, extra: mv.extra }));
|
M.hooks.transportArrived.push((ctx, mv, r) => seen.push({ id: mv.id, added: r.added, extra: mv.extra }));
|
||||||
const send = (cargo) => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo });
|
const send = (cargo) => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo });
|
||||||
assert.throws(() => send({ fiber: 600 }), (e) => e.code === 'capacity_exceeded');
|
assert.throws(() => send({ fiber: D.TRANSPORT.capacityPerLink + 100 }), (e) => e.code === 'capacity_exceeded');
|
||||||
assert.throws(() => send({ fiber: 0 }), (e) => e.code === 'validation_failed');
|
assert.throws(() => send({ fiber: 0 }), (e) => e.code === 'validation_failed');
|
||||||
assert.throws(() => send({ fiber: 5000 }), (e) => e.code === 'capacity_exceeded');
|
assert.throws(() => send({ fiber: 10 * D.TRANSPORT.capacityPerLink }), (e) => e.code === 'capacity_exceeded');
|
||||||
const noIx = T.addOperator(h, 'no-ix', { x: 12, y: 0, infra: { internet_exchange: 0 } });
|
const noIx = T.addOperator(h, 'no-ix', { x: 12, y: 0, infra: { internet_exchange: 0 } });
|
||||||
assert.throws(() => h.run('sendTransport', { userId: noIx.userId, fromTownId: noIx.townId, toTownId: b.townId, cargo: { fiber: 10 } }), (e) => e.code === 'no_transport_link');
|
assert.throws(() => h.run('sendTransport', { userId: noIx.userId, fromTownId: noIx.townId, toTownId: b.townId, cargo: { fiber: 10 } }), (e) => e.code === 'no_transport_link');
|
||||||
const before = T.town(h, a.townId).fiber;
|
const before = T.town(h, a.townId).fiber;
|
||||||
|
|
|
||||||
|
|
@ -142,7 +142,7 @@ test('loot, cache, siege, loyalty, scan, incumbent, decommission, transport plan
|
||||||
const town = { speed: 1, updatedAt: 0, res: { fiber: 400, hardware: 400, capital: 400, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { internet_exchange: { type: 'internet_exchange', level: 2 }, rack_hall: { type: 'rack_hall', level: 5 } } };
|
const town = { speed: 1, updatedAt: 0, res: { fiber: 400, hardware: 400, capital: 400, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { internet_exchange: { type: 'internet_exchange', level: 2 }, rack_hall: { type: 'rack_hall', level: 5 } } };
|
||||||
assert.equal(R.transportPlan(town, { fiber: 100 }, 0, 0).ok, true);
|
assert.equal(R.transportPlan(town, { fiber: 100 }, 0, 0).ok, true);
|
||||||
assert.equal(R.transportPlan(town, { fiber: 100 }, 2, 0).code, 'no_transport_link');
|
assert.equal(R.transportPlan(town, { fiber: 100 }, 2, 0).code, 'no_transport_link');
|
||||||
assert.equal(R.transportPlan(town, { fiber: 501 }, 0, 0).code, 'capacity_exceeded');
|
assert.equal(R.transportPlan(town, { fiber: D.TRANSPORT.capacityPerLink + 1 }, 0, 0).code, 'capacity_exceeded');
|
||||||
assert.equal(R.transportPlan(town, { fiber: 450 }, 0, 0).code, 'not_enough_resources');
|
assert.equal(R.transportPlan(town, { fiber: 450 }, 0, 0).code, 'not_enough_resources');
|
||||||
assert.equal(R.transportPlan(town, { gold: 5 }, 0, 0).code, 'validation_failed');
|
assert.equal(R.transportPlan(town, { gold: 5 }, 0, 0).code, 'validation_failed');
|
||||||
assert.equal(R.transportPlan(town, {}, 0, 0).code, 'validation_failed');
|
assert.equal(R.transportPlan(town, {}, 0, 0).code, 'validation_failed');
|
||||||
|
|
|
||||||
21
test/report-share-cleanup.test.js
Normal file
21
test/report-share-cleanup.test.js
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
'use strict';
|
||||||
|
/* Regression: sharing a report when no reportCleanup event is pending used to throw (ensureCleanup needs ctx.enqueue, which a plain
|
||||||
|
* command ctx lacks) and surface as a 500. Found in a browser run with hand-made reports. */
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const T = require('./military-helpers');
|
||||||
|
const A = require('../server/alliances');
|
||||||
|
|
||||||
|
test('reportShare works when no cleanup event is pending and then schedules one', () => {
|
||||||
|
const h = T.setup();
|
||||||
|
const a = T.addOperator(h, 'alice');
|
||||||
|
const al = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, 'Alpha', 'ALP', a.opId, h.clock.now()).lastInsertRowid);
|
||||||
|
A.addMember(h.db, al, a.opId, 'leader', h.clock.now());
|
||||||
|
const rid = Number(h.db.run('INSERT INTO reports (world_id, type, created_at, expires_at, summary, data) VALUES (?, ?, ?, ?, ?, ?)', h.worldId, 'scan', h.clock.now(), h.clock.now() + 1000, '{}', '{}').lastInsertRowid);
|
||||||
|
h.db.run('INSERT INTO report_recipients (report_id, user_id, role) VALUES (?, ?, ?)', rid, a.userId, 'attacker');
|
||||||
|
assert.equal(h.db.get("SELECT COUNT(*) n FROM events WHERE type = 'reportCleanup' AND status = 'pending'").n, 0);
|
||||||
|
const r = h.run('reportShare', { userId: a.userId, reportId: rid });
|
||||||
|
assert.equal(r.changed, true);
|
||||||
|
assert.equal(h.db.get("SELECT COUNT(*) n FROM events WHERE type = 'reportCleanup' AND status = 'pending'").n, 1);
|
||||||
|
assert.equal(h.run('reportShare', { userId: a.userId, reportId: rid }).changed, false);
|
||||||
|
});
|
||||||
|
|
@ -84,7 +84,7 @@ test('trade: terms - 1:2 ratio band, capacity, distinct resources, links, resour
|
||||||
const { h, a, b } = traders({ aInfra: { internet_exchange: 1 } });
|
const { h, a, b } = traders({ aInfra: { internet_exchange: 1 } });
|
||||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 249 })).code, 'trade_ratio');
|
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 249 })).code, 'trade_ratio');
|
||||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 100, wantAmount: 201 })).code, 'trade_ratio');
|
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 100, wantAmount: 201 })).code, 'trade_ratio');
|
||||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 500, wantAmount: 501 })).code, 'capacity_exceeded');
|
assert.equal(err(() => post(h, a, a.townId, { giveAmount: D.TRANSPORT.capacityPerLink, wantAmount: D.TRANSPORT.capacityPerLink + 1 })).code, 'capacity_exceeded');
|
||||||
assert.equal(err(() => post(h, a, a.townId, { wantRes: 'fiber' })).code, 'validation_failed');
|
assert.equal(err(() => post(h, a, a.townId, { wantRes: 'fiber' })).code, 'validation_failed');
|
||||||
assert.equal(err(() => post(h, a, a.townId, { giveRes: 'power' })).code, 'validation_failed');
|
assert.equal(err(() => post(h, a, a.townId, { giveRes: 'power' })).code, 'validation_failed');
|
||||||
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 0 })).code, 'validation_failed');
|
assert.equal(err(() => post(h, a, a.townId, { giveAmount: 0 })).code, 'validation_failed');
|
||||||
|
|
|
||||||
126
tools/bot.js
Normal file
126
tools/bot.js
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
#!/usr/bin/env node
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* UPSTREAM bot harness: N headless players against the REAL server code, in-process, on a fake clock.
|
||||||
|
*
|
||||||
|
* node tools/bot.js --players 50 --days 14 --speed 1 [--seed 1] [--strategy-mix builder:12,raider:8,...] [--json out.json]
|
||||||
|
*
|
||||||
|
* Options
|
||||||
|
* --players N bots (default 50) --days N simulated days (default 14)
|
||||||
|
* --speed X world speed (default 1) --seed N world + bot seed (default 1)
|
||||||
|
* --radius N map radius in tiles (default: data.js WORLD_DEFAULTS.mapRadius)
|
||||||
|
* --strategy-mix M e.g. builder:12,raider:8,conqueror:3,turtle:6,expander:8,trader:6,alliancer:7 (default: a mix of all)
|
||||||
|
* --sessions-per-day N every bot plays N short sessions a day (default: per archetype, 3-5)
|
||||||
|
* --always-on every bot acts every --step-min minutes (upper bound of what attention could do)
|
||||||
|
* --step-min N tick of --always-on (default 10) --join-days N joining spread over the first N days (default 2)
|
||||||
|
* --session-min N length of a sitting in minutes (default 5; the first one 20, --first-session-min): a bot whose build
|
||||||
|
* finishes inside its sitting starts the next one, so cheap early builds chain, long ones do not
|
||||||
|
* --endgame-step-min N once the landing sites are open, members of alliances that chase the backbone also act every N minutes
|
||||||
|
* (a final push with high attention; default 0 = off, normal sessions only) --endgame-min-members N (default 3)
|
||||||
|
* --field-policy P marginal (default: keep the production mix at the ratio the player spends, upgrade whatever lags) or balanced
|
||||||
|
* (all fields level up together; a lower bound of player skill)
|
||||||
|
* --no-adapt bots do not answer raids with more defence (default: after being hit a bot trains defence up to 1.25 x the
|
||||||
|
* strongest attack it saw, for 5 days; an upper bound of how defenders react)
|
||||||
|
* --sample-min N economy sampling interval (default 120)
|
||||||
|
* --set A.B.c=V override a data.js value for this run (repeatable, value is JSON), e.g. --set FORMULAS.costGrowth=1.25
|
||||||
|
* Only values the code reads at call time are reached; a constant copied at require time (e.g.
|
||||||
|
* ENDGAME.scanStrength in military/landing.js) is silently not overridden.
|
||||||
|
* --json FILE write the full stats as JSON --quiet print only the verdict line --progress progress dots
|
||||||
|
* --exit-0 never exit non-zero (default: exit 1 when an invariant breaks, 2 on usage errors)
|
||||||
|
*
|
||||||
|
* How it drives the server: srv.commands.run(name, args) - the function every REST route calls - so validation, transactions,
|
||||||
|
* events and notifications are the real ones; HTTP, JSON and scrypt are skipped to keep 50 players x 30 days in well under a
|
||||||
|
* minute. Bots read state through the server's own modules and use rules.js previews; they cannot change anything except by
|
||||||
|
* command. Determinism: every choice comes from a generator seeded with (seed, bot, purpose); the same options give the same stats
|
||||||
|
* (wall-clock numbers under `perf` excepted).
|
||||||
|
*/
|
||||||
|
const path = require('path');
|
||||||
|
const D = require('../public/js/data.js');
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const o = { players: 50, days: 14, speed: 1, seed: 1, radius: D.WORLD_DEFAULTS.mapRadius, mix: '', sessionsPerDay: 0, alwaysOn: false, stepMin: 10, joinDays: 2, sampleMin: 120, sessionMin: 5, firstSessionMin: 20, endgameMinMembers: 3, endgameStepMin: 0, adapt: true, fieldPolicy: 'marginal', set: [], json: null, quiet: false, progress: false, exit0: false };
|
||||||
|
const need = (i, k) => { if (i + 1 >= argv.length) throw new Error('missing value for ' + k); return argv[i + 1]; };
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const a = argv[i];
|
||||||
|
const num = (k) => { const v = Number(need(i, k)); if (!Number.isFinite(v)) throw new Error(k + ' needs a number'); i++; return v; };
|
||||||
|
switch (a) {
|
||||||
|
case '--players': o.players = num(a); break;
|
||||||
|
case '--days': o.days = num(a); break;
|
||||||
|
case '--speed': o.speed = num(a); break;
|
||||||
|
case '--seed': o.seed = num(a); break;
|
||||||
|
case '--radius': o.radius = num(a); break;
|
||||||
|
case '--strategy-mix': o.mix = need(i, a); i++; break;
|
||||||
|
case '--sessions-per-day': o.sessionsPerDay = num(a); break;
|
||||||
|
case '--always-on': o.alwaysOn = true; break;
|
||||||
|
case '--step-min': o.stepMin = num(a); break;
|
||||||
|
case '--join-days': o.joinDays = num(a); break;
|
||||||
|
case '--sample-min': o.sampleMin = num(a); break;
|
||||||
|
case '--session-min': o.sessionMin = num(a); break;
|
||||||
|
case '--first-session-min': o.firstSessionMin = num(a); break;
|
||||||
|
case '--endgame-min-members': o.endgameMinMembers = num(a); break;
|
||||||
|
case '--endgame-step-min': o.endgameStepMin = num(a); break;
|
||||||
|
case '--no-adapt': o.adapt = false; break;
|
||||||
|
case '--field-policy': o.fieldPolicy = need(i, a); i++; if (['marginal', 'balanced'].indexOf(o.fieldPolicy) < 0) throw new Error('--field-policy is marginal or balanced'); break;
|
||||||
|
case '--set': o.set.push(need(i, a)); i++; break;
|
||||||
|
case '--json': o.json = need(i, a); i++; break;
|
||||||
|
case '--quiet': o.quiet = true; break;
|
||||||
|
case '--progress': o.progress = true; break;
|
||||||
|
case '--exit-0': o.exit0 = true; break;
|
||||||
|
case '-h': case '--help': o.help = true; break;
|
||||||
|
default: throw new Error('unknown option ' + a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!(o.players >= 1) || !(o.days > 0) || !(o.speed > 0)) throw new Error('players, days and speed must be positive');
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
// "FORMULAS.costGrowth=1.25" -> mutate the shared data module in place; returns a function that puts everything back.
|
||||||
|
function applyOverrides(list) {
|
||||||
|
const undo = [];
|
||||||
|
for (const spec of list || []) {
|
||||||
|
const eq = spec.indexOf('=');
|
||||||
|
if (eq < 0) throw new Error('--set needs PATH=VALUE: ' + spec);
|
||||||
|
const keys = spec.slice(0, eq).split('.');
|
||||||
|
let value;
|
||||||
|
try { value = JSON.parse(spec.slice(eq + 1)); } catch (e) { throw new Error('--set value must be JSON: ' + spec); }
|
||||||
|
let node = D;
|
||||||
|
for (let i = 0; i < keys.length - 1; i++) {
|
||||||
|
if (!node || typeof node[keys[i]] !== 'object') throw new Error('--set: no such path ' + spec.slice(0, eq));
|
||||||
|
node = node[keys[i]];
|
||||||
|
}
|
||||||
|
const last = keys[keys.length - 1];
|
||||||
|
if (!node || !(last in node)) throw new Error('--set: no such path ' + spec.slice(0, eq));
|
||||||
|
const old = node[last];
|
||||||
|
node[last] = value;
|
||||||
|
undo.push(() => { node[last] = old; });
|
||||||
|
}
|
||||||
|
return () => { for (let i = undo.length - 1; i >= 0; i--) undo[i](); };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Library entry (used by the test): runBot({players, days, speed, seed, ...}) -> stats. Overrides are undone afterwards.
|
||||||
|
async function runBot(opts) {
|
||||||
|
const o = Object.assign({ players: 50, days: 14, speed: 1, seed: 1, radius: D.WORLD_DEFAULTS.mapRadius, mix: '', sessionsPerDay: 0, alwaysOn: false, stepMin: 10, joinDays: 2, sampleMin: 120, sessionMin: 5, firstSessionMin: 20, endgameMinMembers: 3, endgameStepMin: 0, adapt: true, fieldPolicy: 'marginal', set: [] }, opts || {});
|
||||||
|
const restore = applyOverrides(o.set);
|
||||||
|
try {
|
||||||
|
const { runSim } = require('./bot/sim');
|
||||||
|
return await runSim(o);
|
||||||
|
} finally { restore(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
let o;
|
||||||
|
try { o = parseArgs(process.argv.slice(2)); } catch (e) { console.error('tools/bot.js: ' + e.message + ' (see --help)'); process.exit(2); }
|
||||||
|
if (o.help) { console.log(require('fs').readFileSync(__filename, 'utf8').split('*/')[0].replace(/^#!.*\n/, '').replace(/^'use strict';\n/, '').replace(/^\/\*\n?/, '')); return; }
|
||||||
|
if (o.progress) o.progress = (d, n) => process.stderr.write(d % 10 === 0 ? ' ' + d + '/' + n + '\n' : '.');
|
||||||
|
let stats;
|
||||||
|
try { stats = await runBot(o); } catch (e) { console.error('bot run failed: ' + (e && e.stack || e)); process.exit(2); }
|
||||||
|
if (o.json) { require('fs').writeFileSync(path.resolve(o.json), JSON.stringify(stats, null, 1)); }
|
||||||
|
const verdict = stats.invariants.ok ? 'INVARIANTS OK' : 'INVARIANTS BROKEN';
|
||||||
|
if (o.quiet) console.log(verdict + ' (' + stats.perf.wallSeconds + ' s, ' + stats.perf.commands + ' commands)');
|
||||||
|
else { console.log(require('./bot/report').render(stats)); console.log('\n' + verdict); }
|
||||||
|
if (!stats.invariants.ok && !o.exit0) process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { runBot, parseArgs, applyOverrides };
|
||||||
|
|
||||||
|
if (require.main === module) main();
|
||||||
700
tools/bot/bots.js
Normal file
700
tools/bot/bots.js
Normal file
|
|
@ -0,0 +1,700 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Bot players. A bot is a seeded decision procedure that plays only through the server's commands (sim.call), looks at the world
|
||||||
|
* only through what a client could see (view.js) and uses rules.js previews (buildPlan, trainPlan, footprintGate, resolveBattle ...)
|
||||||
|
* to avoid sending commands the rules would refuse. It never touches the database to change anything.
|
||||||
|
*
|
||||||
|
* Archetypes differ in a profile (which buildings they push, how much of their income goes to defence / offence), a session
|
||||||
|
* rate (human cadence: a few short sessions a day, see sim.js) and a few behaviours (raid, farm incumbents, settle, trade,
|
||||||
|
* found/join alliances, play the end game). All choices come from the bot's own seeded generator.
|
||||||
|
*/
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const { makeRng, HOUR, DAY } = require('./util');
|
||||||
|
|
||||||
|
const RES = D.RESOURCES;
|
||||||
|
const MIL = D.MILITARY;
|
||||||
|
|
||||||
|
// target(type, F): level the bot wants of an infrastructure building when its weakest field is at level F.
|
||||||
|
const T = (from, mult, add, max) => ({ from, mult, add: add || 0, max: max || 20 });
|
||||||
|
const BASE = {
|
||||||
|
core_router: T(0, 1.0), rack_hall: T(0, 0.8), battery_bank: T(0, 0.4),
|
||||||
|
research_lab: T(4, 0.4), noc: T(4, 0.3), firewall: T(3, 0.3),
|
||||||
|
internet_exchange: T(4, 0.4, 0, 12), peering_office: T(5, 0.25, 0, 4),
|
||||||
|
};
|
||||||
|
const prof = (over) => Object.assign({}, BASE, over);
|
||||||
|
|
||||||
|
const ARCHETYPES = {
|
||||||
|
builder: {
|
||||||
|
sessions: 4, defDays: 0.25, armyDays: 0, maxPops: 3, popF: 9, trade: 'accept', alliance: 'member',
|
||||||
|
profile: prof({ rollout_depot: T(9, 0.3, 0, 5) }),
|
||||||
|
order: ['core_router', 'rack_hall', 'battery_bank', 'peering_office', 'research_lab', 'noc', 'internet_exchange', 'firewall', 'rollout_depot'],
|
||||||
|
weights: { cable_yard: 1, supply_depot: 1, sales_office: 0.9, substation: 0.6 },
|
||||||
|
},
|
||||||
|
raider: {
|
||||||
|
sessions: 5, defDays: 0.1, armyDays: 1.5, maxPops: 2, popF: 12, trade: 'accept', alliance: 'member', raids: true, incumbents: true,
|
||||||
|
profile: prof({ ops_lab: T(3, 0.5, 0, 12), research_lab: T(3, 0.5), noc: T(3, 0.15, 0, 5), firewall: T(6, 0.15), internet_exchange: T(6, 0.25, 0, 6) }),
|
||||||
|
order: ['core_router', 'rack_hall', 'research_lab', 'ops_lab', 'battery_bank', 'peering_office', 'noc', 'firewall', 'internet_exchange', 'rollout_depot'],
|
||||||
|
weights: { cable_yard: 1, supply_depot: 0.8, sales_office: 0.7, substation: 0.9 }, mix: { fiber: 1, hardware: 0.9, capital: 0.35 },
|
||||||
|
},
|
||||||
|
conqueror: {
|
||||||
|
sessions: 5, defDays: 0.1, armyDays: 1.5, maxPops: 3, popF: 10, trade: 'none', alliance: 'member', raids: true, incumbents: true, conquer: true,
|
||||||
|
profile: prof({ ops_lab: T(3, 0.5, 0, 12), research_lab: T(3, 0.5), noc: T(3, 0.15, 0, 5), rollout_depot: T(8, 0.4, 0, 8), internet_exchange: T(6, 0.25, 0, 6) }),
|
||||||
|
order: ['core_router', 'rack_hall', 'research_lab', 'ops_lab', 'battery_bank', 'rollout_depot', 'peering_office', 'noc', 'firewall', 'internet_exchange'],
|
||||||
|
weights: { cable_yard: 1, supply_depot: 0.9, sales_office: 1, substation: 0.9 },
|
||||||
|
},
|
||||||
|
turtle: {
|
||||||
|
sessions: 3, defDays: 2.0, armyDays: 0, maxPops: 2, popF: 12, trade: 'accept', alliance: 'member',
|
||||||
|
profile: prof({ noc: T(2, 0.6), firewall: T(2, 0.8), research_lab: T(3, 0.5), battery_bank: T(0, 0.5) }),
|
||||||
|
order: ['core_router', 'rack_hall', 'noc', 'firewall', 'battery_bank', 'research_lab', 'peering_office', 'internet_exchange', 'rollout_depot'],
|
||||||
|
weights: { cable_yard: 1, supply_depot: 1, sales_office: 0.6, substation: 0.7 }, mix: { fiber: 1, hardware: 1, capital: 0.3 },
|
||||||
|
},
|
||||||
|
expander: {
|
||||||
|
sessions: 4, defDays: 0.2, armyDays: 0, maxPops: 8, popF: 6, trade: 'accept', alliance: 'member',
|
||||||
|
profile: prof({ core_router: T(0, 1.2), rollout_depot: T(6, 0.5, 0, 6), internet_exchange: T(6, 0.3, 0, 6) }),
|
||||||
|
order: ['core_router', 'rack_hall', 'rollout_depot', 'battery_bank', 'peering_office', 'noc', 'research_lab', 'internet_exchange', 'firewall'],
|
||||||
|
weights: { cable_yard: 1, supply_depot: 1, sales_office: 1, substation: 0.6 }, mix: { fiber: 1, hardware: 0.6, capital: 0.6 },
|
||||||
|
},
|
||||||
|
trader: {
|
||||||
|
sessions: 5, defDays: 0.2, armyDays: 0, maxPops: 3, popF: 10, trade: 'active', alliance: 'member',
|
||||||
|
profile: prof({ internet_exchange: T(3, 0.6, 0, 14), rollout_depot: T(10, 0.3, 0, 5) }),
|
||||||
|
order: ['core_router', 'internet_exchange', 'rack_hall', 'battery_bank', 'peering_office', 'noc', 'research_lab', 'firewall', 'rollout_depot'],
|
||||||
|
weights: { cable_yard: 1, supply_depot: 0.6, sales_office: 0.6, substation: 0.6 }, mix: { fiber: 0.7, hardware: 1, capital: 1 },
|
||||||
|
},
|
||||||
|
alliancer: {
|
||||||
|
sessions: 5, defDays: 0.4, armyDays: 0.3, maxPops: 3, popF: 10, trade: 'accept', alliance: 'founder',
|
||||||
|
profile: prof({ peering_office: T(4, 0.5, 0, 8), ops_lab: T(5, 0.4, 0, 10), research_lab: T(4, 0.5), internet_exchange: T(5, 0.5, 0, 14), rollout_depot: T(10, 0.3, 0, 5) }),
|
||||||
|
order: ['core_router', 'rack_hall', 'peering_office', 'battery_bank', 'research_lab', 'noc', 'ops_lab', 'internet_exchange', 'firewall', 'rollout_depot'],
|
||||||
|
weights: { cable_yard: 1, supply_depot: 1, sales_office: 1, substation: 0.7 },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
|
||||||
|
const sumRes = (o) => RES.reduce((s, r) => s + ((o && o[r]) || 0), 0);
|
||||||
|
const mulCost = (c, n) => { const o = {}; for (const r of RES) o[r] = (c[r] || 0) * n; return o; };
|
||||||
|
|
||||||
|
class Bot {
|
||||||
|
constructor(sim, idx, archetype, ids, o) {
|
||||||
|
this.sim = sim; this.idx = idx; this.archetype = archetype; this.arch = ARCHETYPES[archetype];
|
||||||
|
this.userId = ids.userId; this.operatorId = ids.operatorId; this.name = ids.name;
|
||||||
|
this.rng = makeRng(sim.opts.seed, idx, 0xb07);
|
||||||
|
this.sessionsPerDay = o.sessionsPerDay || this.arch.sessions;
|
||||||
|
this.tz = this.rng.int(-1, 1) * HOUR; // wake-up offset
|
||||||
|
this.nextAt = 0;
|
||||||
|
this.intel = new Map(); // townId -> { at, res, units, fw, rack }
|
||||||
|
this.avoid = new Map(); // townId -> until
|
||||||
|
this.hits = []; // raids/attacks that beat this bot's defence: { at }
|
||||||
|
this.scanPending = new Map(); // townId -> arriveAt
|
||||||
|
this.repCursor = { at: 0, seen: new Set() };
|
||||||
|
this.reserve = {};
|
||||||
|
this.spent = {};
|
||||||
|
this.log = { sessions: 0, builds: 0, trains: 0, raids: 0, incumbents: 0, takeovers: 0, scans: 0, settles: 0, offers: 0, accepts: 0 };
|
||||||
|
this.lastDiploDay = -1;
|
||||||
|
this.firstAllianceTry = 0;
|
||||||
|
this.incCache = null;
|
||||||
|
this.takeoverTargets = new Map();
|
||||||
|
this.armyOverride = 0; this.egForce = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ session schedule (human cadence)
|
||||||
|
// The k-th session of day d: spread over a 16 h waking day (07:00..23:00 + own offset) with jitter. Seeded, so the same bot
|
||||||
|
// keeps the same rhythm in every run.
|
||||||
|
sessionTimes(day, t0) {
|
||||||
|
const n = this.sessionsPerDay;
|
||||||
|
const out = [];
|
||||||
|
const base = t0 + day * DAY + 7 * HOUR + this.tz;
|
||||||
|
const slot = 16 * HOUR / n;
|
||||||
|
for (let k = 0; k < n; k++) {
|
||||||
|
const jr = makeRng(this.sim.opts.seed, this.idx * 131 + day, 0x5e55 + k);
|
||||||
|
out.push(Math.round(base + k * slot + jr() * slot));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ one session
|
||||||
|
// A session is a short sitting (sim.opts.sessionMin, the first one longer): when the build in progress finishes before the
|
||||||
|
// sitting is over the player is still there and starts the next one, so cheap early builds chain, expensive ones do not.
|
||||||
|
session(now) {
|
||||||
|
const sim = this.sim, view = sim.view;
|
||||||
|
if (now > (this.sessionEnd || 0)) {
|
||||||
|
this.sessionEnd = now + (this.log.sessions === 0 ? sim.opts.firstSessionMin : sim.opts.sessionMin) * 60000;
|
||||||
|
this.log.sessions += 1;
|
||||||
|
}
|
||||||
|
this.now = now;
|
||||||
|
this.op = view.operator(this.operatorId);
|
||||||
|
this.readReports(now);
|
||||||
|
this.social(now);
|
||||||
|
let towns = view.towns(this.operatorId);
|
||||||
|
if (!towns.length) return;
|
||||||
|
for (const t of towns) this.econ(t, now);
|
||||||
|
towns = view.towns(this.operatorId);
|
||||||
|
const main = towns[0];
|
||||||
|
this.military(main, towns, now);
|
||||||
|
if (this.arch.raids && R.unitsOnline(main, now)) { this.raids(main, now); this.farmIncumbents(main, now); if (this.arch.conquer) this.conquer(main, towns, now); }
|
||||||
|
this.expand(towns, now);
|
||||||
|
this.trade(towns, now);
|
||||||
|
sim.endgame.step(this, towns, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The time of the next step of the current sitting, or null when the sitting is over (or nothing is running).
|
||||||
|
continuation(now) {
|
||||||
|
const r = this.sim.db.get(`SELECT MIN(e.due_at) AS at FROM events e JOIN towns t ON t.id = e.town_id WHERE e.type = 'buildDone' AND e.status = 'pending' AND t.owner_id = ?`, this.operatorId);
|
||||||
|
if (!r || r.at === null || r.at === undefined) return null;
|
||||||
|
const at = Math.max(now + 1000, r.at + 2000);
|
||||||
|
return at <= this.sessionEnd ? at : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
call(name, args) { return this.sim.call(this, name, args); }
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ economy
|
||||||
|
target(type, F) {
|
||||||
|
const p = this.arch.profile[type];
|
||||||
|
if (!p || F < p.from) return 0;
|
||||||
|
return Math.min(p.max, Math.max(1, Math.ceil(p.mult * F + p.add)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The ordered list of building wishes for a POP: infrastructure that lags behind the fields first, then the next field.
|
||||||
|
wishes(t, now, busy) {
|
||||||
|
const view = this.sim.view;
|
||||||
|
busy = busy || new Set();
|
||||||
|
const fields = view.fieldLevels(t).filter((f) => !busy.has(f.key));
|
||||||
|
const F = this.fieldF(view.fieldLevels(t));
|
||||||
|
const sec = !t.isCapital;
|
||||||
|
const out = [];
|
||||||
|
if (!sec && this.egForce) for (const type of Object.keys(this.egForce)) if (view.level(t, type) < this.egForce[type]) out.push({ key: type, type });
|
||||||
|
// a store that keeps hitting its cap is the first thing a player fixes
|
||||||
|
const cur = R.resourcesAt(t, now);
|
||||||
|
if (RES.every((r) => cur.amounts[r] >= 0.8 * cur.caps.fiber) && !busy.has('rack_hall') && view.level(t, 'rack_hall') < Math.min(20, Math.max(2, F + 1))) out.push({ key: 'rack_hall', type: 'rack_hall' });
|
||||||
|
const order = sec ? ['core_router', 'rack_hall', 'battery_bank'] : this.arch.order;
|
||||||
|
for (const type of order) {
|
||||||
|
const tgt = sec ? Math.min(this.target(type, F), 6) : this.target(type, F);
|
||||||
|
if (view.level(t, type) < tgt && !busy.has(type)) out.push({ key: type, type });
|
||||||
|
}
|
||||||
|
out.push(this.pickField(t, fields, F, now));
|
||||||
|
return out.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The level the infrastructure targets follow: the weakest field under the 'balanced' policy, the mean under 'marginal'.
|
||||||
|
fieldF(fields) {
|
||||||
|
if (!fields.length) return 0;
|
||||||
|
if (this.sim.opts.fieldPolicy === 'balanced') return Math.min(...fields.map((f) => f.level));
|
||||||
|
return Math.floor(fields.reduce((s, f) => s + f.level, 0) / fields.length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 'marginal': what a thoughtful player does - keep the production mix at the ratio the player actually spends (buildings and units
|
||||||
|
// cost Fiber : Hardware : Capital of about 1 : 0.7 : 0.5), so the field type that lags its target share is upgraded next, whatever
|
||||||
|
// level the other fields are at; substations only when power is short (or units are wanted).
|
||||||
|
pickFieldMarginal(t, fields, now) {
|
||||||
|
const rates = R.ratesPerHour(t);
|
||||||
|
const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride;
|
||||||
|
const lowest = (type) => fields.filter((f) => f.type === type && f.level < 20).sort((a, b) => a.level - b.level || (a.key < b.key ? -1 : 1))[0];
|
||||||
|
if (rates.powerNet < 4 + 0.04 * rates.powerOut && (unitsWanted || rates.powerNet < 2)) {
|
||||||
|
const s = lowest('substation');
|
||||||
|
if (s) return { key: s.key, type: s.type };
|
||||||
|
}
|
||||||
|
const mix = this.arch.mix || { fiber: 1, hardware: 0.7, capital: 0.5 };
|
||||||
|
let bestType = null, bestScore = Infinity;
|
||||||
|
for (const type of ['cable_yard', 'supply_depot', 'sales_office']) {
|
||||||
|
const res = D.FIELD_PRODUCES[type];
|
||||||
|
if (!lowest(type)) continue;
|
||||||
|
const score = rates[res] / mix[res];
|
||||||
|
if (score < bestScore) { bestScore = score; bestType = type; }
|
||||||
|
}
|
||||||
|
const f = bestType ? lowest(bestType) : null;
|
||||||
|
return f ? { key: f.key, type: f.type } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
pickField(t, fields, F, now) {
|
||||||
|
if (this.sim.opts.fieldPolicy !== 'balanced') return this.pickFieldMarginal(t, fields, now);
|
||||||
|
const w = this.arch.weights;
|
||||||
|
const rates = R.ratesPerHour(t);
|
||||||
|
const power = rates.powerNet;
|
||||||
|
const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride;
|
||||||
|
const lag = fields.filter((f) => f.level === F);
|
||||||
|
if (!lag.length) return null;
|
||||||
|
// power first when it is short and units are on the way
|
||||||
|
if (unitsWanted && power < 4 + 0.04 * (rates.powerOut)) {
|
||||||
|
const s = lag.find((f) => f.type === 'substation') || fields.filter((f) => f.type === 'substation').sort((a, b) => a.level - b.level)[0];
|
||||||
|
if (s && s.level <= F + 2) return { key: s.key, type: s.type };
|
||||||
|
}
|
||||||
|
const prod = {};
|
||||||
|
for (const f of fields) prod[f.type] = (prod[f.type] || 0) + R.fieldOutputPerHour(f.level);
|
||||||
|
let best = null, bestScore = Infinity;
|
||||||
|
for (const f of lag) {
|
||||||
|
const score = (prod[f.type] || 0) / (w[f.type] || 1);
|
||||||
|
if (score < bestScore) { bestScore = score; best = f; }
|
||||||
|
}
|
||||||
|
return { key: best.key, type: best.type };
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(t, wish, pending, now, depth) {
|
||||||
|
const plan = R.buildPlan(t, wish.key, now, pending);
|
||||||
|
if (plan.code === 'requirements_not_met' && depth < 4) {
|
||||||
|
for (const m of plan.missing) {
|
||||||
|
const sub = this.resolve(t, { key: m.type, type: m.type }, pending, now, depth + 1);
|
||||||
|
if (sub) return sub;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return plan;
|
||||||
|
}
|
||||||
|
|
||||||
|
econ(t0, now) {
|
||||||
|
const sim = this.sim, view = sim.view;
|
||||||
|
let t = t0;
|
||||||
|
let guard = 0;
|
||||||
|
this.reserve[t.id] = null;
|
||||||
|
for (;;) {
|
||||||
|
if (++guard > 4) break;
|
||||||
|
const pending = view.pendingBuilds(t.id);
|
||||||
|
if (pending.length >= R.queueSlots(t)) break;
|
||||||
|
const cur = R.resourcesAt(t, now);
|
||||||
|
const cap = cur.caps.fiber;
|
||||||
|
const overflow = RES.some((r) => cur.amounts[r] >= 0.9 * cap);
|
||||||
|
let acted = false;
|
||||||
|
const list = this.wishes(t, now, new Set(pending.map((p) => p.key)));
|
||||||
|
for (const w of list) {
|
||||||
|
const plan = this.resolve(t, w, pending, now, 0);
|
||||||
|
if (plan.ok) {
|
||||||
|
const r = this.call('build', { townId: t.id, key: plan.key });
|
||||||
|
if (r.ok) { this.log.builds += 1; t = view.town(t.id); acted = true; }
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (plan.code === 'not_enough_resources') {
|
||||||
|
if (!this.reserve[t.id]) this.reserve[t.id] = plan.cost;
|
||||||
|
// storage too small for this cost: grow the Rack hall first
|
||||||
|
if (plan.cost && RES.some((r) => plan.cost[r] > cap) && !pending.some((p) => p.key === 'rack_hall')) {
|
||||||
|
const rp = R.buildPlan(t, 'rack_hall', now, pending);
|
||||||
|
if (rp.ok) { const r = this.call('build', { townId: t.id, key: 'rack_hall' }); if (r.ok) { this.log.builds += 1; t = view.town(t.id); acted = true; } }
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (overflow) continue; // do not waste production: spend on something cheaper
|
||||||
|
// saving for the big item only makes sense when it is near: otherwise the other build slots would sit idle for hours
|
||||||
|
let wait = 0;
|
||||||
|
for (const r of RES) { const need = plan.cost[r] - cur.amounts[r]; if (need > 0) wait = Math.max(wait, cur.rates[r] > 0 ? need / cur.rates[r] : Infinity); }
|
||||||
|
if (wait > 8) continue;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (plan.code === 'queue_full') break;
|
||||||
|
// max_level / already_queued / requirements: next wish
|
||||||
|
}
|
||||||
|
if (!acted) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ units
|
||||||
|
prodTotal(t) { const r = R.ratesPerHour(t); return r.fiber + r.hardware + r.capital; }
|
||||||
|
|
||||||
|
// How many of `unit` can be trained now: affordable (above the reserve), power room, batch limit.
|
||||||
|
affordable(t, unit, now, keepReserve) {
|
||||||
|
const def = R.unitDef(unit);
|
||||||
|
const have = R.resourcesAt(t, now).amounts;
|
||||||
|
const rsv = (keepReserve && this.reserve[t.id]) || null;
|
||||||
|
let n = MIL.maxBatch;
|
||||||
|
for (const r of RES) {
|
||||||
|
const avail = have[r] - (rsv ? Math.min(rsv[r] || 0, have[r] * 0.5) : 0);
|
||||||
|
if (def.cost[r] > 0) n = Math.min(n, Math.floor(avail / def.cost[r]));
|
||||||
|
}
|
||||||
|
// power: new units must fit the steady-state output (units in training count too)
|
||||||
|
const rates = R.ratesPerHour(t);
|
||||||
|
let queuedDraw = 0;
|
||||||
|
for (const b of this.sim.view.trainQueue(t.id)) queuedDraw += R.unitDef(b.unit).draw * b.count;
|
||||||
|
const room = rates.powerNet - queuedDraw - 1;
|
||||||
|
if (def.draw > 0) n = Math.min(n, Math.floor(Math.max(0, room) / def.draw));
|
||||||
|
return Math.max(0, n);
|
||||||
|
}
|
||||||
|
|
||||||
|
trainSome(t, unit, want, now, keepReserve) {
|
||||||
|
const view = this.sim.view;
|
||||||
|
const def = R.unitDef(unit);
|
||||||
|
if (!def) return 0;
|
||||||
|
if (R.unitMissing(t, unit).length) return 0;
|
||||||
|
if (view.trainQueue(t.id, def.building).length >= MIL.maxTrainQueue) return 0;
|
||||||
|
const n = Math.min(want, this.affordable(t, unit, now, keepReserve), 400);
|
||||||
|
if (n < 1) return 0;
|
||||||
|
const r = this.call('train', { townId: t.id, unit, count: n });
|
||||||
|
if (r.ok) { this.log.trains += n; return n; }
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
defenceHave(t) {
|
||||||
|
const home = this.sim.view.home(t.id);
|
||||||
|
return R.defencePower(home, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
military(main, towns, now) {
|
||||||
|
const sim = this.sim, view = sim.view;
|
||||||
|
let t = main;
|
||||||
|
// defence
|
||||||
|
if ((this.arch.defDays > 0 || this.hits.length) && view.level(t, 'noc') >= 1) {
|
||||||
|
const fwm = R.firewallMult(view.level(t, 'firewall'));
|
||||||
|
const target = Math.max(this.arch.defDays * 24 * this.prodTotal(t) * 0.42, // value invested ~ days of production, ~0.42 defence points per resource point
|
||||||
|
this.defMatch(now) / fwm);
|
||||||
|
const have = this.defenceHave(t) + this.queuedDefence(t);
|
||||||
|
if (have < target) {
|
||||||
|
const unit = R.unitMissing(t, 'honeypot').length === 0 ? 'honeypot' : 'soc_analyst';
|
||||||
|
const def = R.unitDef(unit);
|
||||||
|
const want = Math.ceil((target - have) / def.defence);
|
||||||
|
if (this.trainSome(t, unit, want, now, this.arch.armyDays === 0)) t = view.town(t.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// offence
|
||||||
|
if ((this.arch.armyDays > 0 || this.armyOverride) && view.level(t, 'ops_lab') >= 1) {
|
||||||
|
const have = this.armyHave(t);
|
||||||
|
const unit = this.armyOverride ? 'script_crew' : (R.unitMissing(t, 'botnet').length === 0 && this.rng.chance(0.3) ? 'botnet' : 'script_crew');
|
||||||
|
const per = sumRes(R.unitDef('script_crew').cost);
|
||||||
|
const target = this.armyOverride ? this.armyOverride : Math.floor(this.arch.armyDays * 24 * this.prodTotal(t) / per);
|
||||||
|
if (have < target) { if (this.trainSome(t, unit, target - have, now, false)) t = view.town(t.id); }
|
||||||
|
// scouts: a handful
|
||||||
|
if (view.level(t, 'noc') >= 1 && (view.home(t.id).port_scanner || 0) < 6) this.trainSome(t, 'port_scanner', 6 - (view.home(t.id).port_scanner || 0), now, false);
|
||||||
|
this.research(t, now);
|
||||||
|
} else if (this.arch.defDays >= 1 && view.level(t, 'research_lab') >= 3) this.research(t, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
queuedDefence(t) {
|
||||||
|
let v = 0;
|
||||||
|
for (const b of this.sim.view.trainQueue(t.id)) { const d = R.unitDef(b.unit); if (d.role === 'defender') v += d.defence * b.count; }
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
armyHave(t) {
|
||||||
|
const home = this.sim.view.home(t.id);
|
||||||
|
let n = (home.script_crew || 0) + 2 * (home.botnet || 0);
|
||||||
|
for (const b of this.sim.view.trainQueue(t.id)) if (b.unit === 'script_crew') n += b.count; else if (b.unit === 'botnet') n += 2 * b.count;
|
||||||
|
for (const m of this.sim.view.outgoing(this.operatorId)) { const u = JSON.parse(m.units || '{}'); n += (u.script_crew || 0) + 2 * (u.botnet || 0); }
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
research(t, now) {
|
||||||
|
const view = this.sim.view;
|
||||||
|
if (view.researchBusy(t.id)) return;
|
||||||
|
const levels = view.researchLevels(t.id);
|
||||||
|
const wants = this.arch.armyDays > 0 ? [['script_crew', 'attack'], ['port_scanner', 'defence'], ['script_crew', 'defence']] : [['honeypot', 'defence'], ['soc_analyst', 'defence']];
|
||||||
|
for (const [unit, stat] of wants) {
|
||||||
|
const cur = levels[R.researchKey(unit, stat)] || 0;
|
||||||
|
const plan = R.researchPlan(t, unit, stat, cur, false, now, 0);
|
||||||
|
if (plan.ok) {
|
||||||
|
// research competes with buildings: only when the stock is comfortably above the cost
|
||||||
|
const have = R.resourcesAt(t, now).amounts;
|
||||||
|
if (RES.every((r) => have[r] >= 1.6 * plan.cost[r])) { this.call('research', { townId: t.id, unit, stat }); return; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ scouting and raids
|
||||||
|
// After being hit a player matches the strongest attacker they saw (the report shows its attack power): the defence target
|
||||||
|
// becomes 1.25 x that for the next 5 world-adjusted days. Without --no-adapt only; the base target of the archetype still applies.
|
||||||
|
defMatch(now) {
|
||||||
|
if (!this.sim.opts.adapt) return 0;
|
||||||
|
const win = 5 * DAY / this.sim.world.speed;
|
||||||
|
this.hits = this.hits.filter((h) => now - h.at < win);
|
||||||
|
let a = 0;
|
||||||
|
for (const h of this.hits) a = Math.max(a, h.atk);
|
||||||
|
return 1.25 * a;
|
||||||
|
}
|
||||||
|
|
||||||
|
readReports(now) {
|
||||||
|
const view = this.sim.view;
|
||||||
|
for (const rep of view.reportsFor(this.userId, this.repCursor)) {
|
||||||
|
const d = rep.data;
|
||||||
|
if (rep.type === 'scan' && rep.role === 'attacker' && d.target) {
|
||||||
|
this.scanPending.delete(d.target.id);
|
||||||
|
if (d.success && d.intel) {
|
||||||
|
const units = Object.assign({}, d.intel.units.home || {});
|
||||||
|
for (const g of d.intel.units.stationed || []) for (const k of Object.keys(g.units)) units[k] = (units[k] || 0) + g.units[k];
|
||||||
|
const bld = d.intel.buildings;
|
||||||
|
const lvl = (type) => { if (!bld) return null; const b = bld.find((x) => x.type === type); return b ? b.level : 0; };
|
||||||
|
this.intel.set(d.target.id, { at: rep.at, res: d.intel.resources, units, fw: lvl('firewall'), rack: lvl('rack_hall'), online: d.intel.online, loyalty: d.intel.loyalty });
|
||||||
|
} else this.avoid.set(d.target.id, rep.at + 12 * HOUR / this.sim.world.speed);
|
||||||
|
} else if ((rep.type === 'raid' || rep.type === 'attack' || rep.type === 'takeover') && rep.role === 'attacker' && d.defender && d.defender.town) {
|
||||||
|
if (d.outcome !== 'attacker_won') this.avoid.set(d.defender.town.id, rep.at + 24 * HOUR / this.sim.world.speed);
|
||||||
|
} else if ((rep.type === 'raid' || rep.type === 'attack' || rep.type === 'takeover') && rep.role === 'defender' && d.outcome === 'attacker_won') {
|
||||||
|
this.hits.push({ at: rep.at, atk: d.power ? d.power.attack : 0, fw: d.power ? d.power.firewallLevel : 0 }); // somebody got through: a player answers with more defence
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
raids(main, now) {
|
||||||
|
const sim = this.sim, view = sim.view, world = sim.world;
|
||||||
|
const home = Object.assign({}, view.home(main.id));
|
||||||
|
if (!(home.script_crew || home.botnet)) return;
|
||||||
|
const speed = world.speed;
|
||||||
|
const maxDist = 32;
|
||||||
|
const op = this.op;
|
||||||
|
const others = view.otherTowns(this.operatorId).map((o) => Object.assign(o, { dist: R.distance(main.x, main.y, o.x, o.y) })).filter((o) => o.dist <= maxDist).sort((a, b) => a.dist - b.dist);
|
||||||
|
const myAlliance = op.alliance_id;
|
||||||
|
const A = require('../../server/alliances');
|
||||||
|
const rack = view.level(main, 'rack_hall');
|
||||||
|
let scans = Math.min(home.port_scanner || 0, 6);
|
||||||
|
let sent = 0;
|
||||||
|
const evaluated = [];
|
||||||
|
for (const o of others) {
|
||||||
|
if (this.avoid.get(o.id) > now) continue;
|
||||||
|
if (myAlliance && o.ally === myAlliance) continue;
|
||||||
|
const arriveGuess = now + R.movementMs(o.dist, { script_crew: 1 }, speed);
|
||||||
|
if (R.isProtected(o.prot, arriveGuess)) continue;
|
||||||
|
if (A.pactPartners(sim.db, this.operatorId, o.ownerId)) continue;
|
||||||
|
const info = this.intel.get(o.id);
|
||||||
|
const fresh = info && now - info.at < 10 * HOUR / speed;
|
||||||
|
if (!fresh) {
|
||||||
|
if (scans > 0 && (home.port_scanner || 0) > 0 && !(this.scanPending.get(o.id) > now)) {
|
||||||
|
const r = this.call('sendMovement', { fromTownId: main.id, type: 'scan', toTownId: o.id, units: { port_scanner: 2 > (home.port_scanner || 0) ? 1 : 2 } });
|
||||||
|
if (r.ok) { scans -= 1; home.port_scanner -= r.args.units.port_scanner; this.scanPending.set(o.id, r.out.arriveAt); this.log.scans += 1; }
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
evaluated.push({ o, info });
|
||||||
|
}
|
||||||
|
// value each candidate, best loot per travel hour first
|
||||||
|
const cands = [];
|
||||||
|
for (const { o, info } of evaluated) {
|
||||||
|
const fw = info.fw === null || info.fw === undefined ? 3 : info.fw;
|
||||||
|
const rk = info.rack === null || info.rack === undefined ? 3 : info.rack;
|
||||||
|
const defRaw = R.defencePower(info.units, {});
|
||||||
|
const Dv = (defRaw + MIL.defenceBase) * R.firewallMult(fw);
|
||||||
|
const hidden = R.cacheFraction(rk);
|
||||||
|
const lootable = RES.reduce((s, r) => s + info.res[r] * (1 - hidden), 0);
|
||||||
|
if (lootable < 200) continue;
|
||||||
|
cands.push({ o, info, Dv, lootable, score: lootable / Math.max(1, o.dist) });
|
||||||
|
}
|
||||||
|
cands.sort((a, b) => b.score - a.score);
|
||||||
|
for (const c of cands) {
|
||||||
|
if (sent >= 8) break;
|
||||||
|
if (!(home.script_crew || home.botnet)) break;
|
||||||
|
// force: botnets first, then crews, until attack >= 1.3 x defence and the carry covers the loot
|
||||||
|
const units = {};
|
||||||
|
let atk = 0, carry = 0;
|
||||||
|
const order = ['botnet', 'script_crew'];
|
||||||
|
for (const u of order) {
|
||||||
|
const have = home[u] || 0;
|
||||||
|
if (!have) continue;
|
||||||
|
const def = R.unitDef(u);
|
||||||
|
const needAtk = Math.max(0, 1.3 * c.Dv - atk), needCarry = Math.max(0, c.lootable - carry);
|
||||||
|
const n = Math.min(have, Math.max(Math.ceil(needAtk / def.attack), Math.ceil(needCarry / def.carry)));
|
||||||
|
if (n > 0) { units[u] = n; atk += n * def.attack; carry += n * def.carry; }
|
||||||
|
}
|
||||||
|
if (atk < 1.3 * c.Dv) continue;
|
||||||
|
const loot = Math.min(carry, c.lootable);
|
||||||
|
const lossFrac = MIL.raidLossFactor * Math.pow(Math.min(1, c.Dv / atk), MIL.lossExponent);
|
||||||
|
let value = 0; for (const u of Object.keys(units)) value += R.unitValue(u) * units[u];
|
||||||
|
if (loot < 150 || loot < 2.5 * lossFrac * value) continue;
|
||||||
|
const r = this.call('sendMovement', { fromTownId: main.id, type: 'raid', toTownId: c.o.id, units, confirmEndProtection: true });
|
||||||
|
if (r.ok) {
|
||||||
|
for (const u of Object.keys(units)) home[u] -= units[u];
|
||||||
|
this.log.raids += 1; sent += 1;
|
||||||
|
this.avoid.set(c.o.id, now + 3 * HOUR / speed); // the stock is gone, do not hit it again at once
|
||||||
|
this.intel.delete(c.o.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attack incumbent sites for the one-time Hardware bonus (defence is public: the world seed is in /me).
|
||||||
|
farmIncumbents(main, now) {
|
||||||
|
const sim = this.sim, view = sim.view, world = sim.world;
|
||||||
|
if (!this.incCache) {
|
||||||
|
const list = [];
|
||||||
|
const rad = 40;
|
||||||
|
for (let dy = -rad; dy <= rad; dy++) for (let dx = -rad; dx <= rad; dx++) {
|
||||||
|
const x = main.x + dx, y = main.y + dy;
|
||||||
|
if (Math.hypot(dx, dy) > rad) continue;
|
||||||
|
if (R.tileAt(world.seed, world.map_radius, x, y).type === 'incumbent') list.push({ x, y, dist: Math.hypot(dx, dy) });
|
||||||
|
}
|
||||||
|
this.incCache = list.sort((a, b) => a.dist - b.dist);
|
||||||
|
}
|
||||||
|
const taken = new Set(sim.db.all('SELECT x, y FROM incumbent_takes WHERE operator_id = ?', this.operatorId).map((r) => r.x + ',' + r.y));
|
||||||
|
const busy = new Set(view.outgoing(this.operatorId).filter((m) => m.type === 'attack' && !m.toTownId).map((m) => m.tx + ',' + m.ty));
|
||||||
|
const home = Object.assign({}, view.home(main.id));
|
||||||
|
const age = R.worldAgeDays(world.start_at, now, world.speed);
|
||||||
|
let sent = 0;
|
||||||
|
for (const s of this.incCache) {
|
||||||
|
if (sent >= 2) break;
|
||||||
|
const k = s.x + ',' + s.y;
|
||||||
|
if (taken.has(k) || busy.has(k)) continue;
|
||||||
|
if (this.avoid.get('inc' + k) > now) continue;
|
||||||
|
const defence = R.incumbentDefence(world.seed, s.x, s.y, age + s.dist / 8 / 24 * world.speed);
|
||||||
|
const units = {};
|
||||||
|
let atk = 0;
|
||||||
|
for (const u of ['botnet', 'script_crew']) {
|
||||||
|
const have = home[u] || 0;
|
||||||
|
if (!have || atk >= 2.4 * defence) continue;
|
||||||
|
const def = R.unitDef(u);
|
||||||
|
const n = Math.min(have, Math.ceil((2.4 * defence - atk) / def.attack));
|
||||||
|
if (n > 0) { units[u] = n; atk += n * def.attack; }
|
||||||
|
}
|
||||||
|
if (atk < 2.4 * defence) continue;
|
||||||
|
const lossFrac = Math.pow(defence / atk, MIL.lossExponent);
|
||||||
|
let value = 0; for (const u of Object.keys(units)) value += R.unitValue(u) * units[u];
|
||||||
|
if (D.INCUMBENT.hardwareBonus < 1.5 * lossFrac * value) continue;
|
||||||
|
const r = this.call('sendMovement', { fromTownId: main.id, type: 'attack', x: s.x, y: s.y, units });
|
||||||
|
if (r.ok) { for (const u of Object.keys(units)) home[u] -= units[u]; sent += 1; this.log.incumbents += 1; this.avoid.set('inc' + k, now + 2 * HOUR); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hostile takeover of other operators' non-capital POPs: scan, attack with an M&A team, repeat while loyalty is low.
|
||||||
|
conquer(main, towns, now) {
|
||||||
|
const sim = this.sim, view = sim.view, world = sim.world;
|
||||||
|
if (view.level(main, 'rollout_depot') < D.UNITS.ma_team.requires[0].level) return;
|
||||||
|
const home = Object.assign({}, view.home(main.id));
|
||||||
|
const ma = home.ma_team || 0;
|
||||||
|
const A = require('../../server/alliances');
|
||||||
|
const gate = R.footprintGate(towns.length, view.footprint(this.operatorId, now));
|
||||||
|
if (!gate.ok) return;
|
||||||
|
// keep one M&A team per wave in stock
|
||||||
|
const queued = view.trainQueue(main.id, 'rollout_depot').reduce((s, b) => s + (b.unit === 'ma_team' ? b.count : 0), 0);
|
||||||
|
if (ma + queued < 2) this.trainSome(main, 'ma_team', 2 - ma - queued, now, false);
|
||||||
|
if (!ma) return;
|
||||||
|
const others = view.otherTowns(this.operatorId).filter((o) => !o.isCapital && R.distance(main.x, main.y, o.x, o.y) <= 30 && !R.isProtected(o.prot, now + 12 * HOUR));
|
||||||
|
others.sort((a, b) => R.distance(main.x, main.y, a.x, a.y) - R.distance(main.x, main.y, b.x, b.y));
|
||||||
|
for (const o of others.slice(0, 5)) {
|
||||||
|
if (A.pactPartners(sim.db, this.operatorId, o.ownerId)) continue;
|
||||||
|
const info = this.intel.get(o.id);
|
||||||
|
if (!info) continue;
|
||||||
|
const fw = info.fw === null || info.fw === undefined ? 3 : info.fw;
|
||||||
|
const Dv = (R.defencePower(info.units, {}) + MIL.defenceBase) * R.firewallMult(fw);
|
||||||
|
const units = { ma_team: 1 };
|
||||||
|
let atk = 0;
|
||||||
|
for (const u of ['botnet', 'script_crew']) {
|
||||||
|
const have = home[u] || 0; if (!have) continue;
|
||||||
|
const n = Math.min(have, Math.ceil(Math.max(0, 1.4 * Dv - atk) / R.unitDef(u).attack));
|
||||||
|
if (n > 0) { units[u] = n; atk += n * R.unitDef(u).attack; }
|
||||||
|
}
|
||||||
|
if (atk < 1.4 * Dv) continue;
|
||||||
|
const r = this.call('sendMovement', { fromTownId: main.id, type: 'takeover', toTownId: o.id, units, confirmEndProtection: true });
|
||||||
|
if (r.ok) { this.log.takeovers += 1; home.ma_team -= 1; for (const u of Object.keys(units)) if (u !== 'ma_team') home[u] -= units[u]; this.intel.delete(o.id); return; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ expansion
|
||||||
|
expand(towns, now) {
|
||||||
|
const sim = this.sim, view = sim.view, world = sim.world;
|
||||||
|
const own = towns.length;
|
||||||
|
if (own >= this.arch.maxPops) return;
|
||||||
|
const main = towns[0];
|
||||||
|
const fields = view.fieldLevels(main);
|
||||||
|
const F = this.fieldF(fields);
|
||||||
|
if (F < this.arch.popF) return;
|
||||||
|
const fp = view.footprint(this.operatorId, now);
|
||||||
|
const gate = R.footprintGate(own, fp);
|
||||||
|
// crews wherever they are at home
|
||||||
|
let holder = null, have = 0;
|
||||||
|
for (const t of towns) { const n = view.home(t.id).rollout_crew || 0; if (n > have) { have = n; holder = t; } }
|
||||||
|
const depotTown = towns.find((t) => view.level(t, 'rollout_depot') >= 1);
|
||||||
|
if (!depotTown) return;
|
||||||
|
const queued = view.trainQueue(depotTown.id, 'rollout_depot').reduce((s, b) => s + (b.unit === 'rollout_crew' ? b.count : 0), 0);
|
||||||
|
if (have + queued < D.EXPANSION.crews && gate.have >= 0.8 * gate.need) {
|
||||||
|
const fresh = view.town(depotTown.id);
|
||||||
|
this.trainSome(fresh, 'rollout_crew', D.EXPANSION.crews - have - queued, now, false);
|
||||||
|
}
|
||||||
|
if (!gate.ok || have < D.EXPANSION.crews || !holder) return;
|
||||||
|
// choose a tile
|
||||||
|
let best = null, bestScore = -1;
|
||||||
|
for (let i = 0; i < 60; i++) {
|
||||||
|
const base = towns[this.rng.int(0, towns.length - 1)];
|
||||||
|
const ang = this.rng() * Math.PI * 2, rr = 3 + this.rng() * 11;
|
||||||
|
const x = Math.round(base.x + Math.cos(ang) * rr), y = Math.round(base.y + Math.sin(ang) * rr);
|
||||||
|
const tile = R.tileAt(world.seed, world.map_radius, x, y);
|
||||||
|
if (tile.type !== 'land' || R.isBackboneSite(world.seed, world.map_radius, x, y)) continue;
|
||||||
|
if (sim.db.get('SELECT 1 AS x FROM towns WHERE world_id = ? AND x = ? AND y = ?', world.id, x, y)) continue;
|
||||||
|
let nearest = Infinity; for (const t of towns) nearest = Math.min(nearest, R.distance(t.x, t.y, x, y));
|
||||||
|
if (nearest > D.EXPANSION.maxDistance) continue;
|
||||||
|
const b = R.ruralBonus(world.seed, world.map_radius, x, y);
|
||||||
|
const score = b.fiber + b.hardware + b.capital + this.rng() * 0.1;
|
||||||
|
if (score > bestScore) { bestScore = score; best = { x, y }; }
|
||||||
|
}
|
||||||
|
if (!best) return;
|
||||||
|
const r = this.call('sendMovement', { fromTownId: holder.id, type: 'settle', x: best.x, y: best.y, units: { rollout_crew: D.EXPANSION.crews }, wild: ['sales_office', 'cable_yard'] });
|
||||||
|
if (r.ok) this.log.settles += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ trade
|
||||||
|
trade(towns, now) {
|
||||||
|
const mode = this.arch.trade;
|
||||||
|
if (mode === 'none') return;
|
||||||
|
const sim = this.sim, view = sim.view, world = sim.world;
|
||||||
|
const db = sim.db;
|
||||||
|
for (const t0 of towns) {
|
||||||
|
const lvl = view.level(t0, D.TRANSPORT.building);
|
||||||
|
if (lvl < 1) continue;
|
||||||
|
let t = t0;
|
||||||
|
const cur = R.resourcesAt(t, now);
|
||||||
|
const cap = cur.caps.fiber;
|
||||||
|
const fill = {}; for (const r of RES) fill[r] = cur.amounts[r] / cap;
|
||||||
|
const sorted = RES.slice().sort((a, b) => fill[b] - fill[a]);
|
||||||
|
const surplus = sorted[0], deficit = sorted[2];
|
||||||
|
if (fill[surplus] - fill[deficit] < 0.35 || cur.amounts[surplus] < 300) continue;
|
||||||
|
const reach = R.tradeReach(lvl);
|
||||||
|
// take a matching open offer: they give what we lack for what we have too much of
|
||||||
|
const offers = db.all("SELECT * FROM trade_offers WHERE world_id = ? AND status = 'open' AND operator_id != ? AND give_res = ? AND want_res = ? ORDER BY id DESC LIMIT 40", world.id, this.operatorId, deficit, surplus);
|
||||||
|
let done = false;
|
||||||
|
for (const o of offers) {
|
||||||
|
const poster = db.get('SELECT x, y FROM towns WHERE id = ?', o.town_id);
|
||||||
|
if (!poster) continue;
|
||||||
|
const dist = R.distance(t.x, t.y, poster.x, poster.y);
|
||||||
|
if (!R.tradeInRange(dist, o.max_distance, lvl)) continue;
|
||||||
|
if (o.want_amount > cur.amounts[surplus] * 0.5) continue;
|
||||||
|
if (o.give_amount < o.want_amount * 0.9) continue; // not worse than ~1:1
|
||||||
|
const r = this.call('tradeAccept', { offerId: o.id, townId: t.id });
|
||||||
|
if (r.ok) { this.log.accepts += 1; done = true; break; }
|
||||||
|
}
|
||||||
|
if (done || mode !== 'active') continue;
|
||||||
|
// post one of our own (one open offer per POP at a time)
|
||||||
|
const open = db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE town_id = ? AND status = 'open'", t.id).n;
|
||||||
|
if (open >= 1) continue;
|
||||||
|
const give = Math.min(D.TRANSPORT.capacityPerLink, Math.floor((cur.amounts[surplus] - 0.4 * cap) * 0.6));
|
||||||
|
if (give < 100) continue;
|
||||||
|
const want = Math.min(D.TRANSPORT.capacityPerLink, Math.max(50, Math.floor(give * (0.9 + this.rng() * 0.2))));
|
||||||
|
const r = this.call('tradeOffer', { townId: t.id, giveRes: surplus, giveAmount: give, wantRes: deficit, wantAmount: want, maxDistance: Math.max(10, Math.min(reach, 40)) });
|
||||||
|
if (r.ok) this.log.offers += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ alliances and diplomacy
|
||||||
|
social(now) {
|
||||||
|
const sim = this.sim, db = sim.db, view = sim.view, world = sim.world;
|
||||||
|
const A = require('../../server/alliances');
|
||||||
|
const op = this.op;
|
||||||
|
const peering = view.peering(this.operatorId);
|
||||||
|
if (!op.alliance_id) {
|
||||||
|
// accept the first invite
|
||||||
|
const inv = db.get("SELECT id, expires_at FROM alliance_invites WHERE operator_id = ? AND status = 'pending' AND expires_at > ? ORDER BY id LIMIT 1", this.operatorId, now);
|
||||||
|
if (inv && peering >= 1) { const r = this.call('allianceInviteAnswer', { inviteId: inv.id, accept: true }); if (r.ok) return; }
|
||||||
|
if (this.arch.alliance === 'founder' && peering >= 1 && now - this.firstAllianceTry > 6 * HOUR) {
|
||||||
|
this.firstAllianceTry = now;
|
||||||
|
const r = this.call('allianceCreate', { worldId: world.id, name: 'Alliance ' + this.name, tag: 'A' + this.idx });
|
||||||
|
if (r.ok) sim.alliancePlans.set(r.out.allianceId, { leaderBot: this.idx, created: now });
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const m = A.membership(db, this.operatorId);
|
||||||
|
if (!m || m.role !== 'leader') return;
|
||||||
|
const alliance = A.getAlliance(db, m.alliance_id);
|
||||||
|
// recruit: nearby operators without an alliance that have a Peering office
|
||||||
|
const count = A.memberCount(db, alliance.id);
|
||||||
|
if (count < A.effectiveCap(db, alliance)) {
|
||||||
|
const pending = db.get("SELECT COUNT(*) AS n FROM alliance_invites WHERE alliance_id = ? AND status = 'pending' AND expires_at > ?", alliance.id, now).n;
|
||||||
|
if (pending < 4) {
|
||||||
|
const main = view.towns(this.operatorId)[0];
|
||||||
|
const cands = db.all(`SELECT o.id, t.x, t.y FROM operators o JOIN towns t ON t.owner_id = o.id AND t.is_capital = 1 WHERE o.world_id = ? AND o.alliance_id IS NULL AND o.id != ?
|
||||||
|
AND EXISTS (SELECT 1 FROM buildings b JOIN towns tt ON tt.id = b.town_id WHERE tt.owner_id = o.id AND b.type = 'peering_office' AND b.level >= 1)
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM alliance_invites i WHERE i.alliance_id = ? AND i.operator_id = o.id AND i.status = 'pending' AND i.expires_at > ?)`, world.id, this.operatorId, alliance.id, now)
|
||||||
|
.map((c) => ({ id: c.id, d: R.distance(main.x, main.y, c.x, c.y) })).sort((a, b) => a.d - b.d).slice(0, 4 - pending);
|
||||||
|
for (const c of cands) this.call('allianceInvite', { allianceId: alliance.id, operatorId: c.id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// diplomacy, at most once per simulated day: answer proposals, propose a pact to the nearest neighbour, raiders declare war now and then
|
||||||
|
const day = Math.floor((now - sim.t0) / DAY);
|
||||||
|
if (day === this.lastDiploDay) return;
|
||||||
|
this.lastDiploDay = day;
|
||||||
|
for (const p of db.all("SELECT id, state FROM alliance_proposals WHERE to_id = ? AND status = 'pending' AND expires_at > ?", alliance.id, now)) {
|
||||||
|
this.call('diploAnswer', { proposalId: p.id, accept: p.state === 'nap' ? this.rng.chance(0.7) : this.rng.chance(0.4) });
|
||||||
|
}
|
||||||
|
if (count >= 3 && this.rng.chance(0.4)) {
|
||||||
|
const others = db.all('SELECT a.id FROM alliances a WHERE a.world_id = ? AND a.id != ? ORDER BY a.id', world.id, alliance.id);
|
||||||
|
if (others.length) {
|
||||||
|
const o = this.rng.pick(others);
|
||||||
|
const rel = A.relationBetween(db, alliance.id, o.id);
|
||||||
|
if (rel === 'neutral') this.call('diploPropose', { allianceId: alliance.id, targetId: o.id, state: this.rng.chance(0.15) ? 'war' : (this.rng.chance(0.3) ? 'confed' : 'nap') });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { Bot, ARCHETYPES, clamp, mulCost, sumRes };
|
||||||
150
tools/bot/collector.js
Normal file
150
tools/bot/collector.js
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Incremental ingestion of what the server wrote down: reports (battles, scans, settles), and the notifications that carry
|
||||||
|
* numbers the ledger needs (cargo lost at delivery, decommissioned units). Reports are cleaned after 14 days, so the harness
|
||||||
|
* ingests at least once per simulated day and keeps its own totals. Everything here only READS the database.
|
||||||
|
*/
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const { bump, addInto, DAY } = require('./util');
|
||||||
|
|
||||||
|
const RES = D.RESOURCES;
|
||||||
|
const lootValue = (l) => RES.reduce((s, r) => s + ((l && l[r]) || 0), 0);
|
||||||
|
const unitsValue = (u) => Object.keys(u || {}).reduce((s, k) => s + (R.unitDef(k) ? R.unitValue(k) * u[k] : 0), 0);
|
||||||
|
|
||||||
|
function newOpStats() { return { raids: 0, raidWins: 0, raidLoot: 0, raidLostValue: 0, attacks: 0, attackWins: 0, hit: 0, hitLoot: 0, defLostValue: 0, scans: 0, scanOk: 0, incumbent: 0, incumbentWins: 0, incumbentHw: 0 }; }
|
||||||
|
|
||||||
|
class Collector {
|
||||||
|
constructor(db) {
|
||||||
|
this.db = db;
|
||||||
|
// Cursors are (created_at, ids seen at that instant), not plain ids: the report cleanup deletes every expired report and SQLite then
|
||||||
|
// reuses low ids (rowid without AUTOINCREMENT), so "id > last id" would silently skip new reports in a long run.
|
||||||
|
this.rep = { at: 0, seen: new Set() }; this.noteCursor = 0;
|
||||||
|
this.foundedTowns = 0;
|
||||||
|
this.unitsLost = {}; // unit -> count, every way of losing units that the ledger knows about
|
||||||
|
this.unitsConsumed = {}; // crews/teams used up (not battle losses)
|
||||||
|
this.byType = {}; // report type -> count
|
||||||
|
this.battles = { raid: { n: 0, att: 0, loot: 0, lootRes: { fiber: 0, hardware: 0, capital: 0 }, attLost: 0, defLost: 0 }, attack: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 }, takeover: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 } };
|
||||||
|
this.raidSamples = []; // { loot, attLostValue, defLostValue, A, D, win, targetAgeDays, undefended }
|
||||||
|
this.takeovers = { attempted: 0, dropped: 0, blocked: {}, captured: 0, loyaltyDropped: 0 };
|
||||||
|
this.scans = { n: 0, ok: 0, failed: 0, detected: 0, revealed: 0 };
|
||||||
|
this.incumbent = { n: 0, wins: 0, hardware: 0, attLostValue: 0 };
|
||||||
|
this.landing = { n: 0, taken: 0, attLostValue: 0 };
|
||||||
|
this.movementFailed = {};
|
||||||
|
this.settles = { ok: 0 };
|
||||||
|
this.siege = { n: 0, levels: 0 };
|
||||||
|
this.ops = new Map(); // operatorId -> opStats
|
||||||
|
this.notes = {}; // notification type -> count
|
||||||
|
this.cargoLostTotal = { fiber: 0, hardware: 0, capital: 0 };
|
||||||
|
this.cargoLostEvents = 0;
|
||||||
|
this.decommissioned = {};
|
||||||
|
this.unitsOfflineNotes = 0;
|
||||||
|
this.opCreated = new Map();
|
||||||
|
this.bounces = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
op(id) { if (!this.ops.has(id)) this.ops.set(id, newOpStats()); return this.ops.get(id); }
|
||||||
|
created(opId) {
|
||||||
|
if (!this.opCreated.has(opId)) { const o = this.db.get('SELECT created_at FROM operators WHERE id = ?', opId); this.opCreated.set(opId, o ? o.created_at : 0); }
|
||||||
|
return this.opCreated.get(opId);
|
||||||
|
}
|
||||||
|
|
||||||
|
ingest(ledger) {
|
||||||
|
const db = this.db;
|
||||||
|
for (const rep of db.all('SELECT id, type, created_at, data FROM reports WHERE created_at >= ? ORDER BY created_at, id', this.rep.at)) {
|
||||||
|
if (rep.created_at === this.rep.at && this.rep.seen.has(rep.id)) continue;
|
||||||
|
if (rep.created_at > this.rep.at) { this.rep.at = rep.created_at; this.rep.seen = new Set(); }
|
||||||
|
this.rep.seen.add(rep.id);
|
||||||
|
bump(this.byType, rep.type);
|
||||||
|
const d = JSON.parse(rep.data);
|
||||||
|
switch (rep.type) {
|
||||||
|
case 'raid': case 'attack': case 'takeover': this.battle(rep, d); break;
|
||||||
|
case 'scan': this.scan(d); break;
|
||||||
|
case 'scan_detected': this.scans.detected += 1; if (d.identityRevealed) this.scans.revealed += 1; break;
|
||||||
|
case 'incumbent': this.incumbentReport(d); break;
|
||||||
|
case 'landing': this.landingReport(d); break;
|
||||||
|
case 'settle': if (d.success) { this.foundedTowns += 1; bump(this.unitsConsumed, D.EXPANSION.settleUnit, D.EXPANSION.crews); this.settles.ok += 1; } break;
|
||||||
|
case 'movement_failed': bump(this.movementFailed, d.movementType + ':' + d.reason); this.bounces += 1; break;
|
||||||
|
default: break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const rows = db.all("SELECT id, type, payload FROM notifications WHERE id > ? AND type IN ('transport_arrived','movement_returned','units_decommissioned','units_offline') ORDER BY id", this.noteCursor);
|
||||||
|
for (const n of rows) {
|
||||||
|
this.noteCursor = n.id;
|
||||||
|
const p = JSON.parse(n.payload);
|
||||||
|
bump(this.notes, n.type);
|
||||||
|
if (n.type === 'units_decommissioned') { addInto(this.decommissioned, p.units); addInto(this.unitsLost, p.units); }
|
||||||
|
else if (n.type === 'units_offline') this.unitsOfflineNotes += 1;
|
||||||
|
else if (p.cargoLost) {
|
||||||
|
let any = false;
|
||||||
|
for (const r of RES) if (p.cargoLost[r]) { this.cargoLostTotal[r] += p.cargoLost[r]; ledger.sinkLost[r] += p.cargoLost[r]; any = true; }
|
||||||
|
if (any) { ledger.lostEvents += 1; this.cargoLostEvents += 1; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// notifications are numbered independently of the filter above: move the cursor past rows we skipped
|
||||||
|
const top = db.get('SELECT MAX(id) AS m FROM notifications').m || 0;
|
||||||
|
if (top > this.noteCursor) this.noteCursor = top;
|
||||||
|
}
|
||||||
|
|
||||||
|
battle(rep, d) {
|
||||||
|
const kind = rep.type;
|
||||||
|
const b = this.battles[kind];
|
||||||
|
b.n += 1;
|
||||||
|
const win = d.outcome === 'attacker_won';
|
||||||
|
const attLost = d.attacker.units.lost || {};
|
||||||
|
const attLostVal = unitsValue(attLost);
|
||||||
|
let defLost = {};
|
||||||
|
for (const g of d.defender.groups || []) addInto(defLost, g.lost);
|
||||||
|
const defLostVal = unitsValue(defLost);
|
||||||
|
addInto(this.unitsLost, attLost); addInto(this.unitsLost, defLost);
|
||||||
|
const loot = lootValue(d.loot);
|
||||||
|
if (win) b.att += 1;
|
||||||
|
b.loot += loot; b.attLost += attLostVal; b.defLost += defLostVal;
|
||||||
|
if (kind === 'raid') addInto(b.lootRes, d.loot);
|
||||||
|
const aId = d.attacker.operator.id, dId = d.defender.operator.id;
|
||||||
|
const a = this.op(aId), df = this.op(dId);
|
||||||
|
if (kind === 'raid') { a.raids += 1; if (win) a.raidWins += 1; a.raidLoot += loot; a.raidLostValue += attLostVal; }
|
||||||
|
else { a.attacks += 1; if (win) a.attackWins += 1; a.raidLoot += loot; a.raidLostValue += attLostVal; }
|
||||||
|
df.hit += 1; df.hitLoot += loot; df.defLostValue += defLostVal;
|
||||||
|
if (d.siege) { this.siege.n += 1; this.siege.levels += d.siege.from - d.siege.to; }
|
||||||
|
if (d.takeover) {
|
||||||
|
const t = d.takeover;
|
||||||
|
this.takeovers.attempted += 1;
|
||||||
|
if (t.blocked) bump(this.takeovers.blocked, t.blocked);
|
||||||
|
if (t.drop > 0) { this.takeovers.dropped += 1; this.takeovers.loyaltyDropped += t.drop; bump(this.unitsConsumed, D.EXPANSION.conquestUnit, 1); }
|
||||||
|
if (t.captured) this.takeovers.captured += 1;
|
||||||
|
}
|
||||||
|
if (kind === 'raid') {
|
||||||
|
const defenderHome = (d.defender.groups || []).reduce((s, g) => s + R.defencePower(g.sent, {}), 0);
|
||||||
|
this.raidSamples.push({
|
||||||
|
loot, attLost: attLostVal, defLost: defLostVal, A: d.power.attack, D: d.power.defence, win,
|
||||||
|
targetAgeDays: (rep.created_at - this.created(dId)) / DAY, undefended: defenderHome <= 0, at: rep.created_at, attacker: aId, defender: dId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scan(d) {
|
||||||
|
this.scans.n += 1;
|
||||||
|
if (d.success) this.scans.ok += 1; else this.scans.failed += 1;
|
||||||
|
addInto(this.unitsLost, (d.scanners && d.scanners.lost) || {});
|
||||||
|
}
|
||||||
|
incumbentReport(d) {
|
||||||
|
this.incumbent.n += 1;
|
||||||
|
if (d.outcome === 'attacker_won') this.incumbent.wins += 1;
|
||||||
|
if (d.bonus) this.incumbent.hardware += d.bonus.hardware || 0;
|
||||||
|
const lost = (d.attacker.units && d.attacker.units.lost) || {};
|
||||||
|
this.incumbent.attLostValue += unitsValue(lost);
|
||||||
|
addInto(this.unitsLost, lost);
|
||||||
|
const a = this.op(d.attacker.operator.id);
|
||||||
|
a.incumbent += 1; if (d.outcome === 'attacker_won') a.incumbentWins += 1; if (d.bonus) a.incumbentHw += d.bonus.hardware || 0;
|
||||||
|
}
|
||||||
|
landingReport(d) {
|
||||||
|
this.landing.n += 1;
|
||||||
|
if (d.taken) this.landing.taken += 1;
|
||||||
|
const lost = (d.attacker.units && d.attacker.units.lost) || {};
|
||||||
|
this.landing.attLostValue += unitsValue(lost);
|
||||||
|
addInto(this.unitsLost, lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { Collector, lootValue, unitsValue };
|
||||||
226
tools/bot/endgame.js
Normal file
226
tools/bot/endgame.js
Normal file
|
|
@ -0,0 +1,226 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* End game bots: once the landing sites open (world age >= ENDGAME.openDay) every alliance with enough members tries for the
|
||||||
|
* backbone, coordinated through a plan kept in memory (what an alliance would agree in its chat):
|
||||||
|
*
|
||||||
|
* 1. site the site that is cheapest to take for the alliance (static defence, a little distance weight)
|
||||||
|
* 2. striker ONE member with an Ops lab trains an army whose attack beats the site's defence on its own (every attack is
|
||||||
|
* resolved separately against the full static defence, so attacks cannot be added up) and attacks
|
||||||
|
* 3. holders once the alliance holds a site every member ships its spare Fiber/Hardware/Capital to it (transport links, 500
|
||||||
|
* each), anyone starts the next Backbone node level when the stockpile pays for it
|
||||||
|
*
|
||||||
|
* Everything goes through the normal commands; the plan only decides who does what.
|
||||||
|
*/
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const { DAY, HOUR } = require('./util');
|
||||||
|
|
||||||
|
const RES = D.RESOURCES;
|
||||||
|
const EG = D.ENDGAME;
|
||||||
|
|
||||||
|
function createEndgame(sim) {
|
||||||
|
const E = require('../../server/endgame');
|
||||||
|
const A = require('../../server/alliances');
|
||||||
|
const M = require('../../server/military/movements');
|
||||||
|
const log = { opened: null, plans: 0, strikes: 0, strikeWins: 0, shipments: 0, shipped: { fiber: 0, hardware: 0, capital: 0 }, builds: 0, buildErrors: {}, strikeSkips: {}, firstCapture: null, shipLinks: 0, wins: null };
|
||||||
|
const plans = sim.alliancePlans;
|
||||||
|
const bump = (o, k) => { o[k] = (o[k] || 0) + 1; };
|
||||||
|
|
||||||
|
const isOpen = (now) => E.isOpen(sim.world, now);
|
||||||
|
|
||||||
|
function members(allianceId) {
|
||||||
|
return sim.bots.filter((b) => { const op = sim.view.operator(b.operatorId); return op && op.alliance_id === allianceId; });
|
||||||
|
}
|
||||||
|
|
||||||
|
function centroid(allianceId) {
|
||||||
|
const ms = members(allianceId);
|
||||||
|
let x = 0, y = 0, n = 0;
|
||||||
|
for (const b of ms) { const t = sim.view.towns(b.operatorId)[0]; if (t) { x += t.x; y += t.y; n += 1; } }
|
||||||
|
return n ? { x: x / n, y: y / n } : { x: 0, y: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the status endpoint shows: every site, with the stored row if somebody touched it, else the incumbent's untouched site.
|
||||||
|
function siteRows(now) {
|
||||||
|
return E.siteStates(sim.db, sim.world, now).map(({ site, row }) => row || { id: null, idx: site.index, x: site.x, y: site.y, holder_alliance_id: null, level: 0, build_to: null, fiber: 0, hardware: 0, capital: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const defenceAt = (s, at) => R.backboneDefence(sim.world.seed, s.x, s.y, E.ageDays(sim.world, at), s.level);
|
||||||
|
|
||||||
|
function choose(plan, allianceId, now) {
|
||||||
|
const c = centroid(allianceId);
|
||||||
|
let best = null, bestScore = Infinity;
|
||||||
|
for (const s of siteRows(now)) {
|
||||||
|
if (s.holder_alliance_id === allianceId) { best = s; bestScore = -1; break; }
|
||||||
|
if (s.holder_alliance_id) {
|
||||||
|
const rel = A.relationBetween(sim.db, allianceId, s.holder_alliance_id);
|
||||||
|
if (rel === 'nap' || rel === 'confed') continue;
|
||||||
|
}
|
||||||
|
const score = defenceAt(s, now + 6 * HOUR) * (1 + R.distance(c.x, c.y, s.x, s.y) / 60);
|
||||||
|
if (score < bestScore) { bestScore = score; best = s; }
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The member who strikes: highest production with an Ops lab (or the best candidate to get one).
|
||||||
|
function pickStriker(allianceId) {
|
||||||
|
let best = null, bestScore = -1;
|
||||||
|
for (const b of members(allianceId)) {
|
||||||
|
if (b.archetype === 'turtle') continue;
|
||||||
|
const t = sim.view.towns(b.operatorId)[0];
|
||||||
|
if (!t) continue;
|
||||||
|
const prod = R.ratesPerHour(t);
|
||||||
|
const score = (prod.fiber + prod.hardware + prod.capital) * (1 + sim.view.level(t, 'ops_lab'));
|
||||||
|
if (score > bestScore) { bestScore = score; best = b; }
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
function armyAttack(t, home, research) {
|
||||||
|
return R.attackPower({ script_crew: home.script_crew || 0, botnet: home.botnet || 0 }, research);
|
||||||
|
}
|
||||||
|
|
||||||
|
function step(bot, towns, now) {
|
||||||
|
if (!isOpen(now) || sim.world.status === 'ended') return;
|
||||||
|
if (log.opened === null) log.opened = (now - sim.t0) / DAY;
|
||||||
|
const op = bot.op;
|
||||||
|
if (!op || !op.alliance_id) return;
|
||||||
|
const allianceId = op.alliance_id;
|
||||||
|
let plan = plans.get(allianceId);
|
||||||
|
if (!plan) { plan = { created: now }; plans.set(allianceId, plan); }
|
||||||
|
const mem = A.memberCount(sim.db, allianceId);
|
||||||
|
if (mem < sim.opts.endgameMinMembers) return;
|
||||||
|
const main = towns[0];
|
||||||
|
|
||||||
|
// (re)plan once a day
|
||||||
|
const day = Math.floor((now - sim.t0) / DAY);
|
||||||
|
if (plan.planDay !== day) {
|
||||||
|
plan.planDay = day;
|
||||||
|
if (!plan.siteHeld) {
|
||||||
|
const site = choose(plan, allianceId, now);
|
||||||
|
if (site) { if (!plan.site || plan.site.idx !== site.idx) log.plans += 1; plan.site = { idx: site.idx, x: site.x, y: site.y }; }
|
||||||
|
}
|
||||||
|
const striker = pickStriker(allianceId);
|
||||||
|
if (striker) plan.striker = striker.idx;
|
||||||
|
}
|
||||||
|
if (!plan.site) return;
|
||||||
|
const row = siteRows(now).find((r) => r.idx === plan.site.idx);
|
||||||
|
plan.siteHeld = !!(row && row.holder_alliance_id === allianceId);
|
||||||
|
|
||||||
|
if (plan.siteHeld) { hold(bot, towns, row, now); return; }
|
||||||
|
// not ours yet: the striker prepares and attacks, the others carry on with their economy
|
||||||
|
bot.egForce = null;
|
||||||
|
if (plan.striker === bot.idx) strike(bot, main, plan, row, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- striker
|
||||||
|
function strike(bot, main, plan, row, now) {
|
||||||
|
const view = sim.view;
|
||||||
|
const site = row || { x: plan.site.x, y: plan.site.y, level: 0 };
|
||||||
|
const flight = R.movementMs(R.distance(main.x, main.y, site.x, site.y), { script_crew: 1 }, sim.world.speed);
|
||||||
|
const dv = defenceAt({ x: site.x, y: site.y, level: site.level || 0 }, now + flight);
|
||||||
|
const research = view.researchLevels(main.id);
|
||||||
|
const mult = R.researchMult(R.researchLevel(research, 'script_crew', 'attack'));
|
||||||
|
const need = Math.ceil(1.12 * dv / (R.unitDef('script_crew').attack * mult));
|
||||||
|
bot.egForce = { ops_lab: 6, research_lab: 5, noc: 1 }; // build what the army needs
|
||||||
|
bot.armyOverride = need;
|
||||||
|
const home = view.home(main.id);
|
||||||
|
const attack = armyAttack(main, home, research);
|
||||||
|
if (attack >= 1.08 * dv) {
|
||||||
|
const units = {};
|
||||||
|
for (const u of ['script_crew', 'botnet']) if (home[u]) units[u] = home[u];
|
||||||
|
const r = bot.call('sendMovement', { fromTownId: main.id, type: 'attack', x: site.x, y: site.y, units });
|
||||||
|
if (r.ok) log.strikes += 1; else bump(log.strikeSkips, r.code);
|
||||||
|
} else bump(log.strikeSkips, 'army_short');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- holders: ship and build
|
||||||
|
function hold(bot, towns, row, now) {
|
||||||
|
const view = sim.view;
|
||||||
|
// start the next level when the stockpile pays for it
|
||||||
|
if (!row.build_to && row.level < EG.maxLevel) {
|
||||||
|
const cost = R.backboneCost(row.level + 1);
|
||||||
|
if (RES.every((r) => row[r] >= cost[r])) {
|
||||||
|
const r = bot.call('backboneBuild', { siteId: row.id });
|
||||||
|
if (r.ok) log.builds += 1; else bump(log.buildErrors, r.code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (row.level >= EG.maxLevel) return;
|
||||||
|
// ship: need = next level (and the one after) minus what is already there / on the road
|
||||||
|
const want = {};
|
||||||
|
const c1 = R.backboneCost(row.level + 1), c2 = R.backboneCost(Math.min(EG.maxLevel, row.level + 2));
|
||||||
|
for (const r of RES) want[r] = Math.max(0, c1[r] + c2[r] - row[r]);
|
||||||
|
const roads = sim.db.all("SELECT cargo FROM movements WHERE status = 'out' AND type = 'transport' AND json_extract(extra, '$.siteId') = ?", row.id);
|
||||||
|
for (const m of roads) { const cg = JSON.parse(m.cargo); for (const r of RES) want[r] = Math.max(0, want[r] - (cg[r] || 0)); }
|
||||||
|
for (const t0 of towns) {
|
||||||
|
let t = t0;
|
||||||
|
const lvl = view.level(t, D.TRANSPORT.building);
|
||||||
|
for (let i = 0; i < lvl; i++) {
|
||||||
|
if (M.activeLinks(sim.db, t.id) >= lvl) break;
|
||||||
|
const cur = R.resourcesAt(t, now);
|
||||||
|
const cap = cur.caps.fiber;
|
||||||
|
const cargo = {};
|
||||||
|
let room = D.TRANSPORT.capacityPerLink;
|
||||||
|
const order = RES.slice().sort((a, b) => want[b] - want[a]);
|
||||||
|
for (const r of order) {
|
||||||
|
const spare = Math.max(0, cur.amounts[r] - 0.12 * cap);
|
||||||
|
const give = Math.floor(Math.min(room, spare, want[r]));
|
||||||
|
if (give > 0) { cargo[r] = give; room -= give; }
|
||||||
|
}
|
||||||
|
let total = 0; for (const r of RES) total += cargo[r] || 0;
|
||||||
|
if (total < 100) break;
|
||||||
|
const res = bot.call('backboneShip', { siteId: row.id, fromTownId: t.id, cargo });
|
||||||
|
if (!res.ok) break;
|
||||||
|
log.shipments += 1; log.shipLinks += 1;
|
||||||
|
for (const r of RES) { log.shipped[r] += cargo[r] || 0; want[r] = Math.max(0, want[r] - (cargo[r] || 0)); }
|
||||||
|
t = view.town(t.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const x0 = (site) => { const p = R.backboneSites(sim.world.seed, sim.world.map_radius).find((q) => q.index === site.idx); return p || { x: 0, y: 0 }; };
|
||||||
|
|
||||||
|
function summary(now) {
|
||||||
|
const world = sim.db.get('SELECT * FROM worlds WHERE id = ?', sim.world.id);
|
||||||
|
const age = E.ageDays(world, now);
|
||||||
|
if (age < EG.openDay && !log.opened) return { open: false, ageDays: age, openDay: EG.openDay };
|
||||||
|
const sites = sim.db.all('SELECT * FROM landing_sites WHERE world_id = ? ORDER BY idx', sim.world.id).map((s) => {
|
||||||
|
const contrib = sim.db.get('SELECT COALESCE(SUM(fiber),0) AS f, COALESCE(SUM(hardware),0) AS h, COALESCE(SUM(capital),0) AS c, COUNT(*) AS n FROM landing_contributions WHERE site_id = ?', s.id);
|
||||||
|
const a = s.holder_alliance_id ? sim.db.get('SELECT tag FROM alliances WHERE id = ?', s.holder_alliance_id) : null;
|
||||||
|
const sunk = { fiber: 0, hardware: 0, capital: 0 };
|
||||||
|
for (let l = 1; l <= s.level; l++) { const c = R.backboneCost(l); for (const r of RES) sunk[r] += c[r]; }
|
||||||
|
const total = contrib.f + contrib.h + contrib.c;
|
||||||
|
const sinceTaken = s.taken_at ? Math.max(1e-9, (now - s.taken_at) / DAY) : null;
|
||||||
|
const rest = { fiber: 0, hardware: 0, capital: 0 };
|
||||||
|
for (let l = s.level + 1; l <= EG.maxLevel; l++) { const c = R.backboneCost(l); for (const r of RES) rest[r] += c[r]; }
|
||||||
|
const restTotal = rest.fiber + rest.hardware + rest.capital;
|
||||||
|
const rate = sinceTaken ? total / sinceTaken : 0;
|
||||||
|
return { idx: s.idx, level: s.level, holder: a ? a.tag : null, takenAt: s.taken_at ? (s.taken_at - sim.t0) / DAY : null, stock: { fiber: s.fiber, hardware: s.hardware, capital: s.capital }, contributors: contrib.n, shippedIn: { fiber: contrib.f, hardware: contrib.h, capital: contrib.c }, builtCost: sunk,
|
||||||
|
shippedPerDay: Math.round(rate), daysToLevel100: rate > 0 ? Math.round(restTotal / rate) : null, sinceTaken };
|
||||||
|
});
|
||||||
|
const remaining = { fiber: 0, hardware: 0, capital: 0 };
|
||||||
|
let bestLevel = 0;
|
||||||
|
for (const s of sites) bestLevel = Math.max(bestLevel, s.level);
|
||||||
|
for (let l = bestLevel + 1; l <= EG.maxLevel; l++) { const c = R.backboneCost(l); for (const r of RES) remaining[r] += c[r]; }
|
||||||
|
// the biggest army any single POP holds (an attack is one movement from one POP): can anybody still take a built-up site?
|
||||||
|
const perTown = {};
|
||||||
|
for (const r of sim.db.all('SELECT town_id, unit, count FROM town_units')) { (perTown[r.town_id] = perTown[r.town_id] || {})[r.unit] = r.count; }
|
||||||
|
let maxPopAttack = 0;
|
||||||
|
for (const id of Object.keys(perTown)) maxPopAttack = Math.max(maxPopAttack, R.attackPower(perTown[id], {}));
|
||||||
|
const bestDefence = sites.filter((x) => x.level > 0).reduce((m, x) => Math.max(m, R.backboneDefence(sim.world.seed, x0(x).x, x0(x).y, E.ageDays(world, now), x.level)), 0);
|
||||||
|
const daysSinceOpen = Math.max(1e-9, (now - sim.t0) / DAY - (log.opened || 0));
|
||||||
|
const shippedTotal = RES.reduce((s, r) => s + log.shipped[r], 0);
|
||||||
|
const perDay = shippedTotal / daysSinceOpen;
|
||||||
|
const remainTotal = RES.reduce((s, r) => s + remaining[r], 0);
|
||||||
|
const links = sim.db.get("SELECT COUNT(*) AS n FROM towns").n;
|
||||||
|
return {
|
||||||
|
open: true, ageDays: age, openedAtSimDay: log.opened, plans: log.plans, strikes: log.strikes, strikeSkips: log.strikeSkips, landingReports: sim.col.landing, shipments: log.shipments, shippedTotal, shipped: log.shipped,
|
||||||
|
maxPopAttackNoResearch: Math.round(maxPopAttack), bestHeldSiteDefenceNow: bestDefence, shippedPerSimDay: Math.round(perDay), buildsStarted: log.builds, buildErrors: log.buildErrors, sites, bestLevel,
|
||||||
|
remainingToLevel100: remaining, remainingTotal: remainTotal, simDaysToFinishAtThisRate: perDay > 0 ? Math.round(remainTotal / perDay) : null,
|
||||||
|
winner: world.winner_alliance_id ? { allianceId: world.winner_alliance_id, tag: world.winner_tag, wonAtSimDay: (world.won_at - sim.t0) / DAY } : null, worldStatus: world.status, towns: links,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return { step, summary, isOpen, log, plans };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createEndgame };
|
||||||
164
tools/bot/ledger.js
Normal file
164
tools/bot/ledger.js
Normal file
|
|
@ -0,0 +1,164 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Conservation ledger for the bot harness.
|
||||||
|
*
|
||||||
|
* RESOURCES. Pools that hold Fiber/Hardware/Capital: POP stock (stored columns, settled values), open trade escrow, cargo of
|
||||||
|
* movements that are `out`, and landing-site stockpiles. The identity checked at every checkpoint:
|
||||||
|
*
|
||||||
|
* pools_now = pools_at_start + sources + production - sinks (to within rounding of reported losses)
|
||||||
|
*
|
||||||
|
* sources the start stock of every operator and of every founded POP, the incumbent Hardware bonus
|
||||||
|
* production EXACT: every `UPDATE towns SET fiber..., res_at ...` (state.settle) writes the lazily grown stock back; the tap
|
||||||
|
* on db.run reads the previous stored value and books the difference. A transaction that rolls back discards its
|
||||||
|
* bookings (db.tx is tapped too), so only committed settles count. Caps are already inside the stored numbers.
|
||||||
|
* sinks build/train/research costs (from the command results), Backbone node levels (from landing_sites), cargo that
|
||||||
|
* did not fit the Rack hall (`cargoLost` in notifications), trade escrow refunds clipped by the Rack hall cap
|
||||||
|
* (tap on the refund statement)
|
||||||
|
*
|
||||||
|
* Anything else is DRIFT: a leak or a duplication in the server (or a missing sink here). Drift is printed and fails the run.
|
||||||
|
*
|
||||||
|
* UNITS. units_alive = trained - lost, where alive = home + stationed + in `out` movements; trained = `trainDone` events that
|
||||||
|
* ran; lost = battle/scan/incumbent/landing reports, decommission notifications, 3 crews per founded POP, 1 M&A team per loyalty drop.
|
||||||
|
*/
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
|
||||||
|
const RES = D.RESOURCES;
|
||||||
|
const zero = () => ({ fiber: 0, hardware: 0, capital: 0 });
|
||||||
|
const addRes = (a, b) => { for (const r of RES) a[r] += (b && b[r]) || 0; return a; };
|
||||||
|
|
||||||
|
const SETTLE_SQL = 'UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ?, res_at = ?, loyalty = ?, loyalty_at = ? WHERE id = ?';
|
||||||
|
const REFUND_RE = /^UPDATE towns SET (fiber|hardware|capital) = \? WHERE id = \?$/;
|
||||||
|
const CLOSE_PREFIX = 'UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?';
|
||||||
|
|
||||||
|
class Ledger {
|
||||||
|
constructor(db) {
|
||||||
|
this.db = db;
|
||||||
|
this.production = zero(); // exact, committed settles only
|
||||||
|
this.sinkCosts = zero(); // build / train / research (command results)
|
||||||
|
this.sinkLost = zero(); // cargoLost notifications
|
||||||
|
this.lostEvents = 0;
|
||||||
|
this.sinkClip = zero(); // trade refund clipped by the Rack hall cap
|
||||||
|
this.clipEvents = 0;
|
||||||
|
this.sourceStart = zero(); // operators' start stock
|
||||||
|
this.stack = [];
|
||||||
|
this.closing = null;
|
||||||
|
this.t = { settles: 0 };
|
||||||
|
this.installed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
frame() { return this.stack.length ? this.stack[this.stack.length - 1] : null; }
|
||||||
|
book(prodDelta, clip, clipN) {
|
||||||
|
const f = this.frame();
|
||||||
|
if (f) { addRes(f.prod, prodDelta); addRes(f.clip, clip); f.clipN += clipN; f.settles += 1; }
|
||||||
|
else { addRes(this.production, prodDelta); addRes(this.sinkClip, clip); this.clipEvents += clipN; this.t.settles += 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
install() {
|
||||||
|
if (this.installed) return;
|
||||||
|
this.installed = true;
|
||||||
|
const db = this.db, self = this;
|
||||||
|
const run = db.run.bind(db), tx = db.tx.bind(db);
|
||||||
|
db.run = function tappedRun(sql, ...p) {
|
||||||
|
if (sql === SETTLE_SQL) {
|
||||||
|
const prev = db.get('SELECT fiber, hardware, capital FROM towns WHERE id = ?', p[8]);
|
||||||
|
if (prev) self.book({ fiber: p[0] - prev.fiber, hardware: p[1] - prev.hardware, capital: p[2] - prev.capital }, zero(), 0);
|
||||||
|
} else if (sql === CLOSE_PREFIX) {
|
||||||
|
self.closing = p[2];
|
||||||
|
} else {
|
||||||
|
const m = REFUND_RE.exec(sql);
|
||||||
|
if (m && self.closing !== null) {
|
||||||
|
const prev = db.get('SELECT ' + m[1] + ' AS v FROM towns WHERE id = ?', p[1]);
|
||||||
|
const off = db.get('SELECT give_amount, give_res FROM trade_offers WHERE id = ?', self.closing);
|
||||||
|
if (prev && off && off.give_res === m[1]) {
|
||||||
|
const credit = p[0] - prev.v;
|
||||||
|
const clip = Math.max(0, off.give_amount - credit);
|
||||||
|
if (clip > 1e-9) { const c = zero(); c[m[1]] = clip; self.book(zero(), c, 1); }
|
||||||
|
}
|
||||||
|
self.closing = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return run(sql, ...p);
|
||||||
|
};
|
||||||
|
db.tx = function tappedTx(fn) {
|
||||||
|
const f = { prod: zero(), clip: zero(), clipN: 0, settles: 0 };
|
||||||
|
self.stack.push(f);
|
||||||
|
let out;
|
||||||
|
try { out = tx(fn); } catch (e) { self.stack.pop(); throw e; }
|
||||||
|
self.stack.pop();
|
||||||
|
const parent = self.frame();
|
||||||
|
if (parent) { addRes(parent.prod, f.prod); addRes(parent.clip, f.clip); parent.clipN += f.clipN; parent.settles += f.settles; }
|
||||||
|
else { addRes(self.production, f.prod); addRes(self.sinkClip, f.clip); self.clipEvents += f.clipN; self.t.settles += f.settles; }
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
sinkCost(cost) { addRes(this.sinkCosts, cost); }
|
||||||
|
|
||||||
|
// ---- pools (committed DB state) ----
|
||||||
|
pools() {
|
||||||
|
const db = this.db;
|
||||||
|
const stock = zero(), escrow = zero(), cargo = zero(), sites = zero();
|
||||||
|
const s = db.get('SELECT COALESCE(SUM(fiber),0) AS fiber, COALESCE(SUM(hardware),0) AS hardware, COALESCE(SUM(capital),0) AS capital FROM towns');
|
||||||
|
addRes(stock, s);
|
||||||
|
for (const r of RES) escrow[r] = db.get("SELECT COALESCE(SUM(give_amount),0) AS n FROM trade_offers WHERE status = 'open' AND give_res = ?", r).n;
|
||||||
|
for (const m of db.all("SELECT cargo FROM movements WHERE status = 'out' AND cargo != '{}'")) addRes(cargo, JSON.parse(m.cargo));
|
||||||
|
const ls = db.get('SELECT COALESCE(SUM(fiber),0) AS fiber, COALESCE(SUM(hardware),0) AS hardware, COALESCE(SUM(capital),0) AS capital FROM landing_sites');
|
||||||
|
addRes(sites, ls);
|
||||||
|
const total = zero();
|
||||||
|
for (const p of [stock, escrow, cargo, sites]) addRes(total, p);
|
||||||
|
return { stock, escrow, cargo, sites, total };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cost of everything ever built on landing sites (levels done + the one running).
|
||||||
|
backboneSunk() {
|
||||||
|
const out = zero();
|
||||||
|
for (const s of this.db.all('SELECT level, build_cost FROM landing_sites')) {
|
||||||
|
for (let l = 1; l <= s.level; l++) addRes(out, R.backboneCost(l));
|
||||||
|
if (s.build_cost) addRes(out, JSON.parse(s.build_cost));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The resource identity. `col` = collector (sources that come from reports), `start` = pools at the first call.
|
||||||
|
checkResources(col) {
|
||||||
|
const db = this.db;
|
||||||
|
const p = this.pools();
|
||||||
|
const nOps = db.get('SELECT COUNT(*) AS n FROM operators').n;
|
||||||
|
const sources = zero();
|
||||||
|
for (const r of RES) sources[r] += nOps * D.START.resources[r] + col.foundedTowns * D.EXPANSION.startResources[r];
|
||||||
|
sources.hardware += db.get('SELECT COUNT(*) AS n FROM incumbent_takes').n * D.INCUMBENT.hardwareBonus;
|
||||||
|
const bb = this.backboneSunk();
|
||||||
|
const res = {};
|
||||||
|
let worst = 0;
|
||||||
|
for (const r of RES) {
|
||||||
|
const expected = sources[r] + this.production[r] - this.sinkCosts[r] - this.sinkLost[r] - this.sinkClip[r] - bb[r];
|
||||||
|
const drift = p.total[r] - expected;
|
||||||
|
res[r] = { pools: p.total[r], sources: sources[r], production: this.production[r], costs: this.sinkCosts[r], lost: this.sinkLost[r], clipped: this.sinkClip[r], backbone: bb[r], drift };
|
||||||
|
worst = Math.max(worst, Math.abs(drift));
|
||||||
|
}
|
||||||
|
const tol = 0.5 * (this.lostEvents + this.clipEvents) + 1;
|
||||||
|
return { ok: worst <= tol, worstDrift: worst, tolerance: tol, perResource: res, pools: p };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Negative stock anywhere.
|
||||||
|
negatives() {
|
||||||
|
const db = this.db;
|
||||||
|
const bad = [];
|
||||||
|
for (const t of db.all('SELECT id, fiber, hardware, capital, battery FROM towns WHERE fiber < -1e-6 OR hardware < -1e-6 OR capital < -1e-6 OR battery < -1e-6')) bad.push({ town: t.id, fiber: t.fiber, hardware: t.hardware, capital: t.capital, battery: t.battery });
|
||||||
|
for (const s of db.all('SELECT id, fiber, hardware, capital FROM landing_sites WHERE fiber < 0 OR hardware < 0 OR capital < 0')) bad.push({ site: s.id });
|
||||||
|
return bad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- units ----
|
||||||
|
function aliveUnits(db) {
|
||||||
|
const out = {};
|
||||||
|
const add = (k, n) => { out[k] = (out[k] || 0) + n; };
|
||||||
|
for (const r of db.all('SELECT unit, SUM(count) AS n FROM town_units GROUP BY unit')) add(r.unit, r.n);
|
||||||
|
for (const r of db.all('SELECT unit, SUM(count) AS n FROM stationed GROUP BY unit')) add(r.unit, r.n);
|
||||||
|
for (const m of db.all("SELECT units FROM movements WHERE status = 'out' AND units != '{}'")) { const u = JSON.parse(m.units); for (const k of Object.keys(u)) add(k, u[k]); }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { Ledger, aliveUnits, zero, addRes };
|
||||||
109
tools/bot/report.js
Normal file
109
tools/bot/report.js
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
'use strict';
|
||||||
|
/* Plain-text report of a bot run (the JSON file has everything; this is what a person reads in the terminal). */
|
||||||
|
const { fmt, table, round } = require('./util');
|
||||||
|
|
||||||
|
const pc = (p, k) => (p && p[k] !== null && p[k] !== undefined ? fmt(p[k]) : '-');
|
||||||
|
|
||||||
|
function render(s, opts) {
|
||||||
|
opts = opts || {};
|
||||||
|
const out = [];
|
||||||
|
const h = (t) => out.push('', '== ' + t + ' ==');
|
||||||
|
const m = s.meta;
|
||||||
|
out.push('UPSTREAM bot run: ' + m.players + ' players, ' + m.days + ' days, world speed ' + m.speed + 'x, seed ' + m.seed + ', radius ' + m.radius +
|
||||||
|
', sessions/day ' + m.sessionsPerDay + (m.alwaysOn ? ', ALWAYS-ON' : '') + (m.set.length ? ', overrides: ' + m.set.join(' ') : ''));
|
||||||
|
out.push('mix: ' + Object.entries(m.mix).map(([k, v]) => k + ':' + v).join(' '));
|
||||||
|
|
||||||
|
h('invariants');
|
||||||
|
const inv = s.invariants;
|
||||||
|
out.push((inv.ok ? 'OK' : 'BROKEN') + ': resources ' + (inv.resources.ok ? 'conserved' : 'DRIFT') + ' (worst drift ' + fmt(inv.resources.worstDrift, 2) + ', tolerance ' + fmt(inv.resources.tolerance, 1) + '), units ' + (inv.units.ok ? 'conserved' : 'DRIFT ' + JSON.stringify(inv.units.drift)) +
|
||||||
|
', negative stock ' + (inv.negativeStock.ok ? 'none' : 'FOUND'), ' failed events ' + inv.failedEvents.n + ', unexpected errors ' + inv.unexpectedErrors.n);
|
||||||
|
for (const r of Object.keys(inv.resources.final)) {
|
||||||
|
const f = inv.resources.final[r];
|
||||||
|
out.push(' ' + r.padEnd(9) + 'pools ' + fmt(f.pools, 0).padStart(9) + ' = sources ' + fmt(f.sources, 0) + ' + production ' + fmt(f.production, 0) + ' - spent ' + fmt(f.costs, 0) + ' - overflow lost ' + fmt(f.lost, 0) + ' - refund clipped ' + fmt(f.clipped, 0) + ' - backbone ' + fmt(f.backbone, 0) + ' drift ' + fmt(f.drift, 3));
|
||||||
|
}
|
||||||
|
for (const e of inv.failedEvents.sample) out.push(' failed event ' + e.id + ' ' + e.type + ': ' + e.error);
|
||||||
|
for (const e of inv.unexpectedErrors.sample.slice(0, 5)) out.push(' unexpected: ' + e.command + ' ' + e.code + ' ' + (e.message || '') + (e.stack ? ' ' + e.stack : ''));
|
||||||
|
for (const l of inv.serverLog.slice(0, 5)) out.push(' server log: ' + l);
|
||||||
|
|
||||||
|
h('economy per day (mean per POP; stock/production per resource F/H/C)');
|
||||||
|
const rows = [];
|
||||||
|
const step = s.days.length > 16 ? Math.ceil(s.days.length / 16) : 1;
|
||||||
|
for (const d of s.days) {
|
||||||
|
if (d.day % step !== 0 && d.day !== 1 && d.day !== s.days.length) continue;
|
||||||
|
rows.push([d.day, d.operators, d.towns, fmt(d.stock.fiber) + '/' + fmt(d.stock.hardware) + '/' + fmt(d.stock.capital), fmt(d.prodPerHour.fiber) + '/' + fmt(d.prodPerHour.hardware) + '/' + fmt(d.prodPerHour.capital),
|
||||||
|
fmt(d.fillPct, 0) + '%', fmt(d.fullPct, 0) + '%', fmt(d.queueUtilPct, 0) + '%', fmt(d.powerNet), fmt(d.powerNegPct, 0) + '%', fmt(d.unitPowerBoundPct, 0) + '%', fmt(d.unitOfflinePct, 0) + '%']);
|
||||||
|
}
|
||||||
|
out.push(table(rows, ['day', 'ops', 'POPs', 'stock F/H/C', 'prod/h F/H/C', 'fill', 'full', 'queue', 'pwrNet', 'unit POPs net<0', 'unit POPs pwr-bound', 'unit POPs offline']));
|
||||||
|
|
||||||
|
out.push('production lost to full storage over the run (share of what the rates would give): fiber ' + s.storageWastePct.fiber + '%, hardware ' + s.storageWastePct.hardware + '%, capital ' + s.storageWastePct.capital + '%');
|
||||||
|
out.push('time at a full store (share of POP-samples >= 95% of the Rack hall) last day: ' + JSON.stringify(s.days[s.days.length - 1].fullBy));
|
||||||
|
|
||||||
|
h('progression per day');
|
||||||
|
const prow = [];
|
||||||
|
for (const d of s.days) {
|
||||||
|
if (d.day % step !== 0 && d.day !== 1 && d.day !== s.days.length) continue;
|
||||||
|
const u = d.units;
|
||||||
|
prow.push([d.day, fmt(d.fieldAvg, 1), pc(d.core, 'p10') + '/' + pc(d.core, 'p50') + '/' + pc(d.core, 'p90'), pc(d.footprint, 'p10') + '/' + pc(d.footprint, 'p50') + '/' + pc(d.footprint, 'p90'), d.multiPop + ' (max ' + d.popsMax + ')', fmt(d.gateReadyPct, 0) + '%',
|
||||||
|
Object.keys(u).sort().map((k) => k.replace(/_.*/, '') + ':' + fmt(u[k], 0)).join(' ')]);
|
||||||
|
}
|
||||||
|
out.push(table(prow, ['day', 'field avg', 'core p10/50/90', 'footprint p10/50/90', 'operators >=2 POPs', 'over gate', 'units alive']));
|
||||||
|
const f = s.final;
|
||||||
|
out.push('time to Core router 10 (days after joining): ' + pc(f.core10Days, 'p10') + '/' + pc(f.core10Days, 'p50') + '/' + pc(f.core10Days, 'p90') + ' (reached by ' + f.core10Reached + ' of ' + m.players + ')');
|
||||||
|
out.push('time to first expansion (days after joining): ' + pc(f.firstExpansionDays, 'p10') + '/' + pc(f.firstExpansionDays, 'p50') + '/' + pc(f.firstExpansionDays, 'p90') + ' (reached by ' + f.firstExpansionReached + ' of ' + m.players + ')');
|
||||||
|
out.push('by archetype, days after joining to Core router 10 / first expansion (p10/50/90): ' + Object.keys(f.milestones || {}).sort().map((a) => a + ' ' + pc(f.milestones[a].core10Days, 'p10') + '/' + pc(f.milestones[a].core10Days, 'p50') + '/' + pc(f.milestones[a].core10Days, 'p90') + ' | ' + pc(f.milestones[a].firstExpansionDays, 'p10') + '/' + pc(f.milestones[a].firstExpansionDays, 'p50') + '/' + pc(f.milestones[a].firstExpansionDays, 'p90')).join('; '));
|
||||||
|
out.push('POPs per operator: ' + Object.keys(f.pops).sort((a, b) => a - b).map((k) => k + ':' + f.pops[k]).join(' '));
|
||||||
|
out.push('infrastructure levels at the capital (mean; the histogram 0..20 is in --json): ' + Object.keys(f.levels).map((k) => k + ' ' + f.levels[k].mean).join(', '));
|
||||||
|
|
||||||
|
h('by archetype (means)');
|
||||||
|
const arows = Object.keys(f.byArchetype).sort().map((a) => {
|
||||||
|
const r = f.byArchetype[a];
|
||||||
|
return [a, r.n, r.footprintMean, r.fieldAvg, r.core, r.pops, fmt(r.spentBuild), fmt(r.spentTrain), fmt(r.stock), fmt(r.netWorth), r.raids + '/' + r.raidWins, fmt(r.lootTaken), fmt(r.raidLostValue), r.timesHit, fmt(r.lootLostToRaids), r.incumbentWins];
|
||||||
|
});
|
||||||
|
out.push(table(arows, ['archetype', 'n', 'footprint', 'field avg', 'core', 'POPs', 'spent build', 'spent units', 'stock', 'net worth', 'raids/won', 'loot taken', 'raid loss value', 'times hit', 'loot lost', 'incumbent wins']));
|
||||||
|
|
||||||
|
h('combat');
|
||||||
|
const c = s.combat;
|
||||||
|
out.push('reports: ' + Object.entries(c.reports).map(([k, v]) => k + ':' + v).join(' '));
|
||||||
|
const r = c.raids;
|
||||||
|
out.push('raids ' + r.n + ', won ' + r.wins + (r.winRate !== null ? ' (' + fmt(r.winRate * 100, 0) + '%)' : '') + ', loot ' + fmt(r.lootTotal) + ' (' + Object.entries(r.lootRes).map(([k, v]) => k[0] + ':' + fmt(v)).join(' ') + '), loot/raid p10/50/90 ' + pc(r.lootPerRaid, 'p10') + '/' + pc(r.lootPerRaid, 'p50') + '/' + pc(r.lootPerRaid, 'p90'));
|
||||||
|
out.push(' attacker lost value ' + fmt(r.attackerLostValue) + ', defender lost value ' + fmt(r.defenderLostValue) + ', loot per lost value ' + fmt(r.lootPerLostValue) + ', share against undefended POPs ' + (r.undefendedShare === null ? '-' : fmt(r.undefendedShare * 100, 0) + '%') + ', attack/defence p10/50/90 ' + pc(r.attackOverDefence, 'p10') + '/' + pc(r.attackOverDefence, 'p50') + '/' + pc(r.attackOverDefence, 'p90'));
|
||||||
|
out.push(' target age at raid (days since the target joined): ' + Object.entries(r.targetAge).map(([k, v]) => k + ':' + v).join(' '));
|
||||||
|
out.push('full attacks ' + c.attacks.n + ' (won ' + c.attacks.att + '), takeover attacks ' + c.takeoverBattles.n + ' (won ' + c.takeoverBattles.att + '), takeovers: attempted ' + c.takeovers.attempted + ', loyalty hits ' + c.takeovers.dropped + ', captured ' + c.takeovers.captured + ', blocked ' + JSON.stringify(c.takeovers.blocked) + ', siege ' + c.siege.n);
|
||||||
|
out.push('scans ' + c.scans.n + ' (ok ' + c.scans.ok + ', failed ' + c.scans.failed + '), detected-by-target reports ' + c.scans.detected + ' (identity revealed ' + c.scans.revealed + ')');
|
||||||
|
out.push('incumbent sites: attacks ' + c.incumbent.n + ', won ' + c.incumbent.wins + ', hardware bonus ' + fmt(c.incumbent.hardware) + ', attacker lost value ' + fmt(c.incumbent.attLostValue));
|
||||||
|
out.push('bounced movements: ' + JSON.stringify(c.movementFailed));
|
||||||
|
out.push('units lost: ' + JSON.stringify(c.unitsLost) + ' consumed: ' + JSON.stringify(c.unitsConsumed) + ' decommissioned: ' + JSON.stringify(c.decommissioned));
|
||||||
|
|
||||||
|
h('trade and alliances');
|
||||||
|
const t = s.trade;
|
||||||
|
out.push('offers by status: ' + Object.entries(t.byStatus).map(([k, v]) => k + ':' + v.n).join(' ') + ', completed volume ' + fmt(t.volumeCompleted) + ', completed give/want ratio p10/50/90 ' + pc(t.ratio, 'p10') + '/' + pc(t.ratio, 'p50') + '/' + pc(t.ratio, 'p90'));
|
||||||
|
out.push('transport overflow lost (' + t.cargoLostEvents + ' deliveries): ' + JSON.stringify(t.cargoLost) + ', trade refunds clipped by the Rack hall cap (' + t.clipEvents + '): ' + JSON.stringify(t.refundClipped));
|
||||||
|
const a = s.alliances;
|
||||||
|
out.push('alliances ' + a.count + ', members p10/50/90 ' + pc(a.members, 'p10') + '/' + pc(a.members, 'p50') + '/' + pc(a.members, 'p90') + ' (max ' + a.membersMax + '), operators in an alliance ' + a.inAlliance + '/' + a.operators + ', relations ' + JSON.stringify(a.relations) + ', proposals ' + JSON.stringify(a.proposals));
|
||||||
|
|
||||||
|
if (s.endgame) {
|
||||||
|
h('end game');
|
||||||
|
const e = s.endgame;
|
||||||
|
if (!e.open) out.push('sites not open yet (world age ' + fmt(e.ageDays, 1) + ' days, opens at ' + e.openDay + ')');
|
||||||
|
else {
|
||||||
|
out.push('opened at simulated day ' + fmt(e.openedAtSimDay, 1) + ' (world age now ' + fmt(e.ageDays, 0) + '), alliance plans ' + e.plans + ', strikes sent ' + e.strikes + ' (landing reports ' + e.landingReports.n + ', taken ' + e.landingReports.taken + ', units lost value ' + fmt(e.landingReports.attLostValue) + '), strike blockers ' + JSON.stringify(e.strikeSkips));
|
||||||
|
out.push('shipments ' + e.shipments + ' carrying ' + fmt(e.shippedTotal) + ' (F ' + fmt(e.shipped.fiber) + ' H ' + fmt(e.shipped.hardware) + ' C ' + fmt(e.shipped.capital) + '), ' + fmt(e.shippedPerSimDay) + ' per simulated day; node levels started ' + e.buildsStarted + ' ' + JSON.stringify(e.buildErrors));
|
||||||
|
out.push(table(e.sites.map((x) => [x.idx, x.holder || '-', x.level, x.takenAt === null ? '-' : fmt(x.takenAt, 1), x.contributors, fmt(x.shippedIn.fiber + x.shippedIn.hardware + x.shippedIn.capital), fmt(x.shippedPerDay), x.daysToLevel100 === null ? '-' : x.daysToLevel100, fmt(x.stock.fiber + x.stock.hardware + x.stock.capital)]), ['site', 'holder', 'node level', 'taken (day)', 'contributors', 'shipped in', 'shipped/day', 'days to lvl 100 at that rate', 'stockpile now']));
|
||||||
|
out.push('largest army (attack, before research) any single POP holds: ' + fmt(e.maxPopAttackNoResearch) + ' against the defence of the best built-up site now: ' + fmt(e.bestHeldSiteDefenceNow) + ' (one attack is one movement from one POP, so attacks cannot be added up)');
|
||||||
|
out.push('best node level ' + e.bestLevel + '; still to ship for level 100 from there (per resource) ' + fmt(e.remainingToLevel100.fiber) + '; world ' + e.worldStatus + (e.winner ? ', WINNER ' + e.winner.tag + ' on day ' + fmt(e.winner.wonAtSimDay, 1) : ', no winner'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h('performance and errors');
|
||||||
|
const p = s.perf;
|
||||||
|
out.push('wall ' + p.wallSeconds + ' s for ' + m.days + ' simulated days (' + p.simulatedPerWallSecond + ' simulated hours per wall second), commands ' + p.commands + ' (' + p.commandsOk + ' ok, ' + p.commandsPerSecond + '/s), p50/p95/p99 latency ' + fmt(p.latencyMs.p50, 2) + '/' + fmt(p.latencyMs.p95, 2) + '/' + fmt(p.latencyMs.p99, 2) + ' ms');
|
||||||
|
out.push('events processed in the loop ' + p.eventsProcessed + ' (' + fmt(p.runDueSeconds, 2) + ' s in runDue), done by type: ' + Object.entries(p.eventsDone).map(([k, v]) => k + ':' + v).join(' '));
|
||||||
|
const slow = Object.entries(p.latencyByCommand).sort((x, y) => (y[1].p95 || 0) - (x[1].p95 || 0)).slice(0, 5);
|
||||||
|
out.push('slowest commands (p95 ms): ' + slow.map(([k, v]) => k + ' ' + fmt(v.p95, 2) + ' (n ' + v.n + ')').join(', '));
|
||||||
|
out.push('bot actions: ' + JSON.stringify(s.botLogs));
|
||||||
|
const er = s.errors.rows.slice(0, 14);
|
||||||
|
out.push('command errors (' + s.errors.expectedTotal + ' expected, ' + s.errors.unexpectedTotal + ' unexpected): ' + er.map((x) => x.key + ' x' + x.n + (x.expected ? '' : ' (!)')).join(', '));
|
||||||
|
return out.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { render };
|
||||||
289
tools/bot/sim.js
Normal file
289
tools/bot/sim.js
Normal file
|
|
@ -0,0 +1,289 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* The simulation: the real server in-process (createServer: in-memory SQLite, FakeClock, autoArm false), N bots playing through
|
||||||
|
* srv.commands.run (the function every REST route calls, so the same validation and transactions, without HTTP/JSON/scrypt
|
||||||
|
* overhead), the clock advanced stop by stop (next bot session / next sample), scheduler.runDue() settling every event that falls due.
|
||||||
|
* Called from tools/bot.js; returns a plain stats object (see report.js for how it is printed).
|
||||||
|
*/
|
||||||
|
const { performance } = require('perf_hooks');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const { FakeClock } = require('../../server/clock');
|
||||||
|
const { HOUR, DAY, makeRng, percentiles, mean, round, bump, addInto } = require('./util');
|
||||||
|
const { Ledger, aliveUnits, zero } = require('./ledger');
|
||||||
|
const { Collector } = require('./collector');
|
||||||
|
|
||||||
|
const RES = D.RESOURCES;
|
||||||
|
const DEFAULT_MIX = { builder: 0.22, raider: 0.14, conqueror: 0.06, turtle: 0.12, expander: 0.16, trader: 0.12, alliancer: 0.18 };
|
||||||
|
|
||||||
|
// Error codes a sensible bot may run into now and then (rules it pre-checks can still change between check and send).
|
||||||
|
const EXPECTED = new Set(['not_enough_resources', 'queue_full', 'requirements_not_met', 'already_queued', 'target_protected', 'protection_active',
|
||||||
|
'footprint_too_low', 'no_transport_link', 'units_offline', 'invalid_target', 'trade_out_of_range', 'alliance_full', 'peering_office_required',
|
||||||
|
'max_level', 'offer_closed', 'own_offer', 'queue_full', 'out_of_range', 'cannot_takeover', 'diplomacy_invalid', 'diplomacy_pending', 'proposal_exists',
|
||||||
|
'proposal_expired', 'invite_expired', 'world_ended', 'already_in_alliance', 'capacity_exceeded', 'conflict', 'backbone_closed', 'not_enough_units', 'alliance_name_taken', 'alliance_tag_taken', 'forbidden']);
|
||||||
|
|
||||||
|
function parseMix(str, n) {
|
||||||
|
const weights = {};
|
||||||
|
if (str) {
|
||||||
|
for (const part of String(str).split(',')) { const [k, v] = part.split(':'); if (k) weights[k.trim()] = Number(v === undefined ? 1 : v); }
|
||||||
|
} else Object.assign(weights, DEFAULT_MIX);
|
||||||
|
const { ARCHETYPES } = require('./bots');
|
||||||
|
for (const k of Object.keys(weights)) if (!Object.prototype.hasOwnProperty.call(ARCHETYPES, k) || !(weights[k] >= 0)) throw new Error('--strategy-mix: unknown archetype or bad weight "' + k + '" (known: ' + Object.keys(ARCHETYPES).join(', ') + ')');
|
||||||
|
const names = Object.keys(weights).filter((k) => weights[k] > 0);
|
||||||
|
if (!names.length) throw new Error('--strategy-mix needs at least one positive weight');
|
||||||
|
const total = names.reduce((s, k) => s + weights[k], 0);
|
||||||
|
// largest remainder, so the counts add up to n
|
||||||
|
const exact = names.map((k) => ({ k, v: weights[k] / total * n }));
|
||||||
|
const counts = {};
|
||||||
|
let used = 0;
|
||||||
|
for (const e of exact) { counts[e.k] = Math.floor(e.v); used += counts[e.k]; }
|
||||||
|
exact.sort((a, b) => (b.v - Math.floor(b.v)) - (a.v - Math.floor(a.v)) || (a.k < b.k ? -1 : 1));
|
||||||
|
for (let i = 0; used < n; i++, used++) counts[exact[i % exact.length].k] += 1;
|
||||||
|
const list = [];
|
||||||
|
for (const k of names) for (let i = 0; i < counts[k]; i++) list.push(k);
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runSim(o) {
|
||||||
|
const { createServer } = require('../../server');
|
||||||
|
const { Bot, ARCHETYPES } = require('./bots');
|
||||||
|
const makeView = require('./view');
|
||||||
|
const { createEndgame } = require('./endgame');
|
||||||
|
|
||||||
|
const logs = [];
|
||||||
|
const clock = new FakeClock(Date.UTC(2026, 0, 1));
|
||||||
|
const t0 = clock.now();
|
||||||
|
const srv = await createServer({
|
||||||
|
port: 0, host: '127.0.0.1', dbPath: ':memory:', clock, autoArm: false,
|
||||||
|
log: (m) => { if (/fail|error|exception/i.test(m)) { if (logs.length < 50) logs.push(m); } },
|
||||||
|
world: { seed: o.seed, speed: o.speed, mapRadius: o.radius, name: 'bot world' },
|
||||||
|
});
|
||||||
|
const db = srv.db;
|
||||||
|
const world = require('../../server/state').loadWorld(db, db.get('SELECT id FROM worlds LIMIT 1').id);
|
||||||
|
const ledger = new Ledger(db);
|
||||||
|
ledger.install();
|
||||||
|
const col = new Collector(db);
|
||||||
|
const view = makeView(db, world);
|
||||||
|
const wall0 = performance.now();
|
||||||
|
|
||||||
|
const sim = { potential: zero(), opts: o, srv, db, world, clock, t0, view, ledger, col, bots: [], alliancePlans: new Map(), call: null, endgame: null };
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- command wrapper (accounting, latency, errors)
|
||||||
|
const lat = {};
|
||||||
|
const counts = {};
|
||||||
|
const errors = {};
|
||||||
|
const unexpected = [];
|
||||||
|
let commandsRun = 0, commandsOk = 0;
|
||||||
|
let runDueMs = 0, eventsProcessed = 0;
|
||||||
|
sim.call = (bot, name, args) => {
|
||||||
|
const a = Object.assign({ userId: bot.userId }, args);
|
||||||
|
const s = performance.now();
|
||||||
|
commandsRun += 1;
|
||||||
|
try {
|
||||||
|
const out = srv.commands.run(name, a);
|
||||||
|
const ms = performance.now() - s;
|
||||||
|
(lat[name] || (lat[name] = [])).push(ms);
|
||||||
|
bump(counts, name); commandsOk += 1;
|
||||||
|
if (out && out.cost && (name === 'build' || name === 'train' || name === 'research')) {
|
||||||
|
ledger.sinkCost(out.cost);
|
||||||
|
const v = RES.reduce((sum, r) => sum + (out.cost[r] || 0), 0);
|
||||||
|
bot.spent[name] = (bot.spent[name] || 0) + v;
|
||||||
|
}
|
||||||
|
return { ok: true, out, args: a };
|
||||||
|
} catch (e) {
|
||||||
|
const ms = performance.now() - s;
|
||||||
|
(lat[name] || (lat[name] = [])).push(ms);
|
||||||
|
const code = e && e.code ? e.code : 'EXC:' + (e && e.message || e);
|
||||||
|
bump(errors, name + ':' + code);
|
||||||
|
if (process.env.BOT_DEBUG && (errors[name + ':' + code] <= 3)) console.error('DEBUG error', name, code, JSON.stringify(a).slice(0, 300), JSON.stringify(e.details || {}));
|
||||||
|
if (!(e && e.code && EXPECTED.has(e.code)) && unexpected.length < 30) unexpected.push({ command: name, code, message: String(e && e.message || e).slice(0, 200), details: e && e.details, stack: e && !e.code ? String(e.stack).split('\n').slice(0, 4).join(' | ') : undefined });
|
||||||
|
return { ok: false, code, error: e, args: a };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
sim.endgame = createEndgame(sim);
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- the bots
|
||||||
|
const mix = parseMix(o.mix, o.players);
|
||||||
|
const order = mix.map((k, i) => ({ k, r: makeRng(o.seed, i, 0xa11)() })).sort((a, b) => a.r - b.r).map((x) => x.k); // seeded shuffle
|
||||||
|
const joinSpan = Math.max(0, o.joinDays) * DAY;
|
||||||
|
const pending = []; // bots waiting to join
|
||||||
|
for (let i = 0; i < o.players; i++) {
|
||||||
|
const jr = makeRng(o.seed, i, 0x70a);
|
||||||
|
pending.push({ idx: i, archetype: order[i], at: t0 + Math.floor(i * joinSpan / Math.max(1, o.players) + jr() * (joinSpan / Math.max(1, o.players)) * 0.9) });
|
||||||
|
}
|
||||||
|
const join = (p) => {
|
||||||
|
const name = 'bot' + p.idx;
|
||||||
|
const r = srv.commands.run('signup', { username: name, passHash: 'x', tokenHash: crypto.createHash('sha256').update('bot-token-' + o.seed + '-' + p.idx).digest('hex'), device: 'bot' });
|
||||||
|
const bot = new Bot(sim, p.idx, p.archetype, { userId: r.userId, operatorId: r.operatorId, name }, { sessionsPerDay: o.sessionsPerDay });
|
||||||
|
bot.joinedAt = clock.now();
|
||||||
|
bot.dayIdx = Math.floor((clock.now() - t0) / DAY);
|
||||||
|
bot.times = bot.sessionTimes(bot.dayIdx, t0).filter((t) => t >= clock.now());
|
||||||
|
bot.times.unshift(clock.now() + 1000); // a first look right after signing up
|
||||||
|
sim.bots.push(bot);
|
||||||
|
bot.nextAt = bot.times.shift();
|
||||||
|
if (o.alwaysOn) bot.nextAt = Infinity;
|
||||||
|
};
|
||||||
|
const advanceBot = (bot) => {
|
||||||
|
if (o.alwaysOn) { bot.nextAt = Infinity; return; }
|
||||||
|
while (!bot.times.length) {
|
||||||
|
bot.dayIdx += 1;
|
||||||
|
bot.times = bot.sessionTimes(bot.dayIdx, t0);
|
||||||
|
}
|
||||||
|
bot.nextAt = bot.times.shift();
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- sampling
|
||||||
|
const sampleEvery = Math.max(10, o.sampleMin) * 60 * 1000;
|
||||||
|
const days = [];
|
||||||
|
const dayAcc = new Map(); // day index -> accumulators of the periodic samples
|
||||||
|
const S = require('../../server/state');
|
||||||
|
const sample = (now) => {
|
||||||
|
const di = Math.floor((now - t0) / DAY);
|
||||||
|
let acc = dayAcc.get(di);
|
||||||
|
if (!acc) { acc = { fullBy: {}, n: 0, towns: 0, stock: zero(), prod: zero(), fill: 0, full: 0, qUtil: 0, qTowns: 0, pNet: 0, pNeg: 0, pEmpty: 0, unitTowns: 0, unitPowerBound: 0, unitOffline: 0, pDraw: 0, pOut: 0, capSum: 0, batFill: 0 }; dayAcc.set(di, acc); }
|
||||||
|
acc.n += 1;
|
||||||
|
const qs = new Map(db.all("SELECT town_id AS id, COUNT(*) AS n FROM events WHERE type = 'buildDone' AND status = 'pending' GROUP BY town_id").map((r) => [r.id, r.n]));
|
||||||
|
for (const row of db.all('SELECT * FROM towns ORDER BY id')) {
|
||||||
|
const t = S.townFromRow(db, row, world);
|
||||||
|
const cur = R.resourcesAt(t, now);
|
||||||
|
const cap = cur.caps.fiber;
|
||||||
|
acc.towns += 1;
|
||||||
|
for (const r of RES) { acc.stock[r] += cur.amounts[r]; acc.prod[r] += cur.rates[r]; }
|
||||||
|
const fills = RES.map((r) => cur.amounts[r] / cap);
|
||||||
|
acc.fill += mean(fills);
|
||||||
|
if (fills.some((f) => f >= 0.95)) acc.full += 1;
|
||||||
|
RES.forEach((r, i) => { if (fills[i] >= 0.95) acc.fullBy[r] = (acc.fullBy[r] || 0) + 1; sim.potential[r] += cur.rates[r] * sampleEvery / HOUR; });
|
||||||
|
const slots = R.queueSlots(t);
|
||||||
|
acc.qUtil += Math.min(1, (qs.get(row.id) || 0) / slots); acc.qTowns += 1;
|
||||||
|
acc.pNet += cur.rates.powerNet; acc.pDraw += cur.rates.powerDraw; acc.pOut += cur.rates.powerOut;
|
||||||
|
const hasUnits = t.unitDraw > 0;
|
||||||
|
if (cur.rates.powerNet < 0 && hasUnits) acc.pNeg += 1;
|
||||||
|
if (hasUnits) { acc.unitTowns += 1; if (cur.rates.powerNet < 3) acc.unitPowerBound += 1; if (cur.amounts.battery <= 1e-6 && cur.rates.powerNet < 0) acc.unitOffline += 1; }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const snapshot = (now, di) => {
|
||||||
|
const acc = dayAcc.get(di) || { n: 1, towns: 1, stock: zero(), prod: zero(), fill: 0, full: 0, qUtil: 0, qTowns: 1, pNet: 0, pNeg: 0, pEmpty: 0, unitTowns: 0, unitPowerBound: 0, unitOffline: 0, pDraw: 0, pOut: 0 };
|
||||||
|
const tn = Math.max(1, acc.towns);
|
||||||
|
const ops = db.all('SELECT id, alliance_id FROM operators ORDER BY id');
|
||||||
|
const fps = [], cores = [], fields = [], pops = [];
|
||||||
|
const gate = { ready: 0, n: 0 };
|
||||||
|
for (const op of ops) {
|
||||||
|
const towns = view.towns(op.id);
|
||||||
|
pops.push(towns.length);
|
||||||
|
if (!towns.length) continue;
|
||||||
|
let fp = 0;
|
||||||
|
for (const t of towns) fp += R.footprintAt(t, now);
|
||||||
|
fps.push(fp);
|
||||||
|
const cap = towns[0];
|
||||||
|
cores.push(view.level(cap, 'core_router'));
|
||||||
|
const fl = view.fieldLevels(cap).map((f) => f.level);
|
||||||
|
fields.push(mean(fl));
|
||||||
|
gate.n += 1;
|
||||||
|
if (R.footprintGate(towns.length, fp).ok) gate.ready += 1;
|
||||||
|
}
|
||||||
|
const units = aliveUnits(db);
|
||||||
|
const stockAvg = {}, prodAvg = {};
|
||||||
|
for (const r of RES) { stockAvg[r] = acc.stock[r] / tn; prodAvg[r] = acc.prod[r] / tn; }
|
||||||
|
days.push({
|
||||||
|
day: di + 1, operators: ops.length, towns: db.get('SELECT COUNT(*) AS n FROM towns').n,
|
||||||
|
stock: stockAvg, prodPerHour: prodAvg, fullBy: Object.fromEntries(RES.map((r) => [r, round((acc.fullBy[r] || 0) / tn * 100, 1)])), fillPct: acc.fill / tn * 100, fullPct: acc.full / tn * 100,
|
||||||
|
queueUtilPct: acc.qUtil / Math.max(1, acc.qTowns) * 100,
|
||||||
|
powerNet: acc.pNet / tn, powerDraw: acc.pDraw / tn, powerOut: acc.pOut / tn, powerNegPct: acc.unitTowns ? acc.pNeg / acc.unitTowns * 100 : 0,
|
||||||
|
unitTownsPct: acc.unitTowns / tn * 100, unitPowerBoundPct: acc.unitTowns ? acc.unitPowerBound / acc.unitTowns * 100 : 0, unitOfflinePct: acc.unitTowns ? acc.unitOffline / acc.unitTowns * 100 : 0,
|
||||||
|
fieldAvg: mean(fields), core: percentiles(cores, [10, 50, 90]), footprint: percentiles(fps, [10, 50, 90]),
|
||||||
|
popsMax: Math.max(0, ...pops), popsMean: mean(pops), multiPop: pops.filter((p) => p >= 2).length, gateReadyPct: gate.n ? gate.ready / gate.n * 100 : 0,
|
||||||
|
units, alliances: db.get('SELECT COUNT(*) AS n FROM alliances').n, allied: db.get('SELECT COUNT(*) AS n FROM operators WHERE alliance_id IS NOT NULL').n,
|
||||||
|
openOffers: db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE status = 'open'").n, eventsPending: db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending'").n,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- invariants, checked at every day boundary
|
||||||
|
const invariantLog = [];
|
||||||
|
const checkpoint = (now, final) => {
|
||||||
|
col.ingest(ledger);
|
||||||
|
const res = ledger.checkResources(col);
|
||||||
|
const neg = ledger.negatives();
|
||||||
|
const failed = db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n;
|
||||||
|
const trained = {};
|
||||||
|
for (const r of db.all("SELECT json_extract(payload, '$.unit') AS u, SUM(json_extract(payload, '$.count')) AS n FROM events WHERE type = 'trainDone' AND status = 'done' GROUP BY u")) trained[r.u] = r.n;
|
||||||
|
const alive = aliveUnits(db);
|
||||||
|
const lost = addInto(addInto({}, col.unitsLost), col.unitsConsumed);
|
||||||
|
const unitDrift = {};
|
||||||
|
for (const k of new Set([...Object.keys(trained), ...Object.keys(alive), ...Object.keys(lost)])) {
|
||||||
|
const d = (alive[k] || 0) - ((trained[k] || 0) - (lost[k] || 0));
|
||||||
|
if (d !== 0) unitDrift[k] = d;
|
||||||
|
}
|
||||||
|
const rec = { day: (now - t0) / DAY, resourcesOk: res.ok, worstDrift: res.worstDrift, tolerance: res.tolerance, negatives: neg.length, failedEvents: failed, unitDrift };
|
||||||
|
invariantLog.push(rec);
|
||||||
|
if (final) rec.detail = res.perResource;
|
||||||
|
return { res, neg, failed, unitDrift, trained, alive, lost };
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- main loop
|
||||||
|
const end = t0 + o.days * DAY;
|
||||||
|
let nextSample = t0 + sampleEvery;
|
||||||
|
let nextDay = t0 + DAY;
|
||||||
|
let guard = 0;
|
||||||
|
while (clock.now() < end) {
|
||||||
|
// next stop
|
||||||
|
let next = end;
|
||||||
|
let kind = 'end', who = null;
|
||||||
|
if (pending.length && pending[0].at < next) { next = pending[0].at; kind = 'join'; }
|
||||||
|
for (const b of sim.bots) if (b.nextAt < next) { next = b.nextAt; kind = 'bot'; who = b; }
|
||||||
|
if (o.alwaysOn) {
|
||||||
|
const tick = Math.ceil((clock.now() + 1) / (o.stepMin * 60000)) * (o.stepMin * 60000);
|
||||||
|
if (tick < next) { next = tick; kind = 'tick'; }
|
||||||
|
}
|
||||||
|
if (o.endgameStepMin > 0 && sim.endgame.isOpen(clock.now())) {
|
||||||
|
const tick = Math.ceil((clock.now() + 1) / (o.endgameStepMin * 60000)) * (o.endgameStepMin * 60000);
|
||||||
|
if (tick < next) { next = tick; kind = 'egtick'; }
|
||||||
|
}
|
||||||
|
if (nextSample < next) { next = nextSample; kind = 'sample'; }
|
||||||
|
if (nextDay <= next) { next = nextDay; kind = 'day'; }
|
||||||
|
if (next < clock.now()) next = clock.now();
|
||||||
|
clock.set(next);
|
||||||
|
const r0 = performance.now();
|
||||||
|
eventsProcessed += srv.scheduler.runDue();
|
||||||
|
runDueMs += performance.now() - r0;
|
||||||
|
if (++guard > 5e6) throw new Error('simulation loop did not terminate');
|
||||||
|
if (kind === 'join') { join(pending.shift()); }
|
||||||
|
else if (kind === 'bot') {
|
||||||
|
if (db.get('SELECT status FROM worlds WHERE id = ?', world.id).status === 'ended') { advanceBot(who); continue; } // the world is over: nothing to play
|
||||||
|
who.session(next);
|
||||||
|
const cont = who.continuation(next);
|
||||||
|
if (cont !== null) who.nextAt = cont; else advanceBot(who);
|
||||||
|
}
|
||||||
|
else if (kind === 'egtick') { for (const b of sim.bots) { if (sim.alliancePlans.has(b.op && b.op.alliance_id) || (b.op && b.op.alliance_id)) { b.session(next); } } }
|
||||||
|
else if (kind === 'tick') { for (const b of sim.bots) { b.session(next); } }
|
||||||
|
else if (kind === 'sample') {
|
||||||
|
sample(next); nextSample += sampleEvery;
|
||||||
|
if (process.env.BOT_DEBUG_DRIFT) {
|
||||||
|
col.ingest(ledger);
|
||||||
|
const c = ledger.checkResources(col);
|
||||||
|
const d = RES.map((r) => c.perResource[r].drift.toFixed(2)).join('/');
|
||||||
|
if (d !== sim.lastDrift) { console.error('drift at day ' + ((next - t0) / DAY).toFixed(3) + ' = ' + d); sim.lastDrift = d; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (kind === 'day') {
|
||||||
|
const di = Math.floor((next - t0) / DAY) - 1;
|
||||||
|
if (!dayAcc.has(di)) sample(next - 1);
|
||||||
|
checkpoint(next, false);
|
||||||
|
snapshot(next, di);
|
||||||
|
nextDay += DAY;
|
||||||
|
if (o.progress) o.progress(di + 1, o.days);
|
||||||
|
if (o.onDay) o.onDay(sim, di + 1); // test hook: lets a test tamper with the world to prove the invariants notice
|
||||||
|
}
|
||||||
|
}
|
||||||
|
srv.scheduler.runDue();
|
||||||
|
const fin = checkpoint(clock.now(), true);
|
||||||
|
const wallMs = performance.now() - wall0;
|
||||||
|
|
||||||
|
const stats = require('./stats').build({ sim, o, days, ledger, col, fin, invariantLog, lat, counts, errors, unexpected, commandsRun, commandsOk, runDueMs, eventsProcessed, wallMs, logs, EXPECTED, mix: order });
|
||||||
|
await srv.close();
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { runSim, parseMix, DEFAULT_MIX, EXPECTED };
|
||||||
172
tools/bot/stats.js
Normal file
172
tools/bot/stats.js
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
'use strict';
|
||||||
|
/* Builds the final stats object (JSON-able) from what the simulation collected. Wall-clock numbers live under `perf` only,
|
||||||
|
* so everything else is identical for the same seed (the determinism test compares it without `perf`). */
|
||||||
|
const D = require('../../public/js/data.js');
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const { DAY, percentiles, mean, round, sum } = require('./util');
|
||||||
|
const { lootValue } = require('./collector');
|
||||||
|
|
||||||
|
const RES = D.RESOURCES;
|
||||||
|
|
||||||
|
function histogram(values, max) {
|
||||||
|
const h = {};
|
||||||
|
for (const v of values) h[v] = (h[v] || 0) + 1;
|
||||||
|
const out = [];
|
||||||
|
for (let i = 0; i <= max; i++) out.push(h[i] || 0);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function build(x) {
|
||||||
|
const { sim, o, days, ledger, col, fin, invariantLog, lat, counts, errors, unexpected, commandsRun, commandsOk, runDueMs, eventsProcessed, wallMs, logs, EXPECTED } = x;
|
||||||
|
const { db, world, view, t0 } = sim;
|
||||||
|
const now = sim.clock.now();
|
||||||
|
const S = require('../../server/state');
|
||||||
|
|
||||||
|
// ---- progression at the end
|
||||||
|
const ops = db.all('SELECT * FROM operators ORDER BY id');
|
||||||
|
const byArch = {};
|
||||||
|
const opArch = new Map(sim.bots.map((b) => [b.operatorId, b]));
|
||||||
|
const levels = {};
|
||||||
|
const fieldMins = [];
|
||||||
|
const popsDist = {};
|
||||||
|
const footprints = [];
|
||||||
|
const core10 = [], expand1 = [];
|
||||||
|
const milestones = {};
|
||||||
|
const core10Rows = new Map(db.all(`SELECT t.owner_id AS oid, MIN(e.due_at) AS at FROM events e JOIN towns t ON t.id = e.town_id
|
||||||
|
WHERE e.type = 'buildDone' AND e.status = 'done' AND json_extract(e.payload, '$.type') = 'core_router' AND json_extract(e.payload, '$.toLevel') >= 10 GROUP BY t.owner_id`).map((r) => [r.oid, r.at]));
|
||||||
|
const exp1Rows = new Map(db.all(`SELECT m.owner_id AS oid, MIN(m.arrive_at) AS at FROM movements m JOIN towns t ON t.world_id = m.world_id AND t.x = m.to_x AND t.y = m.to_y AND t.created_at = m.arrive_at
|
||||||
|
WHERE m.type = 'settle' AND m.status = 'done' GROUP BY m.owner_id`).map((r) => [r.oid, r.at]));
|
||||||
|
const infraTypes = Object.keys(D.BUILDINGS).filter((k) => D.BUILDINGS[k].kind === 'infra' && !D.BUILDINGS[k].special);
|
||||||
|
for (const t of infraTypes) levels[t] = [];
|
||||||
|
for (const op of ops) {
|
||||||
|
const towns = view.towns(op.id);
|
||||||
|
const bot = opArch.get(op.id);
|
||||||
|
const a = bot ? bot.archetype : '?';
|
||||||
|
const row = byArch[a] || (byArch[a] = { n: 0, footprint: [], fieldAvg: [], pops: [], spentBuild: [], spentTrain: [], spentResearch: [], stock: [], core: [] });
|
||||||
|
row.n += 1;
|
||||||
|
popsDist[towns.length] = (popsDist[towns.length] || 0) + 1;
|
||||||
|
if (!towns.length) continue;
|
||||||
|
const fp = towns.reduce((s2, t) => s2 + R.footprintAt(t, now), 0);
|
||||||
|
footprints.push(fp);
|
||||||
|
const cap = towns[0];
|
||||||
|
for (const t of infraTypes) levels[t].push(view.level(cap, t));
|
||||||
|
const fl = view.fieldLevels(cap).map((f) => f.level);
|
||||||
|
fieldMins.push(Math.min(...fl));
|
||||||
|
row.footprint.push(fp); row.fieldAvg.push(mean(fl)); row.pops.push(towns.length); row.core.push(view.level(cap, 'core_router'));
|
||||||
|
row.spentBuild.push(bot ? (bot.spent.build || 0) : 0); row.spentTrain.push(bot ? (bot.spent.train || 0) : 0); row.spentResearch.push(bot ? (bot.spent.research || 0) : 0);
|
||||||
|
row.stock.push(towns.reduce((s2, t) => s2 + RES.reduce((q, r) => q + R.resourcesAt(t, now).amounts[r], 0), 0));
|
||||||
|
if (core10Rows.has(op.id)) { const d0 = (core10Rows.get(op.id) - op.created_at) / DAY; core10.push(d0); (milestones[a] || (milestones[a] = { core10: [], exp1: [] })).core10.push(d0); }
|
||||||
|
if (exp1Rows.has(op.id)) { const d1 = (exp1Rows.get(op.id) - op.created_at) / DAY; expand1.push(d1); (milestones[a] || (milestones[a] = { core10: [], exp1: [] })).exp1.push(d1); }
|
||||||
|
}
|
||||||
|
const archTable = {};
|
||||||
|
for (const a of Object.keys(byArch)) {
|
||||||
|
const r = byArch[a];
|
||||||
|
const cs = col.ops;
|
||||||
|
let raids = 0, wins = 0, loot = 0, lost = 0, hit = 0, hitLoot = 0, incWins = 0, incHw = 0;
|
||||||
|
for (const b of sim.bots) if (b.archetype === a) {
|
||||||
|
const s = cs.get(b.operatorId);
|
||||||
|
if (!s) continue;
|
||||||
|
raids += s.raids; wins += s.raidWins; loot += s.raidLoot; lost += s.raidLostValue; hit += s.hit; hitLoot += s.hitLoot; incWins += s.incumbentWins; incHw += s.incumbentHw;
|
||||||
|
}
|
||||||
|
archTable[a] = {
|
||||||
|
n: r.n, footprintMean: round(mean(r.footprint), 0), footprintP50: round(percentiles(r.footprint, [50]).p50 || 0, 0), fieldAvg: round(mean(r.fieldAvg), 1), core: round(mean(r.core), 1), pops: round(mean(r.pops), 2),
|
||||||
|
spentBuild: round(mean(r.spentBuild), 0), spentTrain: round(mean(r.spentTrain), 0), spentResearch: round(mean(r.spentResearch), 0), stock: round(mean(r.stock), 0),
|
||||||
|
netWorth: round(mean(r.spentBuild) + mean(r.spentTrain) + mean(r.spentResearch) + mean(r.stock), 0),
|
||||||
|
raids: raids, raidWins: wins, lootTaken: round(loot, 0), raidLostValue: round(lost, 0), timesHit: hit, lootLostToRaids: round(hitLoot, 0), incumbentWins: incWins, incumbentHardware: incHw,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- combat summary
|
||||||
|
const raid = col.battles.raid;
|
||||||
|
const samples = col.raidSamples;
|
||||||
|
const ratio = samples.filter((s) => s.attLost > 0).map((s) => s.loot / s.attLost);
|
||||||
|
const lootPerRaid = samples.map((s) => s.loot);
|
||||||
|
const ageBuckets = { '<3d': 0, '3-4d': 0, '4-7d': 0, '7-14d': 0, '14d+': 0 };
|
||||||
|
for (const s of samples) { const a = s.targetAgeDays; ageBuckets[a < 3 ? '<3d' : a < 4 ? '3-4d' : a < 7 ? '4-7d' : a < 14 ? '7-14d' : '14d+'] += 1; }
|
||||||
|
const undefended = samples.filter((s) => s.undefended);
|
||||||
|
const combat = {
|
||||||
|
reports: col.byType,
|
||||||
|
raids: { n: raid.n, wins: raid.att, winRate: raid.n ? raid.att / raid.n : null, lootTotal: round(raid.loot, 0), lootRes: raid.lootRes, lootPerRaid: percentiles(lootPerRaid, [10, 50, 90]), attackerLostValue: round(raid.attLost, 0), defenderLostValue: round(raid.defLost, 0),
|
||||||
|
lootPerLostValue: raid.attLost > 0 ? round(raid.loot / raid.attLost, 2) : null, undefendedShare: samples.length ? round(undefended.length / samples.length, 3) : null, undefendedLoot: round(sum(undefended.map((s) => s.loot)), 0),
|
||||||
|
lootOverLossValue: percentiles(ratio, [10, 50, 90]), targetAge: ageBuckets, attackOverDefence: percentiles(samples.filter((s) => s.D > 0).map((s) => s.A / s.D), [10, 50, 90]) },
|
||||||
|
attacks: col.battles.attack, takeoverBattles: col.battles.takeover, takeovers: col.takeovers, siege: col.siege,
|
||||||
|
scans: col.scans, incumbent: col.incumbent, landing: col.landing, movementFailed: col.movementFailed,
|
||||||
|
unitsLost: col.unitsLost, unitsConsumed: col.unitsConsumed, decommissioned: col.decommissioned, unitsOfflineNotes: col.unitsOfflineNotes,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- trade, alliances
|
||||||
|
const tradeRows = db.all('SELECT status, COUNT(*) AS n, SUM(give_amount) AS give, SUM(want_amount) AS want FROM trade_offers GROUP BY status');
|
||||||
|
const trade = { byStatus: Object.fromEntries(tradeRows.map((r) => [r.status, { n: r.n, give: r.give, want: r.want }])), refundClipped: ledger.sinkClip, clipEvents: ledger.clipEvents,
|
||||||
|
cargoLost: col.cargoLostTotal, cargoLostEvents: col.cargoLostEvents };
|
||||||
|
const completed = db.all("SELECT give_res, give_amount, want_res, want_amount FROM trade_offers WHERE status = 'completed'");
|
||||||
|
trade.volumeCompleted = sum(completed.map((r) => r.give_amount + r.want_amount));
|
||||||
|
trade.ratio = percentiles(completed.map((r) => r.give_amount / r.want_amount), [10, 50, 90]);
|
||||||
|
const allianceRows = db.all('SELECT a.id, a.tag, (SELECT COUNT(*) FROM alliance_members m WHERE m.alliance_id = a.id) AS members FROM alliances a ORDER BY a.id');
|
||||||
|
const relRows = db.all('SELECT state, COUNT(*) AS n FROM alliance_relations GROUP BY state');
|
||||||
|
const alliances = {
|
||||||
|
count: allianceRows.length, members: percentiles(allianceRows.map((a) => a.members), [10, 50, 90]), membersMax: Math.max(0, ...allianceRows.map((a) => a.members)),
|
||||||
|
inAlliance: db.get('SELECT COUNT(*) AS n FROM operators WHERE alliance_id IS NOT NULL').n, operators: ops.length,
|
||||||
|
relations: Object.fromEntries(relRows.map((r) => [r.state, r.n])),
|
||||||
|
proposals: Object.fromEntries(db.all('SELECT status, COUNT(*) AS n FROM alliance_proposals GROUP BY status').map((r) => [r.status, r.n])),
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- endgame
|
||||||
|
const endgame = sim.endgame.summary(now);
|
||||||
|
|
||||||
|
// ---- perf and errors
|
||||||
|
const latency = {};
|
||||||
|
const all = [];
|
||||||
|
for (const k of Object.keys(lat)) { latency[k] = Object.assign({ n: lat[k].length }, percentiles(lat[k], [50, 95, 99])); for (const v of lat[k]) all.push(v); }
|
||||||
|
const failedRows = db.all("SELECT id, type, error FROM events WHERE status = 'failed' ORDER BY id LIMIT 10");
|
||||||
|
const evByStatus = Object.fromEntries(db.all('SELECT status, COUNT(*) AS n FROM events GROUP BY status').map((r) => [r.status, r.n]));
|
||||||
|
const evByType = Object.fromEntries(db.all("SELECT type, COUNT(*) AS n FROM events WHERE status = 'done' GROUP BY type").map((r) => [r.type, r.n]));
|
||||||
|
const errorRows = Object.keys(errors).sort((a, b) => errors[b] - errors[a]).map((k) => ({ key: k, n: errors[k], expected: EXPECTED.has(k.split(':').slice(1).join(':')) }));
|
||||||
|
// production lost to the storage cap: what the rates would have produced (sampled) against what was really stored
|
||||||
|
const unsettled = { fiber: 0, hardware: 0, capital: 0 };
|
||||||
|
for (const row of db.all('SELECT * FROM towns')) { const t = S.townFromRow(db, row, world); const cur = R.resourcesAt(t, now).amounts; for (const r of RES) unsettled[r] += cur[r] - row[r]; }
|
||||||
|
const waste = {};
|
||||||
|
for (const r of RES) { const actual = ledger.production[r] + unsettled[r]; waste[r] = sim.potential[r] > 0 ? round(Math.max(0, 1 - actual / sim.potential[r]) * 100, 1) : 0; }
|
||||||
|
const perf = {
|
||||||
|
wallSeconds: round(wallMs / 1000, 2), commands: commandsRun, commandsOk, commandsPerSecond: round(commandsRun / (wallMs / 1000), 0),
|
||||||
|
latencyMs: Object.assign({ n: all.length }, percentiles(all, [50, 95, 99])), latencyByCommand: latency,
|
||||||
|
eventsProcessed, eventsDone: evByType, runDueSeconds: round(runDueMs / 1000, 2),
|
||||||
|
simulatedPerWallSecond: round(o.days * DAY / 1000 / (wallMs / 1000) / 3600, 1), // simulated hours per wall second
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- invariants
|
||||||
|
const resBad = invariantLog.filter((r) => !r.resourcesOk);
|
||||||
|
const negBad = invariantLog.filter((r) => r.negatives > 0);
|
||||||
|
const unitBad = invariantLog.filter((r) => Object.keys(r.unitDrift).length);
|
||||||
|
const failedEvents = fin.failed;
|
||||||
|
const invariants = {
|
||||||
|
ok: !resBad.length && !negBad.length && !failedEvents && !unitBad.length,
|
||||||
|
resources: { ok: !resBad.length, worstDrift: Math.max(0, ...invariantLog.map((r) => r.worstDrift)), tolerance: fin.res.tolerance, final: fin.res.perResource, firstBad: resBad[0] || null },
|
||||||
|
units: { ok: !unitBad.length, trained: fin.trained, alive: fin.alive, lost: fin.lost, drift: fin.unitDrift, firstBad: unitBad[0] || null },
|
||||||
|
negativeStock: { ok: !negBad.length, firstBad: negBad[0] || null },
|
||||||
|
failedEvents: { n: failedEvents, sample: failedRows },
|
||||||
|
unexpectedErrors: { n: unexpected.length, sample: unexpected.slice(0, 10) },
|
||||||
|
serverLog: logs.slice(0, 10),
|
||||||
|
};
|
||||||
|
if (unexpected.length) invariants.ok = false;
|
||||||
|
if (logs.length) invariants.ok = false;
|
||||||
|
|
||||||
|
const meta = {
|
||||||
|
players: o.players, days: o.days, speed: o.speed, seed: o.seed, radius: o.radius, sessionsPerDay: o.sessionsPerDay || 'per archetype', alwaysOn: !!o.alwaysOn, joinDays: o.joinDays,
|
||||||
|
mix: Object.fromEntries(Object.entries(sim.bots.reduce((m, b) => { m[b.archetype] = (m[b.archetype] || 0) + 1; return m; }, {})).sort()),
|
||||||
|
set: o.set || [], worldId: world.id, endAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
meta, invariants, days,
|
||||||
|
final: { levels: Object.fromEntries(Object.keys(levels).map((k) => [k, { mean: round(mean(levels[k]), 2), hist: histogram(levels[k], 20) }])), fieldMin: percentiles(fieldMins, [10, 50, 90]),
|
||||||
|
pops: popsDist, footprint: percentiles(footprints, [10, 50, 90]), core10Days: percentiles(core10, [10, 50, 90]), core10Reached: core10.length, firstExpansionDays: percentiles(expand1, [10, 50, 90]), firstExpansionReached: expand1.length,
|
||||||
|
milestones: Object.fromEntries(Object.entries(milestones).map(([k, v]) => [k, { core10Days: percentiles(v.core10, [10, 50, 90]), firstExpansionDays: percentiles(v.exp1, [10, 50, 90]) }])),
|
||||||
|
unitsAlive: fin.alive, byArchetype: archTable, eventsFailed: evByStatus.failed || 0 },
|
||||||
|
storageWastePct: waste, combat, trade, alliances, endgame,
|
||||||
|
errors: { rows: errorRows, expectedTotal: errorRows.filter((r) => r.expected).reduce((s2, r) => s2 + r.n, 0), unexpectedTotal: errorRows.filter((r) => !r.expected).reduce((s2, r) => s2 + r.n, 0), commandCounts: counts },
|
||||||
|
botLogs: sim.bots.reduce((m, b) => { for (const k of Object.keys(b.log)) m[k] = (m[k] || 0) + b.log[k]; return m; }, {}),
|
||||||
|
perf,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { build };
|
||||||
61
tools/bot/util.js
Normal file
61
tools/bot/util.js
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
'use strict';
|
||||||
|
/* Small helpers for the bot harness: seeded randomness, statistics, formatting. No game logic here. */
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
|
||||||
|
const HOUR = 3600 * 1000;
|
||||||
|
const DAY = 24 * HOUR;
|
||||||
|
|
||||||
|
// A seeded generator with helpers. Everything a bot decides comes from one of these (never Math.random).
|
||||||
|
function makeRng(seed, a, b) {
|
||||||
|
const next = R.rng(R.hash(seed | 0, a | 0, b | 0));
|
||||||
|
const r = () => next();
|
||||||
|
r.int = (lo, hi) => lo + Math.floor(next() * (hi - lo + 1)); // inclusive
|
||||||
|
r.pick = (list) => list[Math.floor(next() * list.length)];
|
||||||
|
r.chance = (p) => next() < p;
|
||||||
|
r.range = (lo, hi) => lo + next() * (hi - lo);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
function pct(sorted, p) {
|
||||||
|
if (!sorted.length) return 0;
|
||||||
|
const i = Math.min(sorted.length - 1, Math.max(0, Math.round((p / 100) * (sorted.length - 1))));
|
||||||
|
return sorted[i];
|
||||||
|
}
|
||||||
|
function percentiles(values, ps) {
|
||||||
|
const s = values.filter((v) => Number.isFinite(v)).sort((a, b) => a - b);
|
||||||
|
const out = {};
|
||||||
|
for (const p of ps || [10, 50, 90]) out['p' + p] = s.length ? pct(s, p) : null;
|
||||||
|
out.n = s.length;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const mean = (a) => (a.length ? a.reduce((s, v) => s + v, 0) / a.length : 0);
|
||||||
|
const sum = (a) => a.reduce((s, v) => s + v, 0);
|
||||||
|
const round = (v, d) => { const k = Math.pow(10, d === undefined ? 1 : d); return Math.round(v * k) / k; };
|
||||||
|
|
||||||
|
// Seeded string key for a stable iteration order.
|
||||||
|
const byId = (a, b) => a.id - b.id;
|
||||||
|
|
||||||
|
function fmt(v, d) {
|
||||||
|
if (v === null || v === undefined || Number.isNaN(v)) return '-';
|
||||||
|
if (typeof v !== 'number') return String(v);
|
||||||
|
const a = Math.abs(v);
|
||||||
|
if (d !== undefined) return v.toFixed(d);
|
||||||
|
if (a >= 1e6) return (v / 1e6).toFixed(2) + 'M';
|
||||||
|
if (a >= 1e4) return (v / 1e3).toFixed(1) + 'k';
|
||||||
|
if (a >= 100) return String(Math.round(v));
|
||||||
|
if (a >= 10) return v.toFixed(1);
|
||||||
|
return v.toFixed(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function table(rows, header) {
|
||||||
|
const all = header ? [header].concat(rows) : rows;
|
||||||
|
const w = [];
|
||||||
|
for (const r of all) r.forEach((c, i) => { w[i] = Math.max(w[i] || 0, String(c).length); });
|
||||||
|
return all.map((r) => r.map((c, i) => (i === 0 ? String(c).padEnd(w[i]) : String(c).padStart(w[i]))).join(' ')).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add `n` to obj[key] (counter maps).
|
||||||
|
const bump = (obj, key, n) => { obj[key] = (obj[key] || 0) + (n === undefined ? 1 : n); };
|
||||||
|
const addInto = (a, b) => { for (const k of Object.keys(b || {})) a[k] = (a[k] || 0) + b[k]; return a; };
|
||||||
|
|
||||||
|
module.exports = { HOUR, DAY, makeRng, pct, percentiles, mean, sum, round, byId, fmt, table, bump, addInto };
|
||||||
54
tools/bot/view.js
Normal file
54
tools/bot/view.js
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
'use strict';
|
||||||
|
/*
|
||||||
|
* Read helpers for the bots: what a client would see (own POPs with the same shape rules.js previews use, the map's towns,
|
||||||
|
* pending queues). Plain reads through the server's own modules; nothing here writes. Created per run, after the data overrides
|
||||||
|
* were applied (the server modules cache some constants when first required).
|
||||||
|
*/
|
||||||
|
module.exports = function makeView(db, world) {
|
||||||
|
const R = require('../../public/js/rules.js');
|
||||||
|
const S = require('../../server/state');
|
||||||
|
const U = require('../../server/military/units');
|
||||||
|
const trainCmd = require('../../server/commands/train');
|
||||||
|
|
||||||
|
const v = {
|
||||||
|
world,
|
||||||
|
townRows(opId) { return db.all('SELECT * FROM towns WHERE owner_id = ? ORDER BY is_capital DESC, id', opId); },
|
||||||
|
towns(opId) { return v.townRows(opId).map((r) => S.townFromRow(db, r, world)); },
|
||||||
|
town(id) { return S.loadTown(db, id); },
|
||||||
|
pendingBuilds(townId) { return S.pendingBuilds(db, townId); },
|
||||||
|
trainQueue(townId, building) { return trainCmd.pendingBatches(db, townId, building); },
|
||||||
|
researchBusy(townId) { return !!db.get("SELECT 1 AS x FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' LIMIT 1", townId); },
|
||||||
|
researchLevels(townId) { return U.researchLevels(db, townId); },
|
||||||
|
home(townId) { return U.homeUnits(db, townId); },
|
||||||
|
operator(id) { return db.get('SELECT * FROM operators WHERE id = ?', id); },
|
||||||
|
// Every POP of every other operator with what the map shows (position, owner, alliance, protection).
|
||||||
|
otherTowns(opId) {
|
||||||
|
return db.all(`SELECT t.id, t.x, t.y, t.owner_id AS ownerId, t.is_capital AS isCapital, o.protection_until AS prot, o.alliance_id AS ally, o.name AS opName
|
||||||
|
FROM towns t JOIN operators o ON o.id = t.owner_id WHERE t.world_id = ? AND t.owner_id != ? ORDER BY t.id`, world.id, opId);
|
||||||
|
},
|
||||||
|
outgoing(opId) { return db.all("SELECT id, type, to_town_id AS toTownId, to_x AS tx, to_y AS ty, arrive_at AS arriveAt, units, extra FROM movements WHERE owner_id = ? AND status = 'out' AND type != 'return' ORDER BY id", opId); },
|
||||||
|
incomingTo(townIds) {
|
||||||
|
if (!townIds.length) return [];
|
||||||
|
return db.all("SELECT id, type, owner_id AS ownerId, to_town_id AS toTownId, arrive_at AS arriveAt FROM movements WHERE status = 'out' AND type IN ('raid','attack','takeover','scan') AND to_town_id IN (" + townIds.map(() => '?').join(',') + ')', ...townIds);
|
||||||
|
},
|
||||||
|
// New reports of this user since `cursor` ({ at, seen }; mutated). Not "id > last id": see collector.js (ids are reused after a cleanup).
|
||||||
|
reportsFor(userId, cursor) {
|
||||||
|
const rows = db.all(`SELECT r.id, r.type, r.created_at AS at, r.data, rr.role FROM reports r JOIN report_recipients rr ON rr.report_id = r.id
|
||||||
|
WHERE rr.user_id = ? AND r.created_at >= ? AND r.type IN ('scan','raid','attack','takeover','settle','incumbent','landing') ORDER BY r.created_at, r.id`, userId, cursor.at);
|
||||||
|
const out = [];
|
||||||
|
for (const x of rows) {
|
||||||
|
if (x.at === cursor.at && cursor.seen.has(x.id)) continue;
|
||||||
|
if (x.at > cursor.at) { cursor.at = x.at; cursor.seen = new Set(); }
|
||||||
|
cursor.seen.add(x.id);
|
||||||
|
out.push(Object.assign(x, { data: JSON.parse(x.data) }));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
footprint(opId, now) { return U.operatorFootprint(db, opId, now); },
|
||||||
|
level(T, type) { return T.buildings[type] ? T.buildings[type].level : 0; },
|
||||||
|
fieldLevels(T) { const out = []; for (let i = 1; i <= 18; i++) { const b = T.buildings['f' + i]; if (b) out.push({ key: 'f' + i, type: b.type, level: b.level }); } return out; },
|
||||||
|
peering(opId) { return require('../../server/alliances').peeringLevel(db, opId); },
|
||||||
|
R, U,
|
||||||
|
};
|
||||||
|
return v;
|
||||||
|
};
|
||||||
Loading…
Add table
Add a link
Reference in a new issue