Late joiners: a network that joins a server session late starts on its date, with a head start
One calendar for a server session (the user's answer to Q1): a network that joins begins on the session's date, and one that joins after day 180, when the shared market starts to move, gets a head start (answered 2026-11-11). Dormant until the host (T3) passes a start day: in the plain build and in single-device play S.day0 is 0 and the game is as before. - S.day0, the calendar day a network began: 0 in newGame(), repaired in sanitize() (at most S.day), so old saves load. netAge() is the network's age; the first-days rules count it: the charter window (and specSanitize), the tutorial's five days, the DDoS grace and early size cap, route leaks, RPKI, the world's bad news, shortages and control-plane events, sold-out routes, the scrubbing customers, loan offers, the broker's first calls, the Speedrun and Blitz badges and the day counts in the win, lose and Glass Baron windows. The market, the calendar and world events stay on the session's date. - beginState() takes o.day for a session network in Normal mode (lateStart()): the day, the first outage and event, the home POP and the first IPv4 block are stamped with it, so the block cannot be sold on day one at the session's price. - The head start (60-features/81-late-joiners.js): starting cash topped up by the rise in hardware prices (START_CASH x (hwTrend - 1), to $1,000, at most $60k, with the market rule only) and the first 365 days of home broadband matched (R.rev.late: what homes pay after the Australian wholesale cut or levy; outside investors' share, inside revMo). A second welcome with a button to the bank, a Goals card, a bank section, a line in a city's broadband pitch and a toast when the year is over; every label in all six dictionaries. - The "since you started" lines (supply chain, bandwidth market, wave prices) measure from the network's own start. - Server-run engine: srvBegin takes begin.day (an integer from 0, else the begin fails), the fake engine begins there and keeps day0 in its saves, CLOCK.off leaves the shape checker and the contract test, and the fixtures' network begins on day 473 (written again with tests/lib/mp-sim-fixtures.js; a second run changes nothing). - Gameplay rule F11, the agent's day0 doc and status age, ARCHITECTURE and the plans (Q1's game side built, open question 1 answered). - tests/late-joiners.test.js; F11 in tests/gameplay-rules.test.js; a late begin in tests/mp-sim-engine.test.js; one calendar in tests/mp-sim-contract.test.js. Merged onto Starblink and Island Wi-Fi: revMo counts both the islands (V.wisp) and the match (V.late), the revenue share base keeps V.wisp and leaves V.late out; F11 sits before F12 in the gameplay rules and their test; the mp-sim fixtures were written again with tests/lib/mp-sim-fixtures.js (a second run changes nothing).
This commit is contained in:
parent
9067bae1ce
commit
dcdb501f16
51 changed files with 476 additions and 76 deletions
|
|
@ -66,7 +66,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
|
|||
|
||||
| Id | Rule | Why |
|
||||
| --- | --- | --- |
|
||||
| F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | New players learn before they get punished. |
|
||||
| F1 | A new network gets a gentle start (counted from the network's own first day; hardware prices hold for the calendar's first 180 days, see F11): no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | New players learn before they get punished. |
|
||||
| F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. |
|
||||
| F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. |
|
||||
| F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. |
|
||||
|
|
@ -76,6 +76,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
|
|||
| F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. |
|
||||
| F9 | A strict latency contract (`BIZ_T.lowlat`, #137) comes only from customer level 7, is 1.6T or 3.2T and never grows past 3.2T, has a latency limit something you can build meets (`latMaxOf`, as trading links), pays more per Gbps than any other big circuit on the same route even with all their extras, and once its 15-day grace is over credits a day's fee and loses patience faster for every day over its limit. | Real low-latency routes sell at a premium for guaranteed milliseconds and pay service credits when they miss; the cap keeps one contract from carrying a level. |
|
||||
| F10 | Growth goes sideways, plus one paid way up: a PNI bundles eight members per router at its POP, up to 32 (`pniLagMax()`); transit, exchange and fabric LAGs stay at eight (`LAG_MAX`). Giant AI circuits land at campuses (`MEGA`) in at least 30 metros, no metro more than two, picked less often where giant circuits already crowd the city. | Raising caps only moves the wall; a fatter PNI costs a router (its price and its port slots), and the late game's demand spreads over many metros as real AI and cloud campuses do (#61, #323). |
|
||||
| F11 | A network that joins a server session after its first 180 days starts on the session's date with F1's gentle start, the charter and the tutorial counted from its own first day, a starting-cash top-up as large as the rise in hardware prices (START_CASH × (hwTrend − 1), at most $60k), and its first 365 days of home broadband income matched (after wholesale cuts, outside investors' share); the market stays on the session's date. | One market for everyone, and a friend who joins late still gets a fair start. |
|
||||
| F12 | Island Wi-Fi (#83), on a zone's own books at full take-up in era 1 (its homes at island prices less the towers' upkeep and the backhaul rent; the teleport, tracking antennas and a Starblink gateway are shared and left out), makes money on at least one way in; a spur earns more than any satellite option, MEO at least as much as GEO and LEO at least as much as MEO where both reach; spurs up to 250 km pay back within 5 years against the best GEO or MEO stage, up to 1,000 km within 10. | The ladder (GEO, then MEO or LEO, then your own cable) must be worth climbing, and its first rung must not lose money; the longest spurs are a choice, not a given. |
|
||||
|
||||
## DDoS
|
||||
|
|
|
|||
|
|
@ -109,6 +109,7 @@ build stays the static page described above.
|
|||
| `src/game/10-catalog/75-satellites.js`, `src/game/60-features/45-teleports.js`, `src/game/90-actions/87-teleports.js`, `src/game/93-ui/72-teleport-panels.js` | Satellites (#83): teleports at POPs (`p.tele`) and rented GEO and MEO circuits (links of kind `sat`): the birds and their reach, the rules and money, the actions and the panels |
|
||||
| `src/game/10-catalog/76-wisp-zones.js`, `src/game/60-features/46-wisp-zones.js`, `src/game/90-actions/87-wisp-zones.js`, `src/game/93-ui/73-wisp-panels.js` | Island Wi-Fi (#83): zones of outer islands (`WISP`), each a pool of homes at its city's POP (`p.wisp`) whose Gbps join the city's demand; their backhaul from the city's teleport (GEO, MEO, Starblink LEO) or a spur cable, the spur cut (incident `wspur`), the money, the actions and the panels |
|
||||
| `src/game/60-features/89-multiplayer.js`, `src/game/95-modals/48-multiplayer.js`, `src/game/90-actions/92-multiplayer.js`, `src/styles/41-multiplayer.css` | Multiplayer, only in a copy built with `MP_API` ([MULTIPLAYER.md](MULTIPLAYER.md)): `S.mp`, saves and cards sent to the session server, the `#mp=` link; the title screen's door, the session panel and the HUD chip; `srvOn()`, false until server-run play is switched on |
|
||||
| `src/game/60-features/81-late-joiners.js` | Late joiners of a server session: a network begins on the session's date (`S.day0`; `netAge()` counts its first-days rules from there), with a hardware top-up and a year of home broadband matched (`R.rev.late`); the Goals card, the bank section and the city pitch. Dormant until the host passes a start day (T3) |
|
||||
| `src/game/98-server-play/`, `src/styles/43-server-play.css` | The page's side of server-run play (T4), only in a multiplayer build's page; a comment so far ([plans/server-run.md](plans/server-run.md)) |
|
||||
| `scripts/mp-server.js`, `scripts/lib/mp.js` | The multiplayer session server: the command line and the built site, and the API with its storage. `npm run dev -- --mp` mounts the API in the development server |
|
||||
| `scripts/lib/mp-sim-acts.js` | Server-run play's act tables (SEND, ASK, VOTE, LOCAL, CONFIRM, DRAFTS, TEXT, WINDOWS…) and the envelope check every request passes |
|
||||
|
|
|
|||
|
|
@ -83,9 +83,10 @@ The four questions of the server-run design:
|
|||
## Open questions waiting for the user
|
||||
|
||||
Asked on 2026-11-09, not answered yet:
|
||||
1. **Late joiners' prices and beginner grace.** With one calendar, a friend who joins an old session meets its economy
|
||||
from day one: at day 1868, hardware about 18% dearer and customer prices about 34% lower, with the 180-day beginner
|
||||
grace long over. Keep that, or give a grace or extra starting cash counted from the joiner's own start?
|
||||
1. ~~**Late joiners' prices and beginner grace.**~~ *Answered 2026-11-11 ("late joiners get a late joiners bonus and a
|
||||
year of double income per Gbps of FTTP sold/provided") and built: the day-0 rules count from the network's own start
|
||||
(`S.day0`, `netAge()`), and a network that joins after day 180 gets a hardware top-up and its first year of home
|
||||
broadband matched (`60-features/81-late-joiners.js`, gameplay rule F11). Dormant until T3 passes a start day.*
|
||||
2. **Other players' POPs on the map.** Draw other players' POPs and links on your map (from their cards) as part of
|
||||
the server-run work, or wait for phase 2?
|
||||
3. **The other modes in a multiplayer build.** Sandbox, scenarios, puzzles and the weekly keep running on the device.
|
||||
|
|
@ -110,8 +111,9 @@ Asked on 2026-11-09, not answered yet:
|
|||
## Next
|
||||
|
||||
- **After the user's go:** T3 (host and protocol), T4 (the browser client) and the integration of server-run play,
|
||||
as `docs/plans/server-run.md` describes them, with the corrections at its top. That includes the Q1 work: the game's
|
||||
`S.day0` and day-0 rules, a start day for a new network on the server, and `CLOCK.off` taken out of the contract.
|
||||
as `docs/plans/server-run.md` describes them, with the corrections at its top. The game's side of the Q1 work is
|
||||
built (`S.day0`, the day-0 rules, `begin.day`, `CLOCK.off` gone, the late joiner's head start); T3 sends the start
|
||||
day, checks every network's day after each tick and replaces the line-up of 4.7 ("What Q1 changes").
|
||||
|
||||
## Known limitations of what shipped
|
||||
|
||||
|
|
|
|||
|
|
@ -30,9 +30,12 @@ the plain build is unchanged.
|
|||
4. Phase-1 sessions **start fresh**: nothing is migrated. They keep running as phase 1 in the new build (section 8).
|
||||
|
||||
**Open with the user** (asked on 2026-11-09, not answered yet; `next-session.md` has the full list of nine):
|
||||
- A late joiner meets the session's economy from day one. In a session about five years old (day 1868), hardware costs
|
||||
- ~~A late joiner meets the session's economy from day one. In a session about five years old (day 1868), hardware costs
|
||||
about 18% more and customers pay about 34% less, and the 180-day beginner grace is long over. Keep it so, or give a
|
||||
grace or extra starting cash counted from the joiner's own start?
|
||||
grace or extra starting cash counted from the joiner's own start?~~ *Answered 2026-11-11: "late joiners get a late
|
||||
joiners bonus and a year of double income per Gbps of FTTP sold/provided". Built (see "What Q1 changes"): a network
|
||||
that begins after day 180 gets a starting-cash top-up as large as the rise in hardware prices and its first 365 days
|
||||
of home broadband income matched (`60-features/81-late-joiners.js`, gameplay rule F11).*
|
||||
- Other players' POPs and links drawn on your map (from their cards): part of this work, or later?
|
||||
- Sandbox, scenarios, puzzles and the weekly stay on the device in a multiplayer build (section 1). Is that fine, or
|
||||
should sandbox (or all of them) run on the server too?
|
||||
|
|
@ -198,6 +201,18 @@ ASK, or send a circuit's `l2route` entries on demand. Not decided yet; it is T4'
|
|||
|
||||
The design assumes each network keeps its own date (sections 0 and 1, 4.3 "Calendar", `p.net.off` in 4.6, 4.7, 14 and
|
||||
row F4), and T1 and T2 were built that way. Under the answer:
|
||||
|
||||
**Built (2026-11-12, dormant until T3 passes a start day):** the game's `S.day0` and `netAge()`, every day-0 rule below
|
||||
counted from the network's own start (and the scrubbing offers, the loan offers, the broker's first calls and the
|
||||
"since you started" lines of the supply chain, the bandwidth market and the wave prices), `beginState`'s `o.day`
|
||||
(`lateStart()`: the schedules, the home POP and the first IPv4 block stamped with it), `srvBegin`'s `begin.day` (an
|
||||
integer from 0, else the begin fails), the fake engine's start day, `CLOCK.off` out of the shape checker, the fixtures
|
||||
(their network begins on day 473) and the contract test, and the late joiner's head start
|
||||
(`60-features/81-late-joiners.js`). The card's `day` (`mpCard()`) stays the calendar date, which phase 1 compares; the
|
||||
market and the calendar stay the session's. Left for T3: the host sends `begin.day` (the session's day; a session's first
|
||||
network keeps 0, a fresh network after bankruptcy is late again), checks after each tick that every reply's day is `d`
|
||||
(lost and broken networks excepted), drops `off` from the live session and `p.net`, and replaces the line-up of 4.7;
|
||||
"Move to the server" makes a session of one at the save's own day and keeps its `day0`.
|
||||
- **Begin needs a start day.** `srvBegin` calls `beginState` with no day, and the `begin` message carries none. Both
|
||||
take the session day, passed on as `beginState`'s `o.day`. The fake engine begins at the given day.
|
||||
- **`CLOCK.off` goes,** or is pinned to zeros: in `tests/lib/mp-sim-shape.js`, the fixture generator
|
||||
|
|
|
|||
|
|
@ -8,12 +8,15 @@
|
|||
// {t:'loaded', nid, err}], one per network, in order. env: the checkpoint envelope {s, uidN, rt, last,
|
||||
// day} (s: the save text; rt: what the realm needs besides it to play on exactly as before, opaque
|
||||
// here: route memory, R's routing point, key order, the sales desk's memory); begin: {name, home,
|
||||
// preset, asn, mp, tut} builds a new network, checkpointed at once (saved). A network that comes
|
||||
// preset, asn, mp, tut, day?} builds a new network, checkpointed at once (saved); day is the
|
||||
// session's date, where it begins (absent or 0: the session's first day). A network that comes
|
||||
// without a save, whose save does not load, or that cannot begin answers err: broken (4.7), and
|
||||
// the others load. A load of a network that is loaded replaces its realm (a failed one leaves none).
|
||||
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]: {day, lost,
|
||||
// pause?, err?, retried?, ms}}}. Each network in sorted order; one that failed twice answers err and
|
||||
// its day as it was, and is broken from then on (no more days; actions answer 'stopped').
|
||||
// its day as it was, and is broken from then on (no more days; actions answer 'stopped'). One
|
||||
// calendar for the session: the host (T3) checks that every network's day here is d, lost and
|
||||
// broken networks excepted; the engine does not.
|
||||
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd, ms} (upd: the update with the
|
||||
// result, version v; null when stopped) | {t:'err', code, nid, rid, what:'timeout'|'throw', msg}
|
||||
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal?, ui?, err?, ms} (neither modal nor err: the what-if
|
||||
|
|
|
|||
|
|
@ -300,12 +300,15 @@ function srvLoad(inp){const m=JSON.parse(inp),rt=m.rt&&typeof m.rt==='object'?m.
|
|||
SIMR.seen=true;
|
||||
return JSON.stringify({day:S.day,lost:!!S.lost});}
|
||||
const srvClockNow=()=>self.__srvClock?{clock:__srvClock()}:{};
|
||||
// srvBegin: a new network of a server session (T1's beginState, then the server's own marks and the welcome).
|
||||
// srvBegin: a new network of a server session (T1's beginState, then the server's own marks and the welcome). b.day: the
|
||||
// session's date, where the network begins (one calendar for the session; 0 or none: its first day).
|
||||
function srvBegin(inp){const m=JSON.parse(inp),b=m.begin||{};SIMR.strict=!!m.strict;
|
||||
if(typeof b.home!=='string'||!homeOk(b.home))throw new Error('srvBegin: '+String(b.home).slice(0,20)+' cannot be a home city');
|
||||
if(!b.mp||typeof b.mp!=='object')throw new Error('srvBegin: no session');
|
||||
const D=b.day===undefined?0:b.day;
|
||||
if(!Number.isInteger(D)||D<0||D>1e7)throw new Error('srvBegin: '+String(b.day).slice(0,20)+' is no start day');
|
||||
srvSetPrefs(m.prefs);UI.pitched=true;
|
||||
beginState(String(b.name||'').slice(0,24)||randomNetworkName(),b.home,{mode:'normal',preset:b.preset,mp:b.mp,asn:Number(b.asn)});
|
||||
beginState(String(b.name||'').slice(0,24)||randomNetworkName(),b.home,{mode:'normal',preset:b.preset,mp:b.mp,asn:Number(b.asn),day:D});
|
||||
if(!S.mp)throw new Error('srvBegin: the session did not take');
|
||||
S.mp.sim=1;S.tut=b.tut?0:null;compute();srvFresh(m.epoch);
|
||||
// The welcome: in S.log, and an fx that waits for the first update after the first snapshot (srvPullParts).
|
||||
|
|
|
|||
|
|
@ -150,6 +150,7 @@ function createCore(opts = {}) {
|
|||
e.realm = build(n.nid, n.lang);
|
||||
e.lang = e.realm.lang;
|
||||
const epoch = epochOf();
|
||||
// begin: {name, home, preset, asn, mp, tut, day?}, passed on untouched (srvBegin checks it; day: the session's date).
|
||||
const [h] = n.begin
|
||||
? call(e, 'srvBegin', { begin: n.begin, prefs: n.prefs, epoch, strict: !!opts.strict }, T.load)
|
||||
: call(e, 'srvLoad', { save: n.env.s, uidN: n.env.uidN, rt: n.env.rt, prefs: n.prefs, rng: n.rng, epoch, strict: !!opts.strict }, T.load);
|
||||
|
|
|
|||
|
|
@ -2835,6 +2835,17 @@
|
|||
"keys.show_this_list":"Diese Liste zeigen",
|
||||
"keys.space":"Leertaste",
|
||||
"keys.zoom_the_map_out_or":"Karte heraus- oder hineinzoomen",
|
||||
"late.bank_note":"Weil du dieser Session spät beigetreten bist. Verdoppelt wird, was deine Privatkunden dir nach einem Wholesale-Anteil zahlen, und Investoren bekommen davon nichts ab.",
|
||||
"late.bb_pitch":{"one":"Du bist spät dazugekommen: Noch {n} Tag lang wird verdoppelt, was dir die Haushalte hier zahlen.","other":"Du bist spät dazugekommen: Noch {n} Tage lang wird verdoppelt, was dir die Haushalte hier zahlen."},
|
||||
"late.card":{"one":"Heim-Breitband zahlt noch {n} Tag doppelt: gerade +{price}/Monat.","other":"Heim-Breitband zahlt noch {n} Tage doppelt: gerade +{price}/Monat."},
|
||||
"late.hello":"<b>Spät zur Party, aber willkommen.</b> Diese Session läuft schon {n} Tage, und Hardware kostet {p} mehr als an ihrem ersten Tag, also legt die Bank {cash} auf dein Startkapital drauf. In deinem ersten Jahr wird jeder Dollar verdoppelt, den dir deine Privatkunden zahlen: Heim-Breitband zahlt doppelt.",
|
||||
"late.hello_flat":"<b>Spät zur Party, aber willkommen.</b> Diese Session läuft schon {n} Tage. In deinem ersten Jahr wird jeder Dollar verdoppelt, den dir deine Privatkunden zahlen: Heim-Breitband zahlt doppelt.",
|
||||
"late.match":"Heim-Breitband verdoppelt",
|
||||
"late.over":"Dein Jahr als Nachzügler ist vorbei: Heim-Breitband zahlt wieder den normalen Satz.",
|
||||
"late.this_month":"Aufschlag diesen Monat",
|
||||
"late.title":"Vorsprung für Nachzügler",
|
||||
"late.top_up":"Aufstockung des Startkapitals",
|
||||
"late.until":"bis {date}",
|
||||
"latency_contracts.credits_paid":"{price} an SLA-Gutschriften gezahlt",
|
||||
"latency_contracts.over_sla":"<b>{name}</b>: {a} ⇄ {b} läuft mit {ms} ms, über den {max} ms aus dem Vertrag. Jeder Tag darüber kostet dich eine Tagesgebühr an SLA-Gutschriften ({price}).",
|
||||
"latency_contracts.sla_terms":"Latenz-SLA {ms} ms: eine Tagesgebühr zurück für jeden Tag darüber · nie mehr als {max}",
|
||||
|
|
|
|||
|
|
@ -2833,6 +2833,17 @@
|
|||
"keys.show_this_list":"Mostrar esta lista",
|
||||
"keys.space":"Espacio",
|
||||
"keys.zoom_the_map_out_or":"Alejar o acercar el mapa",
|
||||
"late.bank_note":"Por unirte tarde a esta sesión. Se iguala lo que te pagan tus hogares después de cualquier parte mayorista, y los inversores no se llevan nada de ello.",
|
||||
"late.bb_pitch":{"one":"Llegaste tarde: durante {n} día más, se iguala lo que te pagan los hogares de aquí.","other":"Llegaste tarde: durante {n} días más, se iguala lo que te pagan los hogares de aquí."},
|
||||
"late.card":{"one":"La banda ancha doméstica paga el doble durante {n} día más: +{price}/mes ahora mismo.","other":"La banda ancha doméstica paga el doble durante {n} días más: +{price}/mes ahora mismo."},
|
||||
"late.hello":"<b>Llegas tarde a la fiesta, pero bienvenido.</b> Esta sesión tiene {n} días y el hardware cuesta {p} más que en su primer día, así que el banco añade {cash} a tu capital inicial. Durante tu primer año, cada dólar que te pagan tus hogares se iguala: la banda ancha doméstica paga el doble.",
|
||||
"late.hello_flat":"<b>Llegas tarde a la fiesta, pero bienvenido.</b> Esta sesión tiene {n} días. Durante tu primer año, cada dólar que te pagan tus hogares se iguala: la banda ancha doméstica paga el doble.",
|
||||
"late.match":"Banda ancha doméstica igualada",
|
||||
"late.over":"Tu año de recién llegado terminó: la banda ancha doméstica vuelve a pagar la tarifa normal.",
|
||||
"late.this_month":"Igualado este mes",
|
||||
"late.title":"Ventaja del recién llegado",
|
||||
"late.top_up":"Refuerzo del capital inicial",
|
||||
"late.until":"hasta el {date}",
|
||||
"latency_contracts.credits_paid":"{price} pagados en créditos SLA",
|
||||
"latency_contracts.over_sla":"<b>{name}</b>: {a} ⇄ {b} va a {ms} ms, por encima de los {max} ms del contrato. Cada día por encima te cuesta un día de cuota en créditos SLA ({price}).",
|
||||
"latency_contracts.sla_terms":"SLA de latencia {ms} ms: un día de cuota devuelto por cada día por encima · nunca más de {max}",
|
||||
|
|
|
|||
|
|
@ -2833,6 +2833,17 @@
|
|||
"keys.show_this_list":"Afficher cette liste",
|
||||
"keys.space":"Espace",
|
||||
"keys.zoom_the_map_out_or":"Dézoomer ou zoomer la carte",
|
||||
"late.bank_note":"Pour avoir rejoint cette session en retard. Ce que tes abonnés te paient après toute part de gros est doublé, et les investisseurs n’en prennent aucune part.",
|
||||
"late.bb_pitch":{"one":"Tu es arrivé tard : pendant encore {n} jour, ce que les foyers d’ici te paient est doublé.","other":"Tu es arrivé tard : pendant encore {n} jours, ce que les foyers d’ici te paient est doublé."},
|
||||
"late.card":{"one":"Le haut débit résidentiel paie double encore {n} jour : +{price}/mois en ce moment.","other":"Le haut débit résidentiel paie double encore {n} jours : +{price}/mois en ce moment."},
|
||||
"late.hello":"<b>En retard à la fête, mais bienvenue.</b> Cette session a {n} jours et le matériel coûte {p} de plus qu’à son premier jour, alors la banque ajoute {cash} à ta mise de départ. Pendant ta première année, chaque dollar que tes abonnés te paient est doublé : le haut débit résidentiel paie double.",
|
||||
"late.hello_flat":"<b>En retard à la fête, mais bienvenue.</b> Cette session a {n} jours. Pendant ta première année, chaque dollar que tes abonnés te paient est doublé : le haut débit résidentiel paie double.",
|
||||
"late.match":"Haut débit résidentiel doublé",
|
||||
"late.over":"Ton année de retardataire est terminée : le haut débit résidentiel paie de nouveau le tarif normal.",
|
||||
"late.this_month":"Bonus ce mois-ci",
|
||||
"late.title":"Coup de pouce du retardataire",
|
||||
"late.top_up":"Complément de mise de départ",
|
||||
"late.until":"jusqu’au {date}",
|
||||
"latency_contracts.credits_paid":"{price} versés en crédits SLA",
|
||||
"latency_contracts.over_sla":"<b>{name}</b> : {a} ⇄ {b} tourne à {ms} ms, au-delà des {max} ms du contrat. Chaque jour au-dessus te coûte une journée de facture en crédits SLA ({price}).",
|
||||
"latency_contracts.sla_terms":"SLA de latence {ms} ms : une journée de facture remboursée par jour au-dessus · jamais plus de {max}",
|
||||
|
|
|
|||
|
|
@ -2833,6 +2833,17 @@
|
|||
"keys.show_this_list":"Mostra questo elenco",
|
||||
"keys.space":"Spazio",
|
||||
"keys.zoom_the_map_out_or":"Zoom indietro o avanti sulla mappa",
|
||||
"late.bank_note":"Perché sei entrato tardi in questa sessione. Viene raddoppiato quello che ti pagano le tue case dopo l’eventuale quota all’ingrosso, e gli investitori non ne prendono una parte.",
|
||||
"late.bb_pitch":{"one":"Sei arrivato tardi: per {n} altro giorno, quello che ti pagano le case qui viene raddoppiato.","other":"Sei arrivato tardi: per altri {n} giorni, quello che ti pagano le case qui viene raddoppiato."},
|
||||
"late.card":{"one":"La banda larga domestica paga il doppio per {n} altro giorno: +{price}/mese adesso.","other":"La banda larga domestica paga il doppio per altri {n} giorni: +{price}/mese adesso."},
|
||||
"late.hello":"<b>In ritardo alla festa, ma benvenuto.</b> Questa sessione ha {n} giorni e l’hardware costa il {p} in più che al suo primo giorno, quindi la banca aggiunge {cash} al tuo capitale iniziale. Per il tuo primo anno, ogni dollaro che ti pagano le tue case viene raddoppiato: la banda larga domestica paga il doppio.",
|
||||
"late.hello_flat":"<b>In ritardo alla festa, ma benvenuto.</b> Questa sessione ha {n} giorni. Per il tuo primo anno, ogni dollaro che ti pagano le tue case viene raddoppiato: la banda larga domestica paga il doppio.",
|
||||
"late.match":"Banda larga domestica raddoppiata",
|
||||
"late.over":"Il tuo anno da ritardatario è finito: la banda larga domestica torna a pagare la tariffa normale.",
|
||||
"late.this_month":"Raddoppio di questo mese",
|
||||
"late.title":"Vantaggio del ritardatario",
|
||||
"late.top_up":"Integrazione del capitale iniziale",
|
||||
"late.until":"fino al {date}",
|
||||
"latency_contracts.credits_paid":"{price} pagati in crediti SLA",
|
||||
"latency_contracts.over_sla":"<b>{name}</b>: {a} ⇄ {b} viaggia a {ms} ms, oltre i {max} ms del contratto. Ogni giorno sopra ti costa un giorno di canone in crediti SLA ({price}).",
|
||||
"latency_contracts.sla_terms":"SLA di latenza {ms} ms: un giorno di canone restituito per ogni giorno sopra · mai più di {max}",
|
||||
|
|
|
|||
|
|
@ -2833,6 +2833,17 @@
|
|||
"keys.show_this_list":"Mostrar esta lista",
|
||||
"keys.space":"Espaço",
|
||||
"keys.zoom_the_map_out_or":"Afastar ou aproximar o mapa",
|
||||
"late.bank_note":"Por entrar tarde nesta sessão. O que suas residências te pagam depois de qualquer parte do atacado é dobrado, e os investidores não levam parte disso.",
|
||||
"late.bb_pitch":{"one":"Você chegou tarde: por mais {n} dia, o que as residências daqui te pagam é dobrado.","other":"Você chegou tarde: por mais {n} dias, o que as residências daqui te pagam é dobrado."},
|
||||
"late.card":{"one":"A banda larga residencial paga em dobro por mais {n} dia: +{price}/mês agora.","other":"A banda larga residencial paga em dobro por mais {n} dias: +{price}/mês agora."},
|
||||
"late.hello":"<b>Atrasado para a festa, mas boas-vindas.</b> Esta sessão tem {n} dias e o hardware custa {p} a mais do que no primeiro dia dela, então o banco acrescenta {cash} ao seu capital inicial. No seu primeiro ano, cada dólar que suas residências te pagam é dobrado: a banda larga residencial paga em dobro.",
|
||||
"late.hello_flat":"<b>Atrasado para a festa, mas boas-vindas.</b> Esta sessão tem {n} dias. No seu primeiro ano, cada dólar que suas residências te pagam é dobrado: a banda larga residencial paga em dobro.",
|
||||
"late.match":"Banda larga residencial dobrada",
|
||||
"late.over":"Seu ano de retardatário acabou: a banda larga residencial volta a pagar a tarifa normal.",
|
||||
"late.this_month":"Dobra deste mês",
|
||||
"late.title":"Vantagem do retardatário",
|
||||
"late.top_up":"Reforço do capital inicial",
|
||||
"late.until":"até {date}",
|
||||
"latency_contracts.credits_paid":"{price} pagos em créditos de SLA",
|
||||
"latency_contracts.over_sla":"<b>{name}</b>: {a} ⇄ {b} roda a {ms} ms, acima dos {max} ms do contrato. Cada dia acima te custa um dia de mensalidade em créditos de SLA ({price}).",
|
||||
"latency_contracts.sla_terms":"SLA de latência {ms} ms: um dia de mensalidade devolvido por cada dia acima · nunca mais que {max}",
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ const API_STATE_DOC={
|
|||
name:{type:'string',doc:'Your network\'s name.'},
|
||||
asn:{type:'integer',doc:'Your AS number.'},
|
||||
home:{type:'string',doc:'The city you started in.'},
|
||||
day:{type:'integer',doc:'Days since the company was founded.'},
|
||||
day:{type:'integer',doc:'The calendar day (shared by every network of a server session); day − day0 is the network\'s age.'},
|
||||
day0:{type:'integer',doc:'The calendar day this network began: 0, or the session\'s date for a network that joined a server session late.'},
|
||||
cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'},
|
||||
priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'},
|
||||
mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'},
|
||||
|
|
@ -145,7 +146,7 @@ const API_RESULTS_DOC={
|
|||
revMo:{type:'number',doc:'Revenue per month.'},
|
||||
costMo:{type:'number',doc:'Cost per month.'},
|
||||
cost:{type:'map',doc:'Monthly cost by category (transit, pni, ix, links…).'},
|
||||
rev:{type:'map',doc:'Monthly revenue by source.'},
|
||||
rev:{type:'map',doc:'Monthly revenue by source (late: a late joiner\'s first-year match of what its homes pay).'},
|
||||
reachable:{type:'map',doc:'Networks reachable per net id.'},
|
||||
cone:{type:'map',doc:'Which peer\'s customer cone carries each network you reach without transit of your own, by net id.'},
|
||||
ddos:{type:'array',doc:'Per live attack: the target, its size, which ports it fills, what Flowspec and each scrubbing centre cleaned, and what reaches the target.'},
|
||||
|
|
|
|||
|
|
@ -81,7 +81,7 @@ function apiStatus(){
|
|||
const goal=goals().find(g=>S.done[g.id]===undefined),t1=isTier1(),k=o=>Object.fromEntries(Object.entries(o||{}).map(([a,v])=>[a,Math.round(v)]).filter(([,v])=>v));
|
||||
return {
|
||||
name:S.name,asn:S.asn,home:apiCityName(S.home),mode:S.mode,rules:S.rules&&S.rules.preset,
|
||||
day:S.day,date:dateStr(S.day),cash:Math.round(S.cash),level:S.lvl||0,
|
||||
day:S.day,age:netAge(),date:dateStr(S.day),cash:Math.round(S.cash),level:S.lvl||0,
|
||||
tier:tierLabel(),whyNotTier1:t1?null:apiText(t1Why()),
|
||||
goal:goal?{title:apiText(goal.t),what:apiText(goal.d)}:null,
|
||||
monthly:{revenue:Math.round(R.revMo),cost:Math.round(R.costMo),profit:Math.round(R.revMo-R.costMo),revenueBy:k(R.rev),costBy:k(R.cost)},
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ function hwMul(k){if(!S||!rule('market'))return 1;const l=hwLock();if(l)return l
|
|||
const hwLockCost=()=>Math.round((80000+30000*Object.keys(S.pops).length)*(hwShock()?2:1)/1000)*1000;
|
||||
function hwShockStart(){const k=pick(Object.keys(HW_SHOCK)),n=45+Math.floor(Math.random()*31);S.hw=S.hw||{};S.hw.shock={k,until:S.day+n,mul:HW_SHOCK[k].mul};
|
||||
toast(tr(HW_SHOCK[k].msg,{n})+(hwLock()?'<br>'+tr('supply_chain.your_price_lock_covers_you_until',{date:dateStr(hwLock().until)}):''),hwLock()?'':'bad');sfx('alert');}
|
||||
function hwCard(){if(!S||!rule('market')||(S.day<=HW_FREE&&!hwShock()&&!hwLock()))return '';const t=hwTrend(S.day),s=hwShock(),l=hwLock();
|
||||
function hwCard(){if(!S||!rule('market')||(S.day<=HW_FREE&&!hwShock()&&!hwLock()))return '';const t=hwTrend(S.day)/hwTrend(S.day0|0),s=hwShock(),l=hwLock();
|
||||
return `<div class="ibx"><div class="nm">📦 ${tr('common.supply_chain')}</div>
|
||||
<div class="kv"><span>${tr('common.hardware_prices')}</span><b>${t>1.005?tr('supply_chain.p_since_you_started',{p:pct(t-1)}):tr('supply_chain.as_when_you_started')}</b></div>
|
||||
<div class="kv"><span>${tr('lifecycle.bandwidth_prices')}</span><b>${mktTxt()}</b></div>
|
||||
|
|
|
|||
|
|
@ -130,6 +130,6 @@ function loanTick(d){
|
|||
const broke=S.cash<0;
|
||||
// With half a billion in the vault, loan offers are just noise (#52): banks stop calling, open offers lapse.
|
||||
if(S.cash>=RICH_NO_LOANS){if(S.loanOffers.length||!S.richTold){S.loanOffers=[];if(!S.richTold&&S.mode!=='sandbox'){S.richTold=1;toast(tr('banks.the_banks_have_stopped_calling_you',{cash:fmt$(RICH_NO_LOANS)}),'good');}}return;}
|
||||
if(S.loanOffers.length<4&&(broke?Math.random()<0.25:(d>20&&Math.random()<1/40)))spawnLoanOffer(broke);
|
||||
if(S.loanOffers.length<4&&(broke?Math.random()<0.25:(d-S.day0>20&&Math.random()<1/40)))spawnLoanOffer(broke);
|
||||
}
|
||||
const RICH_NO_LOANS=5e8;
|
||||
|
|
|
|||
|
|
@ -58,9 +58,12 @@ function beginState(nm,city,o={}){newGame(nm,city);if(asnOk(o.asn))S.asn=o.asn;S
|
|||
if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}}
|
||||
if(o.scn){const sc=o.scn;S.scn={id:sc.id,rules:sc.rules||{},days:sc.days,name:sc.n||tr('features.weekly_challenge_key',{key:sc.key}),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';S.asn=200000+Math.floor(Math.random()*15000);
|
||||
if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup();
|
||||
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}}
|
||||
for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}}
|
||||
// o.day: a network of a server session begins on the session's date (81-late-joiners.js), after its rules are locked.
|
||||
if(S.mp&&S.mode==='normal'&&Number.isInteger(o.day)&&o.day>0)lateStart(Math.min(o.day,1e7));}
|
||||
// The welcome line: in the log, and on screen.
|
||||
function beginHello(o={}){toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(S.name),asn:S.asn,city:CITY[S.home].name}),'goal');}
|
||||
function beginHello(o={}){toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(S.name),asn:S.asn,city:CITY[S.home].name}),'goal');
|
||||
if(lateIs())lateHello();}
|
||||
function beginShow(city,o={}){
|
||||
// Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen.
|
||||
UI.lastSpeed=rule('clock')?0.5:0;setSpeed(UI.lastSpeed);UI.resumeSpeed=null;
|
||||
|
|
|
|||
|
|
@ -105,7 +105,7 @@ function specDay(d){if(broker())brokerDay(d);if(S.seatOff&&S.seatOff.exp<=d)S.se
|
|||
if(charter()==='boutique'&&!S.solWon&&solRoutes().length>=SOL_ROUTES&&solCust()>=SOL_CUST){S.solWon=Math.max(1,d);track('win_sol');toast(`<b>⚡ ${tr('specialist.speed_of_light')}</b><br>${tr('specialist.your_own_glass_beats_every_leased')}`,'goal');sfx('coin');checkBadges();}}
|
||||
// Saves: the charter, demo orders, a seat on offer and the boutique's and the broker's wins. Old saves are Global
|
||||
// backbone, picked; one still in its first month that never picked is asked again.
|
||||
function specSanitize(s){s.charter=(s.charter==='boutique'||s.charter==='broker')&&s.mode==='normal'&&!s.scn?s.charter:'global';s.chartSet=s.chartSet===false&&s.day<=CHARTER_DAYS?false:true;
|
||||
function specSanitize(s){s.charter=(s.charter==='boutique'||s.charter==='broker')&&s.mode==='normal'&&!s.scn?s.charter:'global';s.chartSet=s.chartSet===false&&s.day-(s.day0|0)<=CHARTER_DAYS?false:true;
|
||||
const dm={};if(s.demo&&typeof s.demo==='object'&&!Array.isArray(s.demo))for(const key of Object.keys(s.demo).slice(0,64)){const [k,id]=key.split(':');if(demoItem(k,id)&&Number.isFinite(+s.demo[key]))dm[key]=Math.round(+s.demo[key]);}s.demo=dm;
|
||||
const o=s.seatOff;s.seatOff=o&&typeof o==='object'&&typeof o.name==='string'&&seatRoute(o.name)&&seatRoute(o.name)[0]===o.a&&seatRoute(o.name)[1]===o.b?{a:o.a,b:o.b,name:o.name,km:seatKm(o.a,o.b),exp:num(o.exp,0)}:null;
|
||||
s.solWon=Number.isFinite(+s.solWon)&&+s.solWon>0?Math.round(+s.solWon):0;s.baronWon=Number.isFinite(+s.baronWon)&&+s.baronWon>0?Math.round(+s.baronWon):0;
|
||||
|
|
|
|||
|
|
@ -22,11 +22,11 @@ const baronOk=()=>cableConts()>=BARON_CONT&&capSalesMo()>=BARON_MO;
|
|||
// On the goals tab, under the charter: how far Glass Baron is.
|
||||
function baronCard(){if(S.baronWon)return `<div class="inc" style="background:var(--tint-g,#EAF7EE)"><div class="nm">🌊 ${tr('broker.glass_baron')}</div><div class="meta">${tr('broker.won_on_date',{date:dateStr(S.baronWon)})}</div></div>`;
|
||||
return `<div class="inc" style="background:var(--tint-b,#E6F4FF)"><div class="nm">🌊 ${tr('broker.glass_baron')}</div><div class="meta">${tr('broker.progress',{c:Math.min(cableConts(),BARON_CONT),n:BARON_CONT,mo:fmt$(capSalesMo()),m:fmt$(BARON_MO)})}</div></div>`;}
|
||||
function showBaronWin(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">🌊 ${tr('broker.glass_baron')}</h1><p class="tagline">${tr('broker.win_text',{name:esc(S.name),asn:S.asn,days:S.day,n:BARON_CONT,mo:fmt$(capSalesMo())})}</p><div class="btns">${btn(tr('help.share_my_network'),'share',{},'pink')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost')}</div>`);}
|
||||
function showBaronWin(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">🌊 ${tr('broker.glass_baron')}</h1><p class="tagline">${tr('broker.win_text',{name:esc(S.name),asn:S.asn,days:netAge(),n:BARON_CONT,mo:fmt$(capSalesMo())})}</p><div class="btns">${btn(tr('help.share_my_network'),'share',{},'pink')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost')}</div>`);}
|
||||
/* Carriers call the broker now and then (about three times a year, from day 60) with a capacity deal on a route the
|
||||
capacity conferences trade: the same deals at the same terms, without the trip. Picked by a hash of the day, so a
|
||||
broker's other dice roll as they would. */
|
||||
function brokerDay(d){if(d<BROKER_CALL_FROM||S.scn||hstr(S.asn+'|capcall|'+d)%BROKER_CALL!==0)return;
|
||||
function brokerDay(d){if(d-S.day0<BROKER_CALL_FROM||S.scn||hstr(S.asn+'|capcall|'+d)%BROKER_CALL!==0)return;
|
||||
const pool=Object.values(CAP_ROUTES).flat().filter(r=>isCity(r[0])&&isCity(r[1])&&!S.offers.some(o=>o.city===r[0]&&o.city2===r[1]&&o.type===r[2]));if(!pool.length)return;
|
||||
const [a,b,t]=pool[hstr(S.asn+'|caproute|'+d)%pool.length],T=BIZ_T[t];
|
||||
const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;};
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ const TUT=[
|
|||
{t:tr('tutorial.your_router_is_live_press_launch'),sel:'[data-act="launchBB"]',ok:()=>S.pops[S.home]&&S.pops[S.home].bb},
|
||||
{t:tr('tutorial.your_customers_want_the_whole'),sel:'[data-act="tab"][data-args*=\'"up"\'],[data-act="buyTransit"]',ok:()=>S.transit.length>0,skip:()=>!NETS.some(n=>sellsAt(n,S.home))},
|
||||
{t:tr('tutorial.transit_costs_money_per_gigabit'),sel:'[data-act="tab"][data-args*=\'"peer"\'],[data-act="buyIx"],[data-act="rs"]',ok:()=>Object.keys(S.rs).length>0,skip:()=>!ixName(S.home)},
|
||||
{t:tr('tutorial.start_the_clock_with_1_and'),sel:'#sp1',ok:()=>S.day>=5},
|
||||
{t:tr('tutorial.start_the_clock_with_1_and'),sel:'#sp1',ok:()=>netAge()>=5},
|
||||
{t:tr('tutorial.grow_drag_from_your_pink_router'),sel:null,ok:()=>S.links.length>0},
|
||||
{t:tr('tutorial.businesses_pop_up_as_bubbles_on'),sel:'[data-act="leftTab"][data-args*=\'"deals"\']',ok:()=>S.biz.length>0},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// Every field a reload gives a game is here from the start (sanitize() would add the rest), so a new game is what a
|
||||
// reload makes of it: a server checks every action against that (tests/canonical-state.test.js).
|
||||
function newGame(name,home){
|
||||
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
|
||||
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,day0:0,cash:START_CASH,
|
||||
ltv:2,t1v:4,auV:1,calV:1,pieV:1,pie:null,ip4:ip4New(),ops:opsNew(),slAuto:slAutoNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
|
||||
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},vol:0,cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,popTiers:ptNew(),won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',cm:cmNew(),chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0},mp:null,
|
||||
lvl:1,hist:[],ach:{},ixn:{},ixPref:{},ixSite:{},confReg:{},cl:{odd:-1e9,mo:[]},sales:{p:null,hired:0,vp:null,golf:null,say:null},baronWon:0};
|
||||
|
|
|
|||
27
src/game/60-features/81-late-joiners.js
Normal file
27
src/game/60-features/81-late-joiners.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
/* ---------- Late joiners (server sessions, docs/plans/server-run.md "What Q1 changes") ----------
|
||||
A network that joins a session after its market started moving starts on the session's date (S.day0), with its
|
||||
first-days rules counted from there (netAge()), a top-up as large as the rise in hardware prices, and its first year
|
||||
of home broadband income matched: what its homes pay after any wholesale cut, outside investors' share (they funded
|
||||
the business, not a subsidy). Only S.day0 is stored; being late, the year and the top-up follow from it. The market
|
||||
and the calendar stay on the session's date: one market for everyone (gameplay rule F11). */
|
||||
// Until day 180 the shared market has not moved (HW_FREE, MK_FREE, IP4_FREE): a joiner then gets nothing extra.
|
||||
const LATE_FROM=180,LATE_DAYS=365;
|
||||
const lateIs=()=>!!S&&(S.day0|0)>LATE_FROM;
|
||||
const lateOn=()=>lateIs()&&S.day<=S.day0+LATE_DAYS;
|
||||
const lateLeft=()=>lateIs()?Math.max(0,S.day0+LATE_DAYS-S.day):0;
|
||||
// The top-up buys what START_CASH bought on day 0 (hardware only: customer prices are what the match makes up for).
|
||||
const lateCash=d=>d>LATE_FROM&&rule('market')?Math.round(START_CASH*(hwTrend(d)-1)/1000)*1000:0;
|
||||
// beginState's last step: the network begins on day D, its schedules and its first block stamped with that day (a block
|
||||
// stamped 0 could be sold on the first day at the session's price).
|
||||
function lateStart(D){S.day=S.day0=D;S.nextFail+=D;S.nextEvent+=D;S.pops[S.home].day=D;for(const b of S.ip4.b)b.d=D;S.cash+=lateCash(D);}
|
||||
// computeMoney: the match, once more what homes pay after the Australian wholesale cut or levy.
|
||||
function lateMoney(V,C){if(!lateOn())return;const v=V.eyeballs-(C.wholesale||0)-(C.levy||0);if(v>0)V.late=v;}
|
||||
function lateHello(){const n=S.day0,g=lateCash(n),t=hwTrend(n)-1;
|
||||
toast(g>0?tr('late.hello',{n,p:pct(t),cash:fmt$(g)}):tr('late.hello_flat',{n}),'goal',[{l:tr('common.bank'),act:'bank',args:{}}]);}
|
||||
function lateDay(d){if(lateIs()&&d===S.day0+LATE_DAYS+1)toast(tr('late.over'),'');}
|
||||
function lateCard(){const n=lateLeft();if(!n)return '';
|
||||
return `<div class="inc" style="background:var(--tint-g,#EAF7EE)"><div class="nm">🎟️ ${tr('late.title')}</div><div class="meta">${trn('late.card',n,{price:fmt$((R&&R.rev&&R.rev.late)||0)})}</div></div>`;}
|
||||
function lateBank(){if(!lateLeft())return '';const g=lateCash(S.day0),kv=(l,v)=>`<div class="kv"><span>${l}</span><b>${v}</b></div>`;
|
||||
return `<section class="bank-gov"><h3 style="font-size:18px;margin-top:14px">🎟️ ${tr('late.title')}</h3><div class="ops-o">${g>0?kv(tr('late.top_up'),fmt$(g)):''}`
|
||||
+kv(tr('late.match'),tr('late.until',{date:dateStr(S.day0+LATE_DAYS)}))+kv(tr('late.this_month'),tr('common.price_mo',{price:fmt$((R&&R.rev&&R.rev.late)||0)}))
|
||||
+`<p class="meta">${tr('late.bank_note')}</p></div></section>`;}
|
||||
|
|
@ -22,6 +22,8 @@ const monthIdx=d=>{const c=cal(d);return (c.y-1)*12+c.m;},monLen=d=>{const c=cal
|
|||
// A monthly date that started on day s: the same day of the month, or the month's last day when it is shorter.
|
||||
const monthiversary=(s,d)=>{if(d<=s)return false;const a=cal(s),b=cal(d);return b.d===Math.min(a.d,monDays(b.y,b.m));};
|
||||
function dateStr(d){const c=cal(d);return tr('helpers.y_y_mon_d',{y:c.y,mon:MONTHS[c.m],d:c.d});}
|
||||
// The network's age in days: S.day is the calendar (a server session's, shared), S.day0 the day this network began.
|
||||
const netAge=()=>S?S.day-(S.day0|0):0;
|
||||
function wrapDx(a,b){let dx=b-a;if(dx>W/2)dx-=W;if(dx<-W/2)dx+=W;return dx;}
|
||||
function kmBetween(a,b){const A=CITY[a],B=CITY[b];return Math.max(20,Math.round(hav(A.lon,A.lat,B.lon,B.lat)));}
|
||||
// Cities on a land bridge belong to two landmasses: Cairo reaches Asia overland across the Sinai, the way
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
const SOLD_WIN=90,SOLD_WHY=[N_('sold_out.a_hyperscaler_bought_every_wave_of'),N_('sold_out.the_carrier_is_out_of_spectrum'),N_('sold_out.the_transponders_for_this_route_are'),N_('sold_out.the_capacity_is_available_in_the'),N_('sold_out.their_capacity_planner_is_on_holiday'),N_('sold_out.the_upgrade_is_planned_for_q3')];
|
||||
const soldP=tier=>Math.min(0.1,0.02+0.012*tier);
|
||||
// Never in the first 90 days: a new network has enough on its plate. Never in the tutorial or a scenario's first quarter either.
|
||||
function soldOut(a,b,tier,via){if(!S||S.day<SOLD_WIN||S.tut||!rule('market'))return null;const k=(a<b?a+b:b+a)+'|'+(via||'')+'|'+tier,off=hstr(k)%SOLD_WIN,ep=Math.floor((S.day+off)/SOLD_WIN),h=hstr(S.asn+'|'+k+'|'+ep);
|
||||
function soldOut(a,b,tier,via){if(!S||netAge()<SOLD_WIN||S.tut||!rule('market'))return null;const k=(a<b?a+b:b+a)+'|'+(via||'')+'|'+tier,off=hstr(k)%SOLD_WIN,ep=Math.floor((S.day+off)/SOLD_WIN),h=hstr(S.asn+'|'+k+'|'+ep);
|
||||
if(h%1000>=soldP(tier)*1000)return null;return {why:SOLD_WHY[(h>>>10)%SOLD_WHY.length],until:(ep+1)*SOLD_WIN-off};}
|
||||
function snubWhy(sn){const d=Math.max(1,sn.until-S.day);return sn.why+' '+trn('sold_out.they_will_reconsider_in_n_day',d);}
|
||||
// Paid-peering giants drop the fee for networks too big to ignore (freeLv: the customer level that does it).
|
||||
|
|
|
|||
|
|
@ -274,9 +274,11 @@ function computeMoney(R2,PX=null){
|
|||
if(PX)pieMoney(PX,R2,V);
|
||||
// The UK grant for Pitcairn, its satellite tier once orbit is known; the Rural Digital Pie Fund (99-pie-subsidies.js).
|
||||
{const on=grantOn(R2),sky=!on&&!!PX&&grantSky(R2);V.grant=on?GRANT_MO:sky?GRANT_SKY_MO:0;if(PX)V.gov=pieGovMo();if(PX)R2.pie.gov={rdf:V.gov||0,sky:sky?GRANT_SKY_MO:0};}
|
||||
// A late joiner's first year: home broadband matched (81-late-joiners.js), outside the investors' share like a grant.
|
||||
lateMoney(V,C);
|
||||
// Investors take their share of what customers and tenants pay (an IPv4 block leased out too, as a leased fiber pair),
|
||||
// not of grants or one-off sales.
|
||||
C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix+(V.orbit||0)+(V.ip4||0)+(V.wisp||0));
|
||||
R2.costMo=Object.values(C).reduce((a,b)=>a+b,0);
|
||||
R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0)+(V.ip4||0)+(V.wisp||0);
|
||||
R2.revMo=V.eyeballs+V.business+V.ix+V.grant+(V.gov||0)+(V.orbit||0)+(V.ip4||0)+(V.wisp||0)+(V.late||0);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ function sanitize(s){
|
|||
const arr=k=>{if(!Array.isArray(s[k]))s[k]=[];},obj=k=>{if(!s[k]||typeof s[k]!=='object'||Array.isArray(s[k]))s[k]={};};
|
||||
['links','nni','transit','pni','caches','biz','offers','inc','usedNames','loans','loanOffers','hist','log'].forEach(arr);
|
||||
['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach','pairMet'].forEach(obj);
|
||||
s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000);
|
||||
s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.day0=int(s.day0,0,s.day,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000);
|
||||
s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0);
|
||||
for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'||k==='ddT'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);}
|
||||
for(const k of ['survived','incidents','peak'])s.stats[k]=num(s.stats[k],0);
|
||||
|
|
@ -136,7 +136,7 @@ function migrate(s){sanitize(s);
|
|||
for(const l of s.links||[])if((l.a===c||l.b===c)&&l.kind==='wave')need(l.tier,'maxLT');
|
||||
for(const t of s.transit||[])if(t.city===c)need(t.tier,'maxP');for(const x of s.pni||[])if(x.city===c)need(x.tier,'maxP');if(s.ixp&&s.ixp[c]!==undefined)need(s.ixp[c],'maxP');p.rgen=g;}}for(const b of s.biz||[])if(!b.reqs)b.reqs=BIZ_T[b.type]&&BIZ_T[b.type].div?['diverse']:[];for(const o of s.offers||[])if(!o.reqs)o.reqs=[];if(!s.lvl)s.lvl=1;s.nni=(Array.isArray(s.nni)?s.nni:[]).filter(x=>x&&own(FAB,x.prov)&&isCity(x.city)&&Number.isInteger(x.tier)&&!!NNI[x.tier]);for(const x of s.nni){const n=Math.floor(+x.n||1);if(n>1)x.n=Math.min(LAG_MAX,n);else delete x.n;}s.cnLic=s.cnLic||{state:'none'};s.ev=s.ev||{};for(const l of s.links){if(!l.kind)l.kind='wave';if(l.mo===undefined)l.mo=Math.round(waveMo(l.km,l.sub,l.tier)*(l.mult||1));}for(const c in s.pops){if(!s.pops[c].routers)s.pops[c].routers=1;}
|
||||
{const all=NETS.map(n=>n.id),seen=Array.isArray(s.seen)?s.seen.filter(x=>typeof x==='string'):null,fresh=seen?all.filter(id=>!seen.includes(id)):all;
|
||||
if(fresh.length&&(s.day||0)>0){const g=s.grace&&s.grace.until>s.day?s.grace:{nets:[]};s.grace={until:s.day+GRACE_DAYS,nets:[...new Set(g.nets.concat(fresh))],fresh:seen?fresh.length:0};}
|
||||
if(fresh.length&&s.day>s.day0){const g=s.grace&&s.grace.until>s.day?s.grace:{nets:[]};s.grace={until:s.day+GRACE_DAYS,nets:[...new Set(g.nets.concat(fresh))],fresh:seen?fresh.length:0};}
|
||||
s.seen=all;}
|
||||
// Australian pricing and peering changed in place (#148): a save that was already there gets told once.
|
||||
if(s.auV!==1){if((s.day||0)>0&&Object.keys(s.pops).some(c=>CITY[c].au))s.auNews=true;s.auV=1;}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ const MK_YR=0.10,MK_FREE=180,MK_FLOOR=0.3,MK_SHOCK={opt:1.15,rt:1.1,build:1.08};
|
|||
function mktBase(d){if(d<=MK_FREE)return 1;const y=(d-MK_FREE)/365;
|
||||
return Math.max(MK_FLOOR,Math.pow(1-MK_YR,y)*Math.sqrt(hwTrend(d))*(1+0.06*Math.sin(2*Math.PI*y/3)));}
|
||||
function mkt(){if(!S||!rule('market'))return 1;const s=hwShock();return mktBase(S.day)*(s?MK_SHOCK[s.k]||1:1);}
|
||||
// The market against the network's own first day (a late joiner's start), as the "since you started" lines say it.
|
||||
const mktRel=()=>S&&rule('market')?mkt()/mktBase(S.day0|0):mkt();
|
||||
|
||||
// Terms in months: enterprise and hosting 1–3 years, wholesale and circuits 2–5, IRUs and fiber pairs 10–20.
|
||||
const CL_TERMS={ip:[12,24,36],whole:[24,36,48,60],iru:[120,180,240]};
|
||||
|
|
@ -99,7 +101,7 @@ function clNews(out){
|
|||
const few=(list,kind)=>{for(const t of list.slice(0,3))toast(t,kind);if(list.length>3)toast(trn('lifecycle.n_more',list.length-3),kind);};
|
||||
few(out.ok,'good');ip4News(out.v4);few(out.lost,'');
|
||||
if(out.ren)toast(trn('lifecycle.n_renewed',out.ren,{p:mktTxt()}),'');}
|
||||
const mktTxt=()=>{const m=mkt();return Math.abs(m-1)<0.005?tr('lifecycle.market_as_start'):m<1?tr('lifecycle.market_below',{p:pct(1-m)}):tr('lifecycle.market_above',{p:pct(m-1)});};
|
||||
const mktTxt=()=>{const m=mktRel();return Math.abs(m-1)<0.005?tr('lifecycle.market_as_start'):m<1?tr('lifecycle.market_below',{p:pct(1-m)}):tr('lifecycle.market_above',{p:pct(m-1)});};
|
||||
|
||||
/* Growth by word of mouth: about every six weeks the happiest long-standing customer (a year or more, 90%+ happy)
|
||||
tells someone like them, who shows up in Deals asking for the smallest size at today's price. */
|
||||
|
|
@ -142,7 +144,7 @@ function clPanel(){const C=S.cl||{mo:[]},mo=C.mo.slice(-12);const soon=S.biz.fil
|
|||
<div class="dgrid" style="margin:0 0 8px"><div class="tile"><div class="lbl">${tr('lifecycle.won')}</div><div class="val">${sum('won')}</div><div class="sub">${tr('lifecycle.last_12_months')}</div></div>
|
||||
<div class="tile"><div class="lbl">${tr('lifecycle.lost')}</div><div class="val" style="color:${sum('lost')>sum('won')?'var(--tx-red,var(--bad))':'inherit'}">${sum('lost')}</div><div class="sub">${trn('lifecycle.n_grew',sum('grew'))}</div></div>
|
||||
<div class="tile"><div class="lbl">${tr('lifecycle.renewals_soon')}</div><div class="val">${soon}</div><div class="sub">${tr('lifecycle.next_30_days')}</div></div>
|
||||
<div class="tile"><div class="lbl">${tr('lifecycle.bandwidth_market')}</div><div class="val">${Math.round(mkt()*100)}</div><div class="sub">${mktTxt()}</div></div></div>`;
|
||||
<div class="tile"><div class="lbl">${tr('lifecycle.bandwidth_market')}</div><div class="val">${Math.round(mktRel()*100)}</div><div class="sub">${mktTxt()}</div></div></div>`;
|
||||
if(mo.length){const max=Math.max(1,...mo.map(e=>Math.max(e.won,Object.values(e.lost).reduce((x,y)=>x+y,0)))),W=600,H=120,mid=H/2,bw=W/12;
|
||||
let g=`<line x1="0" x2="${W}" y1="${mid}" y2="${mid}" stroke="#D5DEEC"/>`;
|
||||
mo.forEach((e,i)=>{const lost=Object.values(e.lost).reduce((x,y)=>x+y,0),x=(i+12-mo.length)*bw+bw*0.2,w=bw*0.6,hw=(mid-12)*e.won/max,hl=(mid-12)*lost/max;
|
||||
|
|
|
|||
|
|
@ -37,13 +37,15 @@ function linkLat(l){if(l.kind==='xp')return xpLat(l);if(l.kind==='sat')return sa
|
|||
Each route also gets its own market mood, and new leases get cheaper every year (~8%). */
|
||||
const WAVE_LAND={EU:0.65,AM:1,SA:1.6,AS:1.4,OC:1.2,AF:2.2},WAVE_SUB={EU:0.8,AM:1,SA:2,AS:1.5,OC:1.5,AF:4.5};
|
||||
const WAVE_NAME={EU:tr('common.europe'),AM:tr('common.north_america'),SA:tr('common.south_america'),AS:tr('common.asia'),OC:tr('common.oceania'),AF:tr('common.africa')};
|
||||
// New leases on day d against day 0: 8% cheaper each year, down to 55%.
|
||||
const waveEro=d=>Math.max(0.55,Math.pow(0.92,Math.floor(d/360)));
|
||||
function waveMarket(a,b,sub){const ra=CITY[a].reg,rb=CITY[b].reg,T=sub?WAVE_SUB:WAVE_LAND,au=sub?AU_WAVE.sub:AU_WAVE.land;
|
||||
const fa=CITY[a].au?au:(T[ra]||1),fb=CITY[b].au?au:(T[rb]||1),reg=sub&&nullPair(a,b)?AU_WAVE.ew:sub&&CITY[a].ph&&CITY[b].ph?PH_WAVE:sub?Math.max(fa,fb):(fa+fb)/2;
|
||||
const key=a<b?a+b:b+a,mood=0.85+(hstr(key+'|mood')%31)/100;
|
||||
const ero=Math.max(0.55,Math.pow(0.92,Math.floor((S?S.day:0)/360)));
|
||||
const ero=waveEro(S?S.day:0);
|
||||
return {m:reg*mood*ero,reg,mood,ero};}
|
||||
function marketNote(a,b,sub){const k=waveMarket(a,b,sub),ra=CITY[a].reg,rb=CITY[b].reg;const where=ra===rb?WAVE_NAME[ra]:tr('geography_and_latency.a_to_b',{a:WAVE_NAME[ra],b:WAVE_NAME[rb]});
|
||||
const lvl=k.reg<0.9?tr('geography_and_latency.cheap_lots_of_competing_fiber'):k.reg<=1.05?tr('common.about_average'):k.reg<2?tr('geography_and_latency.pricey_fewer_carriers'):tr('geography_and_latency.expensive_scarce_capacity');const since=k.ero<1?tr('geography_and_latency.and_prices_have_fallen_p_since',{p:Math.round((1-k.ero)*100)}):'';
|
||||
const lvl=k.reg<0.9?tr('geography_and_latency.cheap_lots_of_competing_fiber'):k.reg<=1.05?tr('common.about_average'):k.reg<2?tr('geography_and_latency.pricey_fewer_carriers'):tr('geography_and_latency.expensive_scarce_capacity');const fell=k.ero/waveEro(S?S.day0|0:0),since=fell<1?tr('geography_and_latency.and_prices_have_fallen_p_since',{p:Math.round((1-fell)*100)}):'';
|
||||
return k.mood<0.97?tr('geography_and_latency.where_lvl_this_route_is_p',{where,lvl,p:Math.round((1-k.mood)*100),since}):k.mood>1.03?tr('geography_and_latency.where_lvl_this_route_is_p_0196',{where,lvl,p:Math.round((k.mood-1)*100),since}):tr('geography_and_latency.where_lvl_this_route_is_right',{where,lvl,since});}
|
||||
function waveRoute(a,b,mult,border){const cabs=cablesOk(a,b),sub=isSub(a,b);let via=UI.via;
|
||||
if(!cabs.find(c=>c.cid===via))via=sub?(cabs[0]?cabs[0].cid:null):(via==='land'||!via?'land':'land');
|
||||
|
|
|
|||
|
|
@ -69,7 +69,7 @@ const ddEraMax=()=>LEVELS.reduce((a,L)=>a*(L.era||1),1);
|
|||
function ddosSize(a){const fl=scnRule('ddos'),r=Math.random(),cap=DD_REC*eraMul()/ddEraMax();
|
||||
if(fl&&r<1/3)return Math.round(Math.min(cap,(800+7800*r)*(1+S.day/365)));
|
||||
const u=fl?(r-1/3)*1.5:r,base=4*eraMul()*(ddGame(a.tgt)?2:1)*(fl?8:1);let g=Math.min(cap,base*Math.pow(Math.max(u,1e-9),-1/0.9));
|
||||
if(!fl&&(S.day<180||Object.keys(S.pops).length<2))g=Math.min(g,2*ddMaxPort());
|
||||
if(!fl&&(netAge()<180||Object.keys(S.pops).length<2))g=Math.min(g,2*ddMaxPort());
|
||||
return Math.max(0.1,Math.round(g*10)/10);}
|
||||
// Flood Season: 3 to 7 days apart, shrinking with age, level and gamers when attacks are spicy.
|
||||
const floodGap=()=>!ddosSpicy()&&!ddAttract()?3+Math.floor(Math.random()*5):Math.max(0.05,(3+Math.random()*5)/(Math.sqrt(1+S.day/180)*(1+ddAttract()/10+Math.max(0,(S.lvl||1)-1)/12)));
|
||||
|
|
@ -77,7 +77,7 @@ function ddosTick(){if(scnRule('ddos')){if(S.mode==='sandbox')return;let next=+S
|
|||
// Unless spicy, floods take turns: the next one waits until the last is over.
|
||||
if(!ddosSpicy()&&ddosAll().length)return;
|
||||
while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next<S.day?S.day+floodGap():next;return;}
|
||||
if(ddosOff()||S.day<=40)return;if(ddosAll().length>=(ddosSpicy()?3:2))return;if(Math.random()<ddosRate())ddosAttack(false);}
|
||||
if(ddosOff()||netAge()<=40)return;if(ddosAll().length>=(ddosSpicy()?3:2))return;if(Math.random()<ddosRate())ddosAttack(false);}
|
||||
// A start older than a week no longer counts toward the cap: forgotten the morning it ages out, as sanitize() forgets it.
|
||||
function ddosForget(d){const s=S.ddosStarts;if(Array.isArray(s)&&s.length&&s[0]<=d-7)S.ddosStarts=s.filter(x=>x>d-7);}
|
||||
// A new attack. With recompute, its outcome is worked out and announced now; otherwise after the day's routing.
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ function* failureRun(only){
|
|||
if(Object.values(S.pops).some(p=>p.site2))opts.push(['ring',1.2]);
|
||||
if(S.transit.some(t=>!(t.down>S.day)))opts.push(['transit',3]);
|
||||
if(Object.keys(S.ixp).length)opts.push(['ixloop',2]);
|
||||
if(S.transit.length&&S.day>60)opts.push(['leak',2]);
|
||||
if(S.transit.length&&netAge()>60)opts.push(['leak',2]);
|
||||
if(fabsUsed.length)opts.push(['fabric',1.5]);
|
||||
// A geomagnetic storm: rare, and only while a LEO circuit of yours is in the sky.
|
||||
if(!leoStorm()&&leoLive())opts.push(['leostorm',LEO_STORM_W]);
|
||||
|
|
@ -32,7 +32,7 @@ function* failureRun(only){
|
|||
let tot=opts.reduce((a,o)=>a+o[1],0),r=Math.random()*tot,type=opts[0][0];
|
||||
for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}
|
||||
if(only)type=only;
|
||||
if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');else if(bare.length)f.push('loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(amps.length)f.push('roadmff');type=pick(f);}
|
||||
if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');else if(bare.length)f.push('loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(S.transit.length)f.push('prepend');if(netAge()>30)f.push('rpki');if(amps.length)f.push('roadmff');type=pick(f);}
|
||||
const before=R.served;
|
||||
if(type==='harmless'){const m=pick(HARMLESS);S.stats.incidents++;S.stats.survived++;toast(`<b>${m[0]}</b><br>${m[1]}`,'goal');sfx('alert');return;}
|
||||
if(type==='ring'){const cs=Object.keys(S.pops).filter(c=>S.pops[c].site2),c=pick(cs),pp=S.pops[c],dur=2+Math.floor(Math.random()*3);pp.ringcut=S.day+dur;
|
||||
|
|
|
|||
|
|
@ -5,11 +5,11 @@ const evRoute=()=>{if(EV_DEFER)EV_DEFER.n++;else compute();};
|
|||
function* eventRun(){const k={n:0};EV_DEFER=k;try{fireEvent();}finally{EV_DEFER=null;}for(let i=0;i<k.n;i++)yield;}
|
||||
function fireEvent(){
|
||||
const opts=['viral','price','grant'];
|
||||
if(S.day>50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic');
|
||||
if(netAge()>50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic');
|
||||
// Without a market (Change Freeze), no shortages and no trade war on optics.
|
||||
if(!rule('market')&&opts.includes('tariff'))opts.splice(opts.indexOf('tariff'),1);
|
||||
if(S.day>HW_FREE&&!hwShock()&&rule('market'))opts.push('hwshock');
|
||||
if(S.day>90&&S.links.filter(l=>l.kind==='wave'&&!l.sub).length>=3)opts.push('ctrlplane');
|
||||
if(netAge()>HW_FREE&&!hwShock()&&rule('market'))opts.push('hwshock');
|
||||
if(netAge()>90&&S.links.filter(l=>l.kind==='wave'&&!l.sub).length>=3)opts.push('ctrlplane');
|
||||
if(Object.keys(S.pops).some(ruCity))opts.push('runet','runet');
|
||||
if(S.pops.doh&&Object.keys(S.pops).some(c=>CITY[c].gcc||CITY[c].uae)&&!(S.ev.gulf>S.day))opts.push('gulf');
|
||||
if(Object.keys(S.pops).some(c=>CITY[c].saudi))opts.push('mega');
|
||||
|
|
|
|||
|
|
@ -27,13 +27,14 @@ function* dayPreRun(){
|
|||
S.day++;
|
||||
const d=S.day;
|
||||
// A charter never picked reads as the classic one once its days are over, as a reload reads it (specSanitize).
|
||||
if(S.chartSet===false&&d>CHARTER_DAYS)S.chartSet=true;
|
||||
if(S.chartSet===false&&d-S.day0>CHARTER_DAYS)S.chartSet=true;
|
||||
ddosForget(d);dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d);
|
||||
yield DAY_REST;
|
||||
if(!S.phpDone&&d>45&&Math.random()<1/400)elephant();
|
||||
if(!S.phpDone&&d-S.day0>45&&Math.random()<1/400)elephant();
|
||||
if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved);
|
||||
{const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('day_tick.you_are_no_longer_tier_1',{why:t1Why()}),'bad');S.t1Now=t1;}
|
||||
if(S.grace&&S.grace.until===d){toast(tr('day_tick.the_courtesy_route_has_ended_new'),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
|
||||
lateDay(d);
|
||||
if(R)ddosTrack(ddosAll(S,false).filter(a=>a.until>=d));
|
||||
ddosExpire();
|
||||
ddosTick();
|
||||
|
|
@ -134,7 +135,7 @@ function* dayPost(d){
|
|||
}
|
||||
function spawnOffer(){
|
||||
const mine=spMine(Object.keys(S.pops).filter(bizCity)),lv=lvl();
|
||||
const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>60)types.push('scrub');
|
||||
const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(netAge()>60)types.push('scrub');
|
||||
if(lv>=2)types.push('isp','stream','edu','host','hft','bulk','event','event');if(mine.length>=3&&lv>=2)types.push('sdwan','sdwan');
|
||||
// A broker's callers are mostly carriers who want capacity on its glass (#300).
|
||||
const bk=broker(),dfR=S.links.some(l=>l.kind==='df'&&l.ready<=S.day),dfO=S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day);
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ const BADGES=[
|
|||
{id:'fifty',i:'🗺️',t:tr('badges.everywhere_at_once'),d:tr('badges.have_pops_in_50_cities'),r:'l',ok:()=>Object.keys(S.pops).length>=50},
|
||||
{id:'unicorn',i:'🦄',t:tr('common.unicorn'),d:tr('badges.hold_a_billion_dollars_in_cash'),r:'l',ok:()=>S.cash>=1e9},
|
||||
{id:'clean',i:'🧼',t:tr('badges.debt_free_tier_1'),d:tr('badges.win_without_ever_taking_a_loan'),r:'l',ok:()=>!!S.won&&!(st().loans||0)&&!(S.loans||[]).length},
|
||||
{id:'speed',i:'⚡',t:tr('common.speedrun'),d:tr('badges.reach_tier_1_within_three_years'),r:'l',ok:()=>!!S.won&&S.day<=1095},
|
||||
{id:'speed',i:'⚡',t:tr('common.speedrun'),d:tr('badges.reach_tier_1_within_three_years'),r:'l',ok:()=>!!S.won&&netAge()<=1095},
|
||||
{id:'te',i:'🧭',t:tr('common.traffic_whisperer'),d:tr('badges.have_auto_te_move_100_gbps'),r:'r',ok:()=>(st().teMax||0)>=100},
|
||||
{id:'street',i:'🚧',t:tr('common.same_street'),d:tr('badges.lose_a_metro_ring_to_one'),r:'r',ok:()=>(st().by||{}).ring>=1},
|
||||
{id:'anchor',i:'⚓',t:tr('common.anchors_aweigh'),d:tr('badges.have_a_cable_cut_by_a'),r:'r',ok:()=>!!(st().f||{}).anchor},
|
||||
|
|
@ -53,7 +53,7 @@ const BADGES=[
|
|||
{id:'unbreak',i:'🛡️',t:tr('common.unbreakable'),d:tr('badges.survive_100_incidents_without'),r:'l',ok:()=>(st().survived||0)>=100},
|
||||
{id:'lv13',i:'🌐',t:tr('badges.is_this_the_internet'),d:tr('badges.reach_customer_level_13'),r:'l',ok:()=>(S.lvl||1)>=13},
|
||||
{id:'gigawatt',i:'⚛️',t:tr('common.gigawatt_landlord'),d:tr('badges.hold_an_ai_wan_a_training'),r:'l',ok:()=>['aiwan','mtrain','ingest','pairs'].every(t=>S.biz.some(b=>b.type===t))},
|
||||
{id:'blitz',i:'🚀',t:tr('common.blitz'),d:tr('badges.reach_tier_1_within_two_years'),r:'l',ok:()=>!!S.won&&S.day<=730},
|
||||
{id:'blitz',i:'🚀',t:tr('common.blitz'),d:tr('badges.reach_tier_1_within_two_years'),r:'l',ok:()=>!!S.won&&netAge()<=730},
|
||||
{id:'tera',i:'📶',t:tr('badges.terabit_club'),d:tr('badges.serve_1_tbps'),r:'c',ok:()=>R.served>=1000},
|
||||
{id:'tera10',i:'🚄',t:tr('badges.ten_terabits'),d:tr('badges.serve_10_tbps'),r:'r',ok:()=>R.served>=10000},
|
||||
{id:'peta',i:'🌌',t:tr('common.hundred_terabits'),d:tr('badges.serve_100_tbps'),r:'e',ok:()=>R.served>=100000},
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ function renderLeft(){checkLayer();
|
|||
$('leftTabs').innerHTML=tabs.map(([k,l])=>`<button class="${UI.left===k?'on':''}" data-act="leftTab" data-args='{"t":"${k}"}'>${l}</button>`).join('')+(innerWidth<760?`<button data-act="toggleLeft" style="margin-left:auto" aria-label="${tr('common.close')}">×</button>`:'');
|
||||
let h='';
|
||||
if(UI.left==='goals'){
|
||||
h+=charterCard()+scnCard()+lvlCard()+t1Card();
|
||||
h+=charterCard()+lateCard()+scnCard()+lvlCard()+t1Card();
|
||||
const cur=G.find(g=>S.done[g.id]===undefined);
|
||||
h+=G.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `<div class="goal ${d?'done':''} ${c?'cur':''}"><div class="ck">${d?'✓':''}</div><div><div class="gt">${esc(g.t)}</div>${c||!d?`<div class="gd">${esc(g.d)}</div>`:''}${!d&&g.r?`<div class="gr">${tr('hud_and_panels.reward_cash',{cash:fmt$(g.r)})}</div>`:''}</div></div>`;}).join('');
|
||||
h+=badgeGrid();
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ function cityPanel(c){
|
|||
if(UI.tab==='cust'){
|
||||
{const nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||1;if(nl>=nc*0.95)h+=`<section><h3 style="color:var(--tx-red,var(--bad))">${tr('city_panel.router_maxed_out')}</h3><p class="lead">${tr('city_panel.your_routers_here_are_forwarding',{load:fmtG(nl),cap:fmtG(nc)})}</p>${btn(tr('common.open_infra'),'tab',{t:'links'},'pink sm')}</section>`;}
|
||||
h+=`<section><h3>${tr('common.home_broadband')}</h3>`;
|
||||
if(!p.bb){const s=bbStart(c);h+=`<p class="lead">${tr('city_panel.sell_internet_to_homes_here_starts',{start:fmtG(s),max:fmtG(eyeP(c)),rate:fmt$(EYE_RATE*arpuOf(c))})}${C.au?` ${scnRule('levy')?tr('city_panel.it_runs_on_your_own_fibre',{pct:pct(AU_LEVY)}):tr('city_panel.the_nearly_broadband_network_keeps',{pct:pct(AU_WHOLESALE)})}`:''}</p>${btn(tr('city_panel.launch_broadband_cost',{cost:fmt$(bbCost(c))}),'launchBB',{city:c},'pink big',S.cash<bbCost(c))}`;}
|
||||
if(!p.bb){const s=bbStart(c);h+=`<p class="lead">${tr('city_panel.sell_internet_to_homes_here_starts',{start:fmtG(s),max:fmtG(eyeP(c)),rate:fmt$(EYE_RATE*arpuOf(c))})}${C.au?` ${scnRule('levy')?tr('city_panel.it_runs_on_your_own_fibre',{pct:pct(AU_LEVY)}):tr('city_panel.the_nearly_broadband_network_keeps',{pct:pct(AU_WHOLESALE)})}`:''}${lateOn()&&lateLeft()?' '+trn('late.bb_pitch',lateLeft()):''}</p>${btn(tr('city_panel.launch_broadband_cost',{cost:fmt$(bbCost(c))}),'launchBB',{city:c},'pink big',S.cash<bbCost(c))}`;}
|
||||
else{const eye=R.cityEye[c]||0;
|
||||
h+=`<div class="kv"><span>${tr('common.eyeball_demand')}</span><b>${tr('city_panel.a_of_b',{a:fmtG(eye),b:fmtG(eyeP(c))})}</b></div><div class="bar me"><i style="width:${Math.min(100,eye/eyeP(c)*100)}%"></i></div>
|
||||
<div class="kv"><span>${tr('city_panel.served_in_city',{city:C.name})}</span><b style="color:${sf<0.9?'var(--tx-red,var(--bad))':'var(--eye)'}">${pct(sf)}</b></div><div class="bar ${sf<0.9?'bad':''}"><i style="width:${sf*100}%"></i></div>
|
||||
|
|
|
|||
|
|
@ -29,6 +29,6 @@ function renderBank(){
|
|||
${B.equity?`<div class="meta">${tr('bank.taking_pct_of_your_revenue_every',{pct:pct(l.share)})}</div>`:`<div class="kv"><span>${tr('common.still_owed')}</span><b>${fmt$(l.bal)}</b></div><div class="bar me"><i style="width:${Math.min(100,(1-l.bal/l.amount)*100)}%"></i></div><div class="meta">${loanLine(l)}</div>`}
|
||||
${covList(l)}${l.breach>=1?`<div class="why">${trn('bank.condition_broken_for_n_day',l.breach)} ${l.breach<10?tr('bank.penalty_in_n_days',{n:10-l.breach}):tr('bank.penalties_are_running')}</div>`:''}
|
||||
<div class="btns" style="margin-top:6px">${btn(UI.confirm===l.id?tr('bank.really_pay_price',{price:fmt$(cost)}):B.equity?tr('bank.buy_them_out_price',{price:fmt$(cost)}):tr('bank.repay_early_price_incl_2_fee',{price:fmt$(cost)}),'repayLoan',{id:l.id},UI.confirm===l.id?'red sm':'sm',S.cash<cost)}</div></div></div>`;}
|
||||
h+=pieGovBank()+ip4Bank();
|
||||
h+=lateBank()+pieGovBank()+ip4Bank();
|
||||
if(h!==UI._bh){UI._bh=h;$('bankCard').innerHTML=h;}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,5 +20,5 @@ function showHelp(){
|
|||
<dt>RouteScript</dt><dd>${tr('help.rules_for_your_auto_te_controller')}</dd>
|
||||
</dl><h3 style="margin:16px 0 0">${tr('help.want_to_know_how_it_really')}</h3>${plugHtml(true)}${chatHtml()}${issueHtml()}</dl><div class="btns" style="margin-top:14px">${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}</div><div class="btns" style="margin-top:6px">${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}${isPhone()?'':btn(tr('keys.keyboard_shortcuts'),'keys',{},'ghost sm')}</div>`);
|
||||
}
|
||||
function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`<div class="btns" style="margin-top:8px">${btn(tr('help.share_my_network'),'share',{},'pink')}</div><p class="meta" style="margin:12px 0 0">${tr('help.you_built_a_cartoon_internet_now')}</p>${plugHtml(true)}`);},0);openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">${tr('help.you_re_a_tier_1')}</h1><p class="tagline">${tr('help.name_as_asn_is_transit_free',{name:esc(S.name),asn:S.asn,days:S.day,n:S.stats.incidents})}</p>${btn(tr('common.keep_building'),'keepPlaying',{},'pink big')}`);sfx('coin');}
|
||||
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">${tr('common.bankrupt')}</h1><p class="tagline">${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}</p>${btn(tr('common.try_again'),'newgame',{},'pink big')}`);if(UI.slot){const id=UI.slot;slotDrop(id);slotFree(id);}}
|
||||
function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`<div class="btns" style="margin-top:8px">${btn(tr('help.share_my_network'),'share',{},'pink')}</div><p class="meta" style="margin:12px 0 0">${tr('help.you_built_a_cartoon_internet_now')}</p>${plugHtml(true)}`);},0);openModal(`<h1 style="font-family:var(--display);font-size:44px;margin:0">${tr('help.you_re_a_tier_1')}</h1><p class="tagline">${tr('help.name_as_asn_is_transit_free',{name:esc(S.name),asn:S.asn,days:netAge(),n:S.stats.incidents})}</p>${btn(tr('common.keep_building'),'keepPlaying',{},'pink big')}`);sfx('coin');}
|
||||
function showLose(){openModal(`<h1 style="font-family:var(--display);font-size:40px;margin:0">${tr('common.bankrupt')}</h1><p class="tagline">${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:netAge(),peak:fmtG(S.stats.peak)})}</p>${btn(tr('common.try_again'),'newgame',{},'pink big')}`);if(UI.slot){const id=UI.slot;slotDrop(id);slotFree(id);}}
|
||||
|
|
|
|||
|
|
@ -2834,6 +2834,17 @@
|
|||
"keys.show_this_list":"Show this list",
|
||||
"keys.space":"Space",
|
||||
"keys.zoom_the_map_out_or":"Zoom the map out or in",
|
||||
"late.bank_note":"For joining this session late. The match is on what your homes pay you after any wholesale cut, and investors take no share of it.",
|
||||
"late.bb_pitch":{"one":"You joined late: for {n} more day, what homes here pay you is matched.","other":"You joined late: for {n} more days, what homes here pay you is matched."},
|
||||
"late.card":{"one":"Home broadband pays double for {n} more day: +{price}/mo right now.","other":"Home broadband pays double for {n} more days: +{price}/mo right now."},
|
||||
"late.hello":"<b>Late to the party, but welcome.</b> This session is {n} days old and hardware costs {p} more than on its first day, so the bank adds {cash} to your starting cash. For your first year, every dollar your homes pay you is matched: home broadband pays double.",
|
||||
"late.hello_flat":"<b>Late to the party, but welcome.</b> This session is {n} days old. For your first year, every dollar your homes pay you is matched: home broadband pays double.",
|
||||
"late.match":"Home broadband matched",
|
||||
"late.over":"Your late joiner's year is over: home broadband pays the usual rate again.",
|
||||
"late.this_month":"Match this month",
|
||||
"late.title":"Late joiner's head start",
|
||||
"late.top_up":"Starting cash top-up",
|
||||
"late.until":"until {date}",
|
||||
"latency_contracts.credits_paid":"{price} paid in SLA credits",
|
||||
"latency_contracts.over_sla":"<b>{name}</b>: {a} ⇄ {b} runs at {ms} ms, over the {max} ms in its contract. Every day over costs you a day's fee in SLA credits ({price}).",
|
||||
"latency_contracts.sla_terms":"Latency SLA {ms} ms: a day's fee back for every day over it · never more than {max}",
|
||||
|
|
|
|||
2
tests/fixtures/mp-sim/clock.json
vendored
2
tests/fixtures/mp-sim/clock.json
vendored
|
|
@ -1 +1 @@
|
|||
{"t":"clock","speed":1,"eff":1,"run":true,"why":null,"votes":{"efgh5678":4},"tally":{"4":1},"need":2,"active":["abcd1234","efgh5678"],"hold":[],"idle":[],"day":518,"last":1,"max":8,"off":{"abcd1234":-473,"efgh5678":0}}
|
||||
{"t":"clock","speed":1,"eff":1,"run":true,"why":null,"votes":{"efgh5678":4},"tally":{"4":1},"need":2,"active":["abcd1234","efgh5678"],"hold":[],"idle":[],"day":518,"last":1,"max":8}
|
||||
|
|
|
|||
2
tests/fixtures/mp-sim/roster.json
vendored
2
tests/fixtures/mp-sim/roster.json
vendored
|
|
@ -1 +1 @@
|
|||
{"t":"roster","code":"K7Q2XD","title":"Friday","preset":"oncall","seed":424242,"created":1730913600000,"players":[{"pid":"abcd1234","name":"Packet Pals","asn":201234,"color":"#3a86ff","card":{"day":45,"name":"Packet Pals","asn":201234,"tier":"t3","t1":false,"lvl":2,"pops":["fra","ams"],"links":[["ams","fra",10]],"ix":[],"transit":["cog"],"ppol":"open","reach":1,"peak":47.5,"served":47.5,"cust":0,"rev":7126,"cashB":5,"score":48},"seen":1731000000000,"joined":1730913600000},{"pid":"efgh5678","name":"Tubular Bells","asn":207777,"color":"#ff4f9a","card":null,"seen":1730999940000,"joined":1730996400000}],"feed":[{"k":"join","pid":"abcd1234","name":"Packet Pals","at":1730913600000},{"k":"join","pid":"efgh5678","name":"Tubular Bells","at":1730996400000},{"k":"chat","pid":"efgh5678","name":"Tubular Bells","at":1730999940000,"text":"peer with me?"}],"on":["abcd1234","efgh5678"]}
|
||||
{"t":"roster","code":"K7Q2XD","title":"Friday","preset":"oncall","seed":424242,"created":1730913600000,"players":[{"pid":"abcd1234","name":"Packet Pals","asn":201234,"color":"#3a86ff","card":{"day":518,"name":"Packet Pals","asn":201234,"tier":"t3","t1":false,"lvl":2,"pops":["fra","ams"],"links":[["ams","fra",10]],"ix":[],"transit":["cog"],"ppol":"open","reach":1,"peak":47.5,"served":47.5,"cust":0,"rev":14252,"cashB":5,"score":48},"seen":1731000000000,"joined":1730913600000},{"pid":"efgh5678","name":"Tubular Bells","asn":207777,"color":"#ff4f9a","card":null,"seen":1730999940000,"joined":1730996400000}],"feed":[{"k":"join","pid":"abcd1234","name":"Packet Pals","at":1730913600000},{"k":"join","pid":"efgh5678","name":"Tubular Bells","at":1730996400000},{"k":"chat","pid":"efgh5678","name":"Tubular Bells","at":1730999940000,"text":"peer with me?"}],"on":["abcd1234","efgh5678"]}
|
||||
|
|
|
|||
2
tests/fixtures/mp-sim/snap.json
vendored
2
tests/fixtures/mp-sim/snap.json
vendored
File diff suppressed because one or more lines are too long
2
tests/fixtures/mp-sim/sub.json
vendored
2
tests/fixtures/mp-sim/sub.json
vendored
File diff suppressed because one or more lines are too long
2
tests/fixtures/mp-sim/upd-act.json
vendored
2
tests/fixtures/mp-sim/upd-act.json
vendored
File diff suppressed because one or more lines are too long
2
tests/fixtures/mp-sim/upd-day.json
vendored
2
tests/fixtures/mp-sim/upd-day.json
vendored
File diff suppressed because one or more lines are too long
|
|
@ -563,6 +563,29 @@ test('F10: growth goes sideways, plus one paid way up (#61, #323)', () => {
|
|||
fail('F10', J("MEGA.filter(m=>!CITY[m.c]).map(m=>m.c)"), 'campuses sit in real cities');
|
||||
});
|
||||
|
||||
test('F11: a late joiner starts on the session\'s date with F1\'s gentle start, a hardware top-up and a year of home broadband matched', () => {
|
||||
const g = load();
|
||||
const D = 1868, MP = { code: 'K7Q2XD', pid: 'abcd1234', asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
|
||||
g.ev(`UI.pitched=true;beginState('Late','fra',{mode:'normal',preset:'oncall',mp:${lit(MP)},day:${D}});S.mp.sim=1;compute()`);
|
||||
// The session's date, F1's start counted from its own first day.
|
||||
assert.deepEqual(JSON.parse(g.ev('JSON.stringify([S.day,S.day0,S.nextFail-S.day0,S.nextEvent-S.day0])')), [D, D, 45, 40], 'F11: the session\'s date, and F1\'s first outage and event');
|
||||
const opts = JSON.parse(g.ev(`(()=>{let o=null;const f=eval('('+fireEvent.toString().replace('const e=pick(opts);','o=opts.slice();return;')+')');S.day=S.day0+45;f();S.day=S.day0;return JSON.stringify(o);})()`));
|
||||
fail('F11', opts.filter((e) => !['viral', 'price', 'grant'].includes(e)), 'no bad events before its day 50 (count S.day-S.day0: netAge())');
|
||||
assert.equal(g.ev("(()=>{for(let a=0;a<90;a++){S.day=S.day0+a;if(CITIES.some(c=>soldOut('fra',c.id,1)))return true;}S.day=S.day0;return false;})()"), false, 'F11: nothing sold out in its first 90 days');
|
||||
// The top-up: the rise in hardware prices on START_CASH, at most $60k; the market stays on the session's date.
|
||||
const top = g.ev('S.cash-START_CASH');
|
||||
assert.ok(top === Math.round(g.ev(`START_CASH*(hwTrend(${D})-1)`) / 1000) * 1000 && top > 0 && top <= 60000, `F11: a top-up of ${top}`);
|
||||
assert.equal(g.ev('lateCash(1e6)'), 60000, 'F11: never more than $60k');
|
||||
assert.equal(g.ev('hwMul("rt")'), g.ev(`hwTrend(${D})`), 'F11: hardware at the session\'s price');
|
||||
// The match: what homes pay after wholesale, for 365 days, outside investors' share.
|
||||
g.ev("S.cash=1e7;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.loans.push({id:'v',bank:'vult',start:S.day,amount:1,got:1,bal:0,share:0.1,covs:[]});compute()");
|
||||
const r = JSON.parse(g.ev('JSON.stringify([R.rev.eyeballs,R.rev.late,R.cost.revshare])'));
|
||||
assert.ok(r[0] > 0 && r[1] === r[0], 'F11: home broadband matched');
|
||||
assert.ok(Math.abs(r[2] - 0.1 * r[0]) < 1e-6, 'F11: investors take no share of the match');
|
||||
assert.equal(g.ev('(()=>{S.day=S.day0+366;compute();const v=R.rev.late;S.day=S.day0;compute();return v===undefined;})()'), true, 'F11: for one year');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('F12: island Wi-Fi pays on its own books on some way in; a spur beats every satellite, and pays back within 5 years up to 250 km, 10 up to 1,000 km', () => {
|
||||
// The zone's own books at full take-up, era 1: its homes at island prices, less the towers' upkeep and the backhaul
|
||||
// rent. The teleport, tracking antennas and a Starblink gateway serve more than one zone and are left out. Each way in
|
||||
|
|
|
|||
219
tests/late-joiners.test.js
Normal file
219
tests/late-joiners.test.js
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
// Late joiners (src/game/60-features/81-late-joiners.js, docs/plans/server-run.md "What Q1 changes"): a network that
|
||||
// joins a server session after day 180 begins on the session's date (S.day0), counts its first-days rules from there
|
||||
// (netAge()), gets a top-up as large as the rise in hardware prices and has its first year of home broadband income
|
||||
// matched, outside investors' share. The market and the calendar stay the session's. Nothing of it outside a session.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
const MP = { code: 'K7Q2XD', pid: 'abcd1234', asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
|
||||
const D = 1868;
|
||||
// A network of a server session, begun the way the server begins one (srvBegin), on day `day` of the session.
|
||||
function late(t, { day = D, home = 'fra', preset = 'oncall', mp = MP } = {}) {
|
||||
const h = load();
|
||||
t.after(() => h.dom.window.close());
|
||||
h.ev(`Date.now=()=>1.7e12;UI.pitched=true;beginState('Late Bloomers',${lit(home)},{mode:'normal',preset:${lit(preset)},${mp ? `mp:${lit(mp)},` : ''}day:${day}});
|
||||
if(S.mp)S.mp.sim=1;compute();beginHello();UI.started=true;UI.speed=0;`);
|
||||
return h;
|
||||
}
|
||||
const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`));
|
||||
// Live S against what a reload makes of it, as text (never deep-compared as objects).
|
||||
const same = (ev) => ev('(()=>{const u=uidN,r=S.rng;try{return JSON.stringify(S)===JSON.stringify(migrate(JSON.parse(JSON.stringify(S))));}finally{uidN=u;S.rng=r;}})()');
|
||||
const homes = (ev, c = 'fra') => ev(`S.cash=1e7;ACT.launchBB({city:${lit(c)}});S.pops[${lit(c)}].bb.d=40;ACT.buyTransit({city:${lit(c)},net:NETS.filter(n=>sellsAt(n,${lit(c)}))[0].id,tier:1});compute();
|
||||
if(!S.transit.length||!(R.rev.eyeballs>0))throw new Error('no homes served');`);
|
||||
|
||||
test('a late network starts on the session\'s date, its schedules and first block stamped with it, and a reload keeps it', (t) => {
|
||||
const { ev, errors } = late(t);
|
||||
assert.deepEqual(J(ev, '[S.day,S.day0,S.nextFail,S.nextEvent,S.pops.fra.day]'), [D, D, D + 45, D + 40, D]);
|
||||
assert.deepEqual(J(ev, 'S.ip4.b.map(b=>[b.d,ip4Held(b)])'), [[D, true]], 'its RIR block cannot be sold on day one at the session\'s price');
|
||||
assert.equal(ev('S.cash'), ev('START_CASH') + 37000, 'hardware costs 18% more on day 1868: the bank adds $37k');
|
||||
assert.equal(ev('netAge()'), 0);
|
||||
// The welcome, then the late welcome, which opens the bank (newest first in the log).
|
||||
const log = J(ev, 'S.log.slice(0,2).map(x=>[x.k,x.h,x.o&&x.o.a])');
|
||||
assert.deepEqual(log, [['goal', 'Late to the party, but welcome.', 'bank'], ['goal', 'Welcome, Late Bloomers!', 'city']]);
|
||||
assert.match(ev('S.log[0].t'), /This session is 1868 days old and hardware costs 18% more than on its first day, so the bank adds \$37\.0k to your starting cash\./);
|
||||
assert.equal(same(ev), true, 'a reload makes the same game');
|
||||
ev('S.nextFail=S.nextEvent=1e9');
|
||||
homes(ev);
|
||||
for (let i = 0; i < 30; i++) {
|
||||
ev('dayTick()');
|
||||
assert.equal(same(ev), true, `day ${i + 1}: a reload makes the same game`);
|
||||
}
|
||||
assert.equal(ev('netAge()'), 30);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the first-days rules count the network\'s age, not the calendar', (t) => {
|
||||
const { ev, errors } = late(t);
|
||||
homes(ev);
|
||||
// Events: none of the world's bad news before age 50, no shortage before 180 (F1's trick: what fireEvent picks from;
|
||||
// a network's own events, like its traffic through the Great Firewall, come whatever its age).
|
||||
const evOpts = (age) => J(ev, `(()=>{let o=null;const f=eval('('+fireEvent.toString().replace('const e=pick(opts);','o=opts.slice();return;')+')');S.day=S.day0+${age};f();return o;})()`);
|
||||
const early = ['sanction', 'tariff', 'hijack', 'landban', 'shutdown', 'redsea', 'baltic', 'hwshock'];
|
||||
assert.deepEqual(evOpts(45).filter((e) => early.includes(e)), [], 'no bad news at age 45');
|
||||
assert.ok(evOpts(51).includes('sanction') && !evOpts(51).includes('hwshock'), 'bad news possible from age 51, a shortage not yet');
|
||||
assert.ok(evOpts(181).includes('hwshock'), 'a shortage from age 181');
|
||||
// Failures: no route leak before age 60, no RPKI mess before age 30.
|
||||
const failOpts = (age) => J(ev, `(()=>{window.__o=null;window.__f=null;S.day=S.day0+${age};const g=eval('('+failureRun.toString().replace('if(!opts.length)return;','__o=opts.map(o=>o[0]);if(!opts.length)return;').replace('type=pick(f);','__f=f.slice();return;')+')');g('funny').next();return {o:__o,f:__f};})()`);
|
||||
let f = failOpts(25);
|
||||
assert.ok(!f.o.includes('leak') && !f.f.includes('rpki'), 'nothing of the sort at age 25');
|
||||
f = failOpts(61);
|
||||
assert.ok(f.o.includes('leak') && f.f.includes('rpki'), 'both from age 61');
|
||||
// DDoS: none through age 40, even with the dice always low; then one may come.
|
||||
ev('S.day=S.day0;window.__r=Math.random;Math.random=()=>0.001');
|
||||
const attacks = J(ev, '(()=>{const n=[];for(let a=1;a<=41;a++){S.day=S.day0+a;ddosTick();n.push(ddosAll().length);}return n;})()');
|
||||
ev('Math.random=__r');
|
||||
assert.deepEqual(attacks.slice(0, 40), Array(40).fill(0), 'no attack through age 40');
|
||||
assert.equal(attacks[40], 1, 'the first at age 41');
|
||||
// Attack sizes stay within twice your biggest port until age 180, with two POPs.
|
||||
ev("S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];ACT.buildPop({city:'ams'});compute()");
|
||||
const maxAt = (age) => ev(`(()=>{S.day=S.day0+${age};__reseed(8);return Math.max(...Array.from({length:500},()=>ddosSize({tgt:'d'})));})()`);
|
||||
assert.ok(maxAt(100) <= 2 * ev('ddMaxPort()'), 'early floods stay small');
|
||||
assert.ok(maxAt(400) > 2 * ev('ddMaxPort()'), 'later ones do not');
|
||||
// Sold-out routes: none in the first 90 days of the network.
|
||||
assert.equal(ev('(()=>{for(let a=0;a<90;a++){S.day=S.day0+a;if(CITIES.some(c=>soldOut(\'fra\',c.id,1)))return true;}return false;})()'), false);
|
||||
// Loan offers: none spawned through age 20, even with the dice always low.
|
||||
ev('S.loanOffers=[];window.__r=Math.random;Math.random=()=>0.001');
|
||||
const offers = J(ev, '(()=>{const n=[];for(let a=1;a<=21;a++){S.day=S.day0+a;loanTick(S.day);n.push(S.loanOffers.length);}return n;})()');
|
||||
ev('Math.random=__r');
|
||||
assert.deepEqual(offers.slice(0, 20), Array(20).fill(0), 'no loan offer through age 20');
|
||||
assert.ok(offers[20] > 0, 'the banks call from age 21');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the charter window, the tutorial, the badges and the win count the network\'s days', (t) => {
|
||||
const { ev, dom, errors } = late(t);
|
||||
ev('S.nextFail=S.nextEvent=1e9');
|
||||
// The charter is still open at age 10, a reload keeps it open, and it closes after 30 days.
|
||||
ev('S.day=S.day0+10');
|
||||
assert.equal(ev('S.chartSet'), false);
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
|
||||
assert.equal(ev('S.chartSet'), false, 'a reload keeps the choice open');
|
||||
ev('S.day=S.day0+30;dayTick()');
|
||||
assert.equal(ev('S.chartSet'), true, 'the classic charter once its days are over');
|
||||
// The tutorial's "start the clock" step: five days of the network's own.
|
||||
const tut = (age) => ev(`(()=>{S.day=S.day0+${age};return TUT.find(s=>s.sel==='#sp1').ok();})()`);
|
||||
assert.deepEqual([tut(4), tut(5)], [false, true]);
|
||||
// Speedrun: Tier 1 within three years of the network's start.
|
||||
const speed = (age) => ev(`(()=>{S.won=true;S.day=S.day0+${age};return BADGES.find(b=>b.id==='speed').ok();})()`);
|
||||
assert.deepEqual([speed(1095), speed(1096)], [true, false]);
|
||||
ev('S.day=S.day0+700;showWin()');
|
||||
const txt = dom.window.document.getElementById('modalCard').textContent;
|
||||
assert.match(txt, /Took you 700 days/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the match: home broadband pays double for a year, net of wholesale, outside investors\' share', (t) => {
|
||||
const { ev, errors } = late(t);
|
||||
ev('S.nextFail=S.nextEvent=1e9');
|
||||
homes(ev);
|
||||
const rev = J(ev, 'R.rev');
|
||||
assert.ok(rev.eyeballs > 0 && rev.late === rev.eyeballs, 'every dollar homes pay is matched');
|
||||
assert.ok(Math.abs(ev('R.revMo') - (rev.eyeballs + rev.business + rev.ix + rev.grant + rev.late)) < 1e-6, 'and counts as revenue');
|
||||
// Investors and the IPv4 bill see what homes pay, never the match.
|
||||
ev("S.loanOffers.push({id:'v1',bank:'vult',amount:500000,exp:S.day+20,covs:['blitz'],share:0.1});ACT.takeLoan({id:'v1'});S.pops.fra.bb.d=400;compute()");
|
||||
const a = J(ev, '[R.cost.revshare,R.cost.ip4||0,R.rev.late]');
|
||||
const b = J(ev, '(()=>{const d0=S.day0;S.day0=0;compute();const o=[R.cost.revshare,R.cost.ip4||0,R.rev.late];S.day0=d0;compute();return o;})()');
|
||||
assert.ok(a[0] > 0 && a[1] > 0 && a[2] > 0, `a share, an IPv4 bill and a match (${a})`);
|
||||
assert.deepEqual(b.slice(0, 2), a.slice(0, 2), 'the same share and IPv4 bill without the match');
|
||||
assert.equal(b[2], null, 'no match for a network that began on day 0');
|
||||
// The last matched day is day0+365; the next day says the year is over.
|
||||
ev('S.day=S.day0+364;dayTick()');
|
||||
assert.equal(ev('S.day'), D + 365);
|
||||
assert.ok(ev('R.rev.late') > 0, 'still matched on day 365');
|
||||
ev('dayTick()');
|
||||
assert.equal(ev('R.rev.late'), undefined, 'not on day 366');
|
||||
assert.ok(ev("S.log.some(x=>x.t===tr('late.over'))"), 'the year is over, in the log');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the match is net of the Australian wholesale cut', (t) => {
|
||||
const { ev, errors } = late(t, { home: 'syd' });
|
||||
homes(ev, 'syd');
|
||||
const r = J(ev, '[R.rev.eyeballs,R.rev.late,R.cost.wholesale,AU_WHOLESALE]');
|
||||
assert.ok(r[0] > 0 && r[2] > 0);
|
||||
assert.ok(Math.abs(r[1] - r[0] * (1 - r[3])) < 1e-6, 'what homes pay after the wholesale cut');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('five seeded days: the match is the only difference in cash, a monthly match paid by the day', (t) => {
|
||||
const { ev, errors } = late(t);
|
||||
ev('S.nextFail=S.nextEvent=1e9');
|
||||
homes(ev);
|
||||
ev('window.__s0=JSON.stringify(S);window.__lm=lateMoney;window.__vd=volDay;window.__late=[];volDay=function(){__late.push((R.rev.late||0)/monLen(S.day));return __vd.apply(this,arguments);}');
|
||||
const run = (match) => ev(`(()=>{S=migrate(JSON.parse(__s0));lateMoney=${match ? '__lm' : '()=>{}'};compute();__reseed(77);__late=[];for(let i=0;i<5;i++)dayTick();return S.cash;})()`);
|
||||
const withM = run(true), sum = J(ev, '__late').reduce((x, y) => x + y, 0), without = run(false);
|
||||
ev('lateMoney=__lm;volDay=__vd');
|
||||
assert.ok(sum > 0);
|
||||
assert.ok(Math.abs(withM - without - sum) < 1e-6, `cash ${withM} − ${without} is the match, ${sum}`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('who is late: after day 180 only, the top-up with the market rule only', (t) => {
|
||||
for (const [day, preset, isLate, topUp] of [[180, 'oncall', false, 0], [181, 'oncall', true, 0], [D, 'freeze', true, 0], [D, 'bgp', true, 37000]]) {
|
||||
const { ev, dom, errors } = late(t, { day, preset });
|
||||
assert.equal(ev('S.day0'), day);
|
||||
assert.equal(ev('lateIs()'), isLate, `day ${day} ${preset}`);
|
||||
assert.equal(ev('S.cash'), ev('START_CASH') + topUp, `day ${day} ${preset}: top-up`);
|
||||
assert.equal(ev("S.log.filter(x=>/Late to the party/.test(x.t)).length"), isLate ? 1 : 0, `day ${day} ${preset}: the late welcome`);
|
||||
homes(ev);
|
||||
assert.equal(ev("'late' in R.rev"), isLate, `day ${day} ${preset}: the match`);
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('outside a server session nothing changes: day 0, no match, and saves repair the start day', (t) => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();compute()");
|
||||
assert.deepEqual(J(ev, "[S.day,S.day0,'late' in R.rev,Object.keys(S).indexOf('day0')-Object.keys(S).indexOf('day')]"), [0, 0, false, 1]);
|
||||
// A day without a session, or a session in sandbox or a scenario, begins on day 0.
|
||||
ev(`beginState('Solo','fra',{mode:'normal',preset:'oncall',day:${D}})`);
|
||||
assert.deepEqual(J(ev, '[S.day,S.day0]'), [0, 0], 'no session, no start day');
|
||||
ev(`beginState('Box','fra',{mode:'sandbox',mp:${lit(MP)},day:${D}})`);
|
||||
assert.deepEqual(J(ev, '[S.day,S.day0,S.mp]'), [0, 0, null], 'sandbox never is a session network');
|
||||
// Saves: a start after the day is the day, a negative one 0, an old save without one 0.
|
||||
const fix = (x) => J(ev, `(()=>{const s=JSON.parse(JSON.stringify(S));Object.assign(s,${lit(x)});if(${lit(x)}.day0===undefined)delete s.day0;const m=migrate(s);return [m.day,m.day0];})()`);
|
||||
assert.deepEqual(fix({ day: 100, day0: 500 }), [100, 100]);
|
||||
assert.deepEqual(fix({ day: 100, day0: -3 }), [100, 0]);
|
||||
assert.deepEqual(fix({ day: 100, day0: 'x' }), [100, 0]);
|
||||
assert.deepEqual(fix({ day: 100 }), [100, 0]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a late network sees its head start on the Goals tab, in the bank and in a city\'s pitch, also on a phone', (t) => {
|
||||
const { ev, dom, errors } = late(t);
|
||||
const doc = dom.window.document;
|
||||
ev("window.innerWidth=360;window.innerHeight=740;UI.left='goals';UI.leftOpen=true;UI.sel=null;renderAll();renderLeft()");
|
||||
// The city pitch before broadband launches.
|
||||
ev("UI.tab='cust';selectCity('fra');renderAll()");
|
||||
assert.match(doc.getElementById('panel').textContent, /You joined late: for 365 more days, what homes here pay you is matched\./);
|
||||
homes(ev);
|
||||
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()");
|
||||
const card = [...doc.querySelectorAll('#leftBody .inc')].find((e) => /Late joiner's head start/.test(e.textContent));
|
||||
assert.ok(card, 'the Goals card');
|
||||
assert.match(card.textContent, new RegExp(`Home broadband pays double for 365 more days: \\+${ev('fmt$(R.rev.late)').replace('$', '\\$')}/mo right now\\.`));
|
||||
ev('ACT.bank()');
|
||||
const bank = doc.getElementById('bankCard').textContent;
|
||||
assert.match(bank, /Late joiner's head start/);
|
||||
assert.match(bank, /Starting cash top-up\$37\.0k/);
|
||||
assert.ok(bank.includes('until ' + ev('dateStr(S.day0+365)')));
|
||||
// The "since you started" lines measure from the network's own first day.
|
||||
assert.equal(ev('mktTxt()'), ev("tr('lifecycle.market_as_start')"));
|
||||
assert.match(ev('hwCard()'), /as when you started/);
|
||||
assert.doesNotMatch(ev("marketNote('fra','ams',false)"), /fallen/);
|
||||
assert.match(ev("(()=>{S.day+=400;const t=marketNote('fra','ams',false)+mktTxt();S.day-=400;return t;})()"), /fallen|below/, 'and move once it ages');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a network that began on day 0 shows none of it', (t) => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e7;UI.tab='cust';selectCity(S.home);renderAll()");
|
||||
assert.doesNotMatch(dom.window.document.getElementById('panel').textContent, /You joined late/);
|
||||
ev("ACT.launchBB({city:S.home});compute();UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft();ACT.bank()");
|
||||
assert.doesNotMatch(dom.window.document.getElementById('leftBody').textContent, /Late joiner/);
|
||||
assert.doesNotMatch(dom.window.document.getElementById('bankCard').textContent, /Late joiner/);
|
||||
assert.deepEqual([ev('lateCard()'), ev('lateBank()')], ['', '']);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -6,7 +6,8 @@
|
|||
// const engine = createFakeEngine({onLost});
|
||||
// engine.load(code, nets:[{nid, env?, begin?, lang, prefs}]) → [{t:'loaded', nid, epoch, day, lost, saved?}], one per
|
||||
// net; a network that did not load is {t:'loaded', nid, err} (broken, 4.7): one with
|
||||
// neither a save (env.s, the save text) nor a begin answers err 'no save to load'
|
||||
// neither a save (env.s, the save text) nor a begin answers err 'no save to load'; a begin
|
||||
// starts on begin.day (the session's date; 0 when it is none)
|
||||
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]:{day, lost,
|
||||
// pause?, err?, retried?, ms}}}; a network of nets that is not loaded is left out
|
||||
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd, ms} (msg: the request body, 5.8)
|
||||
|
|
@ -58,6 +59,8 @@ function createFakeEngine(opts = {}) {
|
|||
const hasSession = (code) => [...realms.keys()].some((k) => k.startsWith(code + '/'));
|
||||
// The day of a save text (the real engine reads the save); else the canned one.
|
||||
const dayOf = (s) => { try { const d = JSON.parse(s).day; return Number.isInteger(d) ? d : F.snap.S.day; } catch (e) { return F.snap.S.day; } };
|
||||
// The day a save's network began (S.day0), at most its day; 0 for a save that does not say.
|
||||
const day0Of = (s, day) => { try { const d = JSON.parse(s).day0; return Number.isInteger(d) && d >= 0 ? Math.min(d, day) : 0; } catch (e) { return 0; } };
|
||||
// A realm the worker had to build again after a timeout: a new epoch, versions from 0.
|
||||
const rebuilt = (r) => { if (r) { r.epoch = newEpoch(); r.v = 0; r.dirty = false; } };
|
||||
// Every answer goes through here: held back, failed, or rejected when the worker exits meanwhile. failed(f): the reply
|
||||
|
|
@ -102,7 +105,7 @@ function createFakeEngine(opts = {}) {
|
|||
}
|
||||
return o;
|
||||
};
|
||||
const savedOf = (code, nid, r) => ({ t: 'saved', nid, txt: JSON.stringify({ ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } }), uidN: 100 + r.day, rt: { load: {}, l2route: {}, efg: {} }, day: r.day, lost: r.lost });
|
||||
const savedOf = (code, nid, r) => ({ t: 'saved', nid, txt: JSON.stringify({ ...F.snap.S, day: r.day, day0: r.day0, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } }), uidN: 100 + r.day, rt: { load: {}, l2route: {}, efg: {} }, day: r.day, lost: r.lost });
|
||||
|
||||
const CLOSED = () => Promise.reject(coded('engine closed', 'CLOSED'));
|
||||
const engine = {
|
||||
|
|
@ -123,8 +126,8 @@ function createFakeEngine(opts = {}) {
|
|||
const one = (n, err) => {
|
||||
if (!err && !n.begin && !(n.env && typeof n.env === 'object' && typeof n.env.s === 'string')) err = 'no save to load';
|
||||
if (err) { realms.delete(key(code, n.nid)); return { t: 'loaded', nid: n.nid, err }; }
|
||||
const day = n.begin ? 0 : Number.isInteger(n.env.day) ? n.env.day : dayOf(n.env.s);
|
||||
const r = { epoch: newEpoch(), v: 0, day, lost: false, broken: false, dirty: false, greeted: false, pause: false, loseNext: false, keep: [], lang: n.lang || 'en' };
|
||||
const day = n.begin ? (Number.isInteger(n.begin.day) ? n.begin.day : 0) : Number.isInteger(n.env.day) ? n.env.day : dayOf(n.env.s);
|
||||
const r = { epoch: newEpoch(), v: 0, day, day0: n.begin ? day : day0Of(n.env.s, day), lost: false, broken: false, dirty: false, greeted: false, pause: false, loseNext: false, keep: [], lang: n.lang || 'en' };
|
||||
realms.set(key(code, n.nid), r);
|
||||
return { t: 'loaded', nid: n.nid, epoch: r.epoch, day, lost: false, ...(n.begin ? { saved: savedOf(code, n.nid, r) } : {}) };
|
||||
};
|
||||
|
|
|
|||
|
|
@ -28,7 +28,8 @@ function make() {
|
|||
ev(`Date.now=()=>${NOW};`);
|
||||
// A network of a server session, built the way the server builds one (beginState, then the server's own marks), with
|
||||
// the intern on every order and a fiber cut it rushes: the snapshot carries a shift's log and the week's tally.
|
||||
ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${JSON.stringify(MP)}});S.mp.sim=1;S.tut=null;compute();beginHello();
|
||||
// It joined the session late (day 473): the session's date, one calendar for every network (S.day0).
|
||||
ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${JSON.stringify(MP)},day:473});S.mp.sim=1;S.tut=null;compute();beginHello();
|
||||
S.nextFail=S.nextEvent=1e9;UI.speed=0;UI.started=true;ACT.charter({k:'global'});
|
||||
ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});
|
||||
UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();
|
||||
|
|
@ -43,7 +44,7 @@ function make() {
|
|||
return { s, del, keys: now }; };
|
||||
const fx = () => JSON.parse(ev('JSON.stringify(__fx.splice(0))'));
|
||||
const clock = { t: 'clock', speed: 1, eff: 1, run: true, why: null, votes: { [PID2]: 4 }, tally: { 4: 1 }, need: 2, active: [PID, PID2], hold: [], idle: [],
|
||||
day: 518, last: 1, max: 8, off: { [PID]: S0day(snapS) - 518, [PID2]: 0 } };
|
||||
day: snapS.day, last: 1, max: 8 };
|
||||
const card = JSON.parse(ev('JSON.stringify(mpCard())'));
|
||||
const roster = { t: 'roster', code: CODE, title: 'Friday', preset: 'oncall', seed: MP.seed, created: NOW - 864e5,
|
||||
players: [{ pid: PID, name: 'Packet Pals', asn: MP.asn, color: MP.color, card, seen: NOW, joined: NOW - 864e5 },
|
||||
|
|
@ -76,9 +77,6 @@ function make() {
|
|||
dom.window.close();
|
||||
return { snap, 'upd-day': updDay, 'upd-act': updAct, sub, clock, roster };
|
||||
}
|
||||
// The calendar offset of the network in the fixtures: its own date against the session day (open question 1).
|
||||
function S0day(S) { return S.day; }
|
||||
|
||||
function write() {
|
||||
fs.mkdirSync(DIR, { recursive: true });
|
||||
const out = make();
|
||||
|
|
|
|||
|
|
@ -102,10 +102,8 @@ const fxList = (v, w, out) => { if (!Array.isArray(v)) return false; v.forEach((
|
|||
const CLOCK = { t: (v) => v === 'clock', speed: (v) => SPEEDS.includes(v), eff: (v) => num(v) && v >= 0, run: bool, why: (v) => WHY.includes(v),
|
||||
votes: mapOf((k) => PID.test(k), (v) => v === null || SPEEDS.includes(v)), tally: mapOf((k) => SPEEDS.includes(+k), nat), need: (v) => int(v) && v >= 1,
|
||||
active: listOf((v) => PID.test(v)), hold: listOf((v) => PID.test(v)), idle: listOf((v) => PID.test(v)), day: nat, last: (v) => SPEEDS.includes(v) && v > 0,
|
||||
max: (v) => SPEEDS.includes(v) && v > 0,
|
||||
// The calendar offset of every network of the session: its own S.day minus the session day (open question 1: "own
|
||||
// date"). One field, so a shared date later only means all zeros.
|
||||
off: mapOf((k) => PID.test(k), int) };
|
||||
// day: the session's date, and every network's (one calendar: a network that joins late begins on it, S.day0).
|
||||
max: (v) => SPEEDS.includes(v) && v > 0 };
|
||||
const PLAYER = { pid: (v) => PID.test(v), name: str, asn: nat, color: (v) => /^#[0-9a-f]{6}$/i.test(v), card: (v) => v === null || obj(v), seen: nat, joined: nat,
|
||||
lost: [bool, 'opt'], broken: [bool, 'opt'] };
|
||||
const ROSTER = { t: (v) => v === 'roster', code: (v) => CODE.test(v), title: str, preset: str, seed: int, created: nat,
|
||||
|
|
|
|||
|
|
@ -153,12 +153,15 @@ test('the canned stream: every fixture passes the shape checker, and the shape c
|
|||
assert.equal(upd.v, upd.from + 1);
|
||||
assert.equal(fixture('upd-day').from, fixture('snap').v, 'the day follows the snapshot');
|
||||
assert.equal(upd.from, fixture('upd-day').v, 'the actions follow the day');
|
||||
assert.ok('off' in fixture('clock'), 'the clock carries each network\'s calendar offset');
|
||||
// One calendar for the session: no offsets, and the network in the snapshot is on the clock's day (it joined late).
|
||||
assert.ok(!('off' in fixture('clock')), 'the clock carries no calendar offsets');
|
||||
assert.equal(fixture('snap').S.day, fixture('clock').day);
|
||||
assert.ok(fixture('snap').S.day0 > 0 && fixture('snap').S.day0 < fixture('snap').S.day, 'the canned network began on the session\'s date');
|
||||
const broken = [
|
||||
[{ ...upd, v: upd.from + 2 }, /from \+ 1/], [{ ...upd, r: { ...upd.r, ef: {} } }, /never carries/], [{ ...upd, fx: [['boom', 1]] }, /unknown effect/],
|
||||
[{ ...upd, acts: [{ rid: 'x', dev: '9f8e7d6c', ui: {} }] }, /rid/], [{ ...fixture('clock'), speed: 3 }, /speed/], [{ ...fixture('roster'), on: ['NOPE'] }, /on/],
|
||||
[{ ...fixture('snap'), S: { ...fixture('snap').S, mp: { ...fixture('snap').S.mp, sim: undefined } } }, /server network/], [{ t: 'bye', why: 'tired' }, /why/], [{ t: 'nope' }, /unknown event/],
|
||||
[{ ...upd, s: { ...upd.s, day: 1 }, day: 2 }, /day/],
|
||||
[{ ...upd, s: { ...upd.s, day: 1 }, day: 2 }, /day/], [{ ...fixture('clock'), off: {} }, /unknown field/],
|
||||
];
|
||||
for (const [e, re] of broken) assert.match(checkEvent(e).join('\n'), re);
|
||||
assert.deepEqual(checkFx(['floater', [1, 2, 'x', '#fff']]), []);
|
||||
|
|
@ -188,12 +191,14 @@ test('the canned state is the game\'s own: migrate() keeps the snapshot and ever
|
|||
test('the fake engine answers every call in the shapes of section 4.2', async () => {
|
||||
const e = createFakeEngine(), code = 'K7Q2XD', a = 'abcd1234', b = 'efgh5678';
|
||||
const all = [];
|
||||
const L = await e.load(code, [{ nid: a, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: 201234, mp: {}, tut: false }, lang: 'en', prefs: {} }, { nid: b, env: { s: sv(40) }, lang: 'de', prefs: {} }]);
|
||||
// A network that joins the session on its day 40 begins on it, beside one loaded at 40: one calendar.
|
||||
const L = await e.load(code, [{ nid: a, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: 201234, mp: {}, tut: false, day: 40 }, lang: 'en', prefs: {} }, { nid: b, env: { s: sv(40) }, lang: 'de', prefs: {} }]);
|
||||
assert.equal(L.length, 2); assert.ok(L[0].saved, 'a new network is checkpointed at once');
|
||||
assert.deepEqual([L[0].day, L[1].day, JSON.parse(L[0].saved.txt).day0], [40, 40, 40]);
|
||||
assert.ok(L[0].epoch && L[1].epoch && L[0].epoch !== L[1].epoch, 'each realm load has its own epoch');
|
||||
all.push(...L);
|
||||
const D = await e.day(code, { d: 1, speed: 1, last: 1, alone: [], nets: [b, a] });
|
||||
assert.deepEqual(Object.keys(D.nets), [a, b]); assert.equal(D.nets[b].day, 41);
|
||||
const D = await e.day(code, { d: 41, speed: 1, last: 1, alone: [], nets: [b, a] });
|
||||
assert.deepEqual(Object.keys(D.nets), [a, b]); assert.deepEqual([D.nets[a].day, D.nets[b].day], [41, 41]);
|
||||
all.push(D);
|
||||
const P1 = await e.pull(code, a, {}), P2 = await e.pull(code, a, {});
|
||||
assert.ok(P1.upd && !P2.upd, 'a pull sends what changed, once'); assert.equal(P2.v, P1.v, 'only a pull with something to send is a version');
|
||||
|
|
@ -204,9 +209,9 @@ test('the fake engine answers every call in the shapes of section 4.2', async ()
|
|||
await e.sub(code, a, { views: [{ link: 'l1' }] }), await e.greet(code, a), await e.save(code, b), await e.card(code, a));
|
||||
assert.equal(await e.prefs(code, a, { prefs: { pauseFurious: true } }), undefined);
|
||||
e.lose(code, b);
|
||||
const D2 = await e.day(code, { d: 2, nets: [a, b] });
|
||||
const D2 = await e.day(code, { d: 42, nets: [a, b] });
|
||||
assert.equal(D2.nets[b].lost, true);
|
||||
const D3 = await e.day(code, { d: 3, nets: [a, b] });
|
||||
const D3 = await e.day(code, { d: 43, nets: [a, b] });
|
||||
assert.equal(D3.nets[b], undefined, 'a lost network has no more days');
|
||||
assert.equal((await e.act(code, b, env('buildPop', { city: 'par' }))).outcome, 'stopped');
|
||||
e.failNext('act', 'timeout');
|
||||
|
|
@ -224,7 +229,7 @@ test('the fake engine answers every call in the shapes of section 4.2', async ()
|
|||
for (const m of all) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
|
||||
// Held answers wait; a worker that dies rejects everything pending.
|
||||
e.hold('day');
|
||||
let done = false; const p = e.day(code, { d: 4, nets: [a] }).then(() => { done = true; });
|
||||
let done = false; const p = e.day(code, { d: 44, nets: [a] }).then(() => { done = true; });
|
||||
await new Promise((r) => setImmediate(r));
|
||||
assert.equal(done, false, 'held');
|
||||
e.release('day'); await p; assert.equal(done, true);
|
||||
|
|
|
|||
|
|
@ -106,6 +106,28 @@ test('a new network: begin, a snapshot, its welcome, actions, days, a what-if, v
|
|||
await assert.rejects(E.act(code, nid, msg('launchBB', { city: 'ams' })), (e) => e.code === 'NO_REALM');
|
||||
});
|
||||
|
||||
test('a network that joins a session late begins on the session\'s date, with its head start; a start day that is none is refused', async () => {
|
||||
const code = 'J01NER', nid = 'late0001';
|
||||
const [L] = await E.load(code, [begin(nid, { day: 518 })]);
|
||||
checked(L);
|
||||
assert.equal(L.day, 518);
|
||||
const sv = JSON.parse(L.saved.txt);
|
||||
assert.deepEqual([sv.day, sv.day0, sv.nextFail, sv.nextEvent], [518, 518, 563, 558], 'its schedules count from its own start');
|
||||
assert.equal(sv.cash, await ev(code, nid, 'return START_CASH+7000'), 'hardware costs 3.7% more by day 518: the bank adds $7k');
|
||||
checked(await E.pull(code, nid, { snap: true }));
|
||||
const G = checked(await E.greet(code, nid));
|
||||
assert.ok(updOf(G).fx.some(([k, p]) => k === 'toast' && p.k === 'goal' && /Late to the party/.test(p.h) && p.a[0].act === 'bank'), 'the late welcome, with a button to the bank');
|
||||
assert.ok(updOf(G).fx.some(([k, p]) => k === 'toast' && /AS201234/.test(p.h)), 'after the usual welcome');
|
||||
const D = await day(code, 519, [nid]);
|
||||
assert.equal(D.nets[nid].day, 519);
|
||||
for (const bad of [-1, 1.5, '518']) {
|
||||
const [B] = await E.load(code, [begin('latebad1', { day: bad })]);
|
||||
checked(B);
|
||||
assert.match(String(B.err), /start day/, JSON.stringify(bad));
|
||||
}
|
||||
await E.unload(code);
|
||||
});
|
||||
|
||||
test('the capture table: every kind of effect comes out as an fx in its shape, at most 60 an update', async () => {
|
||||
const code = 'CAPTVR', nid = 'capt0001';
|
||||
checked((await E.load(code, [begin(nid)]))[0]);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue