diff --git a/CHANGELOG.md b/CHANGELOG.md
index af60927..0e2a378 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
+- Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse.
+- The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary.
- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night.
- Copies of the game you host yourself can now have multiplayer: friends join your session with a six-character code and build their networks next to yours in the same world, with a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player.
- Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80).
@@ -14,6 +16,8 @@ All notable changes to this project are documented here. The project follows
- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through.
- Set a build standard for your whole network: routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes, all in one sheet. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section.
- IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150).
+- France gets seven more cities: Lyon, Toulouse, Lille, Bordeaux, Strasbourg, Rennes and Nantes, all but Nantes with an exchange of their own (#288). SF-Error Telecom and Boy-Egg Telecom bring home broadband and mobile, Ov-Hatch Cloud and Scale-Away bring French clouds, Tangerine Telecom and Free as in Beer reach the new cities, Cogentle reaches Toulouse, Lille, Bordeaux and Strasbourg, and Andorable Telecom comes up to Toulouse. The Atlantic cables now come ashore where they really do: Ami-Tea at Bordeaux and Dunno-ant at Nantes, and Dunno-ant starts at Virginia Beach.
+- Big networks at ×8 no longer stop for a moment when a day reroutes, after a failure, an event, the intern's shift or the sales desk's signing. Every routing a day needs now runs in the background like the day's own, a long day lets the map draw between its steps, and the check for customers afraid of sharks no longer walks every land fiber for each of them. Quiet notifications now also apply while the game is running.
## [3.0.0] — 2026-11-06
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index aad1e5e..af0768b 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -31,10 +31,10 @@ hoisted across files, and top-level statements run in path order. Find code by n
| `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) |
| `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) |
| `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` |
-| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers, orbit ones through `pieSlShape()`; signing for you: `S.slAuto`, `slAutoDay()`) |
+| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers, orbit ones through `pieSlShape()`; signing for you: `S.slAuto`, `slAutoDay()`; renewal haggles: `S.slAuto.ren`, `slRenDay()`) |
| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank |
| `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service |
-| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) |
+| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `failureRun()`/`fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) |
| `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` |
| `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers |
| `91-save.js`, `92-audio.js` | Save, export and import; sound effects |
@@ -103,20 +103,37 @@ Lookup tables built at load: `CITY[id]`, `NET[id]`, `CABLE`, `FAB`, `BIZ_T`, `RE
## The life of a day
-`frame()` (requestAnimationFrame) accumulates time; every `DAY_MS × speed` it calls
-`dayTick()`, at most four times per frame, each inside a try/catch so one bad tick
-never freezes the game.
+`frame()` (requestAnimationFrame) accumulates time (`runClock()`); every `DAY_MS × speed` it starts a day, inside a
+try/catch so one bad tick never freezes the game. In play the day runs with the route worker (below), one day in flight
+at a time: the clock waits for the day, never the other way round, so a machine that cannot keep up at ×8 plays slower
+instead of freezing to catch up. Without a worker it calls `dayTick()`, at most four times per frame.
-`dayTick()`:
+A day is a generator, `dayRun()` (`src/game/88-days/10-day-tick.js`): `dayPreRun()` (the world moves on), then
+`dayPost()`, and the intern's shift (`opsRun()`) and the sales desk's (`slAutoRun()`) inside it are generators too. Each
+`yield` is a `compute()` the day needs before it goes on: the day's own routing, then a recompute after failures and
+events, and after the intern's jobs. `dayTick()` (tests, the fallback) answers each one with `compute()` on the spot
+(`dayGo()`); in play the route worker answers them. `yield DAY_REST` is not a routing, only a place where a long day may
+let a frame through. Same steps, same random numbers either way: routing draws none. Nothing of a day routes on the page:
+a failure (`failureRun()`; `fireFailure()` plays one at once through `runNow()`), a DDoS and Auto-RTBH (`ddosNewsRun()`),
+the chaos monkey's snip (`mkSnipRun()`), an event's cut (`eventRun()`: its routing is deferred to the next yield) and the
+sales desk's trials (a `{trial}` yield the worker answers with yes or no, `offerTrial()`) are all steps. The intern's
+orders are generators too, with a rest after each job. `UI.tick` (what the day itself announces, which quiet
+notifications may keep to the NOC log) is set around every step (`dayStep()`), on both sides of the worker.
+
+The daily mood check asks "a path without subsea" for each customer that wants one: during that loop the land-connected
+islands are worked out once (`TERR`, `terrIslands()`), and two cities have a land path when they share one.
+
+The day:
1. Advances `S.day`, runs scheduled world events (conferences, IX price wars, licences).
2. Runs `compute()` to route today's traffic.
3. Records history for 95th-percentile billing, stats and streaks.
-4. Rolls failures (`fireFailure()`) and events (`fireEvent()`) when their timers run out,
+4. Rolls failures (`failureRun()`) and events (`fireEvent()`) when their timers run out,
and expires incidents.
- Then the NOC intern's standing orders (`opsDay()`), if one is hired: each order clicks the same `ACT`
- actions a player would, muted, within its monthly budget, and the shift recomputes once at the end, only if
- a job changed the network. An order that throws is paused; the day goes on. The NOC gets one notice a week.
+ Then the NOC intern's standing orders (`opsRun()`, or `opsDay()` in one go), if one is hired: each order clicks the
+ same `ACT` actions a player would, muted, within its monthly budget, and the shift routes again (a yield) before
+ decommissioning, which reads today's loads, and at the end, each only if a job changed the network. An order that
+ throws is paused; the day goes on. The NOC gets one notice a week.
Then the sales desk (`slAutoDay()`), if someone runs sales and the player lets them sign: deals are Sales', never
the intern's. Each salesperson signs in their own style (a routing trial a day, or the shark's sign-everything).
5. Updates customer mood, churn and new offers; IX members join; loans tick.
@@ -179,10 +196,14 @@ network does not freeze the page once a day.
run again from a Blob URL, after a short prelude of inert stand-ins for `document`, storage and the other DOM globals,
and the player's dictionary. Nothing is fetched: GitHub Pages still serves one page, and a release cannot mismatch.
In the worker `RW_IN` is true and `boot()` never runs; the catalogs are rebuilt by the same top-level code.
-- **The day split.** `dayTick()` is `dayPre()` (the world moves on), `compute()`, `dayPost()` (bills, moods, offers,
- goals). In play, `frame()` calls `rwDay()` instead: `dayPre()`, then S and what routing reads of yesterday's R
- (`R.load`, `R.l2route`, `R.efg`) are posted, and the next day waits until R comes back and `dayPost()` has run. So a day
- sees exactly the routing it would have had in one go: same results, same random numbers. Half a day is never saved.
+- **The day in steps.** In play, `frame()` calls `rwDay()`, which runs `dayRun()` (see "The life of a day") with
+ `rwGo()`: the steps run on the page up to a yield, then S and what routing reads of yesterday's R (`R.load`,
+ `R.l2route`, `R.efg`) are posted, and the day goes on in `rwDone()` when R comes back. The next day waits until the
+ last step has run. So a day sees exactly the routing it would have had in one go: same results, same random numbers.
+ At a `DAY_REST`, a day that has run `RW.budget` ms (half a frame: 3 to 8, or up to 32 on a device slower than 50 frames a second) already goes on after the next frame
+ (`RW.later`, `rwLater()`), so a phone gets its frames between the steps of a big network's day. Half a day is never
+ saved; nothing else starts meanwhile. `tests/day-steps.test.js` plays a second page as the worker and compares every
+ day with `dayTick()`.
- **What crosses.** `R.ef` and `R.fl` are lazy getters; their pieces (`R.efp`, `R.flc`) travel instead, typed arrays
transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page.
- **Actions mid-day.** Every `compute()` bumps `RW.gen`. If an action routed while a day was in flight, the worker's
@@ -190,8 +211,8 @@ network does not freeze the page once a day.
- **Fallbacks.** Tests (`__TUBES_TEST__`, and jsdom has no Worker), `window.__TUBES_SYNC__`, a browser without workers, a
post that fails or a worker that errors take the synchronous path (`rwKill()` routes the day in flight on the page).
- **Still on the main thread**, because the caller reads R right away: actions (`after()`), loading a game, failures and
- events that fire during a day, standing orders, the chaos monkey, RouteScript what-ifs, the link panel's cut check and
- automatic offers.
+ RouteScript what-ifs and the link panel's cut check. Everything a day routes (failures, events, DDoS, the chaos monkey,
+ the intern's shift, the sales desk's trials) is a yield of the day, so it goes to the worker.
## Actions and rendering
@@ -294,5 +315,5 @@ assert.deepEqual(errors, []);
```
`ev()` runs code inside the page. To force a specific random failure, patch the
-picker, e.g. evaluate `fireFailure` with `.replace('const e=pick(opts);', "const e='x';")`.
+picker, e.g. evaluate `failureRun` with a `.replace(…)` and play it with `runNow(…)` (it is a generator).
Use `window.__reseed(n)` to reset the random sequence mid-test.
diff --git a/site/i18n/de.js b/site/i18n/de.js
index 8e8c786..0b4dacd 100644
--- a/site/i18n/de.js
+++ b/site/i18n/de.js
@@ -2276,6 +2276,10 @@
"find.press_slash_to_search_from":"Tipp: Drück irgendwo auf der Karte /, um zu suchen.",
"find.type_a_city_a_country":"Gib eine Stadt, ein Land oder einen Austauschknoten ein.",
"find.your_pop":"dein POP",
+"france.europe_s_biggest_hosting_cloud_from":"Europas größte Hosting-Cloud, aus Roubaix. Seit dem Brand in Straßburg sichert sie alles doppelt.",
+"france.france_s_number_two_it_bought_a":"Frankreichs Nummer zwei. Kaufte erst eine Kabelfirma, dann ein Medienimperium, dann jede Menge Schulden.",
+"france.the_builder_that_became_a_mobile":"Der Baukonzern, der ein Mobilfunknetz wurde. Nebenbei gießt er immer noch Beton.",
+"france.the_cloud_arm_of_the_free_group":"Der Cloud-Zweig der Free-Gruppe, mit ARM-Servern und einem Rechenzentrum in einem Pariser Bunker.",
"game_and_settings.delete_and_start_over":"Löschen und neu anfangen",
"game_and_settings.export_save_download_a_file":"Spielstand exportieren Datei herunterladen",
"game_and_settings.import_failed_that_save_is_damaged":"Import fehlgeschlagen. Dieser Spielstand ist beschädigt und konnte nicht geladen werden. Dein aktuelles Spiel ist unberührt.",
@@ -3398,6 +3402,9 @@
"ops.fire":"Entlassen",
"ops.fired":"{name} hat den Ausweis abgegeben und den guten Tacker mitgenommen. Deine Daueraufträge ruhen.",
"ops.floor":"Mindestens behalten",
+"ops.good_annie":"Am besten beim Peering: geht die Exchanges jeden Tag durch statt wöchentlich und bestellt zweimal pro Woche PNIs.",
+"ops.good_kevin":"Am besten bei Wartung: zwei Line-System-Tausche pro Nacht statt einem, und nie ein dicker Finger.",
+"ops.good_tracy":"Am besten im Vorausplanen: kauft Transit, Ports, Router und Optiken, als wäre der Traffic schon 10 % höher.",
"ops.hire_an_intern":"NOC-Praktikant einstellen",
"ops.hire_mo":"Einstellen · {price}/Monat",
"ops.hire_pitch_short":"Regeln einmal festlegen, und ein Praktikant klickt jeden Tag die Buttons.",
@@ -4521,8 +4528,22 @@
"sales.locked":"Der Vertrieb öffnet ab Kundenstufe {lv}.",
"sales.never":"nie",
"sales.one_at_a_time":"Immer nur eine Person: Lass sie gehen, um jemand anderen einzustellen.",
+"sales.p_ren":"Nachverhandeln",
"sales.p_sign":"Deals unterschreiben",
"sales.pitch":"Eine Person im Vertrieb holt Deals auf ihre eigene Art. Such sie aus.",
+"sales.ren":"Nachverhandlungen",
+"sales.ren_ceo":"{name} antwortet drei Tage nach Beginn auf die Nachverhandlung eines Kunden, auf dem Golfplatz: mehr Rabatt als verlangt für einen doppelt so langen Vertrag, ein schnelles Ja oder ein Streit, nach dem der Kunde weg ist.",
+"sales.ren_ceo_fight":"{name} hat {cust} erklärt, dass mit ihm niemand verhandelt. Sie sind weg.",
+"sales.ren_ceo_golf":"{name} hat {cust} auf dem Golfplatz geregelt: {price}/Monat, noch weniger als verlangt, fest bis {date}.",
+"sales.ren_ceo_yes":"{name} hat {cust} zugesagt, bevor jemand nachrechnen konnte: {price}/Monat.",
+"sales.ren_eng":"{name} antwortet drei Tage nach Beginn auf die Nachverhandlung eines Kunden. Nerdige Kunden bekommen einen Nachmittag mit den Netzplänen und verlängern meist zum Marktpreis; alle anderen bekommen den Rabatt, den sie wollten. Niemand geht.",
+"sales.ren_eng_cave":"{name} hat {cust} den gewünschten Rabatt gegeben: {price}/Monat. Sie bleiben.",
+"sales.ren_eng_tech":"{name} hat den Engineers von {cust} einen Nachmittag lang das Netz gezeigt. Sie verlängern zu {price}/Monat, ganz ohne Rabatt.",
+"sales.ren_mid":"{name} hat sich mit {cust} in der Mitte getroffen: {price}/Monat.",
+"sales.ren_shark":"{name} antwortet drei Tage nach Beginn auf die Nachverhandlung eines Kunden und schenkt nichts her: die meisten verlängern zum alten Preis, oft mit einem neuen Versprechen, und er stellt dir einen Monat der Ersparnis in Rechnung. Manche gehen, nerdige am ehesten.",
+"sales.ren_shark_hold":"{name} hat {cust} gesagt, der Preis ist der Preis. Sie verlängern zu {price}/Monat, und er stellt dir {fee} für die Rettung in Rechnung.",
+"sales.ren_shark_walk":"{name} hat bei {cust} auf hart gemacht, und sie sind gegangen.",
+"sales.ren_when":"{name} antwortet am {date}, falls du es nicht vorher tust.",
"sales.shark_d":"Holt die größten Deals zu einem Viertel mehr und kassiert einen Monat jedes Deals als Provision. Verkauft zu viel: Die Hälfte kommt mit einem Versprechen, das dein Netz noch nicht hält, und diese Kunden gehen früher. Ignoriert die Nerds: keine technischen Kunden, keine Meetings, und Peering-Desks wollen ein Viertel mehr Verkehr von dir. Gewinnt die meisten Verhandlungen.",
"sales.shark_n":"Der Hai",
"sales.shark_s":"Chad",
diff --git a/site/i18n/es.js b/site/i18n/es.js
index a416061..54e4971 100644
--- a/site/i18n/es.js
+++ b/site/i18n/es.js
@@ -2274,6 +2274,10 @@
"find.press_slash_to_search_from":"Consejo: pulsa / en cualquier parte del mapa para buscar.",
"find.type_a_city_a_country":"Escribe una ciudad, un país o un punto de intercambio.",
"find.your_pop":"tu POP",
+"france.europe_s_biggest_hosting_cloud_from":"La mayor nube de alojamiento de Europa, desde Roubaix. Tras el incendio de Estrasburgo, lo respalda todo dos veces.",
+"france.france_s_number_two_it_bought_a":"El número dos de Francia. Compró una empresa de cable, luego un imperio mediático y luego muchas deudas.",
+"france.the_builder_that_became_a_mobile":"La constructora que se hizo red móvil. Sigue echando hormigón en sus ratos libres.",
+"france.the_cloud_arm_of_the_free_group":"La rama de nube del grupo Free, con servidores ARM y un centro de datos en un búnker de París.",
"game_and_settings.delete_and_start_over":"Borrar y empezar de nuevo",
"game_and_settings.export_save_download_a_file":"Exportar partida descargar un archivo",
"game_and_settings.import_failed_that_save_is_damaged":"Falló la importación. Esa partida está dañada y no se pudo cargar. Tu partida actual sigue intacta.",
@@ -3396,6 +3400,9 @@
"ops.fire":"Despedir",
"ops.fired":"{name} devolvió la tarjeta y se llevó la grapadora buena. Tus órdenes permanentes quedan en pausa.",
"ops.floor":"Conservar al menos",
+"ops.good_annie":"La mejor en peering: repasa los exchanges cada día, no cada semana, y pide PNI dos veces por semana.",
+"ops.good_kevin":"El mejor en mantenimiento: dos cambios de sistema de línea por noche en vez de uno, y nunca un dedazo.",
+"ops.good_tracy":"La mejor planificando: compra tránsito, puertos, routers y ópticas como si el tráfico ya fuera un 10 % mayor.",
"ops.hire_an_intern":"Contratar a un becario del NOC",
"ops.hire_mo":"Contratar · {price}/mes",
"ops.hire_pitch_short":"Fija las reglas una vez y un becario pulsa los botones cada día.",
@@ -4519,8 +4526,22 @@
"sales.locked":"Ventas se abre en el nivel de clientes {lv}.",
"sales.never":"nunca",
"sales.one_at_a_time":"Solo una a la vez: despídela para contratar a otra.",
+"sales.p_ren":"Renegociar",
"sales.p_sign":"Firmar tratos",
"sales.pitch":"Una persona de ventas trae tratos a su manera. Elige quién.",
+"sales.ren":"Renegociaciones",
+"sales.ren_ceo":"{name} responde a la renegociación de un cliente tres días después de que empiece, en el campo de golf: más descuento del pedido a cambio de un contrato el doble de largo, un sí rápido o una pelea tras la que el cliente se va.",
+"sales.ren_ceo_fight":"{name} le dijo a {cust} que con él nadie regatea. Se han ido.",
+"sales.ren_ceo_golf":"{name} arregló lo de {cust} en el campo de golf: {price}/mes, aún menos de lo pedido, cerrado hasta el {date}.",
+"sales.ren_ceo_yes":"{name} le dijo que sí a {cust} antes de que nadie pudiera comprobarlo: {price}/mes.",
+"sales.ren_eng":"{name} responde a la renegociación de un cliente tres días después de que empiece. Los clientes frikis reciben una tarde con los diagramas de la red y suelen renovar a precio de mercado; los demás reciben el descuento que pidieron. Nadie se va.",
+"sales.ren_eng_cave":"{name} le dio a {cust} el descuento que pidió: {price}/mes. Se quedan.",
+"sales.ren_eng_tech":"{name} pasó una tarde enseñando la red a los ingenieros de {cust}. Renuevan a {price}/mes, sin descuento.",
+"sales.ren_mid":"{name} y {cust} se encontraron a medio camino: {price}/mes.",
+"sales.ren_shark":"{name} responde a la renegociación de un cliente tres días después de que empiece, y no regala nada: la mayoría renueva al precio antiguo, a menudo con una promesa nueva, y te cobra un mes de lo que te ahorró. Algunos se van, sobre todo los frikis.",
+"sales.ren_shark_hold":"{name} le dijo a {cust} que el precio es el precio. Renuevan a {price}/mes, y te cobra {fee} por salvarlo.",
+"sales.ren_shark_walk":"{name} se puso duro con {cust}, y se fueron.",
+"sales.ren_when":"{name} responde el {date}, salvo que lo hagas tú antes.",
"sales.shark_d":"Consigue los tratos más grandes a un cuarto más, y se lleva un mes de cada trato de comisión. Vende de más: la mitad llega con una promesa que tu red aún no cumple, y esos clientes se van antes. Ignora a los nerds: nada de clientes técnicos ni de reuniones, y los equipos de peering te piden un cuarto más de tráfico. Gana casi todas las negociaciones.",
"sales.shark_n":"El tiburón",
"sales.shark_s":"Chad",
diff --git a/site/i18n/fr.js b/site/i18n/fr.js
index 6ca08cf..d3d4cd4 100644
--- a/site/i18n/fr.js
+++ b/site/i18n/fr.js
@@ -2274,6 +2274,10 @@
"find.press_slash_to_search_from":"Astuce : appuyez sur / n'importe où sur la carte pour chercher.",
"find.type_a_city_a_country":"Tapez une ville, un pays ou un point d'échange.",
"find.your_pop":"votre POP",
+"france.europe_s_biggest_hosting_cloud_from":"Le plus grand cloud d’hébergement d’Europe, de Roubaix. Depuis l’incendie de Strasbourg, tout est sauvegardé deux fois.",
+"france.france_s_number_two_it_bought_a":"Le numéro deux français. Il a racheté un câblo-opérateur, puis un empire médiatique, puis beaucoup de dettes.",
+"france.the_builder_that_became_a_mobile":"Le constructeur devenu réseau mobile. Il coule toujours du béton à côté.",
+"france.the_cloud_arm_of_the_free_group":"La branche cloud du groupe Free, avec des serveurs ARM et un datacenter dans un bunker parisien.",
"game_and_settings.delete_and_start_over":"Supprimer et recommencer",
"game_and_settings.export_save_download_a_file":"Exporter la sauvegarde télécharger un fichier",
"game_and_settings.import_failed_that_save_is_damaged":"Échec de l’import. Cette sauvegarde est endommagée et n’a pas pu être chargée. Ta partie en cours est intacte.",
@@ -3396,6 +3400,9 @@
"ops.fire":"Remercier",
"ops.fired":"{name} a rendu son badge et emporté la bonne agrafeuse. Tes ordres permanents sont en pause.",
"ops.floor":"Garder au moins",
+"ops.good_annie":"La meilleure en peering : passe les exchanges en revue chaque jour, pas chaque semaine, et commande des PNI deux fois par semaine.",
+"ops.good_kevin":"Le meilleur en maintenance : deux changements de système de ligne par nuit au lieu d’un, et jamais une faute de frappe.",
+"ops.good_tracy":"La meilleure pour anticiper : achète transit, ports, routeurs et optiques comme si le trafic était déjà 10 % plus haut.",
"ops.hire_an_intern":"Recruter un stagiaire NOC",
"ops.hire_mo":"Recruter · {price}/mois",
"ops.hire_pitch_short":"Fixe les règles une fois, un stagiaire clique sur les boutons chaque jour.",
@@ -4519,8 +4526,22 @@
"sales.locked":"Le service commercial ouvre au niveau clients {lv}.",
"sales.never":"jamais",
"sales.one_at_a_time":"Une seule à la fois : laissez-la partir pour en recruter une autre.",
+"sales.p_ren":"Renégocier",
"sales.p_sign":"Signer les contrats",
"sales.pitch":"Un commercial apporte des contrats à sa façon. Choisissez qui.",
+"sales.ren":"Renégociations",
+"sales.ren_ceo":"{name} répond à la renégociation d'un client trois jours après son début, sur le terrain de golf : une remise plus forte que demandé contre un contrat deux fois plus long, un oui rapide, ou une dispute après laquelle le client s'en va.",
+"sales.ren_ceo_fight":"{name} a dit à {cust} que personne ne négocie avec lui. Ils sont partis.",
+"sales.ren_ceo_golf":"{name} a réglé le cas de {cust} sur le terrain de golf : {price}/mois, encore moins que demandé, bloqué jusqu'au {date}.",
+"sales.ren_ceo_yes":"{name} a dit oui à {cust} avant que quiconque puisse vérifier : {price}/mois.",
+"sales.ren_eng":"{name} répond à la renégociation d'un client trois jours après son début. Les clients geeks ont droit à un après-midi avec les schémas du réseau et renouvellent le plus souvent au prix du marché ; les autres obtiennent la remise demandée. Personne ne part.",
+"sales.ren_eng_cave":"{name} a accordé à {cust} la remise demandée : {price}/mois. Ils restent.",
+"sales.ren_eng_tech":"{name} a passé un après-midi à montrer le réseau aux ingénieurs de {cust}. Ils renouvellent à {price}/mois, sans remise.",
+"sales.ren_mid":"{name} a coupé la poire en deux avec {cust} : {price}/mois.",
+"sales.ren_shark":"{name} répond à la renégociation d'un client trois jours après son début, et ne lâche rien : la plupart renouvellent à l'ancien prix, souvent avec une nouvelle promesse, et il vous facture un mois de ce qu'il vous a fait gagner. Certains partent, surtout les geeks.",
+"sales.ren_shark_hold":"{name} a dit à {cust} que le prix, c'est le prix. Ils renouvellent à {price}/mois, et il vous facture {fee} pour l'avoir sauvé.",
+"sales.ren_shark_walk":"{name} a joué les durs avec {cust}, et ils sont partis.",
+"sales.ren_when":"{name} répond le {date}, sauf si vous le faites avant.",
"sales.shark_d":"Décroche les plus gros contrats un quart plus cher, et prend un mois de chaque contrat en commission. Survend : la moitié arrive avec une promesse que votre réseau ne tient pas encore, et ces clients partent plus tôt. Ignore les geeks : pas de clients techniques, pas de NOG, et les équipes peering vous demandent un quart de trafic en plus. Gagne la plupart des négociations.",
"sales.shark_n":"Le requin",
"sales.shark_s":"Chad",
diff --git a/site/i18n/it.js b/site/i18n/it.js
index e0b0bf0..618b5ba 100644
--- a/site/i18n/it.js
+++ b/site/i18n/it.js
@@ -2274,6 +2274,10 @@
"find.press_slash_to_search_from":"Suggerimento: premi / ovunque sulla mappa per cercare.",
"find.type_a_city_a_country":"Scrivi una città, un paese o un exchange.",
"find.your_pop":"il tuo POP",
+"france.europe_s_biggest_hosting_cloud_from":"Il più grande cloud di hosting d’Europa, da Roubaix. Dopo l’incendio di Strasburgo salva tutto due volte.",
+"france.france_s_number_two_it_bought_a":"Il numero due della Francia. Ha comprato una società via cavo, poi un impero mediatico, poi un sacco di debiti.",
+"france.the_builder_that_became_a_mobile":"L’impresa edile diventata rete mobile. Nel tempo libero cola ancora cemento.",
+"france.the_cloud_arm_of_the_free_group":"Il ramo cloud del gruppo Free, con server ARM e un data center in un bunker di Parigi.",
"game_and_settings.delete_and_start_over":"Cancella e ricomincia",
"game_and_settings.export_save_download_a_file":"Esporta salvataggio scarica un file",
"game_and_settings.import_failed_that_save_is_damaged":"Importazione fallita. Quel salvataggio è danneggiato e non si può caricare. La partita in corso non è stata toccata.",
@@ -3396,6 +3400,9 @@
"ops.fire":"Licenzia",
"ops.fired":"{name} ha restituito il badge e si è preso la spillatrice buona. I tuoi ordini permanenti sono in pausa.",
"ops.floor":"Tieni almeno",
+"ops.good_annie":"La migliore nel peering: passa gli exchange ogni giorno, non ogni settimana, e ordina PNI due volte a settimana.",
+"ops.good_kevin":"Il migliore nella manutenzione: due cambi di line system per notte invece di uno, e mai un errore di battitura.",
+"ops.good_tracy":"La migliore a pianificare: compra transito, porte, router e ottiche come se il traffico fosse già più alto del 10%.",
"ops.hire_an_intern":"Assumi uno stagista NOC",
"ops.hire_mo":"Assumi · {price}/mese",
"ops.hire_pitch_short":"Fissa le regole una volta, e uno stagista clicca i pulsanti ogni giorno.",
@@ -4519,8 +4526,22 @@
"sales.locked":"L'ufficio vendite apre al livello clienti {lv}.",
"sales.never":"mai",
"sales.one_at_a_time":"Uno alla volta: lascialo andare per assumerne un altro.",
+"sales.p_ren":"Rinegoziare",
"sales.p_sign":"Firma contratti",
"sales.pitch":"Un venditore porta contratti a modo suo. Scegli chi.",
+"sales.ren":"Rinegoziazioni",
+"sales.ren_ceo":"{name} risponde alla rinegoziazione di un cliente tre giorni dopo l'inizio, sul campo da golf: più sconto di quanto chiesto in cambio di un contratto lungo il doppio, un sì veloce, o una lite dopo cui il cliente se ne va.",
+"sales.ren_ceo_fight":"{name} ha detto a {cust} che con lui nessuno tratta. Se ne sono andati.",
+"sales.ren_ceo_golf":"{name} ha sistemato {cust} sul campo da golf: {price}/mese, ancora meno di quanto chiesto, bloccato fino al {date}.",
+"sales.ren_ceo_yes":"{name} ha detto sì a {cust} prima che qualcuno potesse controllare: {price}/mese.",
+"sales.ren_eng":"{name} risponde alla rinegoziazione di un cliente tre giorni dopo l'inizio. I clienti nerd passano un pomeriggio con gli schemi della rete e di solito rinnovano a prezzo di mercato; gli altri ottengono lo sconto che chiedevano. Nessuno se ne va.",
+"sales.ren_eng_cave":"{name} ha dato a {cust} lo sconto che chiedeva: {price}/mese. Restano.",
+"sales.ren_eng_tech":"{name} ha passato un pomeriggio a mostrare la rete agli ingegneri di {cust}. Rinnovano a {price}/mese, senza sconto.",
+"sales.ren_mid":"{name} è venuto incontro a {cust}: {price}/mese.",
+"sales.ren_shark":"{name} risponde alla rinegoziazione di un cliente tre giorni dopo l'inizio, e non regala niente: quasi tutti rinnovano al vecchio prezzo, spesso con una nuova promessa, e ti fattura un mese di quanto ti ha fatto risparmiare. Alcuni se ne vanno, soprattutto i nerd.",
+"sales.ren_shark_hold":"{name} ha detto a {cust} che il prezzo è il prezzo. Rinnovano a {price}/mese, e lui ti fattura {fee} per averli salvati.",
+"sales.ren_shark_walk":"{name} ha fatto il duro con {cust}, e se ne sono andati.",
+"sales.ren_when":"{name} risponde il {date}, a meno che tu non lo faccia prima.",
"sales.shark_d":"Porta i contratti più grandi a un quarto in più, e si prende un mese di ogni contratto come provvigione. Vende troppo: metà arriva con una promessa che la tua rete non mantiene ancora, e quei clienti se ne vanno prima. Ignora i nerd: niente clienti tecnici, niente incontri, e i peering desk ti chiedono un quarto di traffico in più. Vince quasi tutte le trattative.",
"sales.shark_n":"Lo squalo",
"sales.shark_s":"Chad",
diff --git a/site/i18n/pt.js b/site/i18n/pt.js
index a8014bf..b301858 100644
--- a/site/i18n/pt.js
+++ b/site/i18n/pt.js
@@ -2274,6 +2274,10 @@
"find.press_slash_to_search_from":"Dica: pressione / em qualquer lugar do mapa para pesquisar.",
"find.type_a_city_a_country":"Digite uma cidade, um país ou um exchange.",
"find.your_pop":"seu POP",
+"france.europe_s_biggest_hosting_cloud_from":"A maior nuvem de hospedagem da Europa, de Roubaix. Depois do incêndio de Estrasburgo, faz backup de tudo duas vezes.",
+"france.france_s_number_two_it_bought_a":"O número dois da França. Comprou uma operadora de cabo, depois um império de mídia, depois muitas dívidas.",
+"france.the_builder_that_became_a_mobile":"A construtora que virou rede móvel. Ainda despeja concreto nas horas vagas.",
+"france.the_cloud_arm_of_the_free_group":"O braço de nuvem do grupo Free, com servidores ARM e um data center num bunker de Paris.",
"game_and_settings.delete_and_start_over":"Apagar e recomeçar",
"game_and_settings.export_save_download_a_file":"Exportar save baixar um arquivo",
"game_and_settings.import_failed_that_save_is_damaged":"Falha na importação. Esse save está corrompido e não pôde ser carregado. Seu jogo atual não foi mexido.",
@@ -3396,6 +3400,9 @@
"ops.fire":"Dispensar",
"ops.fired":"{name} devolveu o crachá e levou o grampeador bom. Suas ordens permanentes estão em pausa.",
"ops.floor":"Manter pelo menos",
+"ops.good_annie":"A melhor em peering: passa pelos exchanges todo dia, não toda semana, e pede PNIs duas vezes por semana.",
+"ops.good_kevin":"O melhor em manutenção: duas trocas de sistema de linha por noite em vez de uma, e nunca um dedo gordo.",
+"ops.good_tracy":"A melhor em planejar: compra trânsito, portas, roteadores e ópticas como se o tráfego já estivesse 10% maior.",
"ops.hire_an_intern":"Contratar um estagiário de NOC",
"ops.hire_mo":"Contratar · {price}/mês",
"ops.hire_pitch_short":"Defina as regras uma vez, e um estagiário clica nos botões todo dia.",
@@ -4519,8 +4526,22 @@
"sales.locked":"Vendas abre no nível de clientes {lv}.",
"sales.never":"nunca",
"sales.one_at_a_time":"Uma por vez: dispense para contratar outra.",
+"sales.p_ren":"Renegociar",
"sales.p_sign":"Assinar contratos",
"sales.pitch":"Uma pessoa de vendas traz negócios do jeito dela. Escolha quem.",
+"sales.ren":"Renegociações",
+"sales.ren_ceo":"{name} responde à renegociação de um cliente três dias depois de começar, no campo de golfe: mais desconto do que pediram em troca de um contrato com o dobro da duração, um sim rápido, ou uma briga que termina com o cliente indo embora.",
+"sales.ren_ceo_fight":"{name} disse a {cust} que ninguém pechincha com ele. Foram embora.",
+"sales.ren_ceo_golf":"{name} resolveu {cust} no campo de golfe: {price}/mês, ainda menos do que pediram, fechado até {date}.",
+"sales.ren_ceo_yes":"{name} disse sim a {cust} antes que alguém pudesse conferir: {price}/mês.",
+"sales.ren_eng":"{name} responde à renegociação de um cliente três dias depois de começar. Clientes nerds ganham uma tarde com os diagramas da rede e quase sempre renovam a preço de mercado; os outros recebem o desconto que pediram. Ninguém sai.",
+"sales.ren_eng_cave":"{name} deu a {cust} o desconto que pediram: {price}/mês. Eles ficam.",
+"sales.ren_eng_tech":"{name} passou uma tarde mostrando a rede aos engenheiros da {cust}. Renovam a {price}/mês, sem desconto.",
+"sales.ren_mid":"{name} e {cust} chegaram a um meio-termo: {price}/mês.",
+"sales.ren_shark":"{name} responde à renegociação de um cliente três dias depois de começar, e não cede nada: a maioria renova ao preço antigo, muitas vezes com uma nova promessa, e ele te cobra um mês do que economizou. Alguns vão embora, principalmente os nerds.",
+"sales.ren_shark_hold":"{name} disse a {cust} que preço é preço. Renovam a {price}/mês, e ele te cobra {fee} pelo resgate.",
+"sales.ren_shark_walk":"{name} jogou duro com {cust}, e eles foram embora.",
+"sales.ren_when":"{name} responde em {date}, a não ser que você responda antes.",
"sales.shark_d":"Fecha os maiores negócios por um quarto a mais, e leva um mês de cada contrato de comissão. Vende demais: metade chega com uma promessa que sua rede ainda não cumpre, e esses clientes saem mais cedo. Ignora os nerds: nada de clientes técnicos nem de encontros, e as equipes de peering pedem um quarto a mais de tráfego. Ganha quase todas as negociações.",
"sales.shark_n":"O tubarão",
"sales.shark_s":"Chad",
diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js
index 25cb8db..20b1366 100644
--- a/src/agent/20-commands.js
+++ b/src/agent/20-commands.js
@@ -266,6 +266,8 @@ const API_CMD={
doc:'With the CEO running sales: pay for a board meeting that brings a VP of Sales, who frees the desk a month later.'},
salesAuto:{args:[],watch:['slAuto'],
doc:'With someone at the sales desk: switch automatic signing on or off. Once a game day they sign the offers that fit, in their own style: eng and ceo after a routing trial (one a day; an offer that did not fit waits a week), shark every offer whose POPs are up, promises and all, while the cash covers the commission. Orbit offers sign where the landing dish has room (the shark ignores that). Nobody at the desk: nothing is signed for you.'},
+ salesRen:{args:[],watch:['slAuto'],
+ doc:'Switch whether the sales desk answers renewal haggles for you, 3 days after each opens (only while someone runs sales). The engineer gives business customers their discount and keeps nerdy ones at the market price; the shark holds the old price (sometimes with a new promise, billing a month of the saving) but some walk; the CEO gives 10% more off for a double term, says yes, or picks a fight and loses them.'},
salesMin:{args:[],watch:['slAuto'],
doc:'Step the minimum monthly value under which the sales desk declines offers: never, 2k, 5k, 10k, 25k, 50k. With the CEO, about one decline in three is signed anyway.'},
renewMatch:{args:[['id','entityId']],watch:['biz.#id'],
diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js
index e75ae3c..3fe830f 100644
--- a/src/agent/30-docs.js
+++ b/src/agent/30-docs.js
@@ -36,7 +36,7 @@ const API_STATE_DOC={
biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates (te: the day the term ends, mk: the bandwidth market it was priced in, hag: an open renewal haggle {rate, until}).'},
offers:{type:'array',doc:'Pending customer offers, each expiring on a day (mk: the bandwidth market they were priced in; refN: the customer who referred them).'},
sales:{type:'map',doc:'The sales desk: p (eng, shark, ceo or null), hired (day), vp (the day a VP of Sales takes over from the CEO), golf and say (the CEO\'s next golf deal and opinion). Offers and customers carry by: who brought or signed them, orbit ones too (the shark\'s may carry the skyfull promise).'},
- slAuto:{type:'map',doc:'Deals the sales desk signs for you (only while someone runs sales): on (sign offers that fit), min (decline offers paying less a month; 0 never), wk (this week: w, p who was at the desk, n signed, rev their monthly revenue, x declined, y declined but signed anyway by the CEO) and rep (last week, the same).'},
+ slAuto:{type:'map',doc:'Deals the sales desk signs for you (only while someone runs sales): on (sign offers that fit), min (decline offers paying less a month; 0 never), ren (answer renewal haggles), wk (this week: w, p who was at the desk, n signed, rev their monthly revenue, x declined, y declined but signed anyway by the CEO) and rep (last week, the same).'},
cl:{type:'map',doc:'Customer lifecycle (#178): odd (the day of the last unusual departure) and mo, one entry a month of customers won, renewed, grown, haggling and lost by reason.'},
done:{type:'map',doc:'Goals landed, by goal id → day.'},
ach:{type:'map',doc:'Badges earned this game, by badge id → day.'},
diff --git a/src/game/20-world/40-city-coords.js b/src/game/20-world/40-city-coords.js
index 0b57f2d..9d1fc60 100644
--- a/src/game/20-world/40-city-coords.js
+++ b/src/game/20-world/40-city-coords.js
@@ -50,6 +50,7 @@ const CITY_LL={
"blr":[77.59, 12.97],
"bna":[-86.78,36.16],
"bne":[153.03, -27.47],
+ "bod":[-0.58,44.84],
"bog":[-74.07, 4.71],
"boi":[-116.2,43.62],
"bom":[72.88,19.08],
@@ -201,6 +202,7 @@ const CITY_LL={
"lbv":[9.49,0.5],
"ldb":[-51.16,-23.31],
"lfw":[1.22,6.13],
+ "lil":[3.06,50.63],
"lim":[-76.85,-12.05],
"lis":[-9.14,38.72],
"lit":[-92.29,34.75],
@@ -211,6 +213,7 @@ const CITY_LL={
"lon":[-0.13,51.51],
"lpb":[-68.15,-16.5],
"lun":[28.32,-15.39],
+ "lys":[4.84,45.76],
"maa":[80.18,13.25],
"mad":[-3.7,40.42],
"maj":[171.38,7.09],
@@ -257,6 +260,7 @@ const CITY_LL={
"nou":[166.46,-22.27],
"nqz":[71.45,51.17],
"nsi":[11.5,3.85],
+ "nte":[-1.55,47.22],
"nuk":[-51.72,64.18],
"nyc":[-74.0,40.71],
"nyt":[96.08,19.76],
@@ -312,6 +316,7 @@ const CITY_LL={
"ric":[-77.44,37.54],
"rio":[-43.11,-22.57],
"rix":[24.11,56.95],
+ "rns":[-1.68,48.11],
"rob":[-10.7,6.38],
"rom":[12.5,41.9],
"ror":[134.48,7.34],
@@ -352,6 +357,7 @@ const CITY_LL={
"suv":[178.44,-18.14],
"svd":[-61.22,13.16],
"svg":[5.73,58.97],
+ "sxb":[7.75,48.57],
"syd":[151.21,-33.87],
"tas":[69.24,41.3],
"tbs":[44.79,41.72],
@@ -366,6 +372,7 @@ const CITY_LL={
"tip":[13.19,32.89],
"tlh":[-84.28,30.44],
"tll":[24.45,58.9],
+ "tls":[1.44,43.6],
"tms":[6.73,0.34],
"tnr":[47.52,-18.88],
"tok":[139.69,35.69],
diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js
index ac1f788..4c9d512 100644
--- a/src/game/20-world/50-cities.js
+++ b/src/game/20-world/50-cities.js
@@ -11,6 +11,13 @@ const CITIES=[
{id:'ams',name:'Amsterdam',x:1015,y:245,land:'eu',reg:'EU',cc:'NL',P:350,ix:'HAMS-IX',dc:'Science Park'},
{id:'fra',name:'Frankfurt',x:1075,y:295,land:'eu',reg:'EU',cc:'DE',P:600,ix:'DE-KICKS',dc:'Kleyerstraße Campus',note:tr('cities.europe_s_crossroads_lots_of_networks')},
{id:'par',name:'Paris',x:990,y:320,land:'eu',reg:'EU',cc:'FR',P:900,ix:'Fromage-IX',dc:'Interaction PAR'},
+ {id:'lys',name:'Lyon',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:220,ix:'Quenelle-IX',dc:'Croix-Rousse Silk Rack'},
+ {id:'tls',name:'Toulouse',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:140,ix:'Cassoulet-IX',dc:'Pink City Colo'},
+ {id:'lil',name:'Lille',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:120,ix:'Maroilles-IX',dc:'Belfry Colo'},
+ {id:'bod',name:'Bordeaux',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:120,ix:'Claret-IX',dc:'Wine Cellar DC'},
+ {id:'sxb',name:'Strasbourg',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:80,ix:'Choucroute-IX',dc:'Cathedral Clock DC'},
+ {id:'rns',name:'Rennes',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:75,ix:'Galette-IX',dc:'Breton Cold Room'},
+ {id:'nte',name:'Nantes',x:0,y:0,land:'eu',reg:'EU',cc:'FR',P:90,ix:'',dc:'Mechanical Elephant DC'},
{id:'mrs',name:'Marseille',x:1045,y:378,land:'eu',reg:'EU',cc:'FR',P:250,ix:'Bouilla-IX',dc:'Cable Landing Station',note:tr('cities.subsea_cables_to_africa_and_asia')},
{id:'tor',name:'Toronto',ca:true,x:548,y:252,land:'am',reg:'AM',cc:'CA',P:500,ix:'Sorry-IX',dc:'151 Front Street',note:tr('cities.canada_s_hub_polite_packets_long')},
{id:'bru',name:'Brussels',x:0,y:0,land:'eu',reg:'EU',cc:'BE',P:150,be:true,tape:true,ix:'Frites-IX',dc:'Digital Unreality BRU1',note:tr('cities.right_between_london_amsterdam_paris')},
@@ -466,6 +473,7 @@ const CITY_NUDGE={
khi:[-2,-6],
kwi:[-0.4,0.5],
ldb:[6.2,0.1],
+ lil:[-14,6],
lis:[.8,0],
ljd:[-5.2,-7.7],
mba:[-0.8,0],
@@ -491,6 +499,7 @@ const CITY_NUDGE={
rec:[-2.4,7.2],
ria:[-2.4,4.9],
rix:[-2,18],
+ rns:[-6,2],
sea:[1,4],
sin:[-1.3,-1.3],
sis:[0.3,-0.8],
@@ -500,6 +509,7 @@ const CITY_NUDGE={
stg:[7,1],
tgd:[-0.8,-1.3],
tll:[4,10],
+ tls:[0,-6],
van:[-3,-6],
vie:[-4.5,2.25],
vix:[-0.4,0.4],
diff --git a/src/game/20-world/55-city-pdb.js b/src/game/20-world/55-city-pdb.js
index df12bc0..9cd64bb 100644
--- a/src/game/20-world/55-city-pdb.js
+++ b/src/game/20-world/55-city-pdb.js
@@ -55,6 +55,7 @@ const CITY_PDB={
blr:[14,104,6412],
bna:[7,35,33300], // est.
bne:[21,277,3196],
+ bod:[1,29,2249],
bog:[16,195,598],
boi:[3,12,33300], // est.
bom:[59,1050,6412],
@@ -206,6 +207,7 @@ const CITY_PDB={
lbv:[4,11,12],
ldb:[3,7,9693],
lfw:[1,4,11],
+ lil:[4,24,2249], // pulled 2026-11-06, Tourcoing and Roubaix included
lim:[12,156,267],
lis:[9,129,187],
lit:[2,6,33300], // est.
@@ -216,6 +218,7 @@ const CITY_PDB={
lon:[100,2588,4027],
lpb:[1,2,71],
lun:[4,3,24],
+ lys:[1,84,2249],
maa:[20,374,6412],
mad:[31,578,1341],
maj:[0,0,12],
@@ -262,6 +265,7 @@ const CITY_PDB={
nou:[2,2,19],
nqz:[2,3,284],
nsi:[3,6,61],
+ nte:[1,3,2249], // est.
nuk:[0,0,2], // est.
nyc:[96,1322,33300],
nyt:[0,0,173], // est.
@@ -317,6 +321,7 @@ const CITY_PDB={
ric:[5,25,33300], // est.
rio:[33,577,9693],
rix:[8,60,330], // 8 listed, Perses 2 has 19 networks; presences est.
+ rns:[1,3,2249], // est.
rob:[1,2,18],
rom:[12,213,1534],
ror:[0,0,4],
@@ -357,6 +362,7 @@ const CITY_PDB={
suv:[0,0,23],
svd:[0,2,6], // est.
svg:[2,14,448],
+ sxb:[2,54,2249],
syd:[40,979,3196],
tas:[7,3,140],
tbs:[4,15,185],
@@ -371,6 +377,7 @@ const CITY_PDB={
tip:[0,0,34], // est.
tlh:[1,3,33300], // est.
tll:[7,80,256],
+ tls:[1,18,2249],
tms:[0,0,2], // est.
tnr:[1,4,25], // est.
tok:[58,917,1330],
diff --git a/src/game/20-world/60-cables.js b/src/game/20-world/60-cables.js
index f50860f..b0e1c33 100644
--- a/src/game/20-world/60-cables.js
+++ b/src/game/20-world/60-cables.js
@@ -1,8 +1,8 @@
const CABLES=[
{"id":"marea","name":"Marea Carey","price":0.8,"age":"new","blurb":tr('cables.hits_the_high_notes_across_the'),"pairs":[["ash","bio",[[-75.7,36.85],[-60,39.5],[-40,42.5],[-20.95,44.76],[-4.25,44],[-3.2,43.55]]]]},
{"id":"grace","name":"Grace Hopscotch","price":0.85,"age":"new","blurb":tr('cables.hops_from_new_york_to_the'),"pairs":[["nyc","lon",[[-73.5,40.5],[-70.5,41],[-62.76,43.86],[-55,46],[-5,50],[-1,50],[-0.25,50.75]]],["nyc","bio",[[-70.5,41],[-62,44],[-53.28,45.88],[-43.34,47.11],[-33.84,47.46],[-21.48,46.73],[-4.25,44],[-3.2,43.55]]]]},
- {"id":"dunant","name":"Dunno-ant","price":0.85,"age":"new","blurb":tr('cables.nobody_remembers_who_it_is_named'),"pairs":[["ash","par",[[-74.25,40.5],[-70.5,41],[-61.91,43.92],[-53.25,46],[-5,50],[0,50]]]]},
- {"id":"amitie","name":"Ami-Tea","price":0.9,"age":"new","blurb":tr('cables.a_friendly_cable_with_french_manners'),"pairs":[["nyc","lon",[[-73.5,40.5],[-70.5,41],[-62.76,43.86],[-55,46],[-5,50],[-1,50],[-0.25,50.75]]],["nyc","par",[[-70.5,41],[-61.91,43.92],[-53.25,46],[-5,50],[0,50]]]]},
+ {"id":"dunant","name":"Dunno-ant","price":0.85,"age":"new","blurb":tr('cables.nobody_remembers_who_it_is_named'),"pairs":[["ash","nte",[[-75.7,36.85],[-60,39.5],[-40,43],[-20,46.5],[-5,46.4],[-2.5,46.5]]]]},
+ {"id":"amitie","name":"Ami-Tea","price":0.9,"age":"new","blurb":tr('cables.a_friendly_cable_with_french_manners'),"pairs":[["nyc","lon",[[-73.5,40.5],[-70.5,41],[-62.76,43.86],[-55,46],[-5,50],[-1,50],[-0.25,50.75]]],["nyc","bod",[[-70.5,41],[-61.91,43.92],[-53.25,46],[-20,46.5],[-5,45.2],[-1.6,44.8]]]]},
{"id":"hibx","name":"Hibernia Express-o","price":1.7,"age":"mid","blurb":tr('cables.the_straightest_line_across_the'),"pairs":[["nyc","lon",[[-68,42],[-55,46.5],[-30,51.3],[-11,51.1],[-6.2,50.9],[-4.6,51.25],[-3.1,51.3]]],["nyc","hfx",[[-70.5,41],[-65.25,43]]],["hfx","lon",[[-60,45.5],[-55,46.5],[-30,51.3],[-11,51.1],[-6.2,50.9],[-4.6,51.25],[-3.1,51.3]]]],"lat":0.9},
{"id":"tat","name":"TAT-14 Retirement Home","price":1.3,"age":"old","blurb":tr('cables.laid_last_century_cuts_often_costs'),"pairs":[["nyc","ams",[[-70.5,41],[-55,46],[-1,50]]]]},
{"id":"ella","name":"EllaLink-ing","price":1.0,"age":"new","blurb":tr('cables.brazil_straight_to_iberia_skipping'),"pairs":[["for","mad",[[-37,-2.2],[-32,5],[-22,20],[-14,33],[-10,37.5]]],["sao","mad",[[-42.5,-24],[-38.75,-20.25],[-30,4],[-12.75,29.75],[-6.25,36],[-2.5,36],[0.75,38.75],[0.25,39.5]]],["for","lis",[[-37,-2.2],[-32,5],[-22,20],[-14,33],[-9.6,37.9]]],["for","rai",[[-37,-2.2],[-32,5],[-26,13]]],["rai","lis",[[-22,20],[-14,33],[-9.6,37.9]]]]},
@@ -198,6 +198,6 @@ const bizCity=c=>CITY[c].cc!=='KP';
const OFFC=ALLC.filter(c=>!CITY[c].off&&bizCity(c));
const ruCity=c=>!!CITY[c].ru;
const cnCity=c=>!!CITY[c].cn;
-const BIGC=['man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','ruh','jed','doh','kyv','mel','bne','osa','kul','bkk','sgn','khi','dac','waw','prg','vie','bud','buh','ist','rio','bue','scl','bog','lim','del','maa','blr','hyd','tpe','cpt','auh','ber','zrh','nbo','cai','jkt','mnl','per','akl','dub','lax','tor','mex','dxb','cph','icn','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mrs','mad','sto','bom','sin','hkg','tok','syd','jnb','lag'];
-const MIDC=['man','bcn','mil','lis','atn','den','phx','bos','hou','mel','osa','kul','bkk','waw','vie','ist','rio','bue','scl','bog','del','maa','blr','tpe','auh','ber','zrh','jkt','mnl','dub','lax','tor','dxb','icn','sjc','ash','nyc','chi','dal','mia','lon','ams','fra','par','mad','sin','hkg','tok','syd','bom','sao'];
+const BIGC=['man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','ruh','jed','doh','kyv','mel','bne','osa','kul','bkk','sgn','khi','dac','waw','prg','vie','bud','buh','ist','rio','bue','scl','bog','lim','del','maa','blr','hyd','tpe','cpt','auh','ber','zrh','nbo','cai','jkt','mnl','per','akl','dub','lax','tor','mex','dxb','cph','icn','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mrs','mad','sto','bom','sin','hkg','tok','syd','jnb','lag','lys'];
+const MIDC=['man','bcn','mil','lis','atn','den','phx','bos','hou','mel','osa','kul','bkk','waw','vie','ist','rio','bue','scl','bog','del','maa','blr','tpe','auh','ber','zrh','jkt','mnl','dub','lax','tor','dxb','icn','sjc','ash','nyc','chi','dal','mia','lon','ams','fra','par','mad','sin','hkg','tok','syd','bom','sao','lys'];
diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js
index d2b9ae1..728d2a9 100644
--- a/src/game/30-networks/10-networks.js
+++ b/src/game/30-networks/10-networks.js
@@ -1,12 +1,12 @@
/* ================= NETWORKS ================= */
const NETS=[
- {id:'lvl',name:'Level Tree',asn:3535,type:'t1',pol:'restrictive',share:.07,price:9,col:'#7B61FF',pops:['syd','hfx','bda','hnl','bde','man','edi','svg','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','cph','osl','tor','lax','mex','mtl','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','bio','rio','bue','scl','bog','lim','pan','waw','prg','vie','bud','buh','ist','kcy','cal','van','ott','bru','bet','ham','muc','cpq','gdl','mty','qro','was','mgm','lit','sac','hfd','dov','tlh','boi','spi','ind','dsm','top','fft','btr','aug','anp','lan','stp','jan','jef','hln','lnk','csn','con','ttn','saf','alb','rdu','bis','cmh','okc','sle','har','pvd','cae','pir','bna','aus','mpv','ric','olm','crw','msn','cys'],ix:[],blurb:tr('networks.grew_from_a_seedling_into_a')},
+ {id:'lvl',name:'Level Tree',asn:3535,type:'t1',pol:'restrictive',share:.07,price:9,col:'#7B61FF',pops:['syd','hfx','bda','hnl','bde','man','edi','svg','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','cph','osl','tor','lax','mex','mtl','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','bio','rio','bue','scl','bog','lim','pan','waw','prg','vie','bud','buh','ist','kcy','cal','van','ott','bru','bet','ham','muc','cpq','gdl','mty','qro','was','mgm','lit','sac','hfd','dov','tlh','boi','spi','ind','dsm','top','fft','btr','aug','anp','lan','stp','jan','jef','hln','lnk','csn','con','ttn','saf','alb','rdu','bis','cmh','okc','sle','har','pvd','cae','pir','bna','aus','mpv','ric','olm','crw','msn','cys','lys'],ix:[],blurb:tr('networks.grew_from_a_seedling_into_a')},
{id:'ntt',name:'Not That Telecom',asn:2941,type:'t1',pol:'restrictive',share:.06,price:8,col:'#4B3FC4',pops:['hnl','gum','man','mil','atn','den','bos','hou','phx','jkt','mnl','lax','dxb','icn','sea','sjc','dal','ash','nyc','lon','ams','fra','sin','hkg','tok','syd','tpe','del','maa','blr','hyd','osa','kul','bkk','sgn','kcy','dus','fuk'],ix:[],blurb:tr('networks.huge_in_asia_which_telecom_not')},
- {id:'tly',name:'Tell-Ya Carrier',asn:1229,type:'t1',pol:'restrictive',share:.05,price:8,col:'#9D4EDD',pops:['pdl','tci','svg','edi','man','mil','rom','pmo','ath','ber','osl','cph','hel','beg','sof','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','mrs','hkg','sin','tpe','tll','waw','vie','bud','buh','prg','kyv','van','bru','ham','muc','dus','krs','ebj','rix','zag','bts','got','mmx','hpa'],ix:[],blurb:tr('networks.nordic_backbone_that_tells_you')},
- {id:'cog',name:'Cogentle',asn:714,type:'t1',pol:'restrictive',share:.04,price:3,col:'#B35CF0',pops:['hfx','bde','man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','hel','sof','beg','tor','lax','mex','cph','icn','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','bio','mrs','sto','sin','hkg','tok','rio','bue','scl','bog','lim','osa','waw','prg','vie','bud','buh','ist','kyv','kcy','van','ott','bru','oos','bet','ham','muc','dus','syd','per','was','sac','ind','stp','cmh','aus','bna','rdu','ric','okc','alb','pvd','hfd','har','msn','zag','vno','bts','lju','brn','pry'],ix:[],blurb:tr('networks.cheapest_transit_on_the_map_famously')},
+ {id:'tly',name:'Tell-Ya Carrier',asn:1229,type:'t1',pol:'restrictive',share:.05,price:8,col:'#9D4EDD',pops:['pdl','tci','svg','edi','man','mil','rom','pmo','ath','ber','osl','cph','hel','beg','sof','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','mrs','hkg','sin','tpe','tll','waw','vie','bud','buh','prg','kyv','van','bru','ham','muc','dus','krs','ebj','rix','zag','bts','got','mmx','hpa','lys'],ix:[],blurb:tr('networks.nordic_backbone_that_tells_you')},
+ {id:'cog',name:'Cogentle',asn:714,type:'t1',pol:'restrictive',share:.04,price:3,col:'#B35CF0',pops:['hfx','bde','man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','hel','sof','beg','tor','lax','mex','cph','icn','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','bio','mrs','sto','sin','hkg','tok','rio','bue','scl','bog','lim','osa','waw','prg','vie','bud','buh','ist','kyv','kcy','van','ott','bru','oos','bet','ham','muc','dus','syd','per','was','sac','ind','stp','cmh','aus','bna','rdu','ric','okc','alb','pvd','hfd','har','msn','zag','vno','bts','lju','brn','pry','lys','tls','lil','bod','sxb'],ix:[],blurb:tr('networks.cheapest_transit_on_the_map_famously')},
{id:'tat',name:'Ta-Ta Comms',asn:6543,type:'t1',pol:'restrictive',share:.04,price:9,col:'#6A4C93',pops:['tci','gum','mil','pmo','lis','nbo','cai','jkt','dxb','nyc','ash','lon','fra','mrs','lag','jnb','bom','sin','hkg','tok','del','maa','blr','hyd','cpt','fuj','auh','tpe','khi','dac','cbo','kul','bkk','jed','ruh','doh','jib','dar','mba','dkr'],ix:[],blurb:tr('networks.waves_goodbye_to_latency_across_the')},
- {id:'drz',name:'Drizzle Electric',asn:9369,type:'t2',pol:'open',share:.04,price:4,col:'#1E90FF',auIx:['syd','mel','bne','per'],pops:['man','chc','edi','svg','bde','bcn','mil','rom','pmo','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','nbo','akl','per','jkt','mnl','dub','rek','tor','mtl','lax','mex','sof','osl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','bio','hkg','sin','tok','syd','jnb','for','rio','bue','scl','lim','bog','pan','del','maa','blr','hyd','tpe','auh','cpt','mel','bne','osa','kul','bkk','sgn','khi','dac','cbo','waw','prg','vie','bud','buh','tll','ist','kyv','jed','ruh','doh','kcy','cal','van','ott','bru','oos','bet','ham','muc','ccs','lpb','alg','tun','cas','dkr','dus','was','sac','ind','stp','cmh','aus','bna','rdu','ric','okc','alb','dsm','msn','boi','yeg','ywg','yxe','yqb','tia','zag','vno','skp','bts','lju','pnh','wlg'],ix:'ALL',blurb:tr('networks.will_peer_with_anyone_anywhere')},
- {id:'tng',name:'Tangerine Telecom',asn:5115,type:'t1',cc:['CD','CI','CM','EG','ES','FR','MA','MG','MQ','PL','RE','RO','SN','TN','MD','SK','JO','BF','CF','GN','GW','LR','ML','SL'],pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['tci','bcn','cai','nbo','dxb','fra','par','mrs','mad','bio','lon','ams','lag','jnb','waw','buh','dkr','abj','cas','tun','dla','fih','fdf','run','tnr','kiv','bts','amm','oua','cky','oxb','rob','bko','fna','bgf','ask','nsi','rba'],ix:['bcn','par','mrs','mad','lon','ams','lag','jnb','waw','dkr','abj','cas','tun','dla','fih'],blurb:tr('networks.juicy_reach_into_europe_and_africa')},
+ {id:'drz',name:'Drizzle Electric',asn:9369,type:'t2',pol:'open',share:.04,price:4,col:'#1E90FF',auIx:['syd','mel','bne','per'],pops:['man','chc','edi','svg','bde','bcn','mil','rom','pmo','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','nbo','akl','per','jkt','mnl','dub','rek','tor','mtl','lax','mex','sof','osl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','bio','hkg','sin','tok','syd','jnb','for','rio','bue','scl','lim','bog','pan','del','maa','blr','hyd','tpe','auh','cpt','mel','bne','osa','kul','bkk','sgn','khi','dac','cbo','waw','prg','vie','bud','buh','tll','ist','kyv','jed','ruh','doh','kcy','cal','van','ott','bru','oos','bet','ham','muc','ccs','lpb','alg','tun','cas','dkr','dus','was','sac','ind','stp','cmh','aus','bna','rdu','ric','okc','alb','dsm','msn','boi','yeg','ywg','yxe','yqb','tia','zag','vno','skp','bts','lju','pnh','wlg','lys'],ix:'ALL',blurb:tr('networks.will_peer_with_anyone_anywhere')},
+ {id:'tng',name:'Tangerine Telecom',asn:5115,type:'t1',cc:['CD','CI','CM','EG','ES','FR','MA','MG','MQ','PL','RE','RO','SN','TN','MD','SK','JO','BF','CF','GN','GW','LR','ML','SL'],pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['tci','bcn','cai','nbo','dxb','fra','par','mrs','mad','bio','lon','ams','lag','jnb','waw','buh','dkr','abj','cas','tun','dla','fih','fdf','run','tnr','kiv','bts','amm','oua','cky','oxb','rob','bko','fna','bgf','ask','nsi','rba','lys','tls','lil','bod','sxb','rns','nte'],ix:['bcn','par','mrs','mad','lon','ams','lag','jnb','waw','dkr','abj','cas','tun','dla','fih','lys','tls','lil','sxb'],blurb:tr('networks.juicy_reach_into_europe_and_africa')},
{id:'sgt',name:'SingTell',asn:7474,type:'t2',cc:'SG',pol:'selective',minIx:15,minPni:40,share:.03,price:7,col:'#00A6A6',pops:['jkt','mnl','per','akl','icn','sin','hkg','tok','syd','bom','tpe','maa','kul','bkk','sgn','mel','bne'],ix:['sin','hkg','tok','bom','tpe','maa','kul','bkk'],blurb:tr('networks.sings_your_packets_across_asia')},
{id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',cc:['CD','CZ','DE','EG','ES','GB','GR','IE','MZ','NL','PT','QA','RO','TR','TZ','ZA','AL','LS'],pol:'paid',freeLv:7,paidFee:8000,share:.03,price:6,col:'#E63946',pops:['man','edi','mil','rom','lis','ath','nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa','ist','prg','bud','buh','doh','acc','dar','fih','mpm','dus','tia','msu','pry','dod'],ix:[],blurb:tr('networks.ended_free_peering_across_europe_and')},
{id:'ctc',name:'China Telecomet',asn:4314,type:'t2',cc:'CN',pol:'restrictive',share:.02,price:22,premium:2.5,premAt:['hkg','mos'],premOnly:['mos'],cn:true,col:'#0B5CAD',pops:['pek','sha','hkg','sin','tok','lon','fra','nyc','sjc'],ix:[],blurb:tr('networks.the_biggest_network_in_china_its')},
@@ -105,7 +105,7 @@ NETS.push({id:'stc',name:'Sticky Telecom',asn:39368,type:'t2',cc:['SA','BH','KW'
{id:'ord',name:'Ooh-redoo',asn:8871,type:'eye',cc:['QA','OM','ID','IQ','KW'],pol:'paid',freeLv:11,paidFee:5000,share:.004,up:['tat','tly'],col:'#ED1C24',pops:['doh','dxb','jkt','mct','bgw','kwi'],ix:[],blurb:tr('networks.qatar_s_big_operator_paid_peering')});
NETS.push(
{id:'tim',name:'TIM-Tam Italia',asn:3269,type:'eye',cc:['IT','SM'],pol:'selective',minIx:8,minPni:25,share:.008,up:['skl'],col:'#004691',pops:['mil','rom','pmo','smr'],ix:['mil','rom'],blurb:tr('networks.italy_s_incumbent_sweet_on_the')},
- {id:'skl',name:'Sparkly Seabone',asn:6762,type:'t1',pol:'restrictive',share:.04,price:6,col:'#5B2C83',pops:['pmo','mil','rom','ath','mrs','bcn','mad','bio','lis','par','lon','ams','fra','zrh','vie','bud','prg','waw','buh','sof','ist','ber','sto','nyc','ash','mia','atn','dal','chi','lax','sjc','tor','mex','pan','bog','lim','scl','bue','sao','rio','for','cai','jed','dxb','bom','sin','hkg','tok','hav'],ix:[],blurb:tr('networks.the_tier_1_that_grew_up')},
+ {id:'skl',name:'Sparkly Seabone',asn:6762,type:'t1',pol:'restrictive',share:.04,price:6,col:'#5B2C83',pops:['pmo','mil','rom','ath','mrs','bcn','mad','bio','lis','par','lon','ams','fra','zrh','vie','bud','prg','waw','buh','sof','ist','ber','sto','nyc','ash','mia','atn','dal','chi','lax','sjc','tor','mex','pan','bog','lim','scl','bue','sao','rio','for','cai','jed','dxb','bom','sin','hkg','tok','hav','lys'],ix:[],blurb:tr('networks.the_tier_1_that_grew_up')},
{id:'fwb',name:'Fast-Webby',asn:12874,type:'eye',cc:'IT',pol:'open',share:.004,col:'#FDC300',pops:['mil','rom'],ix:['mil','rom'],blurb:tr('networks.fiber_to_the_italian_home_with')},
{id:'meo',name:'MEO-w Portugal',asn:3243,type:'eye',cc:'PT',pol:'selective',minIx:5,minPni:20,share:.004,col:'#00A3E0',pops:['pdl','lis','mad'],ix:['lis'],blurb:tr('networks.portugal_s_incumbent_purrs_when_you')},
{id:'nos',name:'NOS-y Neighbour',asn:2860,type:'eye',cc:'PT',pol:'open',share:.003,col:'#111111',pops:['lis'],ix:['lis'],blurb:tr('networks.peers_with_anyone_and_wants_to')},
diff --git a/src/game/30-networks/32-homegrown-eyeballs.js b/src/game/30-networks/32-homegrown-eyeballs.js
index a883165..2f079b2 100644
--- a/src/game/30-networks/32-homegrown-eyeballs.js
+++ b/src/game/30-networks/32-homegrown-eyeballs.js
@@ -7,7 +7,7 @@
NETS.push(
{id:'a1b',name:'A-Wan Bulgaria',asn:8717,type:'eye',cc:'BG',pol:'open',share:.0015,up:['aat'],col:'#DA291C',pops:['sof','vie'],ix:['sof'],blurb:tr('homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister')},
{id:'aat',name:'A-Wan Telekom',asn:8447,type:'eye',cc:['AT','BY','HR','MK','SI'],pol:'selective',minIx:6,minPni:20,share:.003,up:['tly','lvl'],col:'#DA291C',pops:['vie','fra','prg','bud','msq','zag','skp','lju'],ix:['vie'],blurb:tr('homegrown_eyeballs.austria_s_incumbent_first_in_line')},
- {id:'adt',name:'Andorable Telecom',asn:6752,type:'t2',cc:'AD',pol:'open',share:.0002,price:11,up:['tng','cog'],col:'#E2001A',pops:['ala','bcn','par'],ix:[],blurb:tr('homegrown_eyeballs.andorra_s_only_telco_by_law')},
+ {id:'adt',name:'Andorable Telecom',asn:6752,type:'t2',cc:'AD',pol:'open',share:.0002,price:11,up:['tng','cog'],col:'#E2001A',pops:['ala','bcn','par','tls'],ix:[],blurb:tr('homegrown_eyeballs.andorra_s_only_telco_by_law')},
{id:'afc',name:'Afri-Sell',asn:37524,type:'eye',cc:['GM','SL'],pol:'open',share:.0006,up:['tng','cog'],col:'#6B2C91',pops:['bjl','fna'],ix:['bjl','fna'],blurb:tr('homegrown_eyeballs.a_mobile_group_from_the_gambia')},
{id:'aft',name:'Afghan Tele-Pass',asn:55330,type:'t2',cc:'AF',pol:'open',share:.0008,price:13,up:['uzt','tta'],col:'#00843D',pops:['kbl','tas'],ix:['kbl'],blurb:tr('homegrown_eyeballs.afghanistan_s_state_telco_finds_transit')},
{id:'agt',name:'Algérie Comme-Ci Comme-Ça',asn:36947,type:'eye',cc:'DZ',pol:'selective',minIx:2,minPni:12,share:.003,up:['tly','cog'],col:'#0B7A3E',pops:['alg','mrs'],ix:['alg'],blurb:tr('homegrown_eyeballs.algeria_s_state_incumbent_so_so')},
@@ -51,7 +51,7 @@ NETS.push(
{id:'erl',name:'Earth-Linky',asn:50710,type:'t2',cc:'IQ',pol:'open',share:.0015,price:12,up:['ttk','stc','cog'],col:'#1D70B8',pops:['bgw'],ix:['bgw'],blurb:tr('homegrown_eyeballs.iraq_s_biggest_home_isp_down')},
{id:'fet',name:'Far EasTone-Deaf',asn:9674,type:'eye',cc:'TW',pol:'selective',minIx:3,minPni:12,share:.003,up:['ntt'],col:'#E60012',pops:['tpe','hkg'],ix:['tpe'],blurb:tr('homegrown_eyeballs.taiwan_s_number_three_never_hears')},
{id:'fl1',name:'FL-One-Liner',asn:20634,type:'t2',cc:'LI',pol:'open',share:.0002,price:10,up:['lvl','aat'],col:'#9F1D35',pops:['vdz','zrh'],ix:['vdz'],blurb:tr('homegrown_eyeballs.liechtenstein_s_telecom_short_enough_for')},
- {id:'fre',name:'Free as in Beer',asn:12322,type:'eye',cc:'FR',pol:'selective',minIx:6,minPni:20,share:.006,up:['cog','lvl'],col:'#CD1E25',pops:['par','mrs','ams','lon','fra'],ix:['par','mrs'],blurb:tr('homegrown_eyeballs.the_challenger_that_made_french_broadband')},
+ {id:'fre',name:'Free as in Beer',asn:12322,type:'eye',cc:'FR',pol:'selective',minIx:6,minPni:20,share:.006,up:['cog','lvl'],col:'#CD1E25',pops:['par','mrs','ams','lon','fra','lys','tls','lil','bod','sxb','rns','nte'],ix:['par','mrs','lys','tls','lil','bod'],blurb:tr('homegrown_eyeballs.the_challenger_that_made_french_broadband')},
{id:'frs',name:'Oh Yas Sénégal',asn:37649,type:'eye',cc:['SN','KM'],pol:'open',share:.0008,up:['tat','tly'],col:'#FFD100',pops:['dkr','hah'],ix:['dkr'],blurb:tr('homegrown_eyeballs.senegal_s_number_two_freshly_renamed')},
{id:'fsm',name:'Island-Hop Micronesia',asn:10130,type:'t2',cc:'FM',pol:'open',share:.0001,price:14,up:['gtg'],col:'#0072CE',pops:['pni','gum'],ix:[],blurb:tr('homegrown_eyeballs.micronesia_s_only_telco_noodling_across')},
{id:'gbt',name:'Gabon Tele-Calm',asn:16058,type:'t2',cc:'GA',pol:'open',share:.0004,price:11,up:['mrc','tng'],col:'#F7941D',pops:['lbv','cas'],ix:['lbv'],blurb:tr('homegrown_eyeballs.gabon_s_old_telco_now_part')},
diff --git a/src/game/30-networks/38-france.js b/src/game/30-networks/38-france.js
new file mode 100644
index 0000000..8f978b2
--- /dev/null
+++ b/src/game/30-networks/38-france.js
@@ -0,0 +1,8 @@
+/* France beyond Paris and Marseille: the second and third mobile operators and the two big French clouds, with real ASNs.
+ Orange (Tangerine Telecom) and Free (Free as in Beer) reach the new cities too; Andorable Telecom comes up to Toulouse.
+ Sits before 40-traffic-shares.js, which indexes NETS. */
+NETS.push(
+ {id:'sfe',name:'SF-Error Telecom',asn:15557,type:'eye',cc:'FR',pol:'selective',minIx:6,minPni:20,share:.005,up:['cog','lvl','tly'],col:'#E4002B',pops:['par','mrs','lys','tls','lil','bod','sxb','rns','nte','lon','ams','fra'],ix:['par','mrs','lys','tls','lil','bod','sxb'],blurb:tr('france.france_s_number_two_it_bought_a')},
+ {id:'byg',name:'Boy-Egg Telecom',asn:5410,type:'eye',cc:'FR',pol:'selective',minIx:6,minPni:20,share:.004,up:['cog','lvl','tng'],col:'#0072CE',pops:['par','mrs','lys','tls','lil','bod','sxb','rns','nte','lon','ams','fra'],ix:['par','mrs','lys','tls','lil','sxb'],blurb:tr('france.the_builder_that_became_a_mobile')},
+ {id:'ovh',name:'Ov-Hatch Cloud',asn:16276,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.004,col:'#123F6D',pops:['par','lil','sxb','lon','fra','ams','waw','sin','syd'],ix:['par','sxb','lon','fra','ams','sin'],blurb:tr('france.europe_s_biggest_hosting_cloud_from')},
+ {id:'sca',name:'Scale-Away',asn:12876,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.002,col:'#4F0599',pops:['par','ams','waw'],ix:['par'],blurb:tr('france.the_cloud_arm_of_the_free_group')});
diff --git a/src/game/60-features/39-sales-auto.js b/src/game/60-features/39-sales-auto.js
index 7251224..029d288 100644
--- a/src/game/60-features/39-sales-auto.js
+++ b/src/game/60-features/39-sales-auto.js
@@ -16,7 +16,7 @@ const slAutoOn=()=>!!(S&&S.slAuto&&slP()&&(S.slAuto.on||S.slAuto.min));
function slWkOk(x){if(!x||typeof x!=='object'||Array.isArray(x)||!own(SALES,x.p))return null;const n=v=>int(v,0,1e6,0);return {w:n(x.w),p:x.p,n:n(x.n),rev:int(x.rev,0,1e10,0),x:n(x.x),y:n(x.y)};}
const slWkAny=x=>!!x&&(x.n>0||x.x>0);
function slAutoFix(s){const a=s.slAuto&&typeof s.slAuto==='object'&&!Array.isArray(s.slAuto)?s.slAuto:{};
- s.slAuto={on:a.on===true,min:SL_MINS.includes(a.min)?a.min:0,wk:slWkOk(a.wk),rep:slWkOk(a.rep)};}
+ s.slAuto={on:a.on===true,min:SL_MINS.includes(a.min)?a.min:0,wk:slWkOk(a.wk),rep:slWkOk(a.rep)};if(a.ren===true)s.slAuto.ren=true;}
// An old save whose intern ran the sales order: the same switch and minimum, now at the sales desk (they run once someone is there).
function slAutoFrom(s,on,p){if(!on||(s.slAuto&&typeof s.slAuto==='object'))return;s.slAuto={on:p.acc!==false,min:SL_MINS.includes(p.min)?p.min:0,wk:null,rep:null};}
// "This week Dave signed 3 customers (+$41k/mo), declined 17 tiny offers."
@@ -24,18 +24,28 @@ function slWeekLine(x,last){const parts=[];if(x.n)parts.push(trn('sales.w_signed
const v={name:tr(SALES[x.p].s),list:parts.join(', ')};return last?tr('sales.w_last',v):tr('sales.w_now',v);}
// An orbit offer fits where its dish has room for it; used: what this shift already signed on each dish.
function slSkyOk(o,used){const L=pieServe(o.city,o.type);if(!L)return null;const k=L.cr+'|'+L.k;return slP()==='shark'||L.left-(used.get(k)||0)>=o.bw?k:null;}
-function slAutoDay(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floor(d/7);
+// Like a day, the desk is a generator: a routing trial is a step the day answers (in play, the route worker does).
+const slAutoDay=d=>dayGo(slAutoRun(d),(g,v)=>g.next(v));
+function* slAutoRun(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floor(d/7);
// A new week: last week's tally becomes the report, and the one notice of the week.
if(!A.wk||A.wk.w!==w){if(slWkAny(A.wk)&&A.wk.w${esc(tr('sales.desk'))} ${esc(slWeekLine(A.rep,true))}`,A.rep.rev>0?'good':'',[],{a:'tab',v:'deals'});}A.wk={w,p,n:0,rev:0,x:0,y:0};}
const W=A.wk,used=new Map();W.p=p;let tries=0,dirty=false;
const tried=UI.slTried&&UI.slTried.s===S?UI.slTried.m:(UI.slTried={s:S,m:new Map()}).m;
const won=o=>{if(S.offers.includes(o))return false;W.n++;W.rev+=Math.round(bizMo(o));dirty=true;return true;};
- opsQuiet(()=>{for(const o of S.offers.slice()){if(!S.offers.includes(o))continue;const T=BIZ_T[o.type];if(!T||!(o.exp>d))continue;const v=T.event?(o.fee||0):bizMo(o);
- if(A.min&&vb0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}continue;}
- if(!A.on||!ip4Fits(o))continue;
- if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cashd)))continue;ACT.accept({id:o.id});won(o);continue;}
- // Each trial is a full routing pass: at most SL_TRIALS a day, and an offer that did not fit waits a week.
- if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)continue;tries++;ACT.accept({id:o.id,auto:true});if(!won(o))tried.set(o.id,d);}});
- if(dirty)compute();}
+ for(const o of S.offers.slice()){
+ // What this offer needs, muted: nothing, or a routing trial (b), which the day answers between the two quiet steps.
+ let b;const todo=opsQuiet(()=>{if(!S.offers.includes(o))return;const T=BIZ_T[o.type];if(!T||!(o.exp>d))return;const v=T.event?(o.fee||0):bizMo(o);
+ if(A.min&&vb0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}return;}
+ if(!A.on||!ip4Fits(o))return;
+ if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cashd)))return;ACT.accept({id:o.id});won(o);return;}
+ // Each trial is a full routing pass: at most SL_TRIALS a day, and an offer that did not fit waits a week.
+ if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)return;tries++;b=offerTrialOf(o);return true;});
+ if(!todo)continue;
+ // o: the offer itself, for a trial the page has to run again on the game as it is by then (dayAgain()).
+ const got=b?yield {trial:b,hx:offerHealthy(b),o}:null;
+ // Signed or declined by hand while the trial routed: it is not the desk's.
+ if(!S.offers.includes(o))continue;
+ opsQuiet(()=>{OFFER_TRIED={o,b:got};try{ACT.accept({id:o.id,auto:true});}finally{OFFER_TRIED=null;}if(!won(o))tried.set(o.id,d);});}
+ if(dirty)yield;}
diff --git a/src/game/60-features/39-sales-renewals.js b/src/game/60-features/39-sales-renewals.js
new file mode 100644
index 0000000..cb26161
--- /dev/null
+++ b/src/game/60-features/39-sales-renewals.js
@@ -0,0 +1,38 @@
+/* ---------- The sales desk answers renewal haggles ----------
+ A customer near the end of its term may ask for a discount (#178, 75-customer-lifecycle.js). With S.slAuto.ren on,
+ whoever runs sales answers it SL_REN_WAIT days after it opens, so the player can still answer first. Each in their way:
+ - the engineer talks technology, not price: nerdy customers get an afternoon with the network diagrams and renew at
+ the market price, now and then halfway; everyone else gets the discount they asked for. Nobody leaves.
+ - the shark gives nothing away: most renew at the old price, often with a fresh promise, and he bills a month of what
+ he saved you. Some walk, nerdy ones most of all.
+ - the CEO settles it on the golf course: a deeper discount than asked for a contract twice as long, a quick yes, or
+ a fight that ends with the customer gone.
+ Each answer is a hash of the contract (clR), so no random numbers are drawn. */
+const SL_REN_WAIT=3;
+const slRenOn=()=>!!(S&&S.slAuto&&S.slAuto.ren&&slP());
+// The day the desk answers this haggle: a few days after it opened (30 days before the term ends), today at the earliest.
+const slRenAt=b=>b.hag.until-30+SL_REN_WAIT;
+// A step of the day (dayPost()): its yield is the routing after a price changed. slRenDay() is the same all at once.
+function slRenDay(d){runNow(slRenRun(d));}
+function* slRenRun(d){if(!slRenOn())return;const p=slP();let any=false;
+ for(const b of S.biz.slice())if(b.hag&&d>=slRenAt(b)&&d({name:esc(slCap()),cust:esc(b.name),...x}),bill=rate=>fmt$(clBill(b,rate));
+ const keep=(rate,how,key,x,s)=>{clRenew(b,rate);clNote('ren');toast(tr(key,v({price:bill(b.rate),...x})),s===undefined?'good':s,[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);return how;};
+ const gone=(how,key)=>{clGone(b,'cheap');toast(tr(key,v({})),'bad');sfx('err');return how;};
+ if(p==='eng'){if(!nerd)return keep(ask,'cave',N_('sales.ren_eng_cave'));
+ return r<0.7?keep(Math.max(ask,Math.min(was,clFair(b))),'tech',N_('sales.ren_eng_tech')):keep(mid,'mid',N_('sales.ren_mid'));}
+ if(p==='shark'){const walk=nerd?0.4:0.12;if(rslRenOn()&&b.hag.until>S.day?`
`:'';
diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js
index 0bb5dc9..79ef239 100644
--- a/src/game/60-features/90-automation.js
+++ b/src/game/60-features/90-automation.js
@@ -1,12 +1,24 @@
/* The sales engine of #185: would this offer work if signed now? The sales desk runs it once a day (39-sales-auto.js).
It trials the new demand on a copy of the game, so a failed trial leaves the live game untouched. */
function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};}
-function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null;
+// OFFER_TRIED: the answer of a trial the intern's sales order already ran for this offer (the customer, or null).
+let OFFER_TRIED=null;
+function autoOffer(o){if(OFFER_TRIED&&OFFER_TRIED.o===o)return OFFER_TRIED.b;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;}
+// The checks on the live game, and the customer the offer would be: null when there is nothing to trial.
+function offerTrialOf(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null;
const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null;
if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null;
if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id;
if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;}
+ return b;}
+const offerFuture=()=>S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day);
+// Who is happy today (indices in S.biz), the one thing the trial reads from the live result: null when future events
+// make the trial route without the offer first and judge on that.
+const offerHealthy=b=>{if(offerFuture())return null;const h=[];S.biz.forEach((x,i)=>{if(!bizWhy(x).length)h.push(i);});return h;};
+/* The trial: the game routed with the customer added, on a copy, S and R put back after. It reads nothing else of the
+ live result than hx (offerHealthy()), so the route worker can run it on the game it is sent (28-route-worker.js). */
+function offerTrial(b,hx){const T=BIZ_T[b.type],start=b.start;
const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day);
// Trial the added demand before signing; failed trials leave the live game untouched.
try{S={...S,biz:S.biz};
@@ -19,6 +31,6 @@ function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.ra
if(!all.some(x=>x.route==='scenic')){if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=all;compute();if(bizWhy(b).length)return null;
const bad=fut.filter(x=>bizWhy(x).length);if(!bad.length)return b;S.biz=fut;compute();return bad.every(x=>bizWhy(x).length)?b:null;}
compute();}
- const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute();
+ const healthy=hx&&!future?hx.map(i=>S.biz[i]):S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute();
return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null;
- }finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}}
+ }finally{S=state;R=result;UI.hotMap=hot;b.start=start;if(T.cap)delete b.live;}}
diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js
index 9f944c6..4484fb2 100644
--- a/src/game/60-features/95-standing-orders.js
+++ b/src/game/60-features/95-standing-orders.js
@@ -3,11 +3,15 @@
would (ACT.*, pniPlace, the #185/#192 planners), so it costs exactly what the click costs, with toasts and redraws
muted and one recompute at the end. Without an intern nothing here runs and no random numbers are drawn. */
const INTERN_MO=6000,OPS_LOG=12,OPS_CAPS=[10000,50000,250000,1e6,5e6,0],OPS_CAPS_MO=[1000,2500,5000,10000,25000,0],OPS_FLOORS=[0,50000,250000,1e6,5e6];
+// Every intern runs every order, the same way and at the same price; each is better at one part of the job (g: what).
+// Annie peers: the IX order every day, the PNI order twice a week. Kevin does maintenance: two line systems a night,
+// and never a fat finger. Tracy plans ahead: the capacity orders act as if traffic were OPS_AHEAD higher already.
const INTERNS={
- annie:{i:'📡',n:N_('ops.anycast_annie'),s:N_('ops.annie'),d:N_('ops.annie_d')},
- kevin:{i:'🌙',n:N_('ops.kevin_from_the_night_shift'),s:N_('ops.kevin'),d:N_('ops.kevin_d')},
- tracy:{i:'🧭',n:N_('ops.tracy_route'),s:N_('ops.tracy'),d:N_('ops.tracy_d')},
+ annie:{i:'📡',n:N_('ops.anycast_annie'),s:N_('ops.annie'),d:N_('ops.annie_d'),g:N_('ops.good_annie')},
+ kevin:{i:'🌙',n:N_('ops.kevin_from_the_night_shift'),s:N_('ops.kevin'),d:N_('ops.kevin_d'),g:N_('ops.good_kevin')},
+ tracy:{i:'🧭',n:N_('ops.tracy_route'),s:N_('ops.tracy'),d:N_('ops.tracy_d'),g:N_('ops.good_tracy')},
};
+const OPS_AHEAD=1.1,opsIs=id=>!!S&&!!S.ops&&S.ops.intern===id,opsAhead=()=>opsIs('tracy')?OPS_AHEAD:1;
// Deals are not the intern's: the sales desk signs them (39-sales-auto.js).
// The orders, in the order the panel shows them. pop: can be switched off per POP. cap: default monthly budget, of setup
// fees, or (mo) of the running costs the order adds, for caches, which are free to rack but cost rent every month.
@@ -137,19 +141,20 @@ function opsTransitOk(n,c){if(n.id==='cog'&&(scnRule('spat')||S.ev.depeer>S.day)
const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)&&opsTransitOk(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0];
// 'cheap' and 'have' (Already connected) name no network: quote the cheapest seller (#249).
const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;return n&&sellsAt(n,c)&&opsTransitOk(n,c)?n:cheapestTransit(c);};
-// The orders. Each takes the shift and does its jobs through the player's own actions.
+// The orders. Each takes the shift and does its jobs through the player's own actions. Most are generators: a yield
+// after a job is only a place where a long shift may let a frame through (opsRun()), nothing changes there.
const OPS_RUN={
// Bring POPs, ports and fiber up to the build standard: the busiest first, a few jobs a shift (96-pop-standard.js).
std(X){bstdShift(X);},
- repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id})))X.did('repair');},
- routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',
- load=c=>Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
+ *repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id}))){X.did('repair');yield;}},
+ *routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',
+ load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
// A chosen model: swap every POP still on a smaller one to it, the busiest first, while the budget lasts. Never a
// step down, never a model that is not unlocked or does not fit, and only with a second router or no traffic there.
if(fix&&rgOpen(m))for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c],g=p.rgen||0;
if(p.rupDay===S.day||g===m||RG[m].cap<=RG[g].cap||modelFits(c,m)||!((p.routers||1)>1||popIdle(c)))continue;
const cost=swapCost(c,m);if(!X.can('routers',cost))continue;
- if(X.pay('routers',()=>ACT.upRouter({city:c,g:m})))X.did('routers',c+' ⇧'+RG[m].pn);}
+ if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}
for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue;
const ld=load(c);if(ld=0&&rgOpen(nx)&&!modelFits(c,nx)&&(rt>1||popIdle(c)),add=rt=4||!add);if(!doSwap&&(how==='swap'||!add))continue;
const cost=doSwap?swapCost(c,nx):routerCost(g,rt);if(!X.can('routers',cost))continue;
- if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));}},
- transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x');
+ if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));yield;}},
+ *transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x');
for(const c of opsPops('transit')){let ts=S.transit.filter(t=>t.city===c);if(!ts.length)continue;
// Thirty days of 95th-percentile-ish history per port; their peaks summed is a safe (high) estimate of the POP's peak.
- const peak=ts.reduce((a,t)=>a+(t.hist||[]).reduce((m,v)=>Math.max(m,v),0),0);if(!(peak>0))continue;
+ const peak=ts.reduce((a,t)=>a+(t.hist||[]).reduce((m,v)=>Math.max(m,v),0),0)*opsAhead();if(!(peak>0))continue;
// "Already connected" (#227): only the providers you buy from here, the smallest first, never a new contract.
const have=opsP('transit','prov')==='have',n=have?null:opsProv(c);if(!have&&!n)continue;
const grow=t=>{const k=t.n||1,up=t.tier+1;
@@ -177,20 +182,20 @@ const OPS_RUN={
else{const need=N*peak-cap,ok=PORT.map((P,i)=>i).filter(i=>portShown(i)&&portOk(c,i)),i=ok.find(i=>PORT[i].g>=need)??ok.at(-1);
if(i!==undefined)job={cost:PORT[i].setup,go:()=>ACT.buyTransit({city:c,net:n.id,tier:i}),w:'+'+PORT[i].n};}}
if(!job||!X.can('transit',job.cost)||!X.pay('transit',job.go))break;
- X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);}}},
+ X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);yield;}}},
// PNIs and IX ports keep Headroom times today's traffic, hottest first. One port at a POP with several routers gets a
// second in a LAG, so it is not the only way out; anything else moves up to the smallest port size that fits. A PNI
// augment lands weeks later, so that port waits for it. A flood fills ports for a day or two: not worth buying for.
- ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[],
+ *ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[],
// Router ports that pending PNI augments will take when they land are spoken for.
resv=c=>S.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0),room=c=>portsMax(c)-portsUsed(c)+1e-9-resv(c);
// Each port: cap() now, use today, lag() and ups() the jobs it could have as {cost, cap after, w for the log, go}, sig() to see a job took.
- for(const p of S.pni){const c=p.city,use=R.usePni[p.id]||0,cap=()=>lagCap(pniG(p),p.n),n=()=>p.n||1;if(!pniOn(p)||p.up||!(use>0)||cap()>=N*use||!opsHere('ports',c))continue;
+ for(const p of S.pni){const c=p.city,use=(R.usePni[p.id]||0)*opsAhead(),cap=()=>lagCap(pniG(p),p.n),n=()=>p.n||1;if(!pniOn(p)||p.up||!(use>0)||cap()>=N*use||!opsHere('ports',c))continue;
L.push({city:c,at:c,use,u:use/cap(),cap,n,rt:(S.pops[c]||{}).routers||1,busy:()=>!!p.up,sig:()=>[p.tier,n(),!!p.g1,!!p.up].join(),
lag:()=>n()ACT.lagP({id:p.id,d:1})}:null,
ups:()=>{const out=[];for(let t=p.g1?0:p.tier+1;tACT.pni({city:c,net:p.net,tier:t})});}return out;}});}
// Nominal capacity, not ixCap(): a LACP fault or one building down halves a LAG for a day or two, not worth a bigger port.
- for(const x in S.ixp){const c=ixCity(x),use=R.useIx[x]||0,n=()=>(S.ixn||{})[x]||1,cap=()=>lagCap(PORT[S.ixp[x]].g,n())*(isRemote(x)?REMOTE_CAP:1),pop=S.pops[c];if(S.myIx[x]||!(use>0)||!(cap()>0)||cap()>=N*use||!opsHere('ports',c))continue;
+ for(const x in S.ixp){const c=ixCity(x),use=(R.useIx[x]||0)*opsAhead(),n=()=>(S.ixn||{})[x]||1,cap=()=>lagCap(PORT[S.ixp[x]].g,n())*(isRemote(x)?REMOTE_CAP:1),pop=S.pops[c];if(S.myIx[x]||!(use>0)||!(cap()>0)||cap()>=N*use||!opsHere('ports',c))continue;
const g=()=>PORT[S.ixp[x]].g;
L.push({city:c,at:x,use,u:use/cap(),cap,n,rt:pop?pop.routers||1:1,busy:()=>false,sig:()=>S.ixp[x]+','+n(),
lag:()=>pop&&n()ACT.lagIx({city:x,d:1})}:null,
@@ -200,10 +205,10 @@ const OPS_RUN={
for(const o of L.sort((a,b)=>b.u-a.u))for(let step=0;step<3&&!o.busy()&&o.cap()1,ups=wantLag&&lag?null:o.ups(),fit=ups&&(ups.find(u=>u.cap>=N*o.use)||ups.at(-1)),job=wantLag?lag||fit:fit||lag,was=o.sig();
if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;}))break;
- X.did('ports',o.at+' '+job.w);}},
- optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o);
+ X.did('ports',o.at+' '+job.w);yield;}},
+ *optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o);
for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day)continue;
- let cap=dfCap(l);const load=(R.load&&R.load[l.id])||0;
+ let cap=dfCap(l);const load=((R.load&&R.load[l.id])||0)*opsAhead();
// New fiber gets its first channel; lit fiber gets more while it runs hot. A fiber that only carries expresses is
// not new: it was left bare so the city in the middle needs no router ports.
for(let step=0;step<8&&(cap<=0?!(l.ch||[]).length&&!xpSlots(l):load>=cap*at);step++){if(chMax(l)-(l.ch||[]).length-soldSlots(l)-xpSlots(l)<=0)break;
@@ -216,20 +221,20 @@ const OPS_RUN={
o=fast||fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||(big&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||gpd(b,l)-gpd(a,l)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)))||cheap[0];if(!o)break;
const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break;
X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break;
- cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);}}},
- optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0;
- const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l));
+ cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);yield;}}},
+ *optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0;
+ const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)*opsAhead()>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l));
const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)).sort((a,b)=>u(b)-u(a));
for(const l of ls){
// The line system: one step at a time up to the chosen one, or the next one where the fiber is full and hot.
const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]S.day)&&X.can('optup',cost)){tries++;const ok=opsDarkOk(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);
+ if(want&&upsS.day)&&X.can('optup',cost)){tries++;const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);
if(ok){const s0=l.sys,top=goal==='next'?to:goal;
for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;}
// The fiber is dark until tomorrow: its optics wait.
- if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);continue;}}}}
+ if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);yield;continue;}}}}
// Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and
// the old optics go on the shelf as spares.
if(!swap)continue;
@@ -243,27 +248,29 @@ const OPS_RUN={
const was=dfCap(l);
X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2});
if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;});
- if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));}}},
- caches(X){const g=opsP('caches','g');
+ if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}},
+ *caches(X){const g=opsP('caches','g');
for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue;
const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9;
- for(const x of want){if(cachePortsAdd(c,[x])>free())continue;if(!X.can('caches',0,cacheMo(x)))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site,...(x.g?{g:x.g}:{})});X.book('caches',0,cacheMo(x));X.did('caches',c);}}},
+ for(const x of want){if(cachePortsAdd(c,[x])>free())continue;if(!X.can('caches',0,cacheMo(x)))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site,...(x.g?{g:x.g}:{})});X.book('caches',0,cacheMo(x));X.did('caches',c);}
+ yield;}},
// Weekly, like a person going through PeeringDB on a Monday: route servers, then every willing member (#192).
- ix(X){if(S.day%7)return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');}
+ ix(X){if(S.day%7&&!opsIs('annie'))return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');}
for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}},
// Weekly too: every willing network above the threshold, at its own minimum size and lead time (#181).
- pni(X){if(S.day%7!==3)return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;const g=opsP('pni','g'),paid=opsP('pni','paid');
+ *pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;const g=opsP('pni','g'),paid=opsP('pni','paid');
// The traffic a PNI there would take over: what your users at that POP send to the network today over transit, an
// exchange or a PNI elsewhere, the same figure the PNI list shows. Not the city's whole demand: a network's own
// cache boxes in that POP already serve most of it (#244).
const loc=q=>pniVal(q.net,q.city).want;
- for(const q of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
- if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}},
+ // Each order quoted again just before it is placed: the player may have ordered the same PNI by hand while the shift
+ // let a frame through or waited for a routing, and the batch's quote would order it a second time.
+ for(const q0 of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
+ const q=pniRequote(q0);if(!q)continue;if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);yield;}},
// Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102).
- decom(X){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'&&l.kind!=='sat'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}
- // Loads must include what this shift already did (a customer just signed, a repair): recompute first, if anything could go.
- if(X.dirty&&[...by.values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'))){compute();X.dirty=false;}
- for(const ls of by.values())for(const l of opsDecomPick(ls)){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}},
+ // Loads must include what this shift already did (a customer just signed, a repair): opsRun() routes first if a
+ // job changed the network and anything could go (opsDecomWaits()).
+ *decom(X){for(const ls of opsPairs().values())for(const l of opsDecomPick(ls)){UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}},
};
// Line system swaps per shift, and how many fibers a shift may test for one: each test routes the whole network once,
// so a shift costs at most one routing more, and only on a night with a fiber to try. A fiber that failed the test is not tested again for a week
@@ -273,9 +280,13 @@ const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,r
function opsAround(l){const adj={};for(const x of S.links){if(x===l||linkDown(x))continue;(adj[x.a]=adj[x.a]||[]).push(x.b);(adj[x.b]=adj[x.b]||[]).push(x.a);}
const seen=new Set([l.a]),q=[l.a];while(q.length){const u=q.pop();if(u===l.b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
// A day without this fiber: does every gigabit still get where it went today, and every circuit stay whole? Today's routing
-// is the yardstick (routed again first if this shift already changed the network); R is put back after.
-function opsDarkOk(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){compute();X.dirty=false;}
- const R0=R,e0=l.eqDown,s0=R0.served,L0=R0.l2||{};
+// is the yardstick (routed again first if this shift already changed the network). Both routings are steps the day
+// answers (OPS_ROUTE, then {dark}: opsDarkTrial(), in play in the route worker).
+const OPS_ROUTE={route:true};
+function* opsDark(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){yield OPS_ROUTE;X.dirty=false;}
+ return !!(yield {dark:l.id,s0:R.served,L0:R.l2||{}});}
+// The test itself, on the game it is given: R is put back after.
+function opsDarkTrial(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const R0=R,e0=l.eqDown,s0=y.s0,L0=y.L0;
try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);}
finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}}
// The waves decom hands back on one city pair (ls: every link between them): the smaller ones the rest carry with 25% to
@@ -288,26 +299,52 @@ function opsDecomPick(ls,cf=capOf){if(!ls||ls.length<2)return [];const live=ls.f
if(opsP('decom','keep')&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);}
for(const l of small.reverse()){if(cap-cf(l)x.id===y.dark);if(!l||S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;
+ return opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});}
// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it (and gone) first.
function opsDecomSafe(l,gone=[]){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true);
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l&&!gone.includes(x));try{return was.every(chk);}finally{S.links=all;}}
+// The links between each pair of cities, VXCs and satellite circuits left out.
+function opsPairs(){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'&&l.kind!=='sat'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}return by;}
+const opsDecomWaits=()=>[...opsPairs().values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'));
const OPS_ORDER=['repair','std','routers','transit','ports','optup','optics','caches','ix','pni','decom'];
// The shift: once per game day from dayTick, after outages and events have had their turn.
-function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};}
+// One shift. Like a day (dayRun()), it is a generator: each yield is a compute() it needs, answered by the route worker
+// in play, so the shift never routes on the page. opsDay() runs it in one go.
+function opsDay(d){dayGo(opsRun(d),(g,v)=>g.next(v));}
+function* opsRun(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};}
// A new week: last week's tally becomes the shift report, and the one NOC notice of the week.
const w=Math.floor(d/7);if(!O.wk||O.wk.w!==w){if(opsWkAny(O.wk)&&O.wk.w${esc(tr('ops.shift_report',{name:opsName()}))} ${esc(opsWeekLine(O.rep))}`,'',[],{a:'ops'});}O.wk=opsWkNew(w);}
const X=opsShift();
// One order that trips over something (an odd save, a bug) is paused and noted; payday, goals and the save still happen.
- opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])try{OPS_RUN[k](X);}catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);}});
+ // Each order is a step of the day: a long shift lets the map draw between two (DAY_REST). The interface the orders
+ // click through (selection, tab, confirmation) goes on from where the last order left it, as in one go; the player's
+ // own is back in between.
+ let ui=null;
+ // One step of an order, muted (opsQuiet()): a plain order all at once, a generator up to its next yield. A bare yield
+ // is a rest; OPS_ROUTE or a {dark} test is a routing the day answers (v, passed back in).
+ const step=(k,st,v)=>opsQuiet(()=>{if(ui){UI.sel=ui.sel;UI.confirm=ui.cf;UI.tab=ui.tab;}st.ask=undefined;
+ try{if(!st.it){const r=OPS_RUN[k](X);if(r&&typeof r.next==='function')st.it=r;else st.done=true;}if(!st.done){const s=st.it.next(v);if(s.done)st.done=true;else st.ask=s.value;}}
+ catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);st.done=true;}
+ ui={sel:UI.sel,cf:UI.confirm,tab:UI.tab};});
+ const order=function*(k){const st={it:null,done:false};let v;for(;;){step(k,st,v);v=undefined;if(st.done)return;
+ if(st.ask===OPS_ROUTE)yield;else if(st.ask&&st.ask.dark)v=yield st.ask;else yield DAY_REST;}};
+ // Every order but the last, decommissioning, which reads today's loads: routed first when a job changed them.
+ for(const k of OPS_ORDER.slice(0,-1))if(O.on[k]){yield* order(k);yield DAY_REST;}
+ if(O.on.decom&&X.dirty&&opsDecomWaits()){yield;X.dirty=false;}
+ ui=null;if(O.on.decom)yield* order('decom');
const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke]]);
// Very rarely, and never under Change Freeze, the intern fat-fingers something harmless.
+ // Kevin rolls the same dice (so a seeded game plays the same whoever is hired) and catches it before pressing Enter.
const ff=OPS_FF_RATE[rulePreset()];if(ff&&Object.keys(S.pops).length&&Math.random()t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;else X.dirty=true;}
- e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);}
+ e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);}}
if(X.up)e.up=Math.round(X.up);if(Math.round(X.mo))e.mo=Math.round(X.mo);
// Stopping at a budget changes nothing a route depends on: no recompute for that.
- if(X.dirty)compute();
+ if(X.dirty)yield;
if(e.r.length||e.f!==undefined){O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);}
// The day's detail stays in the Ops sheet; the NOC gets one notice a week (above).
const W=O.wk;for(const [k,n,ws] of e.r){W.n[k]=(W.n[k]||0)+n;const a=W.wh[k]||(W.wh[k]=[]);for(const x of ws)if(a.length<3&&!a.includes(x))a.push(x);}
diff --git a/src/game/70-rules/35-pni-orders.js b/src/game/70-rules/35-pni-orders.js
index e0c428c..1e42650 100644
--- a/src/game/70-rules/35-pni-orders.js
+++ b/src/game/70-rules/35-pni-orders.js
@@ -13,10 +13,16 @@ function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net);
if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead});
return lead;}
+// The ports a pending augment will add, and those of every pending augment at a city: what an order there must leave free.
+const pniUpSlots=p=>Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
+const pniResv=c=>{let r=0;for(const p of S.pni)if(p.up&&p.city===c)r+=pniUpSlots(p);return r;};
+// A batch's order quoted again on the game as it is now: null if it no longer stands (ordered by hand meanwhile, say).
+// Earlier orders of the batch, placed by now, are in the PNIs themselves: the same ports the batch reserved for them.
+const pniRequote=q=>{const n=pniQuote(q.city,q.net,q.g1?-1:q.tier,pniResv(q.city));return n&&!n.why&&n.ex===q.ex?n:null;};
function pniBatch(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null;
const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0,raised=0;
// Pending augments and earlier orders in this batch already own their future ports.
- for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
+ for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+pniUpSlots(p);
for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city);
// Each network at its own minimum: asking everyone for 10G orders 100G from those that start at 100G.
const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots;
diff --git a/src/game/80-simulation/28-route-worker.js b/src/game/80-simulation/28-route-worker.js
index 57d9fdb..a21f290 100644
--- a/src/game/80-simulation/28-route-worker.js
+++ b/src/game/80-simulation/28-route-worker.js
@@ -1,13 +1,16 @@
/* Routing off the main thread. The worker is this page's own game script run a second time
from a Blob URL: nothing is fetched, so GitHub Pages still serves one page. In the worker, DOM globals are inert
stand-ins and boot() never runs; the catalogs (cities, networks, cones) are rebuilt from the same code.
- Only the day uses it: dayPre(), then S goes to the worker, the day waits (no next day starts) and dayPost() runs
- when R is back, so a day sees exactly the routing it would have had in one go. An action in between routes
- synchronously as always (compute() bumps RW.gen); then the worker's answer is stale and the action's R stands.
+ Only the day uses it: the day is a generator (dayRun(), 10-day-tick.js) whose every yield is a routing it needs.
+ Each one goes to the worker with S, the day waits (no next day starts) and goes on when R is back, so a day sees
+ exactly the routing it would have had in one go. An action in between routes synchronously as always (compute()
+ bumps RW.gen); then the worker's answer is stale and the action's R stands.
Tests (no Worker in jsdom, __TUBES_TEST__) and any worker failure take the synchronous path. */
const RW_IN=!!self.__TUBES_WORKER__;
const RW_EL=!RW_IN&&typeof document!=='undefined'?document.currentScript:null;
-const RW={w:null,dead:false,seq:0,gen:0,job:null,stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}};
+// RW_SLOW: a frame time (ms) above which the device does not keep up anyway, and a day may take longer slices (99-loop.js).
+const RW_SLOW=20;
+const RW={w:null,dead:false,seq:0,gen:0,job:null,budget:8,later:f=>rwLater(f),stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}};
function rwOn(){return !RW_IN&&!RW.dead&&!window.__TUBES_TEST__&&!window.__TUBES_SYNC__&&typeof Worker==='function'&&!!RW_EL;}
function rwStart(){if(RW.w)return RW.w;
try{const L=LANG,dict=L!=='en'&&window.I18N[L]?JSON.stringify(window.I18N[L]):'null';
@@ -20,23 +23,52 @@ if(${dict})self.I18N[${JSON.stringify(L)}]=${dict};
`;
const url=URL.createObjectURL(new Blob([pre,RW_EL.textContent,'\n;self.onmessage=e=>rwServe(e.data);'],{type:'text/javascript'}));
const w=RW.w=new Worker(url);URL.revokeObjectURL(url);
- w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwDone(m);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();};
+ w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwDone(m,t);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();};
}catch(e){console.error('[tubes] no route worker',e);rwKill();}
return RW.w;}
-// Gone for good this session: the day it was routing is routed here instead.
-function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;RW.job=null;if(j){try{compute();dayPost(j.d);}catch(e){tickErr(e);}rwDayDone();}}
-// One day in play: the first half here, the routing in the worker, the second half when it answers.
-function rwDay(){const d=dayPre();if(d===false)return;const w=rwStart();
- if(!w){compute();dayPost(d);rwDayDone();return;}
+// Gone for good this session: the routing in flight is done here instead, and the day goes on without the worker.
+// (A day resting between steps goes on by itself, on the page from then on.)
+function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;if(!j||j.rest)return;RW.job=null;
+ if(j.state!==S){rwDayDone();return;}let v;try{if(j.tr)v=dayAgain(j.tr);else compute();}catch(e){tickErr(e);}rwGo(j.g,v);}
+// One day in play (dayRun(), 10-day-tick.js): its steps run here, every routing it asks for runs in the worker.
+function rwDay(){rwGo(dayRun());}
+// Runs the day's steps up to the next routing, posts it, and returns: rwDone() picks the day up when R is back. At a
+// DAY_REST, a day that has run RW.budget ms already goes on after the next frame (RW.later), so a phone gets its frames
+// between the steps of a big network's day. The day is still in flight meanwhile: no next day starts, nothing saves.
+// v: what the step it resumes asked for (a sales trial's or the intern's fiber test's answer, dayAnswer()).
+function rwGo(g,v){const t0=performance.now();for(;;){let s;try{s=dayStep(g,v);}catch(e){tickErr(e);s={done:true};}v=undefined;
+ if(s.done){rwDayDone();return;}
+ if(s.value===DAY_REST){if(performance.now()-t0{if(tr)v=dayAnswer(tr);else compute();};
+ const w=rwOn()&&rwStart();if(!w){try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;}
const t=performance.now(),seq=++RW.seq;
// The worker also needs what compute() reads from yesterday's R: link loads, and the scenic circuits' paths.
- try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)});}catch(e){console.error('[tubes] route worker post',e);rwKill();compute();dayPost(d);rwDayDone();return;}
- const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,d,gen:RW.gen,t:t1};}
-function rwDone(m){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;const t=performance.now();
- if(m.err){console.error('[tubes] route worker',m.err);compute();}
+ try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg),...(tr?{trial:tr.dark?{dark:tr.dark,s0:tr.s0,L0:tr.L0}:{b:tr.trial,hx:tr.hx}}:{})});}
+ catch(e){console.error('[tubes] route worker post',e);rwKill();try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;}
+ const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,g,gen:RW.gen,t:t1,state:S,tr};return;}}
+/* Where a resting day goes on. A frame drawn moments ago leaves time before the next one: the day goes on in a task of
+ its own, and the browser draws the next frame between two tasks when it is due. Otherwise the day waits for that
+ frame. (Waiting for a frame every time made a day of many short steps take many frames: a slow phone fell behind.) */
+const RW_CH=typeof MessageChannel==='function'&&!RW_IN?new MessageChannel():null,RW_TQ=[];
+if(RW_CH)RW_CH.port1.onmessage=()=>{const f=RW_TQ.shift();if(f)f();};
+function rwLater(f){if(RW_CH&&performance.now()-(RW.lf||-1e9)<(RW.fms||16)*0.75){RW_TQ.push(f);RW_CH.port2.postMessage(0);}
+ else requestAnimationFrame(()=>setTimeout(f,0));}
+// The day rests: it goes on after the next frame, still in flight meanwhile (no next day, no save).
+function rwRest(g,v){const j=RW.job={rest:true,g,state:S};RW.later(()=>{if(RW.job!==j)return;RW.job=null;if(j.state!==S){rwDayDone();return;}rwGo(g,v);});}
+function rwDone(m,t0){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;const t=performance.now();
+ // Another network was loaded meanwhile: the rest of that day belongs to nobody.
+ if(j.state!==S){rwDayDone();return;}
+ let v;
+ // A sales trial: the customer it signed off, or null. Something routed here meanwhile (an action), or the worker
+ // failed: the trial runs again here, checks included, on the game as it is now (dayAgain()).
+ if(j.tr){if(m.err)console.error('[tubes] route worker',m.err);v=m.err||RW.gen!==j.gen?dayAgain(j.tr):j.tr.dark?!!m.ok:m.ok?j.tr.trial:null;}
+ else if(m.err){console.error('[tubes] route worker',m.err);compute();}
else if(RW.gen===j.gen){R=rwUnpack(m.R,m.ef);UI.hotMap=hotByCity();}
const t1=performance.now(),st=RW.stat;st.n++;st.apply+=t1-t;st.wait+=t-j.t;st.work+=m.ms||0;
- try{dayPost(j.d);}catch(e){tickErr(e);}rwDayDone();}
+ // Reading a big answer takes a few ms already: the day goes on after the next frame then, not in the same task.
+ if(t0!==undefined&&t1-t0>RW.budget/2)rwRest(j.g,v);else rwGo(j.g,v);}
function rwDayDone(){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}}
/* R as plain data. R.ef and R.fl are lazy getters, sent as the pieces they are built from (R.efp, R.flc, see efBuild()
and flDefine() in 30-compute.js), their typed arrays moved, not copied. Exits become their ids (all R.fl reads), and an
@@ -52,5 +84,7 @@ const rwEfgOut=efg=>{if(!efg)return null;const o={};for(const k in efg)o[k]=efg[
const rwEfgIn=o=>{const efg={};for(const k in o)efg[k]=new EgSums(o[k]);return efg;};
// In the worker: route the state it was sent, answer with R.
function rwServe(m){try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{};if(m.efg)Object.defineProperty(R,'efg',{value:rwEfgIn(m.efg)});
+ // A sales trial (offerTrial()): its answer only.
+ if(m.trial){const t=performance.now(),ok=m.trial.dark?opsDarkTrial(m.trial):!!offerTrial(m.trial.b,m.trial.hx);postMessage({seq:m.seq,ok,ms:performance.now()-t});return;}
const t=performance.now();compute();const ms=performance.now()-t,{o,p,tr}=rwPack(R);postMessage({seq:m.seq,R:o,ef:p,ms},tr);}
catch(e){postMessage({seq:m.seq,err:String(e&&e.stack||e)});}}
diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js
index 10a499f..0f55d1f 100644
--- a/src/game/80-simulation/60-requirements.js
+++ b/src/game/80-simulation/60-requirements.js
@@ -19,7 +19,16 @@ const REQS={
skyfull:{only:true,bonus:0,l:()=>tr('requirements.promised_a_full_sky',{p:pct(PIE_PROMISE)}),ok:()=>pieHubs().some(id=>pieCov(id)>=PIE_PROMISE)},
puns:{l:tr('requirements.their_ceo_hates_puns_please_do'),bonus:.05,ok:()=>true},
};
-function terrestrialPath(a,b){const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
+/* terrestrialPath() asked for many customers at once (the daily mood check, 10-day-tick.js): the islands the live land
+ links make, worked out the first time one asks (TERR.m: city -> island), and two cities with a land path are two
+ cities of one island. Walking the links is what costs (a dark fiber's capacity, every one of them), not the question.
+ TERR names the game and the routing count it was made for: an action between two steps of the day changes a link
+ only through after(), which routes, so the islands are worked out again; another game, and each question walks. */
+let TERR=null;
+function terrIslands(){const adj={};for(const l of S.links)if(!linkDown(l)&&!l.sub){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}
+ const m=new Map();let n=0;for(const c in adj){if(m.has(c))continue;const q=[c];m.set(c,n);for(let h=0;h!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
const reqOk=b=>(b.reqs||[]).every(k=>REQS[k]&&REQS[k].ok(b));
// Some requirements only make sense for some customers: nobody can reach another continent without getting wet.
const reqCan=(k,b)=>!REQS[k].can||REQS[k].can(b);
diff --git a/src/game/80-simulation/75-customer-lifecycle.js b/src/game/80-simulation/75-customer-lifecycle.js
index 2bba376..8e5aab6 100644
--- a/src/game/80-simulation/75-customer-lifecycle.js
+++ b/src/game/80-simulation/75-customer-lifecycle.js
@@ -119,7 +119,7 @@ const clHags=()=>S?S.biz.reduce((a,b)=>a+(b.hag?1:0),0):0;
function clDealsHtml(){const hs=S.biz.filter(b=>b.hag).sort((a,b)=>a.hag.until-b.hag.until);if(!hs.length)return '';
return `
`;}).join('');}
// The contract line on a customer row.
const clTermTxt=b=>clOn(b)&&b.te?(b.hag?tr('lifecycle.renewal_haggle',{date:dateStr(b.te)}):tr('lifecycle.contract_until',{date:dateStr(b.te)})):'';
diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js
index ae6107e..6a5696d 100644
--- a/src/game/85-incidents/10-incidents-and-ddos.js
+++ b/src/game/85-incidents/10-incidents-and-ddos.js
@@ -89,11 +89,13 @@ function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire();
return a;}
/* After the day's routing: announce new attacks with what they are doing, pull the plug when Auto-RTBH says so, and
teach each lesson once. */
-function ddosNews(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh;
+function ddosNews(){runNow(ddosNewsRun());}
+// The same as a step of the day: its yield is the routing after Auto-RTBH pulled a plug.
+function* ddosNewsRun(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh;
for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue;
if(auto&&!a.bh&&m.full>0&&ddosCol(a)>=0.01){a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);again=true;
toast(tr('ddos.auto_rtbh',{who:esc(ddosWho(a))}),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:a.city});}}
- if(again)compute();
+ if(again)yield;
const T=S.stats.ddT||(S.stats.ddT={});
for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue;
if(a.fresh){delete a.fresh;const fl=scnRule('ddos'),col=ddosCol(a),sf=ddosSf(a),bad=col>=0.01||sf<0.97;
diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js
index 607cc6a..c849d65 100644
--- a/src/game/85-incidents/20-failures.js
+++ b/src/game/85-incidents/20-failures.js
@@ -2,7 +2,12 @@
const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair(l);
// The wet season in the tropical north (November to April): floods close the tracks, so a cut on land takes twice as long to reach.
const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason();
-function fireFailure(only){
+/* failureRun() is a failure as a step of the day (10-day-tick.js): its yield is the routing that tells what it cost,
+ done by the route worker in play. fireFailure() is the same failure all at once, routed on the spot. */
+function fireFailure(only){runNow(failureRun(only));}
+// A step of the day played all at once: every routing it asks for, on the spot (tests, a failure outside a day).
+function runNow(g){dayGo(g,(g,v)=>g.next(v));}
+function* failureRun(only){
const opts=[];
const live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))];
// A fiber that only carries expresses is dark as a link of its own, but there is light in it: a backhoe still finds it.
@@ -114,13 +119,15 @@ function fireFailure(only){
}else if(type==='fabric'){
const f=pick(fabsUsed);S.ev.fab=S.ev.fab||{};S.ev.fab[f]=S.day+2+Math.floor(Math.random()*3);
addInc({type,ref:f,until:S.ev.fab[f],msg:tr('failures.fabric_is_having_a_bad_day',{fabric:FAB[f].name}),cost:0});
- }else if(type==='ddos'){ddosAttack();return;
+ }else if(type==='ddos'){ddosAttack(false);yield;yield* ddosNewsRun();return;
}
- compute();
+ // This failure's incident, kept before the routing: the player may repair it (or another) while the worker routes.
const last=S.inc[S.inc.length-1];
+ yield;
+ if(!last)return;
last.impact=Math.max(0,before-R.served);
if(before>1&&last.impact${incTitle(type)} ${esc(last.msg)} ${tr('failures.traffic_rerouted_customers_barely')}`,'good',[],incOpen(last));}
- else{const paused=pref('pauseIncident')&&autoPause();toast(`${incTitle(type)} ${esc(last.msg)}${paused?` ${tr('common.game_paused')}`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
+ else{const paused=pref('pauseIncident')&&autoPause();toast(`${incTitle(type)} ${esc(last.msg)}${paused?` ${tr('common.game_paused')}`:''}`,'bad',(last.cost&&S.inc.includes(last)?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
sfx('alert');
}
const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0);
diff --git a/src/game/85-incidents/30-events.js b/src/game/85-incidents/30-events.js
index 829a3af..6c3ec27 100644
--- a/src/game/85-incidents/30-events.js
+++ b/src/game/85-incidents/30-events.js
@@ -1,3 +1,8 @@
+/* An event that cuts cables or power routes at once, as its last move (evRoute()). As a step of the day (eventRun())
+ that routing is the day's next yield instead: nothing reads R in between, so it is the same routing. */
+let EV_DEFER=null;
+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;i50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic');
@@ -36,16 +41,16 @@ function fireEvent(){
if(e==='shutdown'){const ps=Object.keys(S.pops).filter(c=>c!==S.home);if(!ps.length)return;const c=pick(ps);S.pops[c].down=Math.max(S.pops[c].down||0,S.day+1);addInc({type:'shutdown',ref:c,until:S.day+1,msg:tr('events.regulators_ordered_every_network_in',{city:CITY[c].name}),cost:0});toast(tr('events.ordered_offline_in_city_a_government',{city:CITY[c].name}),'bad');sfx('alert');return;}
if(e==='typhoon'){const c=pick(['mnl','ceb','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick([tr('common.typhoon_bandwidth'),tr('common.typhoon_latency'),tr('common.typhoon_jitter'),tr('events.typhoon_packet_loss')]);
if(p.gen){S.stats.survived++;toast(tr('events.name_hits_city_the_grid_is',{name:nm,city:CITY[c].name}),'good');sfx('alert');return;}
- p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');compute();return;}
- if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');compute();return;}
+ p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');evRoute();return;}
+ if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');evRoute();return;}
if(e==='baltic'){const BAL=['clion','havf','danice'];const hit=S.links.filter(l=>l.cable&&BAL.includes(l.cable)&&!(l.cut>S.day));
if(!hit.length){toast(tr('events.baltic_cable_damaged_a_cargo_ship'),'goal');return;}
const dur=15+Math.floor(Math.random()*15),en=N_('events.a_cargo_ship_dragged_its_anchor');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);}
- toast(tr('events.baltic_cable_damaged_n_of_your',{n:hit.length,d:dur}),'bad');sfx('alert');compute();return;}
+ toast(tr('events.baltic_cable_damaged_n_of_your',{n:hit.length,d:dur}),'bad');sfx('alert');evRoute();return;}
if(e==='redsea'){const RED=['twoaf','smw6','peace','aae','eig','eassy'];const hit=S.links.filter(l=>l.cable&&RED.includes(l.cable)&&!(l.cut>S.day));
if(!hit.length){toast(tr('events.cables_cut_in_the_red_sea'),'goal');return;}
const dur=20+Math.floor(Math.random()*15),en=N_('events.a_ship_drifting_without_power');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);}
- toast(tr('events.cables_cut_in_the_red_sea_03e8',{n:hit.length,d:dur}),'bad');sfx('alert');compute();return;}
+ toast(tr('events.cables_cut_in_the_red_sea_03e8',{n:hit.length,d:dur}),'bad');sfx('alert');evRoute();return;}
if(e==='golden'){S.ev.golden=S.day+7;toast(tr('events.golden_week_demand_in_mainland_china'),'goal');return;}
if(e==='gfw'){S.ev.gfw=S.day+10;toast(tr('events.the_border_got_stricter_cross_border'),'bad');sfx('alert');return;}
if(e==='viral'){S.ev.viral=S.day+8;toast(tr('events.new_season_of_stranger_pings_just'),'goal');}
diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js
index 28d6afc..5519bcf 100644
--- a/src/game/85-incidents/40-chaos-monkey.js
+++ b/src/game/85-incidents/40-chaos-monkey.js
@@ -18,25 +18,29 @@ const mkBonus=()=>Math.round(Math.min(2e6,Math.max(20000,(R.revMo||0)*0.5))/1000
function mkWeak(l){const trc=l.trench||l.id,adj={};
for(const x of S.links){if(x===l||(x.trench||x.id)===trc||linkDown(x))continue;(adj[x.a]||(adj[x.a]=[])).push(x.b);(adj[x.b]||(adj[x.b]=[])).push(x.a);}
const seen=new Set([l.a]),q=[l.a];while(q.length){const c=q.pop();if(c===l.b)return false;for(const n of adj[c]||[])if(!seen.has(n)){seen.add(n);q.push(n);}}return true;}
-function mkTick(d){const M=S.monkey;if(!M)return;
+function mkTick(d){runNow(mkTickRun(d));}
+// The monkey's day as a step of the day: a snip's yield is the routing that tells what it cost.
+function* mkTickRun(d){const M=S.monkey;if(!M)return;
if(!mkElig()){if(M.on)mkLeave('quiet');return;}
// The first visit is spread by the ASN, not the dice, so a game's other luck stays exactly as it was.
if(M.next==null)M.next=d+(mkSpicy()?180:270)+(S.asn||0)%120;
if(!M.on){if(dl.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l))).length<3){M.next=d+30;return;}mkArrive(d);return;}
if(d>=M.until){mkLeave();return;}
- if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}}
+ if(d>=M.snip){yield* mkSnipRun();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}}
function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121);
S.stats.mkMet=(S.stats.mkMet||0)+1;
Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home});
toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive');
if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);}
-function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l)));if(!live.length)return;
+function mkSnip(){runNow(mkSnipRun());}
+function* mkSnipRun(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'&&(!linkDown(l)||xpBare(l)));if(!live.length)return;
// Weak spots first: a sample keeps this cheap on big networks.
const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x]));
const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served;
hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));M.n++;M.c=l.a;
addInc({type:'cut',ref:trc,until:S.day+dur,msg:tr(pick(MK_SNIPS),{a:A,b:B}),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},'');
- compute();const i=S.inc[S.inc.length-1],imp=Math.max(0,before-R.served);if(i)i.impact=imp;
+ // The snip's incident, kept before the routing: the player may repair it (or another) while the worker routes.
+ const i=S.inc[S.inc.length-1];yield;const imp=Math.max(0,before-R.served);if(i)i.impact=imp;
const felt=before>1&&imp>=before*0.03;if(felt)M.hurt++;else S.stats.survived++;
toast(felt?`🐒 ${incTitle('cut')} ${esc(i?i.msg:'')}`:tr('chaos_monkey.rerouted',{a:A,b:B}),felt?'bad':'good',[],i?incOpen(i):null);sfx(felt?'err':'alert');
if(typeof mkRun==='function'){if(!UI.mk&&CITY[M.c])mkStart(M.c);mkRun(l,1400,felt);}}
diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js
index ba7417b..26d651d 100644
--- a/src/game/88-days/10-day-tick.js
+++ b/src/game/88-days/10-day-tick.js
@@ -1,13 +1,33 @@
/* ---------- daily tick ---------- */
-/* A day is two halves around its routing: dayPre() (the world moves on), compute(), dayPost() (bills, moods, offers).
- In play the routing can run in a worker in between (28-route-worker.js); tests and the fallback run it in one go. */
+/* A day is a few steps around its routing: dayPre() (the world moves on), then dayPost() (bills, moods, offers, the
+ intern's shift). dayRun() is the whole day as a generator: each yield is a compute() it needs before going on, the
+ day's own routing first, then a recompute after a failure or after the intern's jobs. dayTick() (tests, the fallback)
+ answers each with compute() on the spot; in play the route worker answers them (28-route-worker.js), and the page
+ only runs the steps in between. Same steps, same random numbers either way: routing draws none. (A failure
+ routes as a step too, failureRun(); an event still routes on the spot: it reads R right away, every few weeks.) */
// UI.tick: what the day itself announces, which quiet notifications may keep to the NOC log.
-function dayTick(){UI.tick=true;try{const d=dayPre();if(d===false)return;compute();dayPost(d);}finally{UI.tick=false;}}
-function dayPre(){
+// yield DAY_REST: no routing, only a place where the day may let a frame through when it has run long (rwGo()).
+const DAY_REST=1;
+function* dayRun(){const d=yield* dayPreRun();if(d===false)return;yield;yield* dayPost(d);}
+// A step yields undefined (a routing), DAY_REST, or a sales trial ({trial}, 95-standing-orders.js) to answer with the
+// customer it signs off or null (dayAnswer()): here at once, in play by the route worker.
+const dayStep=(g,v)=>{UI.tick=true;try{return g.next(v);}finally{UI.tick=false;}};
+// The intern's fiber test ({dark}, 95-standing-orders.js) is asked the same way, and answers true or false.
+const dayAsk=y=>!!y&&(!!y.trial||!!y.dark);
+const dayAnswer=y=>y.dark?opsDarkTrial(y):offerTrial(y.trial,y.hx);
+// The same trial overtaken by an action (a customer gone shifts S.biz, so hx no longer points at the right ones):
+// its checks, the customer and who is happy, made again on the game as it is now.
+const dayAgain=y=>{if(y.dark)return opsDarkAgain(y);const o=y.o;if(!o||!S.offers.includes(o))return null;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;};
+function dayGo(g,step=dayStep){let v;for(let s=step(g);!s.done;s=step(g,v)){v=undefined;const y=s.value;if(y===DAY_REST)continue;if(dayAsk(y))v=dayAnswer(y);else compute();}}
+function dayTick(){dayGo(dayRun());}
+// dayPre(): the world's morning all at once; dayPreRun() the same with a place or two to let a frame through.
+function dayPre(){const g=dayPreRun();for(;;){const s=g.next();if(s.done)return s.value;}}
+function* dayPreRun(){
if(!S||S.lost||!rule('clock'))return false; // no clock (puzzles): no days, no bills, nothing fires
S.day++;
const d=S.day;
dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d);
+ yield DAY_REST;
if(!S.phpDone&&d>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;}
@@ -27,13 +47,14 @@ function dayPre(){
// resolve incidents
for(const i of S.inc.slice())if(i.until<=d){const o=incOpen(i),l=o&&o.a==='link'&&S.links.find(x=>x.id===o.v),where=l?CITY[l.a].name+'–'+CITY[l.b].name:o&&o.a==='city'?CITY[o.v].name:'';clearInc(i);
toast(where?tr('day_tick.resolved_what_where_is_back_to',{what:incTitle(i.type),where:esc(where)}):tr('day_tick.resolved_what',{what:incTitle(i.type)}),'good',[],o);}
+ yield DAY_REST;
// eyeball growth / churn uses last computed service
for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c)*((R.bbF&&R.bbF[c])??1),P=eyeP(c);
if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);}
else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));}
return d;}
-function dayPost(d){
- ddosNews();ddosTrack();
+function* dayPost(d){
+ yield* ddosNewsRun();ddosTrack();
for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();}
S.cash+=(R.revMo-R.costMo)/monLen(d);
S.stats.peak=Math.max(S.stats.peak,R.served);
@@ -48,7 +69,7 @@ function dayPost(d){
(a.sla||(a.sla=[])).push(b.id);b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1;
toast(tr('day_tick.sla_breach_name_the_attack_on',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}}
// businesses mood
- const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));for(const b of S.biz.slice()){if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b);
+ const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));let nb=0;TERR={S,gen:RW.gen,m:null};try{for(const b of S.biz.slice()){if(++nb%256===0)yield DAY_REST;if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b);
if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2);
else if(S.day-(b.since||0)<15){}
else{const dm=frr*(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));b.mood-=BIZ_T[b.type].orbit?Math.min(dm,PIE_PATIENCE):dm;
@@ -58,11 +79,13 @@ function dayPost(d){
else if(b.mood<30&&!b.warned){b.warned=b.warn60=true;const why=bizWhy(b)[0],paused=pref('pauseFurious')&&autoPause();
toast(tr('day_tick.name_is_furious_fix_service_in',{name:esc(b.name),city:CITY[b.city].name})+(why?` ${esc(why)}`:'')+(paused?` ${tr('common.game_paused')}`:''),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');}
else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('day_tick.name_is_getting_unhappy_happiness_p',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?` ${esc(why)}`:''),'',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);}}
- if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}
+ if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}}finally{TERR=null;}
+ yield DAY_REST;
// contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js)
clDay(d);
// the sales desk: meetings booked, golf played (38-sales-desk.js)
- salesDay(d);
+ salesDay(d);yield* slRenRun(d);
+ yield DAY_REST;
// own IX members join
for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.lengthn.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
@@ -74,19 +97,21 @@ function dayPost(d){
S.offers=S.offers.filter(o=>o.exp>d);
brTick();
if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)*salesSpawn()){const n0=S.offers.length;spawnOffer();mktPrice(n0);salesShape(n0);}
+ yield DAY_REST;
// failures & events
// Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never.
let dirty=false;const cm=chaosMul();
// A visiting chaos monkey does the breaking instead (its snips replace these while it is here).
- mkTick(d);
- if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);}
+ yield* mkTickRun(d);
+ if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;yield* failureRun();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);}
// Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year).
- if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='sat'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);}
- if(dirty)compute();
+ if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&l.kind!=='sat'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;yield* eventRun();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);}
+ if(dirty)yield;
// the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them
- slAutoDay(d);
- opsDay(d);
+ yield* slAutoRun(d);
+ if(opsHired())yield DAY_REST;
+ yield* opsRun(d);
if(S.pie){pieDay(d);pieTier();}
// payday floaters
if(cal(d).d===1){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-arpuOf(c));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');}
diff --git a/src/game/90-actions/52-sales.js b/src/game/90-actions/52-sales.js
index b909207..027cbd3 100644
--- a/src/game/90-actions/52-sales.js
+++ b/src/game/90-actions/52-sales.js
@@ -10,6 +10,7 @@ Object.assign(ACT,{
// The CEO cannot be fired. A board meeting (and its catering) can get you a VP of Sales, who takes over a month later.
// Signing for you (39-sales-auto.js): on or off, and the minimum under which offers are declined.
salesAuto:()=>{if(!slP())return;const A=S.slAuto||(S.slAuto=slAutoNew());A.on=!A.on;sfx('click');after();salesModal();},
+ salesRen:()=>{if(!slP())return;const A=S.slAuto||(S.slAuto=slAutoNew());if(A.ren)delete A.ren;else A.ren=true;sfx('click');after();salesModal();},
salesMin:()=>{if(!slP())return;const A=S.slAuto||(S.slAuto=slAutoNew());A.min=opsCycle(SL_MINS,A.min);sfx('click');after();salesModal();},
salesVp:()=>{if(slP()!=='ceo'||S.sales.vp)return;if(!spend(SALES_VP))return;S.sales.vp=S.day+SALES_VP_DAYS;toast(tr('sales.vp_asked',{n:SALES_VP_DAYS}),'');after();salesModal();},
});
diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js
index e2ba8a6..6d67cb1 100644
--- a/src/game/93-ui/57-ops-panel.js
+++ b/src/game/93-ui/57-ops-panel.js
@@ -20,11 +20,11 @@ function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.o
function opsModal(){if(!S)return;const hired=opsHired();let h=`
`:''}
diff --git a/src/game/93-ui/58-sales-panel.js b/src/game/93-ui/58-sales-panel.js
index b155c20..71e98ea 100644
--- a/src/game/93-ui/58-sales-panel.js
+++ b/src/game/93-ui/58-sales-panel.js
@@ -19,12 +19,15 @@ function salesModal(){if(!S)return;const p=slP(),L=S.sales||{};
// What each of them does in orbit, shown once there is a rocket company to sell for (99-pie-sales.js).
const SL_SKY={eng:N_('sales.eng_sky'),shark:N_('sales.shark_sky'),ceo:N_('sales.ceo_sky')};
const SL_AUTO={eng:N_('sales.auto_eng'),shark:N_('sales.auto_shark'),ceo:N_('sales.auto_ceo')};
+const SL_REN={eng:N_('sales.ren_eng'),shark:N_('sales.ren_shark'),ceo:N_('sales.ren_ceo')};
// Signing for you (39-sales-auto.js): the switch, the minimum, and this week's and last week's tally.
function slAutoHtml(p){const A=S.slAuto||slAutoNew(),w=Math.floor(S.day/7),cur=A.wk&&A.wk.w===w&&slWkAny(A.wk)?A.wk:null,rep=A.rep&&A.rep.w===w-1?A.rep:null;
const row=(x,last)=>`
+ `;}
// On the card in Deals: this week's tally, once there is one.
function slCardLine(){if(!slAutoOn())return '';const A=S.slAuto,x=A.wk&&A.wk.w===Math.floor(S.day/7)&&slWkAny(A.wk)?A.wk:null;return x?esc(slWeekLine(x,false)):'';}
diff --git a/src/game/99-loop.js b/src/game/99-loop.js
index 5a61189..48f2176 100644
--- a/src/game/99-loop.js
+++ b/src/game/99-loop.js
@@ -4,6 +4,11 @@ function frame(now){
// Schedule the next frame first: one bad lookup in a day tick must not freeze the whole game.
if(!window.__TUBES_TEST__)requestAnimationFrame(frame);
const dt=Math.min(250,now-last);last=now;
+ // A day's steps take half a frame at most before letting one through (rwGo()): 8 ms at 60 Hz, 3 ms on a 240 Hz screen,
+ // where 8 ms would be two frames lost. A device that cannot hold 50 frames a second waits a whole slow frame at every
+ // rest, so a big day there would crawl: it gets half of its own frame, up to 32 ms. The frame time is followed slowly,
+ // a long frame counting as two at most.
+ if(dt>0){RW.fms=RW.fms?RW.fms*0.95+Math.min(dt,RW.fms*2)*0.05:dt;RW.budget=RW.fms>RW_SLOW?Math.min(32,RW.fms/2):Math.min(8,Math.max(3,RW.fms/2));}
if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);}
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
// The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them.
@@ -14,12 +19,16 @@ function frame(now){
const t=animOn()?animT:0;
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;}
if(DIAG.on)diagFrame(now);
+ RW.lf=performance.now();
}
// dt of real time at UI.speed: the days it adds up to. The frame calls it; so may a clock that also runs where frames
// do not (src/agent/, a hidden tab), under the frame's own conditions otherwise.
function runClock(dt){acc+=dt*UI.speed;let n=0;
- // With the route worker one day is in flight at a time; time does not pile up behind it.
- if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}}
+ // One day in flight at a time (its routing in the worker, or resting between steps): time does not pile up behind it.
+ // The clock waits for the day, never the other way round: a machine that cannot keep up plays slower, it does not
+ // freeze to catch up.
+ if(RW.job){acc=Math.min(acc,DAY_MS);return;}
+ if(rwOn()){if(!RW.w)rwStart();if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}}
else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}}
/* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map
diff --git a/src/i18n/en.js b/src/i18n/en.js
index 4e8068b..7568d89 100644
--- a/src/i18n/en.js
+++ b/src/i18n/en.js
@@ -2275,6 +2275,10 @@
"find.press_slash_to_search_from":"Tip: press / anywhere on the map to search.",
"find.type_a_city_a_country":"Type a city, a country or an exchange.",
"find.your_pop":"your POP",
+"france.europe_s_biggest_hosting_cloud_from":"Europe’s biggest hosting cloud, from Roubaix. After the Strasbourg fire it backs everything up twice.",
+"france.france_s_number_two_it_bought_a":"France’s number two. It bought a cable company, then a media empire, then a lot of debt.",
+"france.the_builder_that_became_a_mobile":"The builder that became a mobile network. It still pours concrete on the side.",
+"france.the_cloud_arm_of_the_free_group":"The cloud arm of the Free group, with ARM servers and a data centre in a Paris bunker.",
"game_and_settings.delete_and_start_over":"Delete and start over",
"game_and_settings.export_save_download_a_file":"Export save download a file",
"game_and_settings.import_failed_that_save_is_damaged":"Import failed. That save is damaged and could not be loaded. Your current game is untouched.",
@@ -3397,6 +3401,9 @@
"ops.fire":"Let go",
"ops.fired":"{name} handed in the badge and took the good stapler. Your standing orders are paused.",
"ops.floor":"Keep at least",
+"ops.good_annie":"Best at peering: works through the exchanges every day, not weekly, and orders PNIs twice a week.",
+"ops.good_kevin":"Best at maintenance: two line system swaps a night instead of one, and never a fat finger.",
+"ops.good_tracy":"Best at planning ahead: buys transit, ports, routers and optics as if traffic were already 10% higher.",
"ops.hire_an_intern":"Hire a NOC intern",
"ops.hire_mo":"Hire · {price}/mo",
"ops.hire_pitch_short":"Set the rules once, and an intern clicks the buttons every day.",
@@ -4520,8 +4527,22 @@
"sales.locked":"The sales desk opens at customer level {lv}.",
"sales.never":"never",
"sales.one_at_a_time":"One at a time: let them go to hire someone else.",
+"sales.p_ren":"Answer haggles",
"sales.p_sign":"Sign deals",
"sales.pitch":"One salesperson brings in deals their own way. Pick who.",
+"sales.ren":"Renewal haggles",
+"sales.ren_ceo":"{name} answers a customer's haggle three days after it opens, on the golf course: a deeper discount than they asked for in exchange for a contract twice as long, a quick yes, or a fight that ends with the customer gone.",
+"sales.ren_ceo_fight":"{name} told {cust} that nobody haggles with him. They have left.",
+"sales.ren_ceo_golf":"{name} sorted out {cust} on the golf course: {price}/mo, even less than they asked, locked in until {date}.",
+"sales.ren_ceo_yes":"{name} said yes to {cust} before anyone could check: {price}/mo.",
+"sales.ren_eng":"{name} answers a customer's haggle three days after it opens. Nerdy customers get an afternoon with the network diagrams and usually renew at the market price; everyone else gets the discount they asked for. Nobody leaves.",
+"sales.ren_eng_cave":"{name} gave {cust} the discount they asked for: {price}/mo. They stay.",
+"sales.ren_eng_tech":"{name} walked {cust}'s engineers through the network for an afternoon. They renew at {price}/mo, no discount needed.",
+"sales.ren_mid":"{name} met {cust} halfway: {price}/mo.",
+"sales.ren_shark":"{name} answers a customer's haggle three days after it opens, and gives nothing away: most renew at the old price, often with a fresh promise, and he bills you a month of what he saved. Some walk, nerdy ones most of all.",
+"sales.ren_shark_hold":"{name} told {cust} the price is the price. They renew at {price}/mo, and he bills you {fee} for the save.",
+"sales.ren_shark_walk":"{name} played hardball with {cust}, and they walked.",
+"sales.ren_when":"{name} answers this on {date}, unless you do first.",
"sales.shark_d":"Lands the biggest deals at a quarter more, and takes a month of each deal as commission. Oversells: half of them come with a promise your network does not keep yet, and those customers leave sooner. Ignores the nerds: no technical customers, no meetings, and peering desks want a quarter more traffic from you. Wins most haggles.",
"sales.shark_n":"The shark",
"sales.shark_s":"Chad",
diff --git a/src/styles/36-ops.css b/src/styles/36-ops.css
index 94ba823..68fc552 100644
--- a/src/styles/36-ops.css
+++ b/src/styles/36-ops.css
@@ -14,6 +14,7 @@
.ops-sel{display:flex;flex-direction:column;gap:2px;flex:1 1 140px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)}
.ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--text);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px}
.ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto}
+.ops-good{font-size:12.5px;font-weight:800;color:#6B3FD4;margin-top:2px;line-height:1.3}
.ops-mood{margin:6px 0 0;font-style:italic;font-size:13px;color:var(--ink2)}
.ops-rep{border-left:3px solid #8E5CF7;background:var(--tint-v,#F7F2FF);border-radius:0 8px 8px 0;padding:6px 8px;margin:6px 0;font-size:13px;line-height:1.35;overflow-wrap:anywhere}
.ops-rep .eyebrow{margin-bottom:2px}
diff --git a/tests/day-steps.test.js b/tests/day-steps.test.js
new file mode 100644
index 0000000..b9dba8f
--- /dev/null
+++ b/tests/day-steps.test.js
@@ -0,0 +1,241 @@
+// The day as steps (dayRun() in src/game/88-days/10-day-tick.js): every routing a day needs, its own and the
+// recomputes after a failure or the intern's jobs, is a yield the route worker answers in play. jsdom has no Worker, so
+// a second page plays it: rwServe() there, messages cloned both ways the way postMessage clones them. A day played that
+// way must be the day dayTick() plays, move for move, with a frame let through in the middle of each day.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { load } = require('./harness');
+
+const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
+// The big network with an intern running every order, a failure and an event due soon, and its circuits on scenic
+// routes, which read yesterday's R.efg. Ids come from Date.now(),
+// so the clock stands still in every page.
+const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false;
+ S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true;
+ S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0;
+ S.nextFail=S.day+3;S.nextEvent=S.day+5;for(const b of S.biz)if(BIZ_T[b.type].l2&&b.city2)b.route='scenic';compute();__reseed(4242);`;
+const open = (t, seed) => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; };
+// The page, with a stand-in worker: what it posts waits in a queue until pump() hands it to the other page.
+function played(t) {
+ const page = open(t, 777), wk = open(t, 1);
+ page.ev(SETUP);
+ // No time to spare: every DAY_REST waits for the next "frame", which pump() gives it.
+ page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});');
+ wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};');
+ // Answers what is waiting, one message at a time; returns how many routings it served.
+ let rests = 0, trials = 0;
+ const pump = () => { let n = 0; for (;;) {
+ if (page.ev('__later.length')) { rests++; page.ev('__later.shift()()'); continue; }
+ if (!page.ev('__q.length')) break;
+ if (page.ev('!!__q[0].trial')) trials++;
+ wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out');
+ page.ev('rwDone(__a)'); n++; } return n; };
+ // One message to the worker and its answer back (the trial test steps through a day with it).
+ const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); };
+ return { ...page, pump, pump1, rests: () => rests, trials: () => trials };
+}
+// R.egDesc too, key for key and in order.
+const STATE = "JSON.stringify({S,R:{served:R.served,demand:R.demand,rev:R.revMo,cost:R.costMo,load:R.load,useT:R.useT,usePni:R.usePni,egDesc:R.egDesc}})";
+// Equal states, or which of their fields differ.
+const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B = JSON.parse(b), d = [];
+ for (const o of ['S', 'R']) for (const k of new Set([...Object.keys(A[o]), ...Object.keys(B[o])])) if (JSON.stringify(A[o][k]) !== JSON.stringify(B[o][k])) d.push(`${o}.${k}`);
+ assert.fail(`${msg}: ${d.join(', ')} differ`); };
+
+test('a day whose routings the worker answers is the day dayTick() plays', (t) => {
+ const ref = open(t, 777), p = played(t);
+ ref.ev(SETUP);
+ // The page itself never routes, the failure on day 3 (failureRun()) and the sales desk's trials (offerTrial())
+ // included: they are steps like the others, routed by the worker.
+ p.ev('window.__pc=0;window.__tr=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};');
+ let served = 0, extra = 0;
+ for (let i = 0; i < 12; i++) {
+ ref.ev('dayTick()');
+ p.ev('rwDay()');
+ assert.equal(p.ev('!!RW.job'), true, 'the day waits for the worker');
+ const n = p.pump(); served += n; if (n > 1) extra++;
+ assert.equal(p.ev('!!RW.job'), false);
+ same(p.ev(STATE), ref.ev(STATE), `day ${i + 1}`);
+ }
+ // Each day routes once, and some days again after a failure, an event or the intern's jobs: all in the worker.
+ assert.ok(served > 12 && extra > 0, `routings served: ${served}, days with more than one: ${extra}`);
+ assert.ok(ref.ev('S.inc.length') > 0 || ref.ev('S.stats.incidents') > 0, 'a failure happened');
+ assert.equal(p.ev('__pc'), 0, 'no routing on the page');
+ assert.ok(p.trials() > 0, `sales trials the worker ran: ${p.trials()}`);
+ assert.ok(p.ev('S.ops.log.some(e=>e.r.some(([k])=>k==="caches"))'), 'the intern racked cache boxes');
+ // A frame through before the intern's shift, after each of the orders on duty (decommissioning aside), and after
+ // each job of an order (a generator's yields).
+ const orders = p.ev('OPS_ORDER.slice(0,-1).filter(k=>S.ops.on[k]).length');
+ assert.ok(orders > 3, `orders on duty: ${orders}`);
+ assert.ok(p.rests() > 12 * (1 + orders), `each day let a frame through before the shift, between its orders and its jobs: ${p.rests()}`);
+ assert.deepEqual([...ref.errors, ...p.errors], []);
+});
+
+test('a half day is never saved, and a worker lost mid-day finishes it on the page', (t) => {
+ const ref = open(t, 777), p = played(t);
+ ref.ev(SETUP);
+ ref.ev('dayTick()');
+ p.ev("window.__saves=0;const s0=save;save=(...a)=>{if(!RW.job)__saves++;return s0(...a);};rwDay()");
+ p.ev('save()');
+ assert.equal(p.ev('UI.saveDue'), true, 'saving waits for the end of the day');
+ p.ev('rwKill()');
+ assert.equal(p.ev('RW.job&&RW.job.rest'), true, 'the day goes on on the page, up to its rest');
+ assert.equal(p.pump(), 0, 'with no worker left');
+ assert.equal(p.ev('!!RW.job'), false, 'the day is over');
+ assert.equal(p.ev('UI.saveDue'), false, 'and saved');
+ same(p.ev(STATE), ref.ev(STATE), 'the day');
+ assert.deepEqual([...ref.errors, ...p.errors], []);
+});
+
+test('an action while the worker routes stands; another network loaded mid-day gets none of that day', (t) => {
+ const p = played(t);
+ p.ev('rwDay()');
+ // The action routes on the page as always: the worker's answer is stale, and the day goes on with the action's R.
+ p.ev('after()');
+ assert.equal(p.pump() >= 1, true);
+ assert.equal(p.ev('!!RW.job'), false);
+ assert.equal(p.ev('S.day'), p.ev('S.hist[S.hist.length-1].d'), 'the day was finished');
+ // A new game while a day is in flight: the old day's steps never touch it.
+ p.ev('rwDay()');
+ const day = p.ev('S.day');
+ p.ev(`window.__old=S;S=migrate(JSON.parse(${JSON.stringify(BIG)}));compute();`);
+ const fresh = p.ev('JSON.stringify(S.hist)');
+ p.pump();
+ assert.equal(p.ev('JSON.stringify(S.hist)'), fresh);
+ assert.equal(p.ev('__old.day'), day);
+ assert.deepEqual(p.errors, []);
+});
+
+// A sales trial the worker is routing when the player acts (an action routes on the page): its answer was for the game
+// as it was, so the trial runs again on the page, on the game as it is now.
+test("a sales trial overtaken by the player's action runs again on the page", (t) => {
+ const p = played(t);
+ p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};");
+ let found = false;
+ for (let d = 0; d < 20 && !found; d++) {
+ p.ev('rwDay()');
+ // Hand the worker one message at a time until a trial is the one waiting.
+ for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) {
+ if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; }
+ if (!found && p.ev('__q.length&&!!__q[0].trial')) { found = true; p.ev('compute()'); }
+ p.pump1();
+ }
+ }
+ assert.ok(found, 'the sales desk trialled an offer');
+ assert.equal(p.ev('__ot'), 1, 'the overtaken trial ran on the page');
+ assert.deepEqual(p.errors, []);
+});
+
+// The rest of what used to route on the page in a day: a DDoS that a failure starts (and Auto-RTBH pulling a plug), an
+// event that cuts cables or power, and the chaos monkey's snip. Each is a step the worker routes, and the day is still
+// the day dayTick() plays.
+test('DDoS, cable and power events and the chaos monkey route in the worker too, and the day stays the same', (t) => {
+ // A visiting monkey does the breaking instead of the failures: failures first, then the monkey.
+ const MONKEY = 'S.monkey={on:1,start:S.day,until:S.day+60,snip:S.day+1,n:0,hurt:0,c:S.home,next:S.day};';
+ const FORCE = `S.ddosAuto={rtbh:true};mkElig=()=>true;S.monkey={on:0,next:S.day+999};S.nextFail=S.day+1;S.nextEvent=S.day+2;
+ failureRun=eval('('+failureRun.toString().replace('if(only)type=only;',"type=S.day%2?'ddos':'cut';")+')');
+ fireEvent=eval('('+fireEvent.toString().replace('const e=pick(opts);',"const e=['redsea','typhoon','baltic','runet'].find(x=>opts.includes(x))||'redsea';")+')');__reseed(99);`;
+ const ref = open(t, 777), p = played(t);
+ ref.ev(SETUP); ref.ev(FORCE); p.ev(FORCE);
+ // The reference routes an event on the spot, the way it always did (no deferred routing).
+ ref.ev('eventRun=function*(){fireEvent();};');
+ ref.ev("window.__dd=0;const da=ddosAttack;ddosAttack=(...a)=>{const r=da(...a);if(r)__dd++;return r;};window.__ev=0;const fe=fireEvent;fireEvent=(...a)=>{__ev++;return fe(...a);};");
+ p.ev('window.__pc=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};');
+ for (let i = 0; i < 12; i++) {
+ if (i === 6) for (const h of [ref, p]) h.ev(MONKEY);
+ for (const h of [ref, p]) h.ev('S.nextFail=S.day+1;S.nextEvent=S.day+1;');
+ ref.ev('dayTick()');
+ p.ev('rwDay()'); p.pump();
+ same(p.ev(STATE), ref.ev(STATE), `day ${i + 1}`);
+ }
+ assert.ok(ref.ev('__dd') > 0, `DDoS attacks started: ${ref.ev('__dd')}`);
+ assert.ok(ref.ev('S.monkey.n') > 0, `the monkey snipped: ${ref.ev('S.monkey.n')}`);
+ assert.ok(ref.ev('__ev') > 2, `events: ${ref.ev('__ev')}`);
+ assert.equal(p.ev('__pc'), 0, 'no routing on the page');
+ assert.deepEqual([...ref.errors, ...p.errors], []);
+});
+
+// Quiet notifications keep the day's own news to the NOC log (UI.tick, 95-modals/10-toasts.js). Play goes through the
+// worker's steps, not dayTick(): every step of the day is announced as the day's, on both sides of each routing.
+test('quiet notifications hold while the worker plays the day', (t) => {
+ const p = played(t);
+ p.ev("window.__tc=[];const t0=toast;toast=function(m,k){__tc.push(!!UI.tick);return t0.apply(this,arguments);};");
+ for (let i = 0; i < 12; i++) { p.ev('rwDay()'); p.pump(); }
+ const calls = JSON.parse(p.ev('JSON.stringify(__tc)'));
+ assert.ok(calls.length > 0, 'the days had news');
+ assert.deepEqual(calls.filter((x) => !x), [], 'every toast of the day came with UI.tick set');
+ assert.equal(p.ev('UI.tick'), false, 'and it is off between days');
+ assert.deepEqual(p.errors, []);
+});
+
+// What the player does while a step waits for the worker: the step goes on with the game as it is by then.
+const TICK_ERR = "window.__te=[];tickErr=e=>__te.push(String(e&&e.stack||e));";
+
+test('a customer dropped while a sales trial routes: the trial runs again on the customers left', (t) => {
+ const p = played(t);
+ p.ev(TICK_ERR);
+ p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};");
+ let found = false;
+ for (let d = 0; d < 20 && !found; d++) {
+ p.ev('rwDay()');
+ for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) {
+ if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; }
+ // A trial the offer passes, the last customer among the happy ones: that customer goes, and the trial's list of
+ // who was happy (indices in S.biz) now points one past the end.
+ if (!found && p.ev('__q.length&&!!__q[0].trial&&!!__q[0].trial.hx&&__q[0].trial.hx.includes(S.biz.length-1)&&!!offerTrial(__q[0].trial.b,__q[0].trial.hx)')) {
+ found = true; p.ev('__ot=0;const b=S.biz[S.biz.length-1];UI.confirm=b.id;ACT.dropBiz({id:b.id});');
+ }
+ p.pump1();
+ }
+ }
+ assert.ok(found, 'the desk trialled an offer');
+ assert.equal(p.ev('__ot'), 1, 'the overtaken trial ran again on the page');
+ assert.equal(p.ev('JSON.stringify(__te)'), '[]');
+ assert.equal(p.ev('!!RW.job'), false);
+ assert.equal(p.ev('S.day'), p.ev('S.hist[S.hist.length-1].d'), 'the day was finished');
+ assert.deepEqual(p.errors, []);
+});
+
+test("the intern's PNI round never orders again what the player ordered while it waited", (t) => {
+ // The round's batch, then its first rest: the player orders every PNI of the batch by hand meanwhile.
+ const ROUND = (hand) => `while(S.day%7!==3)S.day++;S.ops.on.pni=true;
+ const pb=pniBatch;pniBatch=(...a)=>window.__b=pb(...a);
+ window.__b=null;const X=opsShift(),it=OPS_RUN.pni(X),n0=S.pni.length;let hand=0;
+ for(let s=it.next();!s.done;s=it.next())if(__b&&${hand}&&!hand){hand=1;const af=after;after=()=>{};try{for(const q of __b.orders)ACT.pni({city:q.city,net:q.net,tier:q.g1?-1:q.tier});}finally{after=af;}compute();window.__h=S.pni.length;}
+ window.__n=S.pni.length-n0;`;
+ const key = "S.pni.map(p=>p.city+'|'+p.net)";
+ const ref = open(t, 777), p = open(t, 777);
+ ref.ev(SETUP); p.ev(SETUP);
+ ref.ev(ROUND(false));
+ assert.ok(ref.ev('__b.orders.length') > 0 && ref.ev('__n') > 0, `the intern orders PNIs: ${ref.ev('__n')} of ${ref.ev('__b.orders.length')}`);
+ p.ev(ROUND(true));
+ assert.ok(p.ev('__h') > p.ev('S.pni.length') - p.ev('__n'), 'the player ordered some by hand');
+ assert.equal(p.ev('S.pni.length'), p.ev('__h'), 'the intern ordered nothing more');
+ const keys = p.ev(key);
+ assert.equal(new Set(keys).size, keys.length, 'one PNI per city and network');
+ assert.deepEqual([...ref.errors, ...p.errors], []);
+});
+
+test('an incident repaired while its routing runs: the failure and the monkey still tell its own story', (t) => {
+ const p = open(t, 777);
+ p.ev(SETUP);
+ // On land: a repair clears the incident (at sea it would charter a ship).
+ p.ev("S.rules.sea='timer';S.inc=[];");
+ // Repaired before the answer, the only incident there was: nothing left to read as "the last one".
+ p.ev(`const g=failureRun('cut');g.next();window.__i=S.inc[S.inc.length-1];ACT.fixInc({id:__i.id});g.next();`);
+ assert.equal(p.ev('S.inc.length'), 0);
+ assert.equal(p.ev('typeof __i.impact'), 'number', 'its impact is its own');
+ // An older incident stands: the new one's impact is not pinned on it.
+ p.ev(`runNow(failureRun('cut'));window.__a=S.inc[S.inc.length-1];__a.impact=-7;
+ const g2=failureRun('cut');g2.next();window.__b=S.inc[S.inc.length-1];ACT.fixInc({id:__b.id});g2.next();`);
+ assert.equal(p.ev('__a!==__b&&S.inc.includes(__a)&&!S.inc.includes(__b)'), true);
+ assert.equal(p.ev('__a.impact'), -7, 'the older incident keeps its impact');
+ assert.equal(p.ev('typeof __b.impact'), 'number');
+ // The monkey's snip, the same way.
+ p.ev(`S.monkey={on:1,start:S.day,until:S.day+60,snip:S.day,n:0,hurt:0,c:S.home,next:S.day};
+ const g3=mkSnipRun();g3.next();window.__c=S.inc[S.inc.length-1];ACT.fixInc({id:__c.id});g3.next();`);
+ assert.equal(p.ev('__a.impact'), -7, 'the older incident keeps its impact');
+ assert.equal(p.ev('typeof __c.impact'), 'number');
+ assert.deepEqual(p.errors, []);
+});
diff --git a/tests/frame-pacing.test.js b/tests/frame-pacing.test.js
new file mode 100644
index 0000000..e495306
--- /dev/null
+++ b/tests/frame-pacing.test.js
@@ -0,0 +1,31 @@
+// How long a day may run on the page between two frames (src/game/99-loop.js, rwGo()): half a frame, from 3 to 8 ms.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { load } = require('./harness');
+
+test("a day's steps follow the screen: half a frame between two, from 3 to 8 ms", () => {
+ const { ev, errors } = load();
+ ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;");
+ const run = (hz, n, extra = '') => ev(`(()=>{for(let i=0;i<${n};i++){window.__now=(window.__now||1000)+1000/${hz};${extra};frame(__now);}return RW.budget;})()`);
+ assert.equal(run(240, 300), 3, 'a 240 Hz screen');
+ const b = run(240, 1, '__now+=250');
+ assert.ok(b < 6, `one long frame barely moves it: ${b}`);
+ assert.equal(run(60, 300), 8, 'a 60 Hz screen');
+ assert.ok(Math.abs(run(120, 300) - 1000 / 120 / 2) < 0.1, 'a 120 Hz screen: half its frame');
+ assert.deepEqual(errors, []);
+});
+
+// A slow phone draws 20 frames a second: at 8 ms a slice, a big day there waited a 50 ms frame at almost every step and
+// played a third slower than before the day was split. It gets half of its own frame, never more than 32 ms.
+test("a device that cannot hold 50 frames a second gives a day half its frame, 32 ms at most", () => {
+ const { ev, errors } = load();
+ ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;");
+ const run = (hz, n) => ev(`(()=>{for(let i=0;i<${n};i++){window.__now=(window.__now||1000)+1000/${hz};frame(__now);}return RW.budget;})()`);
+ assert.equal(run(60, 300), 8, 'a 60 Hz screen keeps 8 ms');
+ assert.ok(Math.abs(run(20, 300) - 25) < 0.5, `20 frames a second: half of 50 ms, ${ev('RW.budget')}`);
+ assert.equal(run(8, 300), 32, 'never more than 32 ms');
+ assert.equal(run(240, 400), 3, 'and back to 3 ms on a fast screen');
+ assert.deepEqual(errors, []);
+});
+
+// The diverse-paths map new offers ask about (60-requirements.js) is built a millisecond a frame, before the first one
diff --git a/tests/france.test.js b/tests/france.test.js
new file mode 100644
index 0000000..0355470
--- /dev/null
+++ b/tests/france.test.js
@@ -0,0 +1,50 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { load } = require('./harness');
+
+const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0";
+const NEW = { lys: ['Lyon', 'Quenelle-IX'], tls: ['Toulouse', 'Cassoulet-IX'], lil: ['Lille', 'Maroilles-IX'], bod: ['Bordeaux', 'Claret-IX'],
+ sxb: ['Strasbourg', 'Choucroute-IX'], rns: ['Rennes', 'Galette-IX'], nte: ['Nantes', ''] };
+
+test('Lyon, Toulouse, Lille, Bordeaux, Strasbourg, Rennes and Nantes are French cities on land, with a seller of transit each', () => {
+ const { ev, errors } = load();
+ ev(start);
+ for (const [id, [name, ix]] of Object.entries(NEW)) {
+ assert.equal(ev(`CITY.${id}.name`), name);
+ assert.equal(ev(`CITY.${id}.cc`), 'FR');
+ assert.equal(ev(`CITY.${id}.ix`), ix);
+ assert.equal(ev(`onLand(CITY.${id}.x,CITY.${id}.y)`), true, `${id} is on drawn land`);
+ assert.equal(ev(`NETS.some(n=>sellsAt(n,'${id}'))`), true, `${id} has a transit seller`);
+ assert.equal(ev(`CITY_PDB.${id}.length`), 3, `${id} has calibration`);
+ }
+ assert.deepEqual(errors, []);
+});
+
+test('SF-Error Telecom, Boy-Egg Telecom, Ov-Hatch Cloud and Scale-Away carry the real ASNs, and Orange and Free reach the new cities', () => {
+ const { ev, errors } = load();
+ ev(start);
+ assert.deepEqual(['sfe', 'byg', 'ovh', 'sca'].map((n) => ev(`NET.${n}.asn`)), [15557, 5410, 16276, 12876]);
+ assert.deepEqual(['sfe', 'byg', 'ovh', 'sca'].map((n) => ev(`NET.${n}.name`)), ['SF-Error Telecom', 'Boy-Egg Telecom', 'Ov-Hatch Cloud', 'Scale-Away']);
+ for (const c of Object.keys(NEW)) for (const n of ['tng', 'fre', 'sfe', 'byg']) assert.equal(ev(`NET.${n}.pops.includes('${c}')`), true, `${n} is in ${c}`);
+ assert.equal(ev("NET.ovh.pops.includes('sxb')&&NET.ovh.ix.includes('sxb')"), true, 'Ov-Hatch is on Choucroute-IX in Strasbourg');
+ for (const c of ['lys', 'tls', 'lil', 'bod', 'sxb']) assert.equal(ev(`NET.cog.pops.includes('${c}')`), true, `Cogentle is in ${c}, where PeeringDB lists Cogent`);
+ assert.equal(ev("NET.adt.pops.includes('tls')"), true, 'Andorra’s telco comes up to Toulouse');
+ assert.equal(ev("NETS.filter(n=>n.type!=='cdn'&&[].concat(n.cc||[]).includes('FR')&&n.pops.includes('lys')).length>=4"), true, 'four consumer networks in Lyon');
+ assert.deepEqual(errors, []);
+});
+
+test('Ami-Tea comes ashore at Bordeaux and Dunno-ant at Nantes, and Dunno-ant starts at Virginia Beach, not New Jersey', () => {
+ const { ev, errors } = load();
+ ev(start);
+ const pairs = (id) => JSON.parse(ev(`JSON.stringify(CABLES.find(c=>c.id==='${id}').pairs.map(p=>p.slice(0,2)))`));
+ assert.deepEqual(pairs('amitie'), [['nyc', 'lon'], ['nyc', 'bod']]);
+ assert.deepEqual(pairs('dunant'), [['ash', 'nte']]);
+ assert.deepEqual(JSON.parse(ev("JSON.stringify(CABLES.find(c=>c.id==='dunant').pairs[0][2][0])")), [-75.7, 36.85]);
+ for (const id of ['amitie', 'dunant']) {
+ const wp = JSON.parse(ev(`JSON.stringify(CABLES.find(c=>c.id==='${id}').pairs.flatMap(p=>p[2].map(w=>{const q=proj(w[0],w[1]);return onLand(q[0],q[1])})))`));
+ assert.ok(wp.every((x) => !x), `${id}: every waypoint is at sea`);
+ }
+ assert.equal(ev("CABLE_PAIRS.some(p=>p.cid==='dunant'&&(p.a==='par'||p.b==='par'))"), false, 'nothing lands in inland Paris any more');
+ for (const z of [0.35, 1.4, 6]) ev(`cam.z=${z};draw(performance.now())`);
+ assert.deepEqual(errors, []);
+});
diff --git a/tests/game.test.js b/tests/game.test.js
index c182655..aa21ff1 100644
--- a/tests/game.test.js
+++ b/tests/game.test.js
@@ -47,17 +47,17 @@ test('every incident and event type fires and clears cleanly', () => {
ev("UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});UI.via='grace';openLinkModal('nyc','lon');ACT.buildLink({tier:1});closeModal()");
ev("UI.pending={a:'fra',b:'ams'};UI.lmode='df';UI.dfSys='roadm';ACT.orderDf();UI.lmode='wave';S.pops.fra.rgen=2;S.pops.ams.rgen=2");
ev("const df=S.links.find(l=>l.kind==='df');ACT.addCh({id:df.id,o:'zr4'});df.ready=S.day");
- const failSrc = ev('fireFailure.toString()');
+ const failSrc = ev('failureRun.toString()');
const types = ['harmless','fatwave','label','mtu','oops','cleaner','maxpfx','prepend','rpki','amp','roadmff','optic','ac','cut','crash','power','transit','ixloop','leak','ddos'];
for (const t of types) {
const funny = ['harmless','fatwave','label','mtu','oops','cleaner','maxpfx','prepend','rpki','roadmff','ac'].includes(t);
const patched = failSrc
- .replace(/^function fireFailure/, 'function')
+ .replace(/^function\* failureRun/, 'function*')
.replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${funny ? 'funny' : t}'))return;opts.splice(0,opts.length,['${funny ? 'funny' : t}',1]);let tot=opts.reduce`)
.replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`);
ev('window.__ff=' + patched);
ev('S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute()');
- ev('__ff()');
+ ev('runNow(__ff())');
ev('dayTick()');
}
const evSrc = ev('fireEvent.toString()');
diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js
index c0bb94c..95194de 100644
--- a/tests/gameplay-rules.test.js
+++ b/tests/gameplay-rules.test.js
@@ -107,9 +107,9 @@ const REAL_NAMES = [
// Tier 1s and carriers
'AT&T', 'Bell Aliant', 'BICS', 'Cogent', 'GlobalConnect', 'GTT', 'Hurricane Electric', 'Level 3', 'Level3', 'Liquid', 'Liquid Intelligent Technologies', 'Lumen', 'Northwestel', 'NTT', 'Orange', 'PCCW', 'SaskTel', 'Seacom', 'Singtel', 'Sparkle', 'Tata', 'Tata Communications', 'Telia', 'Telxius', 'Tusass', 'Vodafone', 'Zayo',
// content and clouds
- 'Akamai', 'Alibaba Cloud', 'Amazon', 'Amazon Web Services', 'AWS', 'Baidu', 'ByteDance', 'Cloudflare', 'Facebook', 'Fastly', 'Google', 'Mercado Libre', 'Meta', 'Microsoft', 'Netflix', 'Tencent', 'TikTok', 'VK', 'VKontakte', 'Yandex',
+ 'Akamai', 'Alibaba Cloud', 'Amazon', 'Amazon Web Services', 'AWS', 'Baidu', 'ByteDance', 'Cloudflare', 'Facebook', 'Fastly', 'Google', 'Mercado Libre', 'Meta', 'Microsoft', 'Netflix', 'OVH', 'OVHcloud', 'Scaleway', 'Tencent', 'TikTok', 'VK', 'VKontakte', 'Yandex',
// eyeballs and incumbents
- ', ', 'A1', 'A1 Telekom Austria', 'Afghan Telecom', 'Africell', 'Airtel', 'AIS', 'Algérie Télécom', 'Altibox', 'Altice', 'America Movil', 'Andorra Telecom', 'Angola Cables', 'Antel', 'Areeba', 'ASTCA', 'ATH Kiribati', 'Aussie Broadband', 'AWCC', 'Azercell', 'Aztelekom', 'Batelco', 'Belize Telemedia', 'Bell', 'Bell Canada', 'Belong', 'Beltelecom', 'Bemobile', 'Bezeq International', 'BH Telecom', 'Bhutan Telecom', 'Bitė', 'Brisanet', 'BT', 'BTC', 'Cable & Wireless', 'Cable Bahamas', 'Cablenet', 'Celtiis', 'Cenpac', 'Comores Telecom', 'Congo Telecom', 'Crnogorski Telekom', 'CST', 'Cyta', 'Earthlink', 'Econet', 'EPTC', 'EriTel', 'FL1', 'FSM Telecommunications Corporation', 'Gabon Telecom', 'Gamtel', 'GETESA', 'GO', 'Guyana Telephone & Telegraph', 'Hoi Internet', 'Hormuud', 'Hrvatski Telekom', 'Kazakhtelecom', 'Kcell', 'Kyrgyztelecom', 'L", ', 'Lao Telecom', 'Libyana', 'LTT', 'Magticom', 'Mattel', 'Mauritel', 'MCI', 'Melita', 'MobiCom', 'Moldtelecom', 'Monaco Telecom', 'MPT', 'Muni', 'Natcom', 'Ncell', 'Nepal Telecom', 'Niger Telecoms', 'O!', 'Ocean Link', 'Ogero', 'One Albania', 'Partner', 'SAFITEL', 'SBIN', 'Silknet', 'Slovak Telekom', 'SMART', 'Smart Axiata', 'Somtel', 'Speednet', 'Star JV', 'Sudani', 'Sudatel', 'Syrian Telecom', 'Syriatel', 'Tashi InfoComm', 'TashiCell', 'TCI', 'Team Telecom Armenia', 'Telecel', 'Telecom Liechtenstein', 'Telecom Vanuatu', 'Telekom Slovenije', 'Telenet San Marino', 'Telesur', 'Telia Lietuva', 'Timor Telecom', 'TNM', 'Togocom', 'Tojiktelecom', 'touch', 'Turkmentelecom', 'Tuvalu Telecommunications Corporation', 'Ucom', 'Unified National Networks', 'Unitel', 'Univision', 'UNN', 'Uztelecom', 'YemenNet', 'Zain',
+ ', ', 'A1', 'A1 Telekom Austria', 'Afghan Telecom', 'Africell', 'Airtel', 'AIS', 'Algérie Télécom', 'Altibox', 'Altice', 'America Movil', 'Andorra Telecom', 'Angola Cables', 'Antel', 'Areeba', 'ASTCA', 'ATH Kiribati', 'Aussie Broadband', 'AWCC', 'Azercell', 'Aztelekom', 'Batelco', 'Belize Telemedia', 'Bell', 'Bell Canada', 'Belong', 'Beltelecom', 'Bemobile', 'Bezeq International', 'BH Telecom', 'Bhutan Telecom', 'Bitė', 'Bouygues', 'Bouygues Telecom', 'Brisanet', 'BT', 'BTC', 'Cable & Wireless', 'Cable Bahamas', 'Cablenet', 'Celtiis', 'Cenpac', 'Comores Telecom', 'Congo Telecom', 'Crnogorski Telekom', 'CST', 'Cyta', 'Earthlink', 'Econet', 'EPTC', 'EriTel', 'FL1', 'Free', 'FSM Telecommunications Corporation', 'Gabon Telecom', 'Gamtel', 'GETESA', 'GO', 'Guyana Telephone & Telegraph', 'Hoi Internet', 'Hormuud', 'Hrvatski Telekom', 'Kazakhtelecom', 'Kcell', 'Kyrgyztelecom', 'L", ', 'Lao Telecom', 'Libyana', 'LTT', 'Magticom', 'Mattel', 'Mauritel', 'MCI', 'Melita', 'MobiCom', 'Moldtelecom', 'Monaco Telecom', 'MPT', 'Muni', 'Natcom', 'Ncell', 'Nepal Telecom', 'Niger Telecoms', 'O!', 'Ocean Link', 'Ogero', 'One Albania', 'Partner', 'SAFITEL', 'SBIN', 'SFR', 'Silknet', 'Slovak Telekom', 'SMART', 'Smart Axiata', 'Somtel', 'Speednet', 'Star JV', 'Sudani', 'Sudatel', 'Syrian Telecom', 'Syriatel', 'Tashi InfoComm', 'TashiCell', 'TCI', 'Team Telecom Armenia', 'Telecel', 'Telecom Liechtenstein', 'Telecom Vanuatu', 'Telekom Slovenije', 'Telenet San Marino', 'Telesur', 'Telia Lietuva', 'Timor Telecom', 'TNM', 'Togocom', 'Tojiktelecom', 'touch', 'Turkmentelecom', 'Tuvalu Telecommunications Corporation', 'Ucom', 'Unified National Networks', 'Unitel', 'Univision', 'UNN', 'Uztelecom', 'YemenNet', 'Zain',
// exchanges and data centers
'AMS-IX', 'ANIX', 'Any2', 'ArmIX', 'BALT-IX', 'BCIX', 'BENIN-IX', 'BFIX', 'BHNIX', 'Borneo-IX', 'btIX', 'BY-IX', 'CAMIX', 'CIX', 'CNX', 'CoreSite', 'CyIX', 'DANIX', 'DE-CIX', 'DigiCo', 'Digital Realty', 'Equinix', 'France-IX', 'GABIX', 'GREX', 'HIX', 'Interxion', 'IRAQ-IXP', 'iseek', 'IX.br', 'ix.kw', 'IXP-GUINEE', 'IXP-HN', 'IXP.ge', 'IXP.mk', 'IXPN', 'JPIX', 'KAZ-GOV-IX', 'KG-IX', 'KIVIX', 'LebIX', 'LINX', 'LIONEX1', 'Manama IX', 'MD-IX', 'Michcom-IX', 'MISPA-IXP', 'MIXP', 'MLIX', 'NAPAfrica', 'NetIX', 'NEXTDC', 'NIX', 'NIX.SK', 'NIXA', 'NL-ix', 'npIX', 'RegPEX', 'SIX', 'SIX.SK', 'SIXP', 'SKNIX', 'SNS-IX', 'SUR-IX', 'SVGIX', 'Tehran IX', 'Telehouse', 'TGIX', 'TIX', 'TJ-IX', 'VIX.VU', 'VNIX-HN', 'WIX-NZ', 'WLG-IX',
// cables
@@ -257,7 +257,7 @@ test('M3: every subsystem that can annoy the player reads a rule', () => {
// [function, what it must read]
const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'],
['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'],
- ['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"], ['fireFailure', 'shipsOn()'],
+ ['dfBuildDays', 'leadDays'], ['dayPreRun', "rule('clock')"], ['snub', "rule('market')"], ['failureRun', 'shipsOn()'],
['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()'],
['ip4On', "rule('ip4')"], ['ip4Fits', 'ip4On()'], ['ip4Money', 'ip4On()'], ['ip4Day', 'ip4On()']];
fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)');
diff --git a/tests/gpu-bench.test.js b/tests/gpu-bench.test.js
index e27836e..5c8fb85 100644
--- a/tests/gpu-bench.test.js
+++ b/tests/gpu-bench.test.js
@@ -20,9 +20,10 @@ function open(cfg = {}) {
}
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
-// A day in flight in the worker when the trial ends: rwDone() would run its dayPost() whenever the answer comes.
-const IN_FLIGHT = `window.__old=S;RW.seq=41;RW.job={seq:41,d:201,gen:RW.gen-1,t:0};window.__posts=[];
- dayPost=function(d){__posts.push({d,old:S===__old});};`;
+// A day in flight in the worker when the trial ends: rwDone() would go on with its steps (the rest of the day, a
+// generator, 10-day-tick.js) whenever the answer comes. This one only notes on which save it ends.
+const IN_FLIGHT = `window.__old=S;window.__posts=[];const g=(function*(){yield;__posts.push({d:201,old:S===__old});})();g.next();
+ RW.seq=41;RW.job={seq:41,g,gen:RW.gen-1,t:0,state:S};`;
test('a late answer from the route worker lands on the trial it belongs to, not the next one', async () => {
const { ev, errors } = open();
diff --git a/tests/i18n.test.js b/tests/i18n.test.js
index a7ce585..bd8d7a3 100644
--- a/tests/i18n.test.js
+++ b/tests/i18n.test.js
@@ -38,14 +38,14 @@ function tour(ev) {
['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()'],
// The build standard sheet with every target set (and the game left as it was).
['build standard', "{const was=S.popStd;S.popStd={g:3,rt:2,site2:true,gen:true,lag:2,split:true,ix:true,pni:2,sys:'roadm',opt:'fast',wv:2};ACT.bstdOpen();S.popStd=was;closeModal()}"]]) step(label, src);
- const failSrc = ev('fireFailure.toString()');
+ const failSrc = ev('failureRun.toString()');
for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) {
const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t;
- const patched = failSrc.replace(/^function fireFailure/, 'function')
+ const patched = failSrc.replace(/^function\* failureRun/, 'function*')
.replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${kind}'))return;opts.splice(0,opts.length,['${kind}',1]);let tot=opts.reduce`)
.replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`);
- assert.ok(patched.includes(`['${kind}',1]`) && patched.includes(`f.includes('${t}')`), 'fireFailure still has the hooks this tour forces');
- step('failure ' + t, `window.__ff=${patched};S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute();__ff();dayTick();ACT.leftTab({t:'noc'})`);
+ assert.ok(patched.includes(`['${kind}',1]`) && patched.includes(`f.includes('${t}')`), 'failureRun() still has the hooks this tour forces');
+ step('failure ' + t, `window.__ff=${patched};S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute();runNow(__ff());dayTick();ACT.leftTab({t:'noc'})`);
}
// A cable the Baltic event can hit, so the anchor badge does not depend on what the random days built.
step('baltic cable', "if(!S.pops.hel)ACT.buildPop({city:'hel'});UI.via='clion';openLinkModal('fra','hel');ACT.buildLink({tier:0});closeModal();UI.via=null");
diff --git a/tests/intern-optical-upgrade.test.js b/tests/intern-optical-upgrade.test.js
index a18ad12..f55544f 100644
--- a/tests/intern-optical-upgrade.test.js
+++ b/tests/intern-optical-upgrade.test.js
@@ -6,12 +6,13 @@ const { load } = require('./harness');
// Frankfurt (transit) and Amsterdam (broadband) joined by a full Rainbow-in-a-Box fiber of 16×400G, and the long way
// round through Paris on two waves. Level 6: every line system and optic unlocked. Change Freeze: no fat fingers.
+// Annie runs the shift: Kevin would swap two line systems a night (tests/intern-personas.test.js).
const BASE = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=6;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
"for(const c of ['ams','par'])ACT.buildPop({city:c});for(const c of ['fra','ams','par']){S.pops[c].rgen=mainRG(3);S.pops[c].routers=2;}ACT.launchBB({city:'ams'});" +
"S.transit=[];ACT.buyTransit({city:'fra',net:'cog',tier:2});" +
"S.links=[{id:'f',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(16).fill('zr4'),km:450,trench:'t1',ready:0,cut:0,mo:1,pairs:1}," +
"{id:'w1',a:'fra',b:'par',kind:'wave',tier:4,km:480,cut:0,mo:1},{id:'w2',a:'par',b:'ams',kind:'wave',tier:4,km:430,cut:0,mo:1}];compute();" +
- "ACT.opsHire({id:'kevin'});S.ops.floor=0;S.ops.cap.optup=0;closeModal()";
+ "ACT.opsHire({id:'annie'});S.ops.floor=0;S.ops.cap.optup=0;closeModal()";
function game(t, extra) {
const h = load();
t.after(() => h.dom.window.close());
diff --git a/tests/intern-personas.test.js b/tests/intern-personas.test.js
new file mode 100644
index 0000000..f663cf1
--- /dev/null
+++ b/tests/intern-personas.test.js
@@ -0,0 +1,86 @@
+// The three interns run the same orders the same way, at the same salary; each is better at one part of the job.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { load } = require('./harness');
+
+const BASE = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=6;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
+ "ACT.launchBB({city:'fra'});S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()";
+function game(t, id, extra) {
+ const h = load();
+ t.after(() => h.dom.window.close());
+ h.ev(BASE);
+ if (extra) h.ev(extra);
+ h.ev(`ACT.opsHire({id:'${id}'});S.ops.floor=0;S.ops.cap={};closeModal()`);
+ return h;
+}
+
+test('the same salary, and each says what they are best at, in the hiring list and once hired', t => {
+ const h = load();
+ t.after(() => h.dom.window.close());
+ h.ev(BASE);
+ assert.ok(h.ev("Object.values(INTERNS).every(I=>I.g)"));
+ h.dom.window.innerWidth = 360;
+ h.ev('opsModal()');
+ const txt = h.ev("document.getElementById('modalCard').textContent");
+ for (const s of [/Best at peering/, /Best at maintenance/, /Best at planning ahead/]) assert.match(txt, s);
+ assert.equal(h.ev("document.querySelectorAll('#modalCard [data-act=opsHire]').length"), 3);
+ assert.equal(h.ev("[...document.querySelectorAll('#modalCard [data-act=opsHire]')].every(b=>b.textContent.includes(fmt$(INTERN_MO)))"), true, 'one salary for all');
+ h.ev("ACT.opsHire({id:'tracy'})");
+ assert.match(h.ev("document.getElementById('modalCard').textContent"), /Best at planning ahead/);
+ assert.deepEqual(h.errors, []);
+});
+
+test('Annie peers every day and orders PNIs twice a week; the others weekly', t => {
+ const ix = "ACT.buyIx({city:'fra',tier:0,signed:true});compute()";
+ for (const [id, want] of [['annie', true], ['kevin', false], ['tracy', false]]) {
+ const { ev, errors } = game(t, id, ix);
+ ev("S.ops.on.ix=true;S.day=15;opsDay(S.day)");
+ assert.equal(ev('Object.keys(S.rs).length>0'), want, `${id} on a Tuesday`);
+ // How often the PNI order looks for networks to order from, over one week.
+ ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}");
+ assert.equal(ev('__pb'), want ? 2 : 1, `${id}: PNI rounds a week`);
+ assert.deepEqual(errors, []);
+ }
+});
+
+test('Kevin never fat-fingers, even on the unluckiest roll', t => {
+ for (const [id, want] of [['kevin', false], ['annie', true], ['tracy', true]]) {
+ const { ev, errors } = game(t, id);
+ ev("S.rules=makeRules('bgp');window.__r=Math.random;Math.random=()=>0;opsDay(S.day);Math.random=__r");
+ assert.equal(ev('S.ops.log.some(e=>e.f!==undefined)'), want, id);
+ assert.deepEqual(errors, []);
+ }
+});
+
+test('Kevin swaps two line systems a night, the others one', t => {
+ const fibers = "for(const c of ['ams','par'])ACT.buildPop({city:c});for(const c of ['fra','ams','par']){S.pops[c].rgen=mainRG(3);S.pops[c].routers=2;}" +
+ "S.links=[['f1','fra','ams'],['f2','ams','par'],['f3','par','fra'],['f4','fra','ams']].map(([id,a,b])=>({id,a,b,kind:'df',own:true,sys:'lite',ch:['zr4'],km:450,trench:id,ready:0,cut:0,mo:1,pairs:1}));compute()";
+ for (const [id, want] of [['kevin', 2], ['annie', 1], ['tracy', 1]]) {
+ const { ev, errors } = game(t, id, fibers);
+ ev("S.ops.on.optup=true;S.ops.p.optup={sys:'roadm'};opsDay(S.day)");
+ assert.equal(ev("S.links.filter(l=>l.sys==='roadm').length"), want, id);
+ assert.deepEqual(errors, []);
+ }
+});
+
+test('Tracy buys a little before it runs hot; at the same price as anyone', t => {
+ // A POP at 75% with the order set to 80%: Tracy sees 82.5% and adds a router; the others wait.
+ for (const [id, want] of [['tracy', 2], ['kevin', 1], ['annie', 1]]) {
+ const { ev, errors } = game(t, id);
+ ev("S.ops.on.routers=true;S.ops.p.routers={at:80,how:'add'};compute();R.nodeLoad.fra=R.nodeCap.fra*0.75");
+ const cost = ev("routerCost(S.pops.fra.rgen||0,S.pops.fra.routers||1)"), c0 = ev('S.cash');
+ ev('opsDay(S.day)');
+ assert.equal(ev('S.pops.fra.routers'), want, id);
+ if (want === 2) assert.equal(c0 - ev('S.cash'), cost, 'what Add router costs');
+ assert.deepEqual(errors, []);
+ }
+ // Transit too: a 30-day peak that the headroom just covers, but not with 10% more.
+ for (const [id, grew] of [['tracy', true], ['kevin', false]]) {
+ const { ev, errors } = game(t, id);
+ ev("S.ops.on.transit=true;S.ops.p.transit={x:1.25,prov:'have'};const t=S.transit[0];t.hist=[lagCap(PORT[t.tier].g,t.n)/1.25/1.05]");
+ const n0 = ev('JSON.stringify(S.transit.map(t=>[t.tier,t.n||1]))');
+ ev('opsDay(S.day)');
+ assert.equal(ev('JSON.stringify(S.transit.map(t=>[t.tier,t.n||1]))') !== n0, grew, id);
+ assert.deepEqual(errors, []);
+ }
+});
diff --git a/tests/issues.test.js b/tests/issues.test.js
index c59b76d..55ae84d 100644
--- a/tests/issues.test.js
+++ b/tests/issues.test.js
@@ -256,8 +256,8 @@ test('LACP trouble, partial packet loss and PMTUD black holes fire, hurt and cle
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.lagT({id:S.transit[0].id,d:1});ACT.buyIx({city:'ams',tier:1});ACT.lagIx({city:'ams',d:1});S.day=100;compute()");
- const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function').replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce");
- const fire = (t) => { ev('window.__ff=' + src.replace('type=pick(f);}', `type='${t}';}`)); ev('__ff();compute()'); };
+ const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*').replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce");
+ const fire = (t) => { ev('window.__ff=' + src.replace('type=pick(f);}', `type='${t}';}`)); ev('runNow(__ff());compute()'); };
for (let i = 0; i < 12; i++) { fire('lacp'); }
assert.ok(ev("S.inc.some(i=>i.type==='lacp')"), 'LACP incidents fire');
assert.ok(ev("S.transit[0].lacp||S.ev.ixlacp"), 'a LAG is degraded');
@@ -600,17 +600,18 @@ test('#66 #68 subsea optics: engineered glass reaches further, and the same limi
// counted as land glass it would be 400G, which is what #66 saw
ev("S.links.find(l=>l.id==='oc').sub=false;compute()");
assert.equal(ev("dfCap(S.links.find(l=>l.id==='oc'))"), 400);
- // leased waves: transatlantic London–New York still takes 6.4T (4×1.6T); Paris–Ashburn tops out at 800G
+ // leased waves: transatlantic London–New York still takes 6.4T (4×1.6T); Nantes–Ashburn tops out at 800G
assert.equal(ev("subWaveWhy(5,cablesFor('lon','nyc')[0].km,true)"), '');
- assert.match(ev("subWaveWhy(4,cablesFor('par','ash')[0].km,true)"), /at most 1.2T per carrier/);
- assert.equal(ev("LT[subMaxTier(cablesFor('par','ash')[0].km)].n"), '800G');
+ assert.match(ev("subWaveWhy(4,cablesFor('nte','ash')[0].km,true)"), /at most 1.2T per carrier/);
+ assert.equal(ev("LT[subMaxTier(cablesFor('nte','ash')[0].km)].n"), '800G');
assert.equal(ev("LT[subMaxTier(14000)].n"), '400G', 'the longest cables carry 400G waves');
assert.equal(ev("subWaveWhy(5,4000,false)"), '', 'land waves are not capped this way');
// buying a too-big wave is refused; an old one keeps running
- ev("UI.pending={a:'par',b:'ash'};UI.via=cablesFor('par','ash')[0].cid;const n=S.links.length;ACT.buildLink({tier:4});window.__d=S.links.length-n");
- assert.equal(ev('__d'), 0, 'no 1.6T wave across 6,670 km');
+ ev("ACT.buildPop({city:'nte'});S.pops.nte.rgen=3;compute()");
+ ev("UI.pending={a:'nte',b:'ash'};UI.via=cablesFor('nte','ash')[0].cid;const n=S.links.length;ACT.buildLink({tier:4});window.__d=S.links.length-n");
+ assert.equal(ev('__d'), 0, 'no 1.6T wave across 6,473 km');
ev("ACT.buildLink({tier:3})");
- const w = "S.links.find(l=>l.kind==='wave'&&l.a==='par')";
+ const w = "S.links.find(l=>l.kind==='wave'&&(l.a==='nte'||l.b==='nte'))";
assert.equal(ev(`${w}.tier`), 3, '800G is fine');
ev(`ACT.upLink({id:${w}.id,tier:4})`);
assert.equal(ev(`${w}.tier`), 3, 'and it cannot be upgraded past the cable');
@@ -1315,7 +1316,7 @@ test('#134 an exchange named after its city does not repeat the city in messages
const labs = JSON.parse(ev("JSON.stringify(lagsN().filter(o=>o.k==='ix').map(o=>o.lab))"));
assert.ok(labs.includes('IX.brrr Campinas LAG'), labs.join(' | '));
assert.ok(labs.some(l => / LAG in Frankfurt$/.test(l)), labs.join(' | '));
- ev("S.inc=[];eval('('+fireFailure.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()");
+ ev("S.inc=[];runNow(eval('('+failureRun.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')())");
const msg = ev("S.inc.map(i=>i.msg).join(' ')");
assert.match(msg, /IX\.brrr Campinas/);
assert.doesNotMatch(msg, /in Campinas/);
diff --git a/tests/land-islands.test.js b/tests/land-islands.test.js
new file mode 100644
index 0000000..a52e6a1
--- /dev/null
+++ b/tests/land-islands.test.js
@@ -0,0 +1,35 @@
+// "Afraid of sharks" (a path that never goes under the sea, 60-requirements.js) asked for every customer in the daily
+// mood check: the land islands are worked out once for the check (TERR), and two cities have a land path exactly when
+// they are on one island. Same answers as walking the links each time, with links cut, subsea or not, and cities alone.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { load } = require('./harness');
+
+const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
+
+test('land islands answer "a path without subsea" as walking the links does', () => {
+ const { ev, errors } = load({ seed: 3 });
+ ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;closeModal();compute();`);
+ const cmp = () => JSON.parse(ev(`(()=>{const cs=Object.keys(S.pops).concat(['sin','nyc','lon',null,undefined]);let n=0,yes=0;const bad=[];
+ for(const a of cs.slice(0,60))for(const b of cs){if(!a)continue;TERR=null;const w=terrestrialPath(a,b);TERR={S,gen:RW.gen,m:null};const i=terrestrialPath(a,b);TERR=null;
+ n++;if(w)yes++;if(w!==i)bad.push(a+'-'+b);}return JSON.stringify({n,yes,bad:bad.slice(0,5)});})()`));
+ let r = cmp();
+ assert.deepEqual(r.bad, []);
+ assert.ok(r.yes > 20 && r.yes < r.n, `pairs with a land path: ${r.yes} of ${r.n}`);
+ // Cut a third of the land links (an island splits) and the answers still agree.
+ ev("S.links.forEach((l,i)=>{if(!l.sub&&i%3===0)l.cut=S.day+5;})");
+ const r2 = cmp();
+ assert.deepEqual(r2.bad, []);
+ assert.ok(r2.yes < r.yes, `fewer land paths once links are cut: ${r2.yes} < ${r.yes}`);
+ // Kept for the day, the islands follow an action that routes (RW.gen), and are never used for another game.
+ ev("TERR={S,gen:RW.gen,m:null};terrestrialPath('fra','ams');window.__m=TERR.m;S.links.forEach(l=>{if(!l.sub)l.cut=0;});compute();");
+ assert.equal(ev("terrestrialPath('fra','ams')===(()=>{const t=TERR;TERR=null;const w=terrestrialPath('fra','ams');TERR=t;return w;})()&&TERR.m!==__m"), true, 'made again after routing');
+ ev("const S0=S;S={...S,links:[]};window.__r=terrestrialPath('fra','ams');S=S0;TERR=null;");
+ assert.equal(ev('__r'), false, 'another game walks its own links');
+ // The daily check leaves no islands behind (a later question walks the links of the moment).
+ ev('S.nextFail=S.nextEvent=S.day+99;dayTick()');
+ assert.equal(ev('TERR'), null);
+ assert.deepEqual(errors, []);
+});
diff --git a/tests/peering-desk.test.js b/tests/peering-desk.test.js
index 0bb4ad9..515c245 100644
--- a/tests/peering-desk.test.js
+++ b/tests/peering-desk.test.js
@@ -109,9 +109,9 @@ test('old saves with inbox, max-prefix and Large Peering Model state load and pl
test('max-prefix incidents can no longer fire', () => {
const { ev, errors } = load();
setup(ev);
- assert.equal(ev("fireFailure.toString().includes('maxpfx')"), false);
- ev("S.day=100;const src=fireFailure.toString().replace(/^function fireFailure/,'function').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')");
- ev("__reseed(7);for(let i=0;i<200;i++){__ff();S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}");
+ assert.equal(ev("failureRun.toString().includes('maxpfx')"), false);
+ ev("S.day=100;const src=failureRun.toString().replace(/^function\* failureRun/,'function*').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')");
+ ev("__reseed(7);for(let i=0;i<200;i++){runNow(__ff());S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}");
assert.equal(ev('!!window.__mp'), false);
assert.equal(ev("typeof inboxDay+typeof ibx+typeof ACT.inboxRaiseAll+typeof ACT.inboxBot"), 'undefinedundefinedundefinedundefined');
assert.deepEqual(errors, []);
diff --git a/tests/peering.test.js b/tests/peering.test.js
index ab2d0a7..0bfe532 100644
--- a/tests/peering.test.js
+++ b/tests/peering.test.js
@@ -204,10 +204,10 @@ test('a peer at a rival exchange can de-peer you without stopping the game', ()
test('an IX meltdown at a rival exchange names it, and a failing day tick does not stop the game', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams~2',tier:1});S.day=100");
- const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function')
+ const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*')
.replace('let tot=opts.reduce', "opts.splice(0,opts.length,['ixloop',1]);let tot=opts.reduce");
ev('window.__ff=' + src);
- ev('__ff()');
+ ev('runNow(__ff())');
assert.ok(ev("S.inc.find(i=>i.type==='ixloop').msg.includes(ixName('ams~2'))"));
// a tick that throws is caught, reported once, and the loop keeps going
ev("const dt0=dayTick;window.dayTick=()=>{throw new Error('boom')};UI.speed=1;acc=DAY_MS;last=0;frame(16);window.dayTick=dt0");
diff --git a/tests/regions.test.js b/tests/regions.test.js
index b9927fd..88a41a9 100644
--- a/tests/regions.test.js
+++ b/tests/regions.test.js
@@ -458,9 +458,9 @@ test('#76 Kansas City, Calgary, Vancouver and Ottawa, with two more Canadian gia
assert.equal(ev("NET.tlu.up.every(id=>NET[id].type==='t1')&&NET.rgc.up.every(id=>NET[id].type==='t1')"), true);
// a cut on a Canadian link is often a beaver
ev("ACT.buildPop({city:'van'});ACT.buildPop({city:'cal'});S.links=[];UI.via=null;openLinkModal('van','cal');ACT.buildLink({tier:1});closeModal()");
- const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function');
+ const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*');
ev('window.__ff=' + src.replace('type=pick(f);}', "type='cut';}"));
- ev("for(let i=0;i<40&&!(S.stats.f&&S.stats.f.beaver);i++){for(const l of S.links)l.cut=0;S.inc=[];__ff();}");
+ ev("for(let i=0;i<40&&!(S.stats.f&&S.stats.f.beaver);i++){for(const l of S.links)l.cut=0;S.inc=[];runNow(__ff());}");
assert.ok(ev("!!(S.stats.f&&S.stats.f.beaver)"), 'a beaver chewed through it');
ev('checkBadges()');
assert.ok(ev("(S.badges||[]).includes('beaver')||!!(S.badge&&S.badge.beaver)||BADGES.find(b=>b.id==='beaver').ok()"), 'Dam It');
@@ -504,13 +504,13 @@ test('#79 Benelux: Brussels red tape, the Flanders duopoly, Oostkamp trawlers an
assert.ok(ev("cablesFor('lon','oos').some(c=>c.cid==='clementine')"));
ev("ACT.buildPop({city:'lon'});ACT.buildPop({city:'oos'});S.links=[];UI.lmode='wave';UI.via='clementine';openLinkModal('lon','oos');ACT.buildLink({tier:1});closeModal()");
assert.equal(ev("S.links.length&&S.links[0].sub"), true);
- const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function');
+ const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*');
ev('window.__ff=' + src.replace('type=pick(f);}', "type='cut';}"));
- ev("for(let i=0;i<30&&!S.log.some(e=>/trawler|wind-farm/.test(e.t));i++){for(const l of S.links)l.cut=0;S.inc=[];__ff();}");
+ ev("for(let i=0;i<30&&!S.log.some(e=>/trawler|wind-farm/.test(e.t));i++){for(const l of S.links)l.cut=0;S.inc=[];runNow(__ff());}");
assert.ok(ev("S.log.some(e=>/trawler|wind-farm/.test(e.t))"), 'a North Sea boat found the cable');
// Bettembourg's chillers run on steam from burning waste wood
ev("S.pops={bet:{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}};window.__ac=" + src.replace('type=pick(f);}', "type='ac';}"));
- ev("for(let i=0;i<20&&!S.log.some(e=>/waste-wood/.test(e.t));i++){S.pops.bet.hot=0;S.inc=[];__ac();}");
+ ev("for(let i=0;i<20&&!S.log.some(e=>/waste-wood/.test(e.t));i++){S.pops.bet.hot=0;S.inc=[];runNow(__ac());}");
assert.ok(ev("S.log.some(e=>/waste-wood/.test(e.t))"), 'the forestry strike');
assert.deepEqual(errors, []);
});
@@ -692,18 +692,18 @@ test('Australian failures: cockatoos, kangaroos and emus cut land fiber, and rou
ev("ACT.pickStart({city:'syd'});ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0");
ev("ACT.buildPop({city:'mel'});S.links=[];UI.via=null;UI.lmode='wave';openLinkModal('syd','mel');ACT.buildLink({tier:1});closeModal()");
assert.equal(ev('S.links.length'), 1);
- const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function');
+ const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*');
const AU = /cockatoo|kangaroo|backhoe|emus|Bushfire|copper/;
ev('window.__cut=' + src.replace('type=pick(f);}', "type='cut';}"));
let seen = false;
- for (let i = 0; i < 30 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];__cut()'); seen = AU.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
+ for (let i = 0; i < 30 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];runNow(__cut())'); seen = AU.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
assert.ok(seen, 'an Australian wildlife cut');
seen = false;
- for (let i = 0; i < 80 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];__cut()'); seen = /copper/.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
+ for (let i = 0; i < 80 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];runNow(__cut())'); seen = /copper/.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
assert.ok(seen, 'copper thieves who find fiber');
ev('window.__crash=' + src.replace('type=pick(f);}', "type='crash';}"));
seen = false;
- for (let i = 0; i < 40 && !seen; i++) { ev('for(const c in S.pops){S.pops[c].down=0;S.pops[c].routers=1;}S.inc=[];__crash()'); seen = /Floptus|huntsman/.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
+ for (let i = 0; i < 40 && !seen; i++) { ev('for(const c in S.pops){S.pops[c].down=0;S.pops[c].routers=1;}S.inc=[];runNow(__crash())'); seen = /Floptus|huntsman/.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
assert.ok(seen, 'an Australian router crash');
assert.deepEqual(errors, []);
});
diff --git a/tests/route-worker.test.js b/tests/route-worker.test.js
index 30256d9..116206a 100644
--- a/tests/route-worker.test.js
+++ b/tests/route-worker.test.js
@@ -41,7 +41,8 @@ test('a day split around its routing is the same day; tests never use the worker
const a = big(t), b = big(t);
for (const h of [a, b]) h.ev('S.nextFail=S.nextEvent=S.day+99;__reseed(4242)');
a.ev('for(let i=0;i<3;i++)dayTick()');
- b.ev('for(let i=0;i<3;i++){const d=dayPre();compute();dayPost(d);}');
+ // Every routing it asks for done by hand (a DAY_REST is only a place to let a frame through, not a routing).
+ b.ev("for(let i=0;i<3;i++){const g=dayRun();for(let s=g.next();!s.done;s=g.next())if(s.value!==DAY_REST)compute();}");
const st = "JSON.stringify({day:S.day,cash:S.cash,moods:S.biz.map(b=>b.mood),offers:S.offers.length,served:R.served})";
assert.equal(b.ev(st), a.ev(st));
assert.equal(a.ev('rwOn()'), false);
diff --git a/tests/sales-renewals.test.js b/tests/sales-renewals.test.js
new file mode 100644
index 0000000..606a005
--- /dev/null
+++ b/tests/sales-renewals.test.js
@@ -0,0 +1,105 @@
+// The sales desk answers renewal haggles (39-sales-renewals.js): the engineer talks technology, the shark gives
+// nothing away, the CEO settles it on the golf course. Every answer is a hash of the contract, so the tests make
+// many customers and look at what each kind of salesperson does with them, and never depend on luck.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { load } = require('./harness');
+
+const start = "ACT.start({});S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});compute()";
+// A customer 27 days from the end of its term, asking $700 instead of the $1,000 it pays: the desk answers it today.
+const hag = (id, type = 'dia', extra = '') => `{id:'${id}',city:'ams',city2:null,name:'${id}',type:'${type}',bw:5,rate:1000,reqs:[],mood:90,since:S.day-800,te:S.day+27,mk:1,hag:{rate:700,until:S.day+27}${extra}}`;
+// What one kind of salesperson does with n customers of a type: the outcome of each, its new rate and term.
+const run = (ev, p, type, n = 300) => {
+ ev(`S.sales.p='${p}';S.biz=S.biz.filter(b=>!b.hag)`);
+ return JSON.parse(ev(`(()=>{const out=[];for(let i=0;i<${n};i++){const b=${hag('x', type)};b.id=b.name='${p}-${type}-'+i;S.biz.push(b);const te0=b.te,how=slRenOne(b,'${p}');
+ out.push({how,rate:b.rate,te:b.te-te0,hag:!!b.hag,here:S.biz.includes(b),reqs:b.reqs.length});}return JSON.stringify(out);})()`));
+};
+const share = (o, how) => o.filter((x) => x.how === how).length / o.length;
+
+test('off until you switch it on; the desk answers three days into the haggle, unless you did first', () => {
+ const { ev, errors } = load();
+ ev(start);
+ ev("S.biz.push(" + hag('early') + ");S.biz.find(b=>b.id==='early').hag.until=S.day+29;S.biz.find(b=>b.id==='early').te=S.day+29");
+ ev("S.biz.push(" + hag('due') + ")");
+ ev('slRenDay(S.day)');
+ assert.ok(ev("S.biz.every(b=>!b.id.match(/early|due/)||b.hag)"), 'nobody at the desk: nothing happens');
+ ev("ACT.salesHire({id:'eng'})");
+ ev('slRenDay(S.day)');
+ assert.ok(ev("S.biz.find(b=>b.id==='due').hag"), 'someone at the desk, but the switch is off');
+ assert.equal(ev('!!S.slAuto.ren'), false);
+ ev('ACT.salesOpen()');
+ assert.match(ev("document.getElementById('modal').innerHTML"), /data-act="salesRen"/, 'the switch is in the sales sheet');
+ ev('ACT.salesRen()');
+ assert.equal(ev('S.slAuto.ren'), true);
+ ev("UI.left='deals';renderLeft()");
+ assert.match(ev("document.getElementById('left').innerHTML"), /answers this on/, 'the haggle says when the desk answers');
+ ev('slRenDay(S.day)');
+ assert.equal(ev("!!S.biz.find(b=>b.id==='due').hag"), false, 'three days in: answered');
+ assert.equal(ev("!!S.biz.find(b=>b.id==='early').hag"), true, 'one day in: not yet, you can still answer it');
+ ev("ACT.renewMatch({id:'early'})");
+ assert.equal(ev("S.biz.find(b=>b.id==='early').rate"), 700, 'and your answer is the one that counts');
+ assert.deepEqual(errors, []);
+});
+
+test('the engineer: business customers get their discount, nerds a tour of the network, and nobody leaves', () => {
+ const { ev, errors } = load();
+ ev(start);
+ ev("ACT.salesHire({id:'eng'})");
+ const biz = run(ev, 'eng', 'dia');
+ assert.ok(biz.every((x) => x.how === 'cave' && x.rate === 700 && x.here), 'every business customer renews at what it asked');
+ const nerds = run(ev, 'eng', 'hft');
+ assert.ok(nerds.every((x) => x.here && !x.hag), 'nobody leaves');
+ const tech = share(nerds, 'tech');
+ assert.ok(tech > 0.6 && tech < 0.8, `most nerds pay the market price (${Math.round(tech * 100)}%)`);
+ const fair = ev("clFair(" + hag('f', 'hft') + ")");
+ for (const x of nerds) assert.equal(x.rate, x.how === 'tech' ? Math.max(700, Math.min(1000, fair)) : 850);
+ assert.deepEqual(errors, []);
+});
+
+test('the shark: the old price, a fee for the save and fresh promises; some walk, nerds most of all', () => {
+ const { ev, errors } = load();
+ ev(start);
+ ev("ACT.salesHire({id:'shark'})");
+ const cash = ev('S.cash');
+ const o = run(ev, 'shark', 'dia');
+ const hold = o.filter((x) => x.how === 'hold');
+ assert.ok(hold.length / o.length > 0.4 && hold.length / o.length < 0.6, `most renew at the old price (${hold.length} of ${o.length})`);
+ assert.ok(hold.every((x) => x.rate === 1000 && x.here));
+ assert.equal(cash - ev('S.cash'), hold.length * 5 * 300, 'a month of what he saved you, for each');
+ assert.ok(hold.some((x) => x.reqs > 0), 'with a promise now and then');
+ const walk = share(o, 'walk'), nerdWalk = share(run(ev, 'shark', 'hft'), 'walk');
+ assert.ok(walk > 0.05 && walk < 0.2, `some walk (${Math.round(walk * 100)}%)`);
+ assert.ok(nerdWalk > walk * 2, `nerds walk more (${Math.round(nerdWalk * 100)}%)`);
+ assert.ok(o.filter((x) => x.how === 'walk').every((x) => !x.here), 'and are gone');
+ assert.ok(o.filter((x) => x.how === 'mid').every((x) => x.rate === 850));
+ assert.deepEqual(errors, []);
+});
+
+test('the CEO: a deeper discount for twice the term, a quick yes, or a fight; all from hashes', () => {
+ const { ev, errors } = load();
+ ev(start);
+ ev("ACT.salesHire({id:'ceo'})");
+ ev('window.__r=0;window.__r0=Math.random;Math.random=()=>{__r++;return __r0();};');
+ const o = run(ev, 'ceo', 'dia');
+ ev('Math.random=__r0');
+ assert.equal(ev('__r'), 0, 'no draws from the game\'s random stream');
+ const golf = o.filter((x) => x.how === 'golf'), yes = o.filter((x) => x.how === 'yes'), fight = o.filter((x) => x.how === 'fight');
+ assert.ok(fight.length / o.length > 0.15 && fight.length / o.length < 0.35, `${fight.length} fights`);
+ assert.ok(golf.length && golf.every((x) => x.rate === 630 && x.here), 'golf: 10% under what they asked');
+ const term = (l) => l.reduce((a, x) => a + x.te, 0) / l.length;
+ assert.ok(term(golf) > term(yes) * 1.6, `for a contract about twice as long (${Math.round(term(golf))} vs ${Math.round(term(yes))} days)`);
+ assert.ok(yes.every((x) => x.rate === 700), 'a quick yes is what they asked');
+ assert.ok(fight.every((x) => !x.here));
+ assert.deepEqual(errors, []);
+});
+
+test('saves remember the switch, and an old save has it off', () => {
+ const { ev, errors } = load();
+ ev(start);
+ ev("ACT.salesHire({id:'shark'});ACT.salesRen()");
+ const s = JSON.parse(ev('JSON.stringify(packSave(S))'));
+ assert.equal(JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})).slAuto)`)).ren, true);
+ s.slAuto.ren = 'yes please'; assert.equal(JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})).slAuto)`)).ren, undefined);
+ delete s.slAuto.ren; assert.equal(JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(s))})).slAuto)`)).ren, undefined);
+ assert.deepEqual(errors, []);
+});
diff --git a/tests/scenarios-playtest.test.js b/tests/scenarios-playtest.test.js
index 4e98b7d..51287df 100644
--- a/tests/scenarios-playtest.test.js
+++ b/tests/scenarios-playtest.test.js
@@ -18,7 +18,7 @@ const PLAY = {
stg: { ref: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['link', 'fra', 'ams', 1], ['ix', 'ams'], ['bb', 'ams'], ['link', 'ams', 'lon', 1], ['ix', 'lon'], ['bb', 'lon'], ['link', 'fra', 'par', 1], ['ix', 'par'], ['bb', 'par'], ['hire', ['routers', 'repair', 'caches', 'pni', 'ix', 'sales'], { pni: { paid: true } }], ['link', 'stg', 'muc', 1], ['ix', 'muc'], ['bb', 'muc'], ['wait', 120], ['pnis'], ['link', 'lon', 'nyc', 2], ['ix', 'nyc'], ['bb', 'nyc'], ['wait', 200], ['pnis']],
win: [120, 240], cheese: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['loans'], ['hire', ['routers', 'repair']]], by: null },
// The other way round the planet: Paris, New York, Los Angeles, Tokyo, Hong Kong, Singapore.
- redsea: { ref: [...home('mrs'), ['link', 'mrs', 'par', 1], ['bb', 'par'], ['ix', 'par'], ['link', 'par', 'nyc', 1, 'amitie'], ['tr', 'nyc', 1], ['ix', 'nyc'], ['link', 'nyc', 'lax', 1], ['ix', 'lax'], ['tr', 'lax', 1], ['link', 'lax', 'tok', 1, 'jup'], ['bb', 'tok'], ['tr', 'tok', 1], ['ix', 'tok'], ['link', 'tok', 'hkg', 1, 'apg'], ['bb', 'hkg'], ['tr', 'hkg', 1], ['ix', 'hkg'], ['link', 'hkg', 'sin', 1], ['bb', 'sin'], ['tr', 'sin', 1], ['ix', 'sin'], HIRE],
+ redsea: { ref: [...home('mrs'), ['link', 'mrs', 'par', 1], ['bb', 'par'], ['ix', 'par'], ['link', 'par', 'bod', 1], ['link', 'bod', 'nyc', 1, 'amitie'], ['tr', 'nyc', 1], ['ix', 'nyc'], ['link', 'nyc', 'lax', 1], ['ix', 'lax'], ['tr', 'lax', 1], ['link', 'lax', 'tok', 1, 'jup'], ['bb', 'tok'], ['tr', 'tok', 1], ['ix', 'tok'], ['link', 'tok', 'hkg', 1, 'apg'], ['bb', 'hkg'], ['tr', 'hkg', 1], ['ix', 'hkg'], ['link', 'hkg', 'sin', 1], ['bb', 'sin'], ['tr', 'sin', 1], ['ix', 'sin'], HIRE],
// 2.0.0: no more max-prefix outages to break the 30-day streak, so the reference can finish in under 100 days.
win: [80, 250], cheese: [...home('mrs'), ['loans'], ['link', 'mrs', 'sin', 1], ['bb', 'sin']], by: null },
spat: { ref: [...home('nyc'), HIRE], avoid: ['cog'], win: [50, 140], cheese: [...home('nyc'), ['hire', ['routers', 'repair']]], by: 160 },
diff --git a/tests/specialist.test.js b/tests/specialist.test.js
index 94e9f42..b3a061a 100644
--- a/tests/specialist.test.js
+++ b/tests/specialist.test.js
@@ -114,7 +114,7 @@ test('#173 a consortium seat: offer, pay, build, light, cut, save', () => {
ev(`ACT.subUpgrade({id:'${l.id}',k:'terminal'})`);
assert.equal(ev(`S.links.find(l=>l.id==='${l.id}').subterminal`), undefined, 'the consortium owns the terminals');
// A cut on the cable cuts your share.
- ev(`S.links=S.links.filter(l=>l.id==='${l.id}');eval('('+fireFailure.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')()`);
+ ev(`S.links=S.links.filter(l=>l.id==='${l.id}');runNow(eval('('+failureRun.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')())`);
assert.ok(ev(`linkDown(S.links.find(l=>l.id==='${l.id}'))`), 'the cut takes your pairs down too');
assert.deepEqual(errors, []);
});
diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js
index c871ca6..5f0d6d5 100644
--- a/tests/standing-orders.test.js
+++ b/tests/standing-orders.test.js
@@ -284,7 +284,8 @@ test('the mood follows the week, with no dice', t => {
test('fat fingers: never under Change Freeze, rare and harmless in On-call and BGP at 3 a.m.', t => {
const { ev, errors } = game(t);
- hire(ev);
+ // Kevin never fat-fingers anything: Annie does, now and then.
+ ev("ACT.opsHire({id:'annie'});S.ops.floor=0;closeModal()");
ev('window.__r=Math.random;Math.random=()=>0');
for (let i = 0; i < 50; i++) shift(ev);
assert.equal(ev('S.ops.log.some(e=>e.f!==undefined)'), false, 'Change Freeze: never, even on the unluckiest roll');
@@ -477,7 +478,8 @@ test('one order that throws is paused and noted; the rest of the shift and the d
test('the fat-fingered LAG member respects a paused transit order and per-POP exceptions', t => {
const { ev, errors } = game(t);
- hire(ev);
+ // Kevin never fat-fingers anything: Annie does, now and then.
+ ev("ACT.opsHire({id:'annie'});S.ops.floor=0;closeModal()");
// Each shift rolls: fat finger yes, the only POP, the LAG slip (index 3).
ev("S.rules=makeRules('bgp');window.__r=Math.random;window.__k=0;Math.random=()=>[0,0,0.7][__k++%3]");
const n0 = ev('S.transit[0].n||1'), c0 = cash(ev);