Cable ships: club repair ships sail out to subsea cuts, private charters jump the queue, lay ships build your cables

A subsea cut sends the nearest free ship of its region's maintenance club from its port, along the cable routes at about 500 km a day; the cut lasts while it sails, waits for permits in slow countries and splices (3-5 days shallow, 6-12 deep). Ships stay busy until home (S.fleet). With the club's ships all out the cut waits; a private charter of the quickest free ship costs $1M + $200/km sailed. Own subsea builds show survey/factory, then a lay ship at 150 km/day; a second lay ship can be booked before laying ($3M + $150k/day saved), and crews no longer speed up cables at sea. Ships are drawn on the map and can be tapped.
This commit is contained in:
Frederic Jung 2026-11-01 11:24:37 +00:00
parent 1fa5566d66
commit 96e2c2f537
No known key found for this signature in database
28 changed files with 606 additions and 138 deletions

View file

@ -31,7 +31,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one
| Id | Rule | Why |
| --- | --- | --- |
| N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. |
| N2 | Names are puns: no network, cable, exchange, data center, router or optic is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. |
| N2 | Names are puns: no network, cable, exchange, data center, router, optic, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. |
| N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. |
| N4 | No upstream cycles. | Cones must be trees, not loops. |
| N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. |

View file

@ -12,7 +12,10 @@ All notable changes to this project are documented here. The project follows
- Cache boxes now share router ports through an aggregation switch: one port carries as many 100G boxes as its speed holds, so 32 fit on a 3.2T port (#252). Each site gets its own.
- Opening a link from a list now moves the map to it, zoomed so the whole line fits beside the open panel.
- Traffic for a carrier now leaves through that carrier's own transit port at the same POP, instead of being shared with every other transit port there. Networks that buy transit from the carrier get the same treatment, and a new switch on each transit port, Carry here, pulls that traffic across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win, and Prefer only does so at the POP where you set it.
- Hurrying anything at sea now takes a cable ship, and there are only a few dozen in the world, so it costs millions. Speeding up your own subsea cable charters another ship for $3M plus $500 per km for every 30 days saved, and a rush repair on a subsea cut costs $1M plus $200 per km, where a cut on land still costs a few thousand.
- Cable ships now sail out to fix your subsea cables, and you can watch them on the map. A cut at sea calls the nearest free ship of its region's repair club, from ports such as Cornwall, Curaçao, Cape Town, Marseille, Vancouver, Tokyo, Manila and Singapore. The cut lasts while the ship sails out (about 500 km a day), splices for 3 to 5 days in shallow water or a week or two in the deep, and in some countries waits weeks for a repair permit. A ship is busy until it is home again.
- When every ship of a region's club is out, a subsea cut waits for the first one back. A private charter of the quickest free ship anywhere jumps the queue for $1M plus $200 per km it sails; the NOC intern's rush-repair order can pay it within its budget.
- Building your own subsea cable now shows the survey, permits and cable factory first, then a lay ship laying about 150 km a day. Crews can no longer speed up a cable at sea: book a second lay ship before laying starts instead, for $3M plus $150k a day, and it lays from the other end to halve that part.
- Tap a cable ship on the map to see its name, its club and what it is doing.
## [2.3.0] — 2026-10-31

View file

@ -32,7 +32,7 @@ hoisted across files, and top-level statements run in path order. Find code by n
| `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()`) |
| `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, geography pricing and latency, second sites and service |
| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()` |
| `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`) |
| `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 |

View file

@ -420,6 +420,24 @@
"businesses.your_network_diagram_is_a_photo":"Dein Netzplan ist ein Foto von einem Whiteboard.",
"businesses.your_noc_has_a_chat_channel":"Dein NOC hat einen Chat-Kanal namens #its-always-the-fiber, und es ist immer die Glasfaser.",
"businesses.your_routing_table_needs_its_own":"Deine Routing-Tabelle braucht eine eigene Routing-Tabelle.",
"cable_ships.at_anchor_off_home":"liegt vor {home} vor Anker, binnen eines Tages auslaufbereit.",
"cable_ships.book_a_second_lay_ship":"Zweites Verlegeschiff buchen <small>{price} · −{n} Tage</small>",
"cable_ships.charter_ship":"{ship} chartern",
"cable_ships.every_club_ship_is_out":"Jedes Schiff des {club} ist im Einsatz. Der Schnitt wartet auf das erste, das zurückkommt, oder auf eine private Charter.",
"cable_ships.km_of_km":"{km} von {of} km",
"cable_ships.lay_ship_tap":"<b>{ship}</b><br>Verlegt dein Kabel von {a} nach {b}: {km} von {of} km liegen am Meeresgrund.",
"cable_ships.laying_starts_in_n_days":{"one":"Verlegung beginnt in {n} Tag","other":"Verlegung beginnt in {n} Tagen"},
"cable_ships.private_at_anchor":"liegt vor {home} vor Anker, zu chartern für alle, die zahlen.",
"cable_ships.private_operator":"Privater Betreiber",
"cable_ships.sailing_home_to_home":{"one":"auf dem Heimweg nach {home}, in {n} Tag wieder frei.","other":"auf dem Heimweg nach {home}, in {n} Tagen wieder frei."},
"cable_ships.second_lay_ship_booked":{"one":"<b>{ship} ist gebucht.</b><br>Es verlegt vom anderen Ende: Das Kabel ist {n} Tag früher fertig.","other":"<b>{ship} ist gebucht.</b><br>Es verlegt vom anderen Ende: Das Kabel ist {n} Tage früher fertig."},
"cable_ships.ship_and_ship":"{a} und {b}",
"cable_ships.ship_chartered":"<b>{ship} ist gechartert.</b><br>Es läuft aus {home} aus; das Kabel ist in etwa {n} T. wieder da.",
"cable_ships.ship_is_splicing":{"one":"{ship} spleißt das Kabel: wieder da in {n} Tag.","other":"{ship} spleißt das Kabel: wieder da in {n} Tagen."},
"cable_ships.ship_sails_from_home":"{ship} läuft aus {home} aus: in {n} T. vor Ort, Kabel in etwa {m} T. wieder da.",
"cable_ships.ship_waits_for_a_permit":"{ship} ist vor Ort und wartet {n} T. auf eine Reparaturgenehmigung. Kabel in etwa {m} T. wieder da.",
"cable_ships.ships_lay_the_cable":"{ships} auf See, beim Verlegen",
"cable_ships.survey_permits_and_the_cable_factory":"Vermessung, Genehmigungen und die Kabelfabrik",
"cables.a_bet_on_a_tiny_island":"Eine Wette auf eine winzige Insel mitten im Pazifik.",
"cables.a_buffet_of_landings_down_norway":"Ein Buffet aus Anlandungen entlang der norwegischen Küste, von den Ölfeldern bis Oslo.",
"cables.a_friendly_cable_with_french_manners":"Ein freundliches Kabel mit französischen Manieren.",
@ -1918,7 +1936,6 @@
"failures.geopolitical_cable_cut":"Geopolitischer Kabelschnitt",
"failures.hash_polarisation_on_your_lab_nearly":"Hash-Polarisation auf deinem {lab}: Fast jeder Flow landet auf demselben Mitglied. Das Bündel sagt, es ist up. Es ist auch voll.",
"failures.hide_the_vacuum":"Staubsauger verstecken",
"failures.jump_the_cable_ship_queue":"Beim Kabelschiff vordrängeln",
"failures.lacp_fast_slow_timer_mismatch_on":"LACP-Fast/Slow-Timer-Mismatch auf deinem {lab}: Ein Mitglied fliegt ständig per Timeout aus dem Bündel und kommt wieder.",
"failures.lightning_hit_an_amp_site_on":"Ein Blitz hat einen Verstärkerstandort an {a}–{b} getroffen. Der Überspannungsschutz war Deko.",
"failures.load_shedding_in_city_stage_n":"<b>Lastabwurf in {city}</b><br>Heute Stufe {n}. Dein Generator hat gehustet, dann blieb das Licht an.",
@ -1999,7 +2016,6 @@
"failures.your_spares_kit_gets_it_back":"Dein Ersatzteillager bringt es morgen zurück.",
"features.done_in_d_days":"fertig in {d} Tagen",
"features.weekly_challenge_key":"Wochen-Challenge {key}",
"fiber_and_hardware.another_cable_ship_joins_the_lay":{"one":"<b>Ein weiteres Kabelschiff verlegt mit.</b><br>Das Kabel ist {n} Tag voraus.","other":"<b>Ein weiteres Kabelschiff verlegt mit.</b><br>Das Kabel ist {n} Tage voraus."},
"fiber_and_hardware.can_t_add_optic_why":"<b>{optic} kann nicht hinzugefügt werden.</b><br>{why}",
"fiber_and_hardware.dark_fiber_iru_signed_a_b":"<b>Dark-Fiber-IRU unterschrieben.</b><br>{a}–{b} wird in etwa 30 Tagen gespleißt und übergeben.",
"fiber_and_hardware.fiber_pair_n_is_lit_a":"<b>Faserpaar {n} ist beleuchtet: {a}–{b}.</b><br>Noch ein ROADMaster 9000 und eine frische Kette von Verstärkern. Platz für {m} weitere Kanäle.",
@ -2415,7 +2431,6 @@
"link_panels.build_a_pop_here_first":"Bau hier zuerst einen POP.",
"link_panels.cancel_the_iru":"IRU kündigen",
"link_panels.carry_here":"Hierher leiten",
"link_panels.charter_another_cable_ship_price_30":"Noch ein Kabelschiff chartern <small>{price} · −30 Tage</small>",
"link_panels.click_to_tear_down":"Klicken zum Abbauen",
"link_panels.collecting_data_check_back_in_a":"Daten werden gesammelt. Schau in ein paar Tagen wieder rein.",
"link_panels.congested_upgrade_it_or_add_a":"Überlastet. Rüste ihn auf oder füg einen parallelen Pfad hinzu.",

View file

@ -418,6 +418,24 @@
"businesses.your_network_diagram_is_a_photo":"Tu diagrama de red es una foto de una pizarra.",
"businesses.your_noc_has_a_chat_channel":"Tu NOC tiene un canal de chat llamado #siempre-es-la-fibra, y siempre es la fibra.",
"businesses.your_routing_table_needs_its_own":"Tu tabla de rutas necesita su propia tabla de rutas.",
"cable_ships.at_anchor_off_home":"fondeado frente a {home}, listo para zarpar en un día.",
"cable_ships.book_a_second_lay_ship":"Reservar un segundo buque tendedor <small>{price} · −{n} días</small>",
"cable_ships.charter_ship":"Fletar {ship}",
"cable_ships.every_club_ship_is_out":"Todos los buques del {club} están en un trabajo. El corte espera al primero que vuelva, o a un flete privado.",
"cable_ships.km_of_km":"{km} de {of} km",
"cable_ships.lay_ship_tap":"<b>{ship}</b><br>Tiende tu cable de {a} a {b}: {km} de {of} km en el fondo del mar.",
"cable_ships.laying_starts_in_n_days":{"one":"El tendido empieza en {n} día","other":"El tendido empieza en {n} días"},
"cable_ships.private_at_anchor":"fondeado frente a {home}, en flete para quien pague.",
"cable_ships.private_operator":"Operador privado",
"cable_ships.sailing_home_to_home":{"one":"volviendo a {home}, libre de nuevo en {n} día.","other":"volviendo a {home}, libre de nuevo en {n} días."},
"cable_ships.second_lay_ship_booked":{"one":"<b>{ship} está reservado.</b><br>Tiende desde el otro extremo: el cable estará listo {n} día antes.","other":"<b>{ship} está reservado.</b><br>Tiende desde el otro extremo: el cable estará listo {n} días antes."},
"cable_ships.ship_and_ship":"{a} y {b}",
"cable_ships.ship_chartered":"<b>{ship} está fletado.</b><br>Zarpa de {home}; el cable vuelve en unos {n} d.",
"cable_ships.ship_is_splicing":{"one":"{ship} está empalmando el cable: vuelve en {n} día.","other":"{ship} está empalmando el cable: vuelve en {n} días."},
"cable_ships.ship_sails_from_home":"{ship} zarpa de {home}: en el sitio en {n} d, el cable vuelve en unos {m} d.",
"cable_ships.ship_waits_for_a_permit":"{ship} está en el sitio y espera {n} d un permiso de reparación. El cable vuelve en unos {m} d.",
"cable_ships.ships_lay_the_cable":"{ships} en el mar, tendiendo",
"cable_ships.survey_permits_and_the_cable_factory":"Estudio, permisos y la fábrica de cable",
"cables.a_bet_on_a_tiny_island":"Una apuesta por una isla diminuta en medio del Pacífico.",
"cables.a_buffet_of_landings_down_norway":"Un bufé de aterrizajes por la costa noruega, de los campos petrolíferos a Oslo.",
"cables.a_friendly_cable_with_french_manners":"Un cable simpático con modales franceses.",
@ -1916,7 +1934,6 @@
"failures.geopolitical_cable_cut":"Corte geopolítico de cable",
"failures.hash_polarisation_on_your_lab_nearly":"Polarización de hash en tu {lab}: casi todos los flujos caen en el mismo miembro. El paquete dice que está activo. También está lleno.",
"failures.hide_the_vacuum":"Esconder la aspiradora",
"failures.jump_the_cable_ship_queue":"Colarse en la cola del buque cablero",
"failures.lacp_fast_slow_timer_mismatch_on":"Desajuste de temporizadores LACP rápido/lento en tu {lab}: un miembro sale del paquete por tiempo y vuelve una y otra vez.",
"failures.lightning_hit_an_amp_site_on":"Un rayo cayó en un sitio de amplificación en {a}–{b}. El protector contra sobretensiones era decorativo.",
"failures.load_shedding_in_city_stage_n":"<b>Cortes programados en {city}</b><br>Fase {n} hoy. Tu generador tosió y luego mantuvo las luces encendidas.",
@ -1997,7 +2014,6 @@
"failures.your_spares_kit_gets_it_back":"Tu kit de repuestos lo recupera mañana.",
"features.done_in_d_days":"listo en {d} días",
"features.weekly_challenge_key":"Desafío semanal {key}",
"fiber_and_hardware.another_cable_ship_joins_the_lay":{"one":"<b>Otro buque cablero se suma al tendido.</b><br>El cable va {n} día adelantado.","other":"<b>Otro buque cablero se suma al tendido.</b><br>El cable va {n} días adelantado."},
"fiber_and_hardware.can_t_add_optic_why":"<b>No se puede añadir {optic}.</b><br>{why}",
"fiber_and_hardware.dark_fiber_iru_signed_a_b":"<b>IRU de fibra oscura firmada.</b><br>{a}–{b} se empalmará y se entregará en unos 30 días.",
"fiber_and_hardware.fiber_pair_n_is_lit_a":"<b>El par de fibra {n} está iluminado: {a}–{b}.</b><br>Otro ROADMaster 9000 y una cadena nueva de amplificadores. Hay sitio para {m} canales más.",
@ -2413,7 +2429,6 @@
"link_panels.build_a_pop_here_first":"Construye primero un POP aquí.",
"link_panels.cancel_the_iru":"Cancelar la IRU",
"link_panels.carry_here":"Llevar aquí",
"link_panels.charter_another_cable_ship_price_30":"Fletar otro buque cablero <small>{price} · −30 días</small>",
"link_panels.click_to_tear_down":"Haz clic para desmontar",
"link_panels.collecting_data_check_back_in_a":"Recopilando datos. Vuelve en unos días.",
"link_panels.congested_upgrade_it_or_add_a":"Congestionado. Mejóralo o añade una ruta paralela.",

View file

@ -418,6 +418,24 @@
"businesses.your_network_diagram_is_a_photo":"Ton schéma réseau est une photo de tableau blanc.",
"businesses.your_noc_has_a_chat_channel":"Ton NOC a un canal de chat nommé #c-est-toujours-la-fibre, et c’est toujours la fibre.",
"businesses.your_routing_table_needs_its_own":"Ta table de routage a besoin de sa propre table de routage.",
"cable_ships.at_anchor_off_home":"au mouillage devant {home}, prêt à appareiller en un jour.",
"cable_ships.book_a_second_lay_ship":"Réserver un second navire câblier <small>{price} · −{n} jours</small>",
"cable_ships.charter_ship":"Affréter {ship}",
"cable_ships.every_club_ship_is_out":"Tous les navires du {club} sont en mission. La coupure attend le premier qui rentre, ou un affrètement privé.",
"cable_ships.km_of_km":"{km} sur {of} km",
"cable_ships.lay_ship_tap":"<b>{ship}</b><br>Pose ton câble de {a} à {b} : {km} sur {of} km sur le fond.",
"cable_ships.laying_starts_in_n_days":{"one":"La pose commence dans {n} jour","other":"La pose commence dans {n} jours"},
"cable_ships.private_at_anchor":"au mouillage devant {home}, à affréter pour qui paie.",
"cable_ships.private_operator":"Opérateur privé",
"cable_ships.sailing_home_to_home":{"one":"rentre à {home}, libre dans {n} jour.","other":"rentre à {home}, libre dans {n} jours."},
"cable_ships.second_lay_ship_booked":{"one":"<b>{ship} est réservé.</b><br>Il pose depuis l’autre bout : le câble est prêt {n} jour plus tôt.","other":"<b>{ship} est réservé.</b><br>Il pose depuis l’autre bout : le câble est prêt {n} jours plus tôt."},
"cable_ships.ship_and_ship":"{a} et {b}",
"cable_ships.ship_chartered":"<b>{ship} est affrété.</b><br>Il appareille de {home} ; le câble est rétabli dans environ {n} j.",
"cable_ships.ship_is_splicing":{"one":"{ship} épisse le câble : rétabli dans {n} jour.","other":"{ship} épisse le câble : rétabli dans {n} jours."},
"cable_ships.ship_sails_from_home":"{ship} appareille de {home} : sur place dans {n} j, câble rétabli dans environ {m} j.",
"cable_ships.ship_waits_for_a_permit":"{ship} est sur place et attend {n} j un permis de réparation. Câble rétabli dans environ {m} j.",
"cable_ships.ships_lay_the_cable":"{ships} en mer, en pose",
"cable_ships.survey_permits_and_the_cable_factory":"Relevés, permis et usine de câble",
"cables.a_bet_on_a_tiny_island":"Un pari sur une minuscule île au milieu du Pacifique.",
"cables.a_buffet_of_landings_down_norway":"Un buffet d’atterrissements le long de la côte norvégienne, des champs pétroliers jusqu’à Oslo.",
"cables.a_friendly_cable_with_french_manners":"Un câble sympathique aux manières bien françaises.",
@ -1916,7 +1934,6 @@
"failures.geopolitical_cable_cut":"Coupure de câble géopolitique",
"failures.hash_polarisation_on_your_lab_nearly":"Polarisation du hash sur ton {lab} : presque tous les flux tombent sur le même membre. Le bundle se dit up. Il est aussi plein.",
"failures.hide_the_vacuum":"Cacher l’aspirateur",
"failures.jump_the_cable_ship_queue":"Doubler la file du navire câblier",
"failures.lacp_fast_slow_timer_mismatch_on":"Timers LACP fast/slow incohérents sur ton {lab} : un membre n’arrête pas de sortir du bundle sur timeout et d’y revenir.",
"failures.lightning_hit_an_amp_site_on":"La foudre a frappé un site d’amplification sur {a}–{b}. Le parafoudre était décoratif.",
"failures.load_shedding_in_city_stage_n":"<b>Délestage à {city}</b><br>Niveau {n} aujourd’hui. Ton groupe électrogène a toussé, puis a gardé la lumière allumée.",
@ -1997,7 +2014,6 @@
"failures.your_spares_kit_gets_it_back":"Ton kit de rechange le remet en route demain.",
"features.done_in_d_days":"réussi en {d} jours",
"features.weekly_challenge_key":"Défi hebdo {key}",
"fiber_and_hardware.another_cable_ship_joins_the_lay":{"one":"<b>Un autre navire câblier rejoint la pose.</b><br>Le câble a {n} jour d’avance.","other":"<b>Un autre navire câblier rejoint la pose.</b><br>Le câble a {n} jours d’avance."},
"fiber_and_hardware.can_t_add_optic_why":"<b>Impossible d’ajouter {optic}.</b><br>{why}",
"fiber_and_hardware.dark_fiber_iru_signed_a_b":"<b>IRU de fibre noire signé.</b><br>{a}–{b} sera soudée et livrée dans environ 30 jours.",
"fiber_and_hardware.fiber_pair_n_is_lit_a":"<b>Paire de fibres {n} allumée : {a}–{b}.</b><br>Encore un ROADMaster 9000 et une nouvelle chaîne d’amplificateurs. De la place pour {m} canaux de plus.",
@ -2413,7 +2429,6 @@
"link_panels.build_a_pop_here_first":"Construis d’abord un POP ici.",
"link_panels.cancel_the_iru":"Résilier l’IRU",
"link_panels.carry_here":"Acheminer ici",
"link_panels.charter_another_cable_ship_price_30":"Affréter un autre navire câblier <small>{price} · −30 jours</small>",
"link_panels.click_to_tear_down":"Clique pour couper la session",
"link_panels.collecting_data_check_back_in_a":"Collecte des données en cours. Repasse dans quelques jours.",
"link_panels.congested_upgrade_it_or_add_a":"Saturé. Augmente sa capacité ou ajoute un chemin parallèle.",

View file

@ -418,6 +418,24 @@
"businesses.your_network_diagram_is_a_photo":"Il tuo schema di rete è la foto di una lavagna.",
"businesses.your_noc_has_a_chat_channel":"Il tuo NOC ha un canale chat chiamato #è-sempre-la-fibra, ed è sempre la fibra.",
"businesses.your_routing_table_needs_its_own":"La tua tabella di routing ha bisogno di una tabella di routing tutta sua.",
"cable_ships.at_anchor_off_home":"alla fonda davanti a {home}, pronta a salpare entro un giorno.",
"cable_ships.book_a_second_lay_ship":"Prenota una seconda nave posacavi <small>{price} · −{n} giorni</small>",
"cable_ships.charter_ship":"Noleggia {ship}",
"cable_ships.every_club_ship_is_out":"Tutte le navi del {club} sono in missione. Il taglio aspetta la prima che rientra, o un noleggio privato.",
"cable_ships.km_of_km":"{km} di {of} km",
"cable_ships.lay_ship_tap":"<b>{ship}</b><br>Posa il tuo cavo da {a} a {b}: {km} di {of} km sul fondale.",
"cable_ships.laying_starts_in_n_days":{"one":"La posa inizia tra {n} giorno","other":"La posa inizia tra {n} giorni"},
"cable_ships.private_at_anchor":"alla fonda davanti a {home}, a noleggio per chi paga.",
"cable_ships.private_operator":"Operatore privato",
"cable_ships.sailing_home_to_home":{"one":"rientra a {home}, di nuovo libera tra {n} giorno.","other":"rientra a {home}, di nuovo libera tra {n} giorni."},
"cable_ships.second_lay_ship_booked":{"one":"<b>{ship} è prenotata.</b><br>Posa dall’altro capo: il cavo è pronto {n} giorno prima.","other":"<b>{ship} è prenotata.</b><br>Posa dall’altro capo: il cavo è pronto {n} giorni prima."},
"cable_ships.ship_and_ship":"{a} e {b}",
"cable_ships.ship_chartered":"<b>{ship} è noleggiata.</b><br>Salpa da {home}; il cavo torna su tra circa {n} g.",
"cable_ships.ship_is_splicing":{"one":"{ship} sta giuntando il cavo: di nuovo su tra {n} giorno.","other":"{ship} sta giuntando il cavo: di nuovo su tra {n} giorni."},
"cable_ships.ship_sails_from_home":"{ship} salpa da {home}: sul posto tra {n} g, cavo di nuovo su tra circa {m} g.",
"cable_ships.ship_waits_for_a_permit":"{ship} è sul posto e aspetta {n} g un permesso di riparazione. Cavo di nuovo su tra circa {m} g.",
"cable_ships.ships_lay_the_cable":"{ships} in mare, in posa",
"cable_ships.survey_permits_and_the_cable_factory":"Rilievi, permessi e fabbrica del cavo",
"cables.a_bet_on_a_tiny_island":"Una scommessa su un’isoletta in mezzo al Pacifico.",
"cables.a_buffet_of_landings_down_norway":"Un buffet di approdi lungo la costa norvegese, dai giacimenti di petrolio fino a Oslo.",
"cables.a_friendly_cable_with_french_manners":"Un cavo amichevole con le buone maniere francesi.",
@ -1916,7 +1934,6 @@
"failures.geopolitical_cable_cut":"Taglio geopolitico dei cavi",
"failures.hash_polarisation_on_your_lab_nearly":"Polarizzazione dell’hash su {lab}: quasi tutti i flussi finiscono sullo stesso membro. Il bundle dice di essere su. È anche pieno.",
"failures.hide_the_vacuum":"Nascondi l’aspirapolvere",
"failures.jump_the_cable_ship_queue":"Salta la coda della nave posacavi",
"failures.lacp_fast_slow_timer_mismatch_on":"Timer LACP fast/slow non allineati su {lab}: un membro continua a uscire dal bundle per timeout e a rientrare.",
"failures.lightning_hit_an_amp_site_on":"Un fulmine ha colpito un sito di amplificazione su {a}–{b}. Lo scaricatore era decorativo.",
"failures.load_shedding_in_city_stage_n":"<b>Distacchi a rotazione a {city}</b><br>Oggi stage {n}. Il tuo generatore ha tossito, poi ha tenuto le luci accese.",
@ -1997,7 +2014,6 @@
"failures.your_spares_kit_gets_it_back":"Il tuo kit di ricambi lo rimette in piedi domani.",
"features.done_in_d_days":"fatto in {d} giorni",
"features.weekly_challenge_key":"Sfida settimanale {key}",
"fiber_and_hardware.another_cable_ship_joins_the_lay":{"one":"<b>Un’altra nave posacavi si unisce alla posa.</b><br>Il cavo è in anticipo di {n} giorno.","other":"<b>Un’altra nave posacavi si unisce alla posa.</b><br>Il cavo è in anticipo di {n} giorni."},
"fiber_and_hardware.can_t_add_optic_why":"<b>Impossibile aggiungere {optic}.</b><br>{why}",
"fiber_and_hardware.dark_fiber_iru_signed_a_b":"<b>IRU di dark fiber firmato.</b><br>{a}–{b} sarà giuntata e consegnata in circa 30 giorni.",
"fiber_and_hardware.fiber_pair_n_is_lit_a":"<b>Coppia di fibre {n} accesa: {a}–{b}.</b><br>Un altro ROADMaster 9000 e una nuova catena di amplificatori. Spazio per altri {m} canali.",
@ -2413,7 +2429,6 @@
"link_panels.build_a_pop_here_first":"Prima costruisci un POP qui.",
"link_panels.cancel_the_iru":"Disdici l’IRU",
"link_panels.carry_here":"Instrada qui",
"link_panels.charter_another_cable_ship_price_30":"Noleggia un’altra nave posacavi <small>{price} · −30 giorni</small>",
"link_panels.click_to_tear_down":"Clicca per chiudere la sessione",
"link_panels.collecting_data_check_back_in_a":"Raccolta dati in corso. Ripassa tra qualche giorno.",
"link_panels.congested_upgrade_it_or_add_a":"Congestionato. Potenzialo o aggiungi un percorso parallelo.",

View file

@ -418,6 +418,24 @@
"businesses.your_network_diagram_is_a_photo":"Seu diagrama de rede é uma foto de um quadro branco.",
"businesses.your_noc_has_a_chat_channel":"Seu NOC tem um canal de chat chamado #é-sempre-a-fibra, e é sempre a fibra.",
"businesses.your_routing_table_needs_its_own":"Sua tabela de roteamento precisa de uma tabela de roteamento própria.",
"cable_ships.at_anchor_off_home":"fundeado diante de {home}, pronto para zarpar em um dia.",
"cable_ships.book_a_second_lay_ship":"Reservar um segundo navio lançador <small>{price} · −{n} dias</small>",
"cable_ships.charter_ship":"Fretar {ship}",
"cable_ships.every_club_ship_is_out":"Todos os navios do {club} estão em serviço. O corte espera o primeiro que voltar, ou um frete privado.",
"cable_ships.km_of_km":"{km} de {of} km",
"cable_ships.lay_ship_tap":"<b>{ship}</b><br>Lançando seu cabo de {a} a {b}: {km} de {of} km no fundo do mar.",
"cable_ships.laying_starts_in_n_days":{"one":"O lançamento começa em {n} dia","other":"O lançamento começa em {n} dias"},
"cable_ships.private_at_anchor":"fundeado diante de {home}, para frete a quem pagar.",
"cable_ships.private_operator":"Operador privado",
"cable_ships.sailing_home_to_home":{"one":"voltando para {home}, livre de novo em {n} dia.","other":"voltando para {home}, livre de novo em {n} dias."},
"cable_ships.second_lay_ship_booked":{"one":"<b>{ship} está reservado.</b><br>Lança pela outra ponta: o cabo fica pronto {n} dia antes.","other":"<b>{ship} está reservado.</b><br>Lança pela outra ponta: o cabo fica pronto {n} dias antes."},
"cable_ships.ship_and_ship":"{a} e {b}",
"cable_ships.ship_chartered":"<b>{ship} está fretado.</b><br>Zarpa de {home}; o cabo volta em cerca de {n} d.",
"cable_ships.ship_is_splicing":{"one":"{ship} está emendando o cabo: de volta em {n} dia.","other":"{ship} está emendando o cabo: de volta em {n} dias."},
"cable_ships.ship_sails_from_home":"{ship} zarpa de {home}: no local em {n} d, cabo de volta em cerca de {m} d.",
"cable_ships.ship_waits_for_a_permit":"{ship} está no local e espera {n} d por uma licença de reparo. Cabo de volta em cerca de {m} d.",
"cable_ships.ships_lay_the_cable":"{ships} no mar, lançando",
"cable_ships.survey_permits_and_the_cable_factory":"Levantamento, licenças e a fábrica de cabo",
"cables.a_bet_on_a_tiny_island":"Uma aposta numa ilhota no meio do Pacífico.",
"cables.a_buffet_of_landings_down_norway":"Um rodízio de pontos de chegada pela costa norueguesa, dos campos de petróleo até Oslo.",
"cables.a_friendly_cable_with_french_manners":"Um cabo simpático com bons modos franceses.",
@ -1916,7 +1934,6 @@
"failures.geopolitical_cable_cut":"Corte geopolítico de cabo",
"failures.hash_polarisation_on_your_lab_nearly":"Polarização de hash no seu {lab}: quase todo fluxo cai no mesmo membro. O bundle diz que está up. Também está lotado.",
"failures.hide_the_vacuum":"Esconder o aspirador",
"failures.jump_the_cable_ship_queue":"Furar a fila do navio cabeiro",
"failures.lacp_fast_slow_timer_mismatch_on":"Timer LACP fast/slow desencontrado no seu {lab}: um membro vive dando timeout no bundle e voltando.",
"failures.lightning_hit_an_amp_site_on":"Um raio atingiu um site de amplificação em {a}–{b}. O protetor de surto era decorativo.",
"failures.load_shedding_in_city_stage_n":"<b>Rodízio de energia em {city}</b><br>Stage {n} hoje. Seu gerador tossiu, depois manteve as luzes acesas.",
@ -1997,7 +2014,6 @@
"failures.your_spares_kit_gets_it_back":"Seu kit de sobressalentes traz de volta amanhã.",
"features.done_in_d_days":"feito em {d} dias",
"features.weekly_challenge_key":"Desafio semanal {key}",
"fiber_and_hardware.another_cable_ship_joins_the_lay":{"one":"<b>Outro navio cabeiro entra no lançamento.</b><br>O cabo está {n} dia adiantado.","other":"<b>Outro navio cabeiro entra no lançamento.</b><br>O cabo está {n} dias adiantado."},
"fiber_and_hardware.can_t_add_optic_why":"<b>Não dá para adicionar {optic}.</b><br>{why}",
"fiber_and_hardware.dark_fiber_iru_signed_a_b":"<b>IRU de dark fiber assinado.</b><br>{a}–{b} será emendada e entregue em uns 30 dias.",
"fiber_and_hardware.fiber_pair_n_is_lit_a":"<b>Par de fibras {n} aceso: {a}–{b}.</b><br>Mais um ROADMaster 9000 e uma nova cadeia de amplificadores. Espaço para mais {m} canais.",
@ -2413,7 +2429,6 @@
"link_panels.build_a_pop_here_first":"Construa um POP aqui primeiro.",
"link_panels.cancel_the_iru":"Cancelar o IRU",
"link_panels.carry_here":"Trazer para cá",
"link_panels.charter_another_cable_ship_price_30":"Fretar outro navio cabeiro <small>{price} · −30 dias</small>",
"link_panels.click_to_tear_down":"Clique para encerrar",
"link_panels.collecting_data_check_back_in_a":"Coletando dados. Volte em alguns dias.",
"link_panels.congested_upgrade_it_or_add_a":"Congestionado. Faça upgrade ou adicione um caminho paralelo.",

View file

@ -20,11 +20,8 @@ function setCableReady(l,ready,day=S.day){const shift=ready-l.ready;
const f='sub'+k;if(Number.isFinite(l[f])&&l[f]>day)l[f]=Math.max(day+1,l[f]+shift);
}l.ready=ready;
}
// Hurrying anything at sea means a cable ship, and there are only a few dozen in the world, booked months ahead:
// a second one for your build is a multi-million charter, and jumping the repair queue costs about what a repair does.
const SHIP_MOB=3000000,SHIP_KM=500,SHIP_FIX=1000000,SHIP_FIX_KM=200;
const crewCost=l=>Math.round(l.sub?SHIP_MOB+l.km*SHIP_KM:15000+l.km*6);
const shipFix=km=>Math.round(SHIP_FIX+km*SHIP_FIX_KM);
// Crews hurry a build on land. At sea only a cable ship does (85-incidents/50-cable-ships.js).
const crewCost=l=>Math.round(15000+l.km*6);
const crewSteps=l=>Math.max(0,Math.ceil((l.ready-S.day-1)/30));
// Old saves lack purchase dates. Only shorten dates beyond any valid remaining
// commissioning window. Credit elapsed time since the actual cable finish;

View file

@ -0,0 +1,35 @@
/* ---------- cable ships ----------
About sixty ships in the world can lay or repair a subsea cable, and only a few dozen do mostly repairs. Cable owners
pay a yearly fee per km to a regional maintenance club, which keeps ships on standby in fixed ports, ready to sail
within a day. When every club ship is out, the next cut waits. A private charter jumps the queue, for millions.
The game keeps one or two ships at the real clubs' bases (Cornwall, Curaçao, Cape Town, the French Riviera,
Vancouver Island, Yokohama, Subic Bay, Singapore) and two private operators. Names are puns, as everywhere. */
const SHIP_CLUBS={atl:{n:'Atlantic Splice Society'},med:{n:'Mediterranean Mending Club'},naz:{n:'North Pacific Patch Pact'},prv:{n:''},sea:{n:'SEA-IO Fix-It Club'},yok:{n:'Knot-a-hama Zone'}};
const SHIPS=[
{id:'buoy',n:'Buoy Oh Buoy',club:'naz',home:'van'},
{id:'cguy',n:'Cable Guy',club:'atl',home:'cpt'},
{id:'grap',n:'Grapnel Grandma',club:'sea',home:'mnl'},
{id:'hook',n:'Hook, Line & Splicer',club:'sea',home:'sin'},
{id:'joint',n:'Jointly Liable',club:'sea',home:'sin'},
{id:'junk',n:'Junk Bond',club:'prv',home:'sha'},
{id:'knot',n:'Knot Again',club:'atl',home:'bde'},
{id:'loose',n:'Loose Ends',club:'yok',home:'tok'},
{id:'mend',n:'Mend & Tonic',club:'med',home:'mrs'},
{id:'reel',n:'Reel Deal',club:'atl',home:'cur'},
{id:'saw',n:'Sea-Saw',club:'prv',home:'fuj'},
{id:'splice',n:'Splice Girl',club:'atl',home:'bde'},
{id:'spool',n:'Spool of Thought',club:'yok',home:'tok'},
{id:'tea',n:'Spliced Tea',club:'med',home:'mrs'},
];
const SHIP=Object.fromEntries(SHIPS.map(s=>[s.id,s]));
// The installation fleet lays new cables: your own cable gets one of these, and a second one can be booked.
const LAY_SHIPS=['Lay-Z Susan','Long Haul Lass','Reel Estate','Spoolhardy'];
/* Real numbers, rounded: a cable ship cruises at 10 to 12 knots (about 500 km a day) and leaves within a day of the
call; a repair takes 3 to 5 days on site in shallow water and a week or two in deep water; most faults (anchors and
fishing gear) are in shallow water near the shore; some countries take weeks to grant a repair permit in their
waters. A repair costs $0.5M to $1M; jumping the queue with a private charter costs more. A lay ship lays a
transoceanic cable at roughly 150 km a day. */
const SHIP_KMD=500,SHIP_MOB_D=1,SHIP_SHALLOW=300,LAY_KMD=150;
const SHIP_FIX=1000000,SHIP_FIX_KM=200,SHIP_MOB=3000000,LAY_DAY=150000;
// Days to get a repair permit in a country's waters, [fewest, most]; anywhere else the ship just goes.
const SHIP_PERMIT={CN:[14,28],EG:[7,21],ID:[21,42],IN:[21,42],VN:[14,28]};

View file

@ -1,6 +1,6 @@
function newGame(name,home){
S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH,
ltv:2,t1v:3,auV:1,ops:opsNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{},
done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}};
done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}};
}

View file

@ -62,6 +62,16 @@ function sanitize(s){
{const c=s.core&&typeof s.core==='object'?s.core:null,lv=c?int(c.lv,0,4,0):(s.te?2:0);s.core={lv,run:c?int(c.run,0,lv,lv):lv};if(c?c.legacy===true:!!s.te)s.core.legacy=true;if(c&&c.lab===true)s.core.lab=true;if(c&&c.since!==undefined)s.core.since=num(c.since,0);}
s.capDeal=s.capDeal&&typeof s.capDeal==='object'&&own(CAP_ROUTES,s.capDeal.c)?{at:num(s.capDeal.at,0),c:s.capDeal.c}:null;
s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.type==='maxpfx'&&(i.type='ixloop'),i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i));
// Cable ships (85-incidents/50-cable-ships.js): voyages of known ships, and what a subsea cut knows about its ship.
{const F=s.fleet&&typeof s.fleet==='object'&&!Array.isArray(s.fleet)?s.fleet:{},o={};
for(const id of Object.keys(F)){const f=F[id];if(!own(SHIP,id)||!f||typeof f!=='object')continue;const n=k=>num(f[k],s.day);
const v={inc:typeof f.inc==='string'?f.inc.slice(0,40):null,link:typeof f.link==='string'?f.link.slice(0,40):'',t:clamp(num(f.t,0.5),0,1),e:f.e==='b'?'b':'a',dep:n('dep'),arr:n('arr'),done:n('done'),back:n('back'),fx:num(f.fx,0),fy:num(f.fy,0)};
if(f.rs!=null){v.rs=n('rs');v.rt=clamp(num(f.rt,0),0,1);}v.arr=Math.max(v.arr,v.dep);v.done=Math.max(v.done,v.arr);v.back=Math.max(v.back,v.done);if(v.back>s.day)o[id]=v;}
s.fleet=o;
for(const i of s.inc){if(i.type!=='cut'||i.st==null){for(const k of ['ship','seaq','st','sw','sp','sl'])delete i[k];continue;}
i.st=clamp(num(i.st,0.5),0.03,0.97);i.sw=int(i.sw,1,30,4);i.sp=int(i.sp,0,60,0);i.sl=typeof i.sl==='string'?i.sl.slice(0,40):'';i.rushed=!!i.rushed||undefined;
if(i.ship!=null&&!(own(SHIP,i.ship)&&o[i.ship]&&o[i.ship].inc===i.id))i.ship=null;if(i.ship==null){i.ship=null;i.seaq=1;}else delete i.seaq;}
for(const l of s.links)if(l.ship2&&l.kind==='df'&&l.own&&l.sub)l.ship2=1;else delete l.ship2;}
s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));for(const l of s.loans){if(l.model!==undefined&&!['balloon','storm','transit','astro'].includes(l.model))delete l.model;for(const k of ['apr0','cut','share'])if(l[k]!==undefined&&!isFinite(+l[k]))delete l[k];if(!Array.isArray(l.covs))l.covs=[];l.covs=l.covs.filter(c=>own(COVS,c));}s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank));
s.usedNames=[...new Set(s.usedNames.filter(x=>typeof x==='string'))];s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&e.o.a==='inbox'?{a:'tab',v:'nets'}:e&&e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'||e.o.a==='ops'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null;
return {id:typeof e.id==='string'&&e.id.length<=40?e.id:uid(),d:num(e.d,0),t:e.t.slice(0,600),h:typeof e.h==='string'?e.h.slice(0,200):'',k:LOG_KINDS.includes(e.k)?e.k:'',at:Number.isFinite(+e.at)?+e.at:0,o,n:int(e.n,1,9999,1)};});

View file

@ -84,7 +84,9 @@ function fireFailure(only){
const pool=only&&scnRule('anchors')?live.filter(anchorProne):live;if(!pool.length)return;const l=pick(pool.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=10+Math.floor(Math.random()*8),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));
const A=CITY[l.a].name,B=CITY[l.b].name,au=CITY[l.a].au&&CITY[l.b].au,auSummer=mon>=11||mon<=1;
const en=l.sub&&(CITY[l.a].au||CITY[l.b].au)&&!(l.cable&&CAB[l.cable].fragile)&&Math.random()<0.35?pick([N_('failures.box_jellyfish_season_at_the_a'),N_('failures.a_great_white_took_an_interest')]):l.cable&&CAB[l.cable].fragile&&Math.random()<0.8?pick([N_('failures.your_a_b_cable_is_cut'),N_('failures.a_b_is_down_same_cable')]):!l.sub&&CITY[l.a].land==='nzs'&&CITY[l.b].land==='nzs'&&Math.random()<0.75?pick([N_('failures.a_kea_pulled_the_rubber_seals'),N_('failures.the_sandflies_drove_your_splicing'),N_('failures.a_farmer_s_post_hole_digger')]):l.cable==='cook'&&Math.random()<0.6?N_('failures.a_ferry_dropped_anchor_in_cook'):!l.sub&&au&&Math.random()<0.75?pick([N_('failures.a_sulphur_crested_cockatoo_chewed'),N_('failures.a_kangaroo_hit_the_fiber_hut'),N_('failures.thieves_dug_up_your_a_b'),N_('failures.a_kilometre_of_copper_went_missing'),N_('failures.a_backhoe_putting_in_a_new'),N_('failures.the_emus_won_again_a_mob'),N_('failures.a_kangaroo_boxed_your_field_tech'),N_('failures.a_drop_bear_fell_on_the'),N_('failures.an_eastern_brown_snake_moved_into'),...((S.day%365)/30.42>=8&&(S.day%365)/30.42<11?[N_('failures.magpie_swooping_season_the_field')]:[]),...(auSummer?[N_('failures.bushfire_season_the_fiber_along_a')]:[]),...(nullPair(l.a,l.b)?[N_('failures.your_a_b_fiber_broke_somewhere')]:[])]):l.sub&&(l.a==='bda'||l.b==='bda')&&Math.random()<0.7?pick([N_('failures.your_a_b_cable_went_quiet'),N_('failures.the_repair_ship_s_compass_spun')]):l.sub&&(l.a==='tbu'||l.b==='tbu')&&Math.random()<0.7?pick([N_('failures.an_undersea_volcano_erupted_next_to'),N_('failures.the_seabed_off_tonga_slid_down')]):vn(l)&&Math.random()<0.8?pick([N_('failures.another_of_vietnam_s_subsea_cables'),N_('failures.your_a_b_cable_broke_in')]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([N_('failures.a_crocodile_took_a_bite_out'),N_('failures.termites_ate_the_duct_on_a')]):tw(l)&&Math.random()<0.8?pick([N_('failures.a_cargo_ship_forgot_to_raise'),N_('failures.another_anchor_another_cut_your_a'),N_('failures.a_fishing_boat_with_an_unusually')]):l.sub&&(l.a==='oos'||l.b==='oos')&&Math.random()<0.8?pick([N_('failures.a_trawler_off_ostend_dragged_its'),N_('failures.a_wind_farm_service_vessel_dropped')]):!l.sub&&(CITY[l.a].ca||CITY[l.b].ca)&&Math.random()<0.4?pick([N_('failures.a_beaver_chewed_through_your_a'),N_('failures.your_a_b_fiber_is_down'),N_('failures.frost_heave_cracked_the_duct_on')]):!l.sub&&andesPair(l.a,l.b)?pick([N_('failures.a_landslide_in_the_andes_buried'),N_('failures.snow_closed_the_mountain_pass_and'),N_('failures.an_earthquake_shook_your_a_b'),N_('failures.a_llama_herd_trampled_the_fiber')]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([N_('failures.road_widening_near_a_cut_your'),N_('failures.the_monsoon_flooded_a_manhole_on'),N_('failures.a_digger_found_your_a_b')]):l.sub?pick([N_('failures.a_curious_shark_bit_your_subsea'),N_('failures.a_ship_dragged_its_anchor_across'),N_('failures.an_undersea_landslide_snapped_a_b')]):pick([N_('failures.a_backhoe_found_your_fiber_between'),N_('failures.squirrels_chewed_through_a_b_they'),N_('failures.road_works_cut_a_b_nobody')]);
addInc({type,ref:trc,until:S.day+dur,msg:tr(en,{a:A,b:B})+(hit.length>1?' '+tr('failures.all_n_links_in_that_trench',{n:hit.length}):''),...cutFix(l,hit)},en);
addInc({type,ref:trc,until:S.day+dur,msg:tr(en,{a:A,b:B})+(hit.length>1?' '+tr('failures.all_n_links_in_that_trench',{n:hit.length}):''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},en);
// At sea a cable ship sails out to it (50-cable-ships.js): it sets how long the cut lasts and what a charter costs.
if(l.sub&&!pzOn())shipCut(S.inc[S.inc.length-1],l);
}else if(type==='crash'||type==='power'){
const c=pick(Object.keys(S.pops).flatMap(x=>type==='power'&&(CITY[x].za||CITY[x].blackout)?[x,x,x]:type==='crash'&&RG[S.pops[x].rgen||0].flaky?[x,x,x]:[x])),pp=S.pops[c],slow=slowBoot(c),dur=(type==='crash'?2+Math.floor(Math.random()*2):3+Math.floor(Math.random()*3))*(type==='crash'&&S.ev.sanction>S.day?2:1)+(slow?2+Math.floor(Math.random()*3):0);
if(type==='crash'&&(pp.routers||1)>=2){pp.rdown=S.day+dur;S.stats.incidents++;S.stats.survived++;toast(tr('failures.router_crash_in_city_one_router',{city:CITY[c].name,slow:slow?' '+tr('failures.the_crashed_one_what',{what:esc(pick(SLOW_BOOT))}):'',d:dur}),'good');sfx('alert');return;}
@ -119,8 +121,6 @@ const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0);
const FLOOD_WHO=[N_('failures.a_botnet_of_40_000_smart'),N_('failures.every_unpatched_baby_monitor_in'),N_('failures.a_gaming_clan_that_lost_one'),N_('failures.a_fridge_that_achieved_sentience_and'),N_('failures.a_crypto_bro_shorting_your_stock'),N_('failures.a_teenager_with_a_stolen_credit'),N_('failures.a_rival_isp_s_stress_test'),N_('failures.ten_thousand_smart_light_bulbs'),N_('failures.a_printer_just_one_printer_nobody'),N_('failures.a_botnet_run_from_a_cloud'),N_('failures.somebody_who_did_not_like_your'),N_('failures.the_internet_connected_kettles_of_a')];
function incTitle(t){return {ring:tr('failures.metro_ring_cut'),site:tr('common.site_outage'),cut:tr('common.fiber_cut'),crash:tr('common.router_crash'),power:tr('common.power_outage'),transit:tr('common.upstream_outage'),ixloop:tr('common.ix_meltdown'),leak:tr('common.route_leak'),ddos:tr('common.ddos_attack'),fabric:tr('common.fabric_outage'),depeer:tr('common.peering_spat'),fatwave:tr('failures.fat_fingered_wave'),label:tr('failures.patch_panel_mishap'),interop:tr('core.interop_failure'),mtu:tr('common.mtu_mismatch'),krroute:tr('failures.rerouted_via_hong_kong'),ctrlplane:tr('failures.control_plane_meltdown'),lacp:tr('common.lacp_trouble'),loss:tr('common.packet_loss'),pmtud:tr('failures.pmtud_black_hole'),oops:tr('common.oops'),cleaner:tr('common.vacuum_incident'),prepend:tr('common.prepend_ageddon'),rpki:tr('common.rpki_invalid'),amp:tr('common.amplifier_failure'),roadmff:tr('failures.fat_fingered_roadm'),optic:tr('common.dead_optic'),maint:tr('common.maintenance_window_3a92'),ac:tr('common.cooling_failure'),hijack:tr('common.bgp_hijack'),shutdown:tr('common.government_shutdown'),redsea:tr('failures.geopolitical_cable_cut')}[t]||tr('common.incident');}
const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label','interop'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic'];
// A rush repair: crews for a trench, a cable ship for the sea (shipFix, 60-reach-and-subsea.js).
const cutFix=(l,hit)=>{const c=Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5));return l.sub?{cost:Math.max(c,shipFix(l.km)),fix:tr('failures.jump_the_cable_ship_queue')}:{cost:c};};
function remainUntil(pred){let u=0;for(const x of S.inc)if(pred(x))u=Math.max(u,x.until);return u;}
// Remove an incident, then restore each affected thing to whatever other incidents still hold it down.
function clearInc(i){

View file

@ -35,7 +35,7 @@ function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkD
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}),...cutFix(l,hit)},'');
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;
const felt=before>1&&imp>=before*0.03;if(felt)M.hurt++;else S.stats.survived++;
toast(felt?`<b>🐒 ${incTitle('cut')}</b><br>${esc(i?i.msg:'')}`:tr('chaos_monkey.rerouted',{a:A,b:B}),felt?'bad':'good',[],i?incOpen(i):null);sfx(felt?'err':'alert');

View file

@ -0,0 +1,79 @@
/* ---------- cable ships at work (data and real numbers: 20-world/70-cable-ships.js) ----------
A subsea cut sends a ship from its club's port: it leaves a day after the call, sails the cable routes at about
500 km a day, may wait for a permit, splices for days, and sails home before it can take the next job. The cut lasts
until the splice is done. With every ship of the zone's club out, the cut waits; a private charter (any free ship,
from anywhere) jumps the queue for $1M plus $200 per km it sails. Voyages live in S.fleet so a ship on its way
home stays busy after the cut is mended; positions are worked out from them, so the map needs no state of its own. */
let SHIP_G=null;
// The cable routes as a graph of landing cities: ships sail where the cables are, which is open sea.
function shipGraph(){if(SHIP_G)return SHIP_G;const g=new Map(),add=(u,e)=>{let L=g.get(u);if(!L)g.set(u,L=[]);L.push(e);};
CABLE_PAIRS.forEach((p,i)=>{add(p.a,{to:p.b,km:p.km,i});add(p.b,{to:p.a,km:p.km,i});});return SHIP_G=g;}
// Shortest sailing distance from the sources ({city: km already to go}) to every port, with the way back.
function shipDij(src){const G=shipGraph(),dist=new Map(),prev=new Map(),h=[];for(const c in src){dist.set(c,src[c]);h.push([src[c],c]);}
while(h.length){let b=0;for(let i=1;i<h.length;i++)if(h[i][0]<h[b][0])b=i;const [d,u]=h[b];h[b]=h[h.length-1];h.pop();if(d>dist.get(u))continue;
for(const e of G.get(u)||[]){const nd=d+e.km;if(nd<(dist.get(e.to)??Infinity)){dist.set(e.to,nd);prev.set(e.to,{from:u,e});h.push([nd,e.to]);}}}
return {dist,prev};}
const shipFree=s=>{const f=S.fleet[s.id];return !f||S.day>=f.back;};
const shipLink=i=>S.links.find(x=>x.id===i.sl)||S.links.find(x=>(x.trench||x.id)===i.ref);
const shipSea=i=>i.type==='cut'&&(i.ship!=null||!!i.seaq);
// Where on the cable the fault is (share of the way from l.a): mostly in shallow water near a shore, where anchors and
// trawls reach the cable; sometimes out in the deep.
function shipFaultT(l){const near=Math.min(0.45,SHIP_SHALLOW/Math.max(1,l.km||1));
if(Math.random()<0.75){const d=Math.random()*near;return Math.random()<0.5?0.03+d:0.97-d;}return 0.03+Math.random()*0.94;}
const shipShallow=(l,t)=>Math.min(t,1-t)*(l.km||0)<=SHIP_SHALLOW;
// A fault seen from the sea: sailing distances from it to every port.
const shipFrom=(i,l)=>shipDij({[l.a]:i.st*l.km,[l.b]:(1-i.st)*l.km});
// The club whose zone the fault is in: the one with the nearest port.
function shipZone(D){let best=null,bd=Infinity;for(const s of SHIPS){if(s.club==='prv')continue;const d=D.dist.get(s.home)??Infinity;if(d<bd){bd=d;best=s.club;}}return best;}
// Sailing distance for a ship, and the timetable if it left today.
function shipPlan(s,i,l,D){let km=D.dist.get(s.home);
if(!(km<Infinity)){const A=CITY[l.a],B=CITY[l.b],H=CITY[s.home];km=Math.round(hav(H.lon,H.lat,A.lon+(B.lon-A.lon)*i.st,A.lat+(B.lat-A.lat)*i.st)*1.4);}
const sail=Math.max(1,Math.ceil(km/SHIP_KMD)),dep=S.day,arr=dep+SHIP_MOB_D+sail,done=arr+(i.sp||0)+(i.sw||4);return {s,km:Math.round(km),dep,arr,done,back:done+sail};}
// The way a ship sails to the fault: the cable endpoint it comes in by (following the shortest route back from its port).
function shipEnd(s,l,D){let c=s.home;
if(!D.dist.has(c)){const H=CITY[c],A=CITY[l.a],B=CITY[l.b];return hav(H.lon,H.lat,A.lon,A.lat)<=hav(H.lon,H.lat,B.lon,B.lat)?'a':'b';}
for(let n=0;n<999;n++){const p=D.prev.get(c);if(!p)break;c=p.from;}return c===l.b?'b':'a';}
// The cut ends with the splice: every link in the trench follows, as clearInc() works it out.
function shipUntil(i,u){i.until=u;for(const l of S.links)if((l.trench||l.id)===i.ref)l.cut=remainUntil(x=>(LINKCUT_TR.includes(x.type)&&x.ref===(l.trench||l.id))||(LINKCUT_ID.includes(x.type)&&x.ref===l.id));}
function shipSend(i,l,P,D){const g=linkGeom(l),pt=polyAt(g.pts,g.cum,i.st);
S.fleet[P.s.id]={inc:i.id,link:l.id,t:i.st,e:shipEnd(P.s,l,D),dep:P.dep,arr:P.arr,done:P.done,back:P.back,fx:pt[0],fy:pt[1]};
i.ship=P.s.id;delete i.seaq;shipUntil(i,P.done);}
// The quickest free ship from anywhere, if it would finish sooner than the plan: what a private charter offers.
function shipQuote(i,l,D){D=D||shipFrom(i,l);let best=null;const cur=i.ship!=null&&S.fleet[i.ship]?S.fleet[i.ship].done:Infinity;
for(const s of SHIPS)if(shipFree(s)){const P=shipPlan(s,i,l,D);if(!best||P.done<best.done)best=P;}
if(best&&best.done<cur-1){i.cost=Math.round(SHIP_FIX+best.km*SHIP_FIX_KM);i.fix=tr('cable_ships.charter_ship',{ship:best.s.n});}else{i.cost=0;delete i.fix;}return best;}
// Send the zone's club ship that gets there first; with none free, the cut waits for one.
function shipAssign(i,l){const D=shipFrom(i,l),z=shipZone(D);let best=null;
for(const s of SHIPS)if(s.club===z&&shipFree(s)){const P=shipPlan(s,i,l,D);if(!best||P.done<best.done)best=P;}
if(best)shipSend(i,l,best,D);else if(!i.seaq){i.seaq=1;i.ship=null;shipUntil(i,S.day+365);}
shipQuote(i,l,D);}
// A fresh cut on a subsea cable: roll where it is and how long the work takes, then call the club.
function shipCut(i,l){if(!S.fleet)S.fleet={};i.sl=l.id;i.st=+shipFaultT(l).toFixed(3);i.sw=shipShallow(l,i.st)?rint(3,3):rint(6,7);
const near=CITY[i.st<0.5?l.a:l.b],pm=shipShallow(l,i.st)&&SHIP_PERMIT[near.cc];i.sp=pm?rint(pm[0],pm[1]-pm[0]+1):0;shipAssign(i,l);}
// A ship whose job went away (the cable was given up, or another ship was chartered) turns round where it is.
function shipRecall(id){const f=S.fleet[id];if(!f||S.day>=f.done)return;const m=f.dep+SHIP_MOB_D;
if(S.day>=f.arr){const sail=f.back-f.done;f.done=S.day;f.back=S.day+sail;f.inc=null;return;}
const out=Math.max(0,S.day-m);f.rt=+(out/Math.max(1,f.arr-m)).toFixed(4);f.rs=S.day;f.arr=f.done=S.day;f.back=S.day+out;f.inc=null;}
// Pay for the charter: the quickest free ship goes, whichever club or company it sails for.
function shipRush(i){const l=shipLink(i);if(!l||!shipSea(i))return false;const D=shipFrom(i,l),P=shipQuote(i,l,D);if(!P||!i.cost)return false;
if(!spend(i.cost))return false;if(i.ship!=null)shipRecall(i.ship);shipSend(i,l,P,D);i.cost=0;delete i.fix;i.rushed=true;return true;}
// Every day: ships home from a voyage are free again, waiting cuts get one, charter prices follow the fleet.
function shipDay(){if(!S.fleet)S.fleet={};
for(const id in S.fleet){const f=S.fleet[id];if(S.day>=f.back){delete S.fleet[id];continue;}if(f.inc&&S.day<f.done&&!S.inc.some(i=>i.id===f.inc&&i.ship===id))shipRecall(id);}
for(const i of S.inc.filter(shipSea).sort((a,b)=>(a.start||0)-(b.start||0))){const l=shipLink(i);if(!l)continue;if(i.seaq)shipAssign(i,l);else if(!i.rushed)shipQuote(i,l);}}
// What the ship on a cut is doing, for the panels and the NOC.
function shipStatus(i){if(!shipSea(i))return '';const l=shipLink(i);if(!l)return '';
if(i.seaq){const D=shipFrom(i,l),z=shipZone(D);return tr('cable_ships.every_club_ship_is_out',{club:SHIP_CLUBS[z]?SHIP_CLUBS[z].n:''});}
const s=SHIP[i.ship],f=S.fleet[i.ship];if(!s||!f)return '';const d=S.day,home=CITY[s.home].name,end=Math.max(1,f.done-d);
if(d<f.arr)return tr('cable_ships.ship_sails_from_home',{ship:s.n,home,n:f.arr-d,m:end});
if(d<f.arr+(i.sp||0))return tr('cable_ships.ship_waits_for_a_permit',{ship:s.n,n:f.arr+(i.sp||0)-d,m:end});
return trn('cable_ships.ship_is_splicing',end,{ship:s.n});}
/* Laying your own subsea cable: the last part of the build is a lay ship at sea, about 150 km a day. A second ship,
booked before laying starts, works from the other end and halves that part; nothing at sea speeds up the survey,
the permits or the cable factory. */
const layDays=l=>Math.max(1,Math.ceil((l.km||0)/LAY_KMD)),layLen=l=>l.ship2?Math.ceil(layDays(l)/2):layDays(l),layStart=l=>l.ready-layLen(l);
const layOwn=l=>l.kind==='df'&&l.own&&l.sub;
const layName=(l,k=0)=>{let h=0;for(const ch of String(l.id))h=(h*31+ch.charCodeAt(0))>>>0;return LAY_SHIPS[(h+k)%LAY_SHIPS.length];};
function layQuote(l){if(!layOwn(l)||l.ship2||S.day>=layStart(l)||l.ready<=S.day+1)return null;const save=Math.floor(layDays(l)/2);if(save<1)return null;return {save,cost:SHIP_MOB+save*LAY_DAY};}
// How much of the cable is on the seabed, 0 to 1.
const layDone=(l,T)=>clamp((T-layStart(l))/layLen(l),0,1);

View file

@ -18,6 +18,8 @@ function dayTick(){
for(const k in S.peers){const [id,c]=k.split('@'),sn=snub(id,c);if(!sn)continue;delete S.peers[k];S.stats.depeered=(S.stats.depeered||0)+1;
{const v={net:esc(NET[id].name),ix:esc(ixName(c)),city:esc(CITY[ixCity(c)].name),why:esc(sn.why)};toast(ixNamesCity(c)?tr('day_tick.net_de_peered_you_at_ix',v):tr('day_tick.net_de_peered_you_at_ix_caef',v),'bad');}}
if(S.cnLic&&S.cnLic.state==='pending'&&d>=S.cnLic.ready){S.cnLic.state='ok';toast(tr('day_tick.license_granted_your_joint_venture'),'goal');sfx('coin');}
// cable ships: home again, sent to waiting cuts (50-cable-ships.js)
shipDay();
// 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);}

View file

@ -7,7 +7,9 @@ Object.assign(ACT,{
const n=chBack(l?[l]:[]);if(n)toast(trn('links.n_optic_back_on_the_spares_shelf',n),'good');}S.links=S.links.filter(l=>l.id!==id);prunePairMet();UI.sel=null;UI.confirm=null;after();},
// The chaos monkey takes a banana and goes home early (no bonus).
mkBanana:()=>{if(!mkOn())return;if(!spend(mkBananaCost()))return;S.stats.bananas=(S.stats.bananas||0)+1;mkLeave('banana');track('monkey_banana');after();},
fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))return;if(i.slow&&i.rushed)return;if(!spend(i.cost))return;
fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))return;
// At sea, paying means a private charter: another ship sails, it does not appear (50-cable-ships.js).
if(shipSea(i)){if(shipRush(i)){const s=SHIP[i.ship];toast(tr('cable_ships.ship_chartered',{ship:esc(s.n),home:esc(CITY[s.home].name),n:Math.max(1,i.until-S.day)}),'good');sfx('coin');after();}return;}if(i.slow&&i.rushed)return;if(!spend(i.cost))return;
if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();},
myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();},
foundIx:({city})=>{if(!S.pops[city]||S.myIx[city]||CITY[city].ix||CITY[city].cn)return;if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name;

View file

@ -33,6 +33,9 @@ Object.assign(ACT,{
addPair:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||!isRdm(l.sys)||l.ready>S.day)return;const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return;if((l.ch||[]).length+soldSlots(l)<chMax(l)){toast(tr('fiber_and_hardware.fill_this_pair_first_light_all',{max:chMax(l)}),'bad');sfx('err');return;}if(!spend(pairCost(l)))return;l.pairs=n+1;toast(tr('fiber_and_hardware.fiber_pair_n_is_lit_a',{n:n+1,a:CITY[l.a].name,b:CITY[l.b].name,m:DF_SYS[l.sys].max}),'good');sfx('build');after();},
upSys:({id})=>{const l=S.links.find(x=>x.id===id),to=l&&sysNext(l);if(!to||!techOk('sys',to,DF_SYS[to].lvl))return;if(!spend(sysUpCost(l)))return;l.sys=to;if(l.ready<=S.day){l.eqDown=S.day+1;toast(tr('fiber_and_hardware.line_system_swap_all_channels_are'),'bad');}after();},
spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();},
crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.ready<=S.day+1)return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(S.day+1,l.ready-30*n),saved=l.ready-ready;setCableReady(l,ready);toast(l.sub?trn('fiber_and_hardware.another_cable_ship_joins_the_lay',saved,{n:saved}):trn('fiber_and_hardware.more_crews_on_site_construction_is',saved,{n:saved}),'good');after();},
// Your own subsea cable: book a second lay ship before laying starts; it lays from the other end (50-cable-ships.js).
layShip:({id})=>{const l=S.links.find(x=>x.id===id);const q=l&&layQuote(l);if(!q||!spend(q.cost))return;l.ship2=1;setCableReady(l,l.ready-q.save);
toast(trn('cable_ships.second_lay_ship_booked',q.save,{ship:esc(layName(l,1)),n:q.save}),'good');sfx('coin');after();},
crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.sub||l.ready<=S.day+1)return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(S.day+1,l.ready-30*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('fiber_and_hardware.more_crews_on_site_construction_is',saved,{n:saved}),'good');after();},
addGen:({city})=>{const p=S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,tr('common.generator'),'#FF8A3D');after();},
});

View file

@ -52,7 +52,7 @@ function renderLeft(){checkLayer();
h+=`<p class="lead">${tr('hud_and_panels.your_network_operations_center_every')}</p>`;
h+=opsCard()+mkCard()+ddosPanel();
// Incidents come first, the ones you can fix with one click at the top (#63): no scrolling past hot ports to replace an optic.
for(const i of S.inc.filter(i=>i.type!=='ddos').sort((a,b)=>(b.cost?1:0)-(a.cost?1:0)||(b.impact||0)-(a.impact||0))){h+=`<div class="inc"><div class="nm">${incTitle(i.type)}</div><div class="meta">${esc(i.msg)}</div><div class="meta">${trn('hud_and_panels.auto_fix_in_n_day',i.until-S.day)}${i.impact?` · ${tr('hud_and_panels.g_lost',{g:fmtG(i.impact)})}`:''}</div>${i.cost?`<div class="btns">${btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash<i.cost)}</div>`:''}</div>`;}
for(const i of S.inc.filter(i=>i.type!=='ddos').sort((a,b)=>(b.cost?1:0)-(a.cost?1:0)||(b.impact||0)-(a.impact||0))){h+=`<div class="inc"><div class="nm">${incTitle(i.type)}</div><div class="meta">${esc(i.msg)}</div><div class="meta">${shipSea(i)?'🚢 '+esc(shipStatus(i)):trn('hud_and_panels.auto_fix_in_n_day',i.until-S.day)}${i.impact?` · ${tr('hud_and_panels.g_lost',{g:fmtG(i.impact)})}`:''}</div>${i.cost?`<div class="btns">${btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash<i.cost)}</div>`:''}</div>`;}
h+=logSection();UI.logSeen=Date.now();
h+=ddosSettings();
if(S.grace&&S.grace.until>S.day&&R.graceNets)h+=`<div class="kv"><span>${tr('common.courtesy_route')}</span><b>${tr('hud_and_panels.n_networks_d_days_left',{n:R.graceNets,d:S.grace.until-S.day})}</b></div><p class="meta" style="margin:0 0 6px">${tr('hud_and_panels.reaches_networks_from_the_last')}</p>`;

View file

@ -99,12 +99,21 @@ function subUpgradePanel(l){return `<h4 class="sub4">${tr('common.submarine_tran
const at=l['sub'+k],done=subUpgradeReady(l,k),cost=subUpgradeCost(l,k),preview={...l,['sub'+k]:S.day},use=at!==undefined||subHelps(l.km,k,l['sub'+subOther(k)]!==undefined);
const status=done?tr('common.installed'):at!==undefined?tr('link_panels.ready_in_n_days',{n:Math.max(0,at-S.day)}):tr('link_panels.price_n_days',{price:fmt$(cost),n:leadDays(U.days)});
return `<div class="row"><div class="grow"><div class="nm">${tr(U.n)}</div><div class="meta">${status}</div><div class="meta">${tr('common.up_to_g_per_channel',{g:fmtG(submarineRate(preview))})}</div>${use?'':`<div class="why">${tr('reach_and_subsea.makes_no_difference_on_this_cable')}</div>`}</div>${at===undefined?btn(tr('common.install'),'subUpgrade',{id:l.id,k},'sm',!use||lvl()<4||S.cash<cost):''}</div>`;}).join('');}
// The cable ship on a subsea cut (50-cable-ships.js), under the cut's story.
const shipNote=i=>{const t=i&&shipStatus(i);return t?`<p class="note">🚢 ${esc(t)}</p>`:'';};
// Building your own subsea cable: survey and factory first, then the lay ship at sea; a second one can be booked.
function layPanel(l){const d=S.day,st=layStart(l),q=layQuote(l),km=Math.round(layDone(l,d)*l.km),two=l.ship2?tr('cable_ships.ship_and_ship',{a:layName(l),b:layName(l,1)}):layName(l);
let h=d<st?`<div class="kv"><span>${tr('cable_ships.survey_permits_and_the_cable_factory')}</span><b>${trn('cable_ships.laying_starts_in_n_days',st-d)}</b></div>`
:`<div class="kv"><span>${tr('cable_ships.ships_lay_the_cable',{ships:esc(two)})}</span><b>${tr('cable_ships.km_of_km',{km:km.toLocaleString(),of:Math.round(l.km).toLocaleString()})}</b></div>`;
if(q)h+=`<div class="btns">${btn(tr('cable_ships.book_a_second_lay_ship',{price:fmt$(q.cost),n:q.save}),'layShip',{id:l.id},'sm',S.cash<q.cost)}</div><p class="note">${tr('link_panels.only_a_few_dozen_cable_ships')}</p>`;
else if(!l.ship2&&d<st)h+=`<p class="note">${tr('link_panels.only_a_few_dozen_cable_ships')}</p>`;
return h;}
function dfPanel(l){
const load=R.load[l.id]||0,cap=dfCap(l),u=cap?load/cap:0,bld=l.ready>S.day,A=CITY[l.a].name,B=CITY[l.b].name,inc=S.inc.find(i=>i.ref===l.id||i.ref===(l.trench||l.id)),amps=ampCount(l.km),sysD=DF_SYS[l.sys];
let h=`<div class="ph"><div><div class="eyebrow">${tr('link_panels.dark_fiber_kind_km_km',{kind:l.own?tr('link_panels.your_own_build'):tr('common.leased_iru'),km:l.km.toLocaleString()})}</div><h2>${A} ⇄ ${B}</h2></div><button class="x" data-act="closePanel" aria-label="${tr('common.close')}">×</button></div><div class="scroll">`;
if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1);
h+=`<section><h3>${l.own?tr('common.under_construction'):tr('common.being_spliced')}</h3><div class="kv"><span>${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}</span><b>${tr('common.n_days_left',{n:l.ready-S.day})}</b></div><div class="bar me"><i style="width:${done*100}%"></i></div>${l.own?`<div class="btns">${btn(l.sub?tr('link_panels.charter_another_cable_ship_price_30',{price:fmt$(crewCost(l))}):tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',l.ready<=S.day+1||S.cash<crewCost(l))}${btn(tr('link_panels.finish_in_1_day_price',{price:fmt$(crewSteps(l)*crewCost(l))}),'crews',{id:l.id,all:1},'sm',!crewSteps(l)||S.cash<crewSteps(l)*crewCost(l))}</div>${l.sub?`<p class="note">${tr('link_panels.only_a_few_dozen_cable_ships')}</p>`:''}`:''}<p class="note">${tr('link_panels.you_can_pre_install_optics_now')}</p></section>`;}
else if(inc&&linkDown(l))h+=`<section><h3 style="color:var(--bad)">${tr('common.dark_6bf5')}</h3><p class="lead">${esc(inc.msg)}</p>${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
h+=`<section><h3>${l.own?tr('common.under_construction'):tr('common.being_spliced')}</h3><div class="kv"><span>${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}</span><b>${tr('common.n_days_left',{n:l.ready-S.day})}</b></div><div class="bar me"><i style="width:${done*100}%"></i></div>${l.own&&l.sub?layPanel(l):l.own?`<div class="btns">${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',l.ready<=S.day+1||S.cash<crewCost(l))}${btn(tr('link_panels.finish_in_1_day_price',{price:fmt$(crewSteps(l)*crewCost(l))}),'crews',{id:l.id,all:1},'sm',!crewSteps(l)||S.cash<crewSteps(l)*crewCost(l))}</div>`:''}<p class="note">${tr('link_panels.you_can_pre_install_optics_now')}</p></section>`;}
else if(inc&&linkDown(l))h+=`<section><h3 style="color:var(--bad)">${tr('common.dark_6bf5')}</h3><p class="lead">${esc(inc.msg)}</p>${shipNote(inc)}${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
h+=`<section><h3>${tr('common.capacity')}</h3><div class="kv"><span>${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
${seatPanel(l)}${l.own&&l.sub?`<div class="kv"><span>${tr('common.cable_design')}</span><b>${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}</b></div>`:''}
<div class="kv"><span>${tr('common.latency')}</span><b>${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}</b></div><div class="kv"><span>${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}</span><b>${tr('common.price_mo',{price:fmt$(l.mo)})}</b></div><div class="kv"><span>${tr('link_panels.n_amp_huts',{n:amps})}</span><b>${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}</b></div>${!bld&&!(l.ch||[]).length?`<p class="why">${tr('link_panels.this_fiber_is_dark_add_optics')}</p>`:''}</section>`;
@ -136,7 +145,7 @@ function linkPanel(id){
if(l.kind==='df')return dfPanel(l);
const load=R.load[l.id]||0,cap=LT[l.tier].g,u=load/cap,cut=l.cut>S.day,trk=l.trench||l.id,inc=S.inc.find(i=>(LINKCUT_TR.includes(i.type)&&i.ref===trk)||((i.type==='fatwave'||i.type==='label'||i.type==='mtu')&&i.ref===l.id)),sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc'),mates=sib.filter(x=>(x.trench||x.id)===trk);
let h=`<div class="ph"><div><div class="eyebrow">${l.cable?esc(CAB[l.cable].name):l.sub?tr('common.subsea_cable'):tr('common.terrestrial_fiber')} · ${l.km.toLocaleString()} km</div><h2>${CITY[l.a].name} ⇄ ${CITY[l.b].name}</h2></div><button class="x" data-act="closePanel" aria-label="${tr('common.close')}">×</button></div><div class="scroll">`;
if(cut)h+=`<section><h3 style="color:var(--bad)">${tr('common.cut_2e50')}</h3><p class="lead">${inc?esc(inc.msg):''} ${tr('link_panels.back_in_n_days',{n:l.cut-S.day})}</p>${inc&&inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
if(cut)h+=`<section><h3 style="color:var(--bad)">${tr('common.cut_2e50')}</h3><p class="lead">${inc?esc(inc.msg):''} ${inc&&shipSea(inc)?'':tr('link_panels.back_in_n_days',{n:l.cut-S.day})}</p>${shipNote(inc)}${inc&&inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash<inc.cost):''}</section>`;
h+=`<section><h3>${tr('common.capacity')}</h3><div class="kv"><span>${tr('link_panels.name_wave',{name:LT[l.tier].n})}</span><b>${fmtG(load)} / ${fmtG(cap)}</b></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div>
<div class="kv"><span>${tr('common.latency')}</span><b>${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}</b></div>${l.cable?`<div class="kv"><span>${tr('common.cable_system')}</span><b>${esc(CAB[l.cable].name)}</b></div>`:''}
<div class="kv"><span>${tr('common.wave_lease')}</span><b>${tr('common.price_mo',{price:fmt$(l.mo)})}</b></div>${u>=0.9?`<p class="why">${tr('link_panels.congested_upgrade_it_or_add_a')}</p>`:''}

View file

@ -94,6 +94,8 @@ function drawFrame(now){
if(ly===null&&(prio(v)===0||(prio(v)===1&&(v.C.id===S.home||UI.hover===v.C.id)))){ly=below;const r={x:v.sx-tw/2,y:below-10,w:tw,h:21};rects.push(r);labs.push(r);}
v.ly=ly;}
if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,csc,now);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,csc,now,v.ly,v.dem);
// cable ships at sea (88-cable-ships.js), over the city labels so a ship leaving port stays in sight
drawShips(ks,now);
// Architect runs: what the tubes between two cities are (one trench, or separate paths), above the cities.
for(const [x,y,t,one] of AR_PILLS){ctx.font='800 11px "Baloo 2", sans-serif';const tw=ctx.measureText(t).width+12;ctx.fillStyle=one?'#FFE3C2':'#DDF7E7';ctx.strokeStyle=one?'#FF8A3D':'#16A866';ctx.lineWidth=2;rr(x-tw/2,y-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,x,y+1);}
// the chaos monkey (woken here after a reload, wherever it last snipped)

View file

@ -0,0 +1,49 @@
/* Cable ships on the map (85-incidents/50-cable-ships.js): club ships at anchor off their ports, sailing out to a cut,
splicing on site and sailing home; lay ships along a cable you are building. Where they are comes from S.fleet and
the clock, so nothing here is saved; their routes are worked out once per voyage and kept in SHIP_PATH. */
const SHIP_PATH=new Map(),SHIP_HITS=[];
// Off the port: the first point of a cable leaving it, so a ship rides at anchor at sea and not in town.
function shipHomePt(s){const k='h:'+s.id;let p=SHIP_PATH.get(k);if(p)return p;const C=CITY[s.home];p=[C.x,C.y];
for(const cp of CABLE_PAIRS){if(cp.a===s.home){p=cp.pts[1].slice();break;}if(cp.b===s.home){p=cp.pts[cp.pts.length-2].slice();break;}}
const n=SHIPS.filter(x=>x.home===s.home).indexOf(s);p[0]+=n*7;p[1]+=n*4;SHIP_PATH.set(k,p);return p;}
// Out along the cable routes to the cable's end, then along the cable to the fault.
function shipRoute(s,f){const key=s.id+'|'+f.dep+'|'+f.link+'|'+f.e+'|'+f.t;let r=SHIP_PATH.get(key);if(r)return r;if(SHIP_PATH.size>300)SHIP_PATH.clear();
const pts=[shipHomePt(s).slice()],push=q=>{const b=pts[pts.length-1];pts.push([q[0]+W*Math.round((b[0]-q[0])/W),q[1]]);},l=S.links.find(x=>x.id===f.link);
if(l){const end=f.e==='b'?l.b:l.a,D=shipDij({[end]:0});let c=s.home;
for(let n=0;n<999&&c!==end;n++){const p=D.prev.get(c);if(!p)break;const cp=CABLE_PAIRS[p.e.i],q=cp.a===c?cp.pts:cp.pts.slice().reverse();for(let j=1;j<q.length-1;j++)push(q[j]);c=p.from;}
const g=linkGeom(l);if(f.e==='a'){for(let j=1;j<g.pts.length-1&&g.cum[j]<f.t;j++)push(g.pts[j]);}else for(let j=g.pts.length-2;j>0&&g.cum[j]>f.t;j--)push(g.pts[j]);
push(polyAt(g.pts,g.cum,f.t));}
else push([f.fx,f.fy]);
const cum=[0];let L=0;for(let j=1;j<pts.length;j++){L+=Math.hypot(pts[j][0]-pts[j-1][0],pts[j][1]-pts[j-1][1]);cum.push(L);}for(let j=0;j<cum.length;j++)cum[j]/=L||1;
r={pts,cum};SHIP_PATH.set(key,r);return r;}
// Where a ship is at time T (days, with the part of today gone by) and what it is doing.
function shipAt(s,T){const f=S.fleet&&S.fleet[s.id],H=shipHomePt(s);if(!f||T>=f.back)return {x:H[0],y:H[1],m:'port',dx:1};
const r=shipRoute(s,f),m=f.dep+SHIP_MOB_D;let p,mode;
if(f.rs!=null&&T>=f.rs){p=f.rt*(1-clamp((T-f.rs)/Math.max(0.01,f.back-f.rs),0,1));mode='back';}
else if(T<m){p=0;mode='port';}else if(T<f.arr){p=(T-m)/Math.max(0.01,f.arr-m);mode='out';}else if(T<f.done){p=1;mode='work';}
else{p=1-(T-f.done)/Math.max(0.01,f.back-f.done);mode='back';}
p=clamp(p,0,1);const [x,y]=polyAt(r.pts,r.cum,p),[x2]=polyAt(r.pts,r.cum,clamp(p+(mode==='back'?-0.01:0.01),0,1));return {x,y,m:mode,dx:x2-x||1};}
// A cartoon cable ship: red hull, white bridge, the yellow bow sheave cable ships are known by; a wake when under way.
function shipSprite(x,y,face,sc,col,now,mode){const c=ctx;c.save();c.translate(x,y+Math.sin(now/420+x*0.05)*1.2*sc);c.scale(face*sc,sc);
if(mode!=='port'&&mode!=='work'){c.strokeStyle='rgba(255,255,255,.85)';c.lineWidth=1.6;c.beginPath();c.moveTo(-10,3);c.quadraticCurveTo(-16,1,-22,4);c.moveTo(-10,5);c.quadraticCurveTo(-15,8,-21,9);c.stroke();}
c.fillStyle=col;c.strokeStyle='#1E2640';c.lineWidth=1.6;c.lineJoin='round';c.beginPath();c.moveTo(-11,0);c.lineTo(11,0);c.lineTo(8,6);c.lineTo(-9,6);c.closePath();c.fill();c.stroke();
c.fillStyle='#fff';c.beginPath();c.rect(-7,-7,8,7);c.fill();c.stroke();c.fillStyle='#1E2640';c.fillRect(-5,-5,4,2);
c.beginPath();c.arc(9,-2,2.6,0,7);c.fillStyle='#FFD23F';c.fill();c.stroke();
if(mode==='work'&&Math.floor(now/350)%2){c.fillStyle='#FFD23F';c.font='900 11px sans-serif';c.textAlign='center';c.fillText('✦',12,-8);}
c.restore();}
function drawShips(ks,now){SHIP_HITS.length=0;if(!S||pzOn()||!S.fleet)return;
const T=S.day+(UI.speed?clamp(acc/DAY_MS,0,0.999):0),z=cam.z,sc=Math.max(0.75,Math.min(1.4,Math.sqrt(z)))*(lodFar()?0.8:1),list=[];
for(const s of SHIPS){const p=shipAt(s,T);if(p.m==='port'&&z<1.1)continue;list.push({p,s,col:s.club==='prv'?'#7A5CFF':'#FF4D5E'});}
for(const l of S.links)if(layOwn(l)&&l.ready>S.day&&T>=layStart(l)){const g=linkGeom(l),q=layDone(l,T),two=!!l.ship2;
const put=(t,k,dir)=>{const [x,y]=polyAt(g.pts,g.cum,clamp(t,0,1)),[x2]=polyAt(g.pts,g.cum,clamp(t+dir*0.01,0,1));list.push({p:{x,y,m:'lay',dx:x2-x||dir},lay:l,k,col:'#16A866'});};
if(two){put(q/2,0,1);put(1-q/2,1,-1);}else put(q,0,1);}
for(const it of list)for(const k of ks){const [sx,sy]=toS(it.p.x,it.p.y,k);if(sx<-30||sx>CW+30||sy<-30||sy>CH+30)continue;
shipSprite(sx,sy,it.p.dx<0?-1:1,sc,it.col,now,it.p.m);SHIP_HITS.push({x:sx,y:sy,r:14*sc,it});}}
function shipHit(cx,cy){const r=cv.getBoundingClientRect(),x=cx-r.left,y=cy-r.top;let best=null,bd=Infinity;
for(const h of SHIP_HITS){const d=Math.hypot(h.x-x,h.y-y);if(d<=h.r+6&&d<bd){bd=d;best=h.it;}}return best;}
// Tapping a ship says who it is and what it is doing, with a way to the cable it works on.
function shipTap(it){if(it.lay){const l=it.lay;sfx('click');toast(tr('cable_ships.lay_ship_tap',{ship:esc(layName(l,it.k)),a:esc(CITY[l.a].name),b:esc(CITY[l.b].name),km:Math.round(layDone(l,S.day)*l.km).toLocaleString(),of:Math.round(l.km).toLocaleString()}),'',[{l:tr('common.open'),act:'selLink',args:{id:l.id}}]);return;}
const s=it.s,f=S.fleet[s.id],club=s.club==='prv'?tr('cable_ships.private_operator'):SHIP_CLUBS[s.club].n,home=esc(CITY[s.home].name);sfx('click');
const i=f&&f.inc&&S.inc.find(x=>x.id===f.inc&&x.ship===s.id),l=f&&S.links.find(x=>x.id===f.link);
const what=!f||S.day>=f.back?(s.club==='prv'?tr('cable_ships.private_at_anchor',{home}):tr('cable_ships.at_anchor_off_home',{home})):i?esc(shipStatus(i)):trn('cable_ships.sailing_home_to_home',Math.max(1,f.back-S.day),{home});
toast(`<b>${esc(s.n)}</b><br>${esc(club)} · ${what}`,'',l&&i?[{l:tr('common.open'),act:'selLink',args:{id:l.id}}]:[]);}

View file

@ -26,6 +26,7 @@ function endPtr(e){
ptrs.delete(e.pointerId);const d=UI.drag;if(!d)return;
if(d.mode==='pinch'){if(ptrs.size===0){UI.drag=null;UI.snap=null;cv.classList.remove('linking');}return;}
if(d.mode==='link'){if(UI.snap&&UI.snap.id!==d.from){if(pzOn())pzLinkModal(d.from,UI.snap.id);else openLinkModal(d.from,UI.snap.id);sfx('click');}}
else if(!d.moved&&S&&shipHit(e.clientX,e.clientY))shipTap(shipHit(e.clientX,e.clientY));
else if(!d.moved&&S&&mkOn()&&mkHit(e.clientX,e.clientY)){sfx('click');toast(tr('chaos_monkey.tap'),'',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}]);}
else if(!d.moved&&S){const h=pickCity(e.clientX,e.clientY);
if(h){selectCity(h.id);renderLeft();sfx('click');}

View file

@ -419,6 +419,24 @@
"businesses.your_network_diagram_is_a_photo":"Your network diagram is a photo of a whiteboard.",
"businesses.your_noc_has_a_chat_channel":"Your NOC has a chat channel called #its-always-the-fiber, and it is always the fiber.",
"businesses.your_routing_table_needs_its_own":"Your routing table needs its own routing table.",
"cable_ships.at_anchor_off_home":"at anchor off {home}, ready to sail within a day.",
"cable_ships.book_a_second_lay_ship":"Book a second lay ship <small>{price} · −{n} days</small>",
"cable_ships.charter_ship":"Charter {ship}",
"cable_ships.every_club_ship_is_out":"Every {club} ship is out on a job. The cut waits for the first one back, or a private charter.",
"cable_ships.km_of_km":"{km} of {of} km",
"cable_ships.lay_ship_tap":"<b>{ship}</b><br>Laying your cable from {a} to {b}: {km} of {of} km on the seabed.",
"cable_ships.laying_starts_in_n_days":{"one":"Laying starts in {n} day","other":"Laying starts in {n} days"},
"cable_ships.private_at_anchor":"at anchor off {home}, for charter to anyone who pays.",
"cable_ships.private_operator":"Private operator",
"cable_ships.sailing_home_to_home":{"one":"sailing home to {home}, free again in {n} day.","other":"sailing home to {home}, free again in {n} days."},
"cable_ships.second_lay_ship_booked":{"one":"<b>{ship} is booked.</b><br>It lays from the other end: the cable is ready {n} day sooner.","other":"<b>{ship} is booked.</b><br>It lays from the other end: the cable is ready {n} days sooner."},
"cable_ships.ship_and_ship":"{a} and {b}",
"cable_ships.ship_chartered":"<b>{ship} is chartered.</b><br>It sails from {home}; the cable is back in about {n}d.",
"cable_ships.ship_is_splicing":{"one":"{ship} is splicing the cable: back in {n} day.","other":"{ship} is splicing the cable: back in {n} days."},
"cable_ships.ship_sails_from_home":"{ship} is sailing from {home}: on site in {n}d, cable back in about {m}d.",
"cable_ships.ship_waits_for_a_permit":"{ship} is on site, waiting {n}d for a repair permit. Cable back in about {m}d.",
"cable_ships.ships_lay_the_cable":"{ships} at sea, laying",
"cable_ships.survey_permits_and_the_cable_factory":"Survey, permits and the cable factory",
"cables.a_bet_on_a_tiny_island":"A bet on a tiny island in the middle of the Pacific.",
"cables.a_buffet_of_landings_down_norway":"A buffet of landings down the Norwegian coast, from the oil fields to Oslo.",
"cables.a_friendly_cable_with_french_manners":"A friendly cable with French manners.",
@ -1917,7 +1935,6 @@
"failures.geopolitical_cable_cut":"Geopolitical cable cut",
"failures.hash_polarisation_on_your_lab_nearly":"Hash polarisation on your {lab}: nearly every flow hashes onto the same member. The bundle says it is up. It is also full.",
"failures.hide_the_vacuum":"Hide the vacuum",
"failures.jump_the_cable_ship_queue":"Jump the cable-ship queue",
"failures.lacp_fast_slow_timer_mismatch_on":"LACP fast/slow timer mismatch on your {lab}: one member keeps timing out of the bundle and coming back.",
"failures.lightning_hit_an_amp_site_on":"Lightning hit an amp site on {a}–{b}. The surge protector was decorative.",
"failures.load_shedding_in_city_stage_n":"<b>Load shedding in {city}</b><br>Stage {n} today. Your generator coughed, then kept the lights on.",
@ -1998,7 +2015,6 @@
"failures.your_spares_kit_gets_it_back":"Your spares kit gets it back tomorrow.",
"features.done_in_d_days":"done in {d} days",
"features.weekly_challenge_key":"Weekly challenge {key}",
"fiber_and_hardware.another_cable_ship_joins_the_lay":{"one":"<b>Another cable ship joins the lay.</b><br>The cable is {n} day ahead.","other":"<b>Another cable ship joins the lay.</b><br>The cable is {n} days ahead."},
"fiber_and_hardware.can_t_add_optic_why":"<b>Can't add {optic}.</b><br>{why}",
"fiber_and_hardware.dark_fiber_iru_signed_a_b":"<b>Dark fiber IRU signed.</b><br>{a}–{b} will be spliced and handed over in about 30 days.",
"fiber_and_hardware.fiber_pair_n_is_lit_a":"<b>Fiber pair {n} is lit: {a}–{b}.</b><br>Another ROADMaster 9000 and a fresh chain of amplifiers. Room for {m} more channels.",
@ -2414,7 +2430,6 @@
"link_panels.build_a_pop_here_first":"Build a POP here first.",
"link_panels.cancel_the_iru":"Cancel the IRU",
"link_panels.carry_here":"Carry here",
"link_panels.charter_another_cable_ship_price_30":"Charter another cable ship <small>{price} · −30 days</small>",
"link_panels.click_to_tear_down":"Click to tear down",
"link_panels.collecting_data_check_back_in_a":"Collecting data. Check back in a few days.",
"link_panels.congested_upgrade_it_or_add_a":"Congested. Upgrade it or add a parallel path.",

238
tests/cable-ships.test.js Normal file
View file

@ -0,0 +1,238 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Cable ships (src/game/20-world/70-cable-ships.js, src/game/85-incidents/50-cable-ships.js): a subsea cut sends a club
// ship from its port, the cut lasts until it has sailed out and spliced, the ship is busy until it is home again, and a
// cut waits when every ship of its zone's club is out, unless a private charter jumps the queue.
const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.day=200;S.nextFail=S.nextEvent=1e8;for(const g of GOALS)S.done[g.id]=0;";
const wave = (id, a, b, cable, km) => `{id:'${id}',a:'${a}',b:'${b}',kind:'wave',sub:true,tier:0,km:${km},cable:'${cable}',cut:0,mo:1000}`;
// A cut with a known fault: t of the way from a, sw days of splicing, sp days of permits.
const cut = (id, link, t, sw = 4, sp = 0) => `(()=>{const l=S.links.find(x=>x.id==='${link}');S.inc.push({id:'${id}',type:'cut',ref:l.trench||l.id,until:S.day+15,msg:'cut',cost:4000,start:S.day});
const i=S.inc[S.inc.length-1];i.sl=l.id;i.st=${t};i.sw=${sw};i.sp=${sp};shipAssign(i,l);})()`;
const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`));
test('a subsea cut sends the nearest free club ship, and lasts until it has sailed out and spliced', () => {
const { ev, errors } = load();
ev(start + `S.links=[${wave('med', 'bcn', 'mrs', 'medusa', 365)}];S.inc=[];` + cut('c1', 'med', 0.9));
const i = J(ev, "S.inc[0]"), f = J(ev, "S.fleet[S.inc[0].ship]");
assert.ok(['mend', 'tea'].includes(i.ship), 'a Mediterranean Mending Club ship from Marseille');
// 10% of 365 km from Marseille: one day to sail, one to get going, four to splice.
assert.equal(f.arr, 200 + 1 + 1);
assert.equal(f.done, f.arr + 4);
assert.equal(f.back, f.done + 1);
assert.equal(i.until, f.done);
assert.equal(ev("S.links[0].cut"), f.done);
assert.equal(ev("linkDown(S.links[0])"), true);
assert.match(ev("shipStatus(S.inc[0])"), /is sailing from Marseille: on site in 2d, cable back in about 6d/);
// The cut ends with the splice; the ship sails home and only then takes another job.
for (let d = 200; d < f.done; d++) ev('dayTick()');
assert.equal(ev("S.inc.length"), 0);
assert.equal(ev("linkDown(S.links[0])"), false);
assert.ok(ev(`!shipFree(SHIP.${i.ship})`), 'still sailing home');
ev('dayTick()');
assert.ok(ev(`shipFree(SHIP.${i.ship})`));
assert.equal(ev(`S.fleet.${i.ship}`), undefined);
assert.deepEqual(errors, []);
});
test('with every club ship out the cut waits; a private charter jumps the queue, for millions', () => {
const { ev, errors } = load();
ev(start + `S.links=[${wave('med', 'bcn', 'mrs', 'medusa', 365)}];S.inc=[];`
+ "for(const id of ['mend','tea'])S.fleet[id]={inc:null,link:'x',t:0.5,e:'a',dep:190,arr:195,done:205,back:230,fx:0,fy:0};" + cut('c1', 'med', 0.5));
const i = J(ev, "S.inc[0]");
assert.equal(i.ship, null);
assert.equal(i.seaq, 1);
assert.equal(ev("linkDown(S.links[0])"), true);
assert.match(ev("shipStatus(S.inc[0])"), /Every Mediterranean Mending Club ship is out on a job/);
// The charter is the quickest free ship anywhere: from Cornwall, about 4,800 km away.
assert.ok(i.cost >= 1000000 + 4000 * 200, `charter costs ${i.cost}`);
assert.match(i.fix, /^Charter /);
const cash = ev('S.cash');
ev("ACT.fixInc({id:'c1'})");
assert.equal(cash - ev('S.cash'), i.cost);
const now = J(ev, "S.inc[0]"), f = J(ev, "S.fleet[S.inc[0].ship]");
assert.ok(now.ship && !['mend', 'tea'].includes(now.ship), `chartered ${now.ship}`);
assert.equal(now.seaq, undefined);
assert.equal(now.until, f.done);
assert.ok(f.done < 260, 'back well within the next weeks');
assert.equal(ev("S.inc[0].cost"), 0, 'nothing more to buy');
assert.deepEqual(errors, []);
});
test('a waiting cut gets the first club ship home', () => {
const { ev, errors } = load();
ev(start + `S.links=[${wave('med', 'bcn', 'mrs', 'medusa', 365)}];S.inc=[];`
+ "S.fleet.mend={inc:null,link:'x',t:0.5,e:'a',dep:190,arr:195,done:200,back:202,fx:0,fy:0};S.fleet.tea={...S.fleet.mend,back:260};" + cut('c1', 'med', 0.5));
assert.equal(ev("S.inc[0].seaq"), 1);
ev('dayTick();dayTick()');
assert.equal(ev("S.inc[0].ship"), 'mend');
assert.equal(ev("S.inc[0].until"), ev("S.fleet.mend.done"));
assert.deepEqual(errors, []);
});
test('a charter while a club ship is on its way turns that ship round', () => {
const { ev, errors } = load();
// Both Cornwall ships are out, so the club sends the next one, from Curaçao: a long way round by the cable routes.
ev(start + `S.links=[${wave('atl', 'nyc', 'bde', 'apollo', 5564)}];S.inc=[];`
+ "for(const id of ['knot','splice'])S.fleet[id]={inc:null,link:'x',t:0.5,e:'a',dep:190,arr:195,done:200,back:201,fx:0,fy:0};" + cut('c1', 'atl', 0.7));
const first = ev("S.inc[0].ship");
assert.ok(['reel', 'cguy'].includes(first), `another Atlantic Splice Society ship: ${first}`);
// Next day a Cornwall ship is home: chartering it beats waiting for the long voyage.
ev('S.day=201;shipDay()');
const i = J(ev, "S.inc[0]");
assert.ok(i.cost > 0, 'the Cornwall ship would be there sooner');
ev("ACT.fixInc({id:'c1'})");
assert.ok(['knot', 'splice'].includes(ev("S.inc[0].ship")));
const f = J(ev, `S.fleet.${first}`);
assert.equal(f.inc, null, 'the first ship has no job any more');
assert.equal(f.rs, 201);
assert.ok(f.back <= 202, 'it turns back after a day under way');
assert.deepEqual(errors, []);
});
test('repairs in slow-permit waters wait for the paperwork; deep water takes longer on site', () => {
const { ev, errors } = load();
ev(start + `S.links=[${wave('in', 'bom', 'maa', 'bbg', 2315)},${wave('atl', 'nyc', 'bde', 'apollo', 5564)}];S.inc=[];`);
for (let seed = 1; seed <= 24; seed++) {
ev(`window.__reseed(${seed});S.fleet={};S.inc=[];(()=>{const l=S.links[${seed % 2}];S.inc.push({id:'c',type:'cut',ref:l.id,until:S.day+15,msg:'',cost:0,start:S.day});shipCut(S.inc[0],l);})()`);
const i = J(ev, "S.inc[0]"), km = seed % 2 ? 5564 : 2315, shallow = Math.min(i.st, 1 - i.st) * km <= 300;
if (seed % 2 === 0 && shallow) assert.ok(i.sp >= 21 && i.sp <= 42, `Indian waters: ${i.sp} days of permits`);
else assert.equal(i.sp, 0, 'no permit in the open sea, nor off New York or Cornwall');
if (shallow) assert.ok(i.sw >= 3 && i.sw <= 5); else assert.ok(i.sw >= 6 && i.sw <= 12);
}
assert.deepEqual(errors, []);
});
test('fireFailure on a subsea wave calls a ship; a cut on land does not', () => {
const { ev, errors } = load();
ev(start + `S.links=[${wave('med', 'bcn', 'mrs', 'medusa', 365)}];S.inc=[];fireFailure('cut')`);
const sea = J(ev, "S.inc.find(i=>i.type==='cut')");
assert.ok(sea.ship || sea.seaq);
assert.ok(sea.st > 0 && sea.st < 1);
ev("S.links=[{id:'land',a:'fra',b:'ams',kind:'wave',tier:0,km:400,cut:0,mo:1000}];S.inc=[];S.fleet={};fireFailure('cut')");
const land = J(ev, "S.inc.find(i=>i.type==='cut')");
assert.equal(land.ship, undefined);
assert.equal(land.cost, 4000);
assert.deepEqual(J(ev, "Object.keys(S.fleet)"), []);
assert.deepEqual(errors, []);
});
test('ships and their jobs survive a save; broken or old saves are repaired', () => {
const { ev, errors } = load();
ev(start + `S.links=[${wave('med', 'bcn', 'mrs', 'medusa', 365)}];S.inc=[];` + cut('c1', 'med', 0.9));
const before = J(ev, "[S.inc[0],S.fleet]");
ev('S=migrate(JSON.parse(JSON.stringify(S)))');
assert.deepEqual(J(ev, "[S.inc[0],S.fleet]"), before);
// Unknown ships, nonsense numbers and a job that points nowhere.
ev("S.fleet.titanic={dep:1,arr:2,done:3,back:9e9};S.fleet[S.inc[0].ship].arr='soon';S.inc[0].st=7;S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev("S.fleet.titanic"), undefined);
assert.ok(ev("Number.isFinite(S.fleet[S.inc[0].ship].arr)"));
assert.equal(ev("S.inc[0].st"), 0.97);
ev("S.inc[0].ship='titanic';S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev("S.inc[0].ship"), null);
assert.equal(ev("S.inc[0].seaq"), 1, 'a cut that lost its ship waits for the next one');
// A save from before cable ships: no fleet, and a cut with no ship keeps working as it did.
ev("const o=JSON.parse(JSON.stringify(S));delete o.fleet;o.inc=[{id:'old',type:'cut',ref:'med',until:o.day+5,msg:'old cut',cost:4000}];S=migrate(o)");
assert.deepEqual(J(ev, 'S.fleet'), {});
assert.equal(ev("S.inc[0].ship"), undefined);
assert.equal(ev("shipSea(S.inc[0])"), false);
ev('dayTick()');
assert.deepEqual(errors, []);
});
test('ships are drawn where their voyage puts them, and tapping one says what it does', () => {
const { ev, dom, errors } = load();
ev(start + `S.links=[${wave('med', 'bcn', 'mrs', 'medusa', 365)}];S.inc=[];` + cut('c1', 'med', 0.5));
const id = ev("S.inc[0].ship");
const home = J(ev, `shipHomePt(SHIP.${id})`), f = J(ev, `S.fleet.${id}`);
assert.equal(J(ev, `shipAt(SHIP.${id},200.5)`).m, 'port', 'getting under way');
const out = J(ev, `shipAt(SHIP.${id},${f.arr - 0.5})`);
assert.equal(out.m, 'out');
const work = J(ev, `shipAt(SHIP.${id},${f.arr + 1})`);
assert.equal(work.m, 'work');
assert.ok(Math.abs(work.x - f.fx) < 1 && Math.abs(work.y - f.fy) < 1, 'on the fault');
const back = J(ev, `shipAt(SHIP.${id},${f.back + 1})`);
assert.ok(Math.abs(back.x - home[0]) < 1e-6 && Math.abs(back.y - home[1]) < 1e-6, 'home again');
// Drawn on the map, and found by a tap.
ev(`const C=CITY.mrs;cam.x=C.x;cam.y=C.y;cam.z=3;UI.speed=1;draw(0)`);
assert.ok(ev('SHIP_HITS.length') >= 2, 'the ship at work and its sister ship in port');
const hit = J(ev, `SHIP_HITS.find(h=>h.it.s&&h.it.s.id==='${id}')`);
ev(`(()=>{const r=cv.getBoundingClientRect();shipTap(shipHit(${hit.x}+r.left,${hit.y}+r.top))})()`);
assert.match(dom.window.document.body.innerHTML, /Mediterranean Mending Club/);
assert.deepEqual(errors, []);
});
test('the link panel and the NOC say where the ship is, on a phone too', () => {
const { ev, dom, errors } = load();
ev(start + `S.links=[${wave('med', 'bcn', 'mrs', 'medusa', 365)}];S.inc=[];` + cut('c1', 'med', 0.5));
ev("window.innerWidth=360;UI.sel={type:'link',id:'med'};renderPanel()");
const panel = dom.window.document.querySelector('#panelBody').textContent;
assert.match(panel, /is sailing from Marseille/);
assert.doesNotMatch(panel, /Back in \d+ days/);
ev("UI.left='noc';UI.leftOpen=true;renderLeft()");
assert.match(dom.window.document.querySelector('#leftBody').textContent, /is sailing from Marseille/);
assert.deepEqual(errors, []);
});
test('your own subsea cable: survey and factory first, then a lay ship; a second one can be booked, crews cannot help', () => {
const { ev, dom, errors } = load();
ev(start + "S.links=[{id:'own',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:6000,ch:[],day:200,ready:800,cut:0,mo:1}];");
assert.equal(ev('layDays(S.links[0])'), 40);
assert.equal(ev('layStart(S.links[0])'), 760);
assert.deepEqual(J(ev, 'layQuote(S.links[0])'), { save: 20, cost: 3000000 + 20 * 150000 });
ev("UI.sel={type:'link',id:'own'};renderPanel()");
const panel = () => dom.window.document.querySelector('#panelBody').textContent;
assert.match(panel(), /Survey, permits and the cable factory/);
assert.match(panel(), /Laying starts in 560 days/);
assert.match(panel(), /Book a second lay ship/);
assert.doesNotMatch(panel(), /Hire extra crews|Finish in 1 day/);
const cash = ev('S.cash');
ev("ACT.crews({id:'own'})");
assert.equal(ev('S.cash'), cash, 'no crews at sea');
ev("ACT.layShip({id:'own'})");
assert.equal(cash - ev('S.cash'), 6000000);
assert.equal(ev('S.links[0].ready'), 780);
assert.equal(ev('layStart(S.links[0])'), 760, 'laying starts the same day, two ships finish sooner');
assert.equal(ev('layQuote(S.links[0])'), null, 'one second ship is all');
ev("ACT.layShip({id:'own'})");
assert.equal(cash - ev('S.cash'), 6000000);
// At sea: both ships on the map, from both ends.
ev("S.day=770;UI.sel={type:'link',id:'own'};renderPanel();const C=CITY.lag;cam.x=C.x;cam.y=C.y;cam.z=0.5;UI.speed=0;draw(0)");
assert.match(panel(), /at sea, laying/);
assert.match(panel(), /3,000 of 6,000 km/);
assert.equal(ev("SHIP_HITS.filter(h=>h.it.lay).length>=1"), true);
// Too late to book once laying has started.
ev("S.links[0].ship2=undefined;S.links[0].ready=800");
assert.equal(ev('layQuote(S.links[0])'), null);
ev('S=migrate(JSON.parse(JSON.stringify(S)))');
assert.deepEqual(errors, []);
});
test('a second lay ship moves pending subsea upgrades with the finish', () => {
const { ev, errors } = load();
ev(start + "S.links=[{id:'own',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:15000,ch:[],day:200,ready:1000,cut:0,mo:1}];");
ev("ACT.subUpgrade({id:'own',k:'terminal'});ACT.subUpgrade({id:'own',k:'engineering'})");
const before = J(ev, '[S.links[0].ready,S.links[0].subterminal,S.links[0].subengineering]');
ev("ACT.layShip({id:'own'})");
const save = Math.floor(Math.ceil(15000 / 150) / 2);
assert.deepEqual(J(ev, '[S.links[0].ready,S.links[0].subterminal,S.links[0].subengineering]'), before.map((d) => d - save));
assert.deepEqual(errors, []);
});
test('the NOC intern’s rush-repair order pays a charter only within its budget', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');"
+ "ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();S.day=200;"
+ `S.links=[${wave('med', 'bcn', 'mrs', 'medusa', 365)}];S.inc=[];`
+ "for(const id of ['mend','tea'])S.fleet[id]={inc:null,link:'x',t:0.5,e:'a',dep:190,arr:195,done:205,back:230,fx:0,fy:0};" + cut('c1', 'med', 0.5));
const cost = ev('S.inc[0].cost'), cash = ev('S.cash');
ev("S.ops.on.repair=true;S.ops.p.repair={};S.ops.cap.repair=1e6;opsDay(S.day)");
assert.equal(ev('S.inc[0].seaq'), 1, 'over budget: the cut keeps waiting');
assert.equal(ev('S.cash'), cash);
assert.ok(cost > 1e6 && cost < 5e6, `a charter from Cornwall: ${cost}`);
ev('S.ops.cap.repair=5e6;opsDay(S.day)');
assert.equal(cash - ev('S.cash'), cost);
assert.ok(ev('S.inc[0].ship') && !ev('S.inc[0].seaq'));
assert.deepEqual(errors, []);
});

View file

@ -99,6 +99,8 @@ const REAL_NAMES = [
'AMS-IX', 'Any2', 'BCIX', 'CoreSite', 'DE-CIX', 'Digital Realty', 'Equinix', 'France-IX', 'Interxion', 'IX.br', 'JPIX', 'LINX', 'NAPAfrica', 'NetIX', 'NIX', 'NL-ix', 'SIX', 'Telehouse',
// cables
'2Africa', 'Amitié', 'Dunant', 'EllaLink', 'Equiano', 'Grace Hopper', 'Hibernia Express', 'Jupiter', 'MAREA', 'PEACE', 'SEA-ME-WE 6',
// cable ships, their operators and maintenance clubs
'ACMA', 'ASEAN Explorer', 'ASEAN Protector', 'ASEAN Restorer', 'Cable Innovator', 'Cable Retriever', 'Global Marine', 'Léon Thévenin', 'MECMA', 'Orange Marine', 'Pierre de Fermat', 'René Descartes', 'SEAIOCMA', 'Sophie Germain', 'Sovereign', 'Wave Sentinel', 'Yokohama Zone',
// vendors
'Arista', 'Brocade', 'Ciena', 'Cisco', 'Extreme Networks', 'Huawei', 'Infinera', 'Juniper', 'MikroTik', 'Nokia',
];
@ -159,11 +161,11 @@ test('N1: network ids and ASNs are unique, ASNs are valid', () => {
fail('N1', J("NETS.filter(n=>!Number.isInteger(n.asn)||n.asn<1||n.asn>4294967294||n.asn>=64512&&n.asn<=65534).map(n=>n.id)"), 'use the real, public ASN');
});
test('N2: names are puns: no network, cable, exchange, data center, router or optic carries a real name', () => {
test('N2: names are puns: no network, cable, exchange, data center, router, optic or cable ship carries a real name', () => {
const norm = (s) => String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’`]/g, "'").replace(/\s+/g, ' ').trim();
const real = new Set(REAL_NAMES.map(norm));
const names = J(`[...NETS.map(n=>['network',n.name]),...CABLES.map(c=>['cable',c.name]),...XIX.map(x=>['exchange',x.name]),
...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]])].filter(x=>x[1])`);
...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]]),...SHIPS.map(x=>['cable ship',x.n]),...LAY_SHIPS.map(n=>['cable ship',n]),...Object.values(SHIP_CLUBS).map(c=>['maintenance club',c.n])].filter(x=>x[1])`);
fail('N2', names.filter(([, n]) => real.has(norm(n))).map(([k, n]) => `${k} “${n}” is a real name`), 'find a pun');
fail('N2', names.filter(([, n]) => /-ish\b/i.test(n)).map(([k, n]) => `${k} “${n}”`), 'no lazy -ish names: find a real pun, or keep the plain word');
});

View file

@ -1,60 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Hurrying anything at sea takes a cable ship: a charter for a build, a place in the repair queue for a cut. Both cost
// millions, while the same hurry on land stays cheap.
const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.day=200;for(const g of GOALS)S.done[g.id]=0;";
test('more crews on a subsea build means chartering a cable ship, for millions', () => {
const { ev, dom, errors } = load();
ev(start + "S.links=[{id:'sea',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:6000,ch:[],day:200,ready:800,cut:0,mo:1},"
+ "{id:'land',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',km:400,ch:[],day:200,ready:500,cut:0,mo:1}]");
assert.equal(ev("crewCost(S.links[0])"), 3000000 + 6000 * 500, 'mobilising a ship plus its time at sea');
assert.ok(ev("crewCost(S.links[1])") < 50000, 'land crews stay cheap');
const cash = ev('S.cash');
ev("ACT.crews({id:'sea'})");
assert.equal(cash - ev('S.cash'), 6000000);
assert.equal(ev('S.links[0].ready'), 770);
assert.match(dom.window.document.body.innerHTML, /Another cable ship joins the lay/);
ev("UI.sel={type:'link',id:'sea'};renderPanel()");
const panel = () => dom.window.document.querySelector('#panelBody').textContent;
assert.match(panel(), /Charter another cable ship/);
assert.match(panel(), /Only a few dozen cable ships exist/);
assert.doesNotMatch(panel(), /Hire extra crews/);
ev("UI.sel={type:'link',id:'land'};renderPanel()");
assert.match(panel(), /Hire extra crews/);
assert.doesNotMatch(panel(), /cable ship/);
// The whole lay in one go is the charter times every 30 days left.
ev("S.cash=1e9;UI.sel={type:'link',id:'sea'};renderPanel()");
assert.equal(ev("crewSteps(S.links[0])*crewCost(S.links[0])"), 19 * 6000000);
assert.deepEqual(errors, []);
});
test('a rush repair on a subsea cut, even on a leased wave, costs a cable ship, a trench cut stays cheap', () => {
const { ev, errors } = load();
ev(start + "S.links=[{id:'sea',a:'lag',b:'bde',kind:'wave',sub:true,tier:0,km:6000,cut:0,mo:1000}];S.inc=[];fireFailure('cut')");
const sea = JSON.parse(ev("JSON.stringify(S.inc.find(i=>i.type==='cut'))"));
assert.equal(sea.cost, 1000000 + 6000 * 200);
assert.equal(sea.fix, 'Jump the cable-ship queue');
ev("S.links=[{id:'land',a:'fra',b:'ams',kind:'wave',tier:0,km:400,cut:0,mo:1000}];S.inc=[];fireFailure('cut')");
const land = JSON.parse(ev("JSON.stringify(S.inc.find(i=>i.type==='cut'))"));
assert.equal(land.cost, 4000);
assert.equal(land.fix, undefined);
// Paying it brings the cable back at once, like any rush repair.
ev("S.links=[{id:'sea',a:'lag',b:'bde',kind:'wave',sub:true,tier:0,km:6000,cut:0,mo:1000}];S.inc=[];fireFailure('cut')");
const id = ev("S.inc.find(i=>i.type==='cut').id"), cash = ev('S.cash');
ev(`ACT.fixInc({id:'${id}'})`);
assert.equal(cash - ev('S.cash'), 2200000);
assert.equal(ev("linkDown(S.links[0])"), false);
assert.deepEqual(errors, []);
});
test('the chaos monkey snipping a subsea cable prices the rush the same way', () => {
const { ev, errors } = load();
ev(start + "S.links=[{id:'sea',a:'lag',b:'bde',kind:'wave',sub:true,tier:0,km:3000,cut:0,mo:1000}];S.inc=[];"
+ "S.monkey={n:0,hurt:0,until:S.day+100};mkSnip()");
const i = JSON.parse(ev("JSON.stringify(S.inc.find(i=>i.type==='cut'))"));
assert.equal(i.cost, 1000000 + 3000 * 200);
assert.deepEqual(errors, []);
});

View file

@ -2,51 +2,50 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(ev) {
// A 15,000 km cable of your own: 100 days of laying at the end of the build, and a second lay ship saves 50.
function setup(ev, sub = true) {
ev(`ACT.start({});S.cash=1e11;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0;
S.links=[{id:'cable',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:15000,ch:[],day:100,ready:1000,cut:0,mo:1}];`);
S.links=[{id:'cable',a:'lag',b:'bde',kind:'df',own:true,sub:${sub},sys:'roadm',km:15000,ch:[],day:100,ready:1000,cut:0,mo:1}];`);
}
function dates(ev) {
return JSON.parse(ev('JSON.stringify([S.links[0].ready,S.links[0].subterminal,S.links[0].subengineering])'));
}
test('upgrades queued during construction follow crews and keep their 30/180-day commissioning time', () => {
test('upgrades queued during construction follow a second lay ship and keep their 30/180-day commissioning time', () => {
const { ev, dom, errors } = load();
try {
setup(ev);
ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'})");
assert.deepEqual(dates(ev), [1000, 1030, 1180]);
const paid = ev('S.links[0].paid');
ev("ACT.crews({id:'cable'})");
assert.deepEqual(dates(ev), [970, 1000, 1150]);
ev("for(let i=0;i<29;i++)ACT.crews({id:'cable'})");
assert.deepEqual(dates(ev), [101, 131, 281], 'last crew purchase shifts dates by 29 days, not 30');
ev("ACT.layShip({id:'cable'})");
assert.deepEqual(dates(ev), [950, 980, 1130]);
const cash = ev('S.cash');
ev("ACT.crews({id:'cable'})");
assert.equal(ev('S.cash'), cash, 'one day remaining: crews cannot charge for saving zero days');
assert.deepEqual(dates(ev), [101, 131, 281], 'commissioning cannot be rushed further through the cable');
ev("ACT.layShip({id:'cable'})");
assert.equal(ev('S.cash'), cash, 'one second ship: a second booking charges nothing');
assert.deepEqual(dates(ev), [950, 980, 1130], 'commissioning cannot be rushed further through the cable');
ev("UI.sel={type:'link',id:'cable'};renderPanel()");
assert.equal(dom.window.document.querySelector('#panelBody [data-act=crews]').disabled, true);
assert.equal(dom.window.document.querySelector('#panelBody [data-act=layShip]'), null);
assert.equal(ev('S.links[0].paid'), paid, 'no second upgrade charge');
ev('S=migrate(JSON.parse(JSON.stringify(S)))');
assert.deepEqual(dates(ev), [101, 131, 281], 'save round trip preserves commissioning windows');
ev('S.day=130');assert.equal(ev("subUpgradeReady(S.links[0],'terminal')"), false);
ev('S.day=131');assert.equal(ev("subUpgradeReady(S.links[0],'terminal')"), true);
ev('S.day=280');assert.equal(ev("subUpgradeReady(S.links[0],'engineering')"), false);
ev('S.day=281');assert.equal(ev("subUpgradeReady(S.links[0],'engineering')"), true);
assert.deepEqual(dates(ev), [950, 980, 1130], 'save round trip preserves commissioning windows');
ev('S.day=979');assert.equal(ev("subUpgradeReady(S.links[0],'terminal')"), false);
ev('S.day=980');assert.equal(ev("subUpgradeReady(S.links[0],'terminal')"), true);
ev('S.day=1129');assert.equal(ev("subUpgradeReady(S.links[0],'engineering')"), false);
ev('S.day=1130');assert.equal(ev("subUpgradeReady(S.links[0],'engineering')"), true);
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});
test('ordering upgrades early is as fast as ordering after rushing the cable', () => {
test('ordering upgrades early is as fast as ordering after booking the second lay ship', () => {
const { ev, dom } = load();
try {
setup(ev);
ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'});for(let i=0;i<30;i++)ACT.crews({id:'cable'})");
ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'});ACT.layShip({id:'cable'})");
const early = dates(ev);
setup(ev);
ev("for(let i=0;i<30;i++)ACT.crews({id:'cable'});S.day=101;ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'})");
ev("ACT.layShip({id:'cable'});S.day=101;ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'})");
assert.deepEqual(dates(ev), early);
} finally { dom.window.close(); }
});
@ -58,7 +57,9 @@ test('packages included in the original order stay aligned with its accelerated
ev("S.won=true;UI.pending={a:'sin',b:'lax'};UI.seaterminal=UI.seaengineering=true;ACT.orderCable();S.links=[S.links.at(-1)]");
assert.equal(ev('S.links[0].subterminal'), ev('S.links[0].ready'));
assert.equal(ev('S.links[0].subengineering'), ev('S.links[0].ready'));
ev("ACT.crews({id:S.links[0].id})");
const ready = ev('S.links[0].ready');
ev("ACT.layShip({id:S.links[0].id})");
assert.ok(ev('S.links[0].ready') < ready, 'the second lay ship finishes sooner');
assert.equal(ev('S.links[0].subterminal'), ev('S.links[0].ready'));
assert.equal(ev('S.links[0].subengineering'), ev('S.links[0].ready'));
ev('S=migrate(JSON.parse(JSON.stringify(S)))');
@ -103,11 +104,11 @@ test('old saves repair excessive pending waits without changing valid dates, cha
} finally { dom.window.close(); }
});
test('land fiber, leased cables, invalid upgrades and rejected crew purchases remain unaffected', () => {
test('land fiber, leased cables, invalid upgrades and rejected lay ship bookings remain unaffected', () => {
const { ev, dom } = load();
try {
setup(ev);
ev("S.links[0].subterminal=1030;S.links[0].subengineering=1180;S.cash=0;ACT.crews({id:'cable'})");
ev("S.links[0].subterminal=1030;S.links[0].subengineering=1180;S.cash=0;ACT.layShip({id:'cable'})");
assert.deepEqual(dates(ev), [1000, 1030, 1180]);
ev(`S.links.push({...S.links[0],id:'land',sub:false},{...S.links[0],id:'leased',own:false});
setCableReady(S.links[1],970);setCableReady(S.links[2],970);`);
@ -121,27 +122,32 @@ test('land fiber, leased cables, invalid upgrades and rejected crew purchases re
} finally { dom.window.close(); }
});
test('one-click completion costs the same as repeated crew hires and advances pending upgrades identically', () => {
test('one-click completion on land costs the same as repeated crew hires', () => {
const { ev, dom, errors } = load();
try {
setup(ev);
ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'});UI.sel={type:'link',id:'cable'};renderPanel()");
setup(ev, false);
ev("UI.sel={type:'link',id:'cable'};renderPanel()");
const button = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all);
assert.ok(button && !button.disabled, 'one-click option is available');
const cash = ev('S.cash');
assert.ok(button.textContent.includes(ev('fmt$(30*Math.round(3000000+15000*500))')), 'full price is shown before purchase');
assert.ok(button.textContent.includes(ev('fmt$(30*Math.round(15000+15000*6))')), 'full price is shown before purchase');
button.click();
const bulkDates = dates(ev), bulkCash = ev('S.cash');
assert.deepEqual(bulkDates, [101, 131, 281]);
assert.equal(cash - bulkCash, 30 * 10500000);
const bulkReady = ev('S.links[0].ready'), bulkCash = ev('S.cash');
assert.equal(bulkReady, 101);
assert.equal(cash - bulkCash, 30 * 105000);
const after = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')];
assert.ok(after.every(b => b.disabled), 'both options stop at one day');
ev("ACT.crews({id:'cable',all:1})");
assert.equal(ev('S.cash'), bulkCash, 'repeat submission cannot charge again');
setup(ev);
ev("ACT.subUpgrade({id:'cable',k:'terminal'});ACT.subUpgrade({id:'cable',k:'engineering'});for(let i=0;i<30;i++)ACT.crews({id:'cable'})");
assert.deepEqual(dates(ev), bulkDates);
setup(ev, false);
ev("for(let i=0;i<30;i++)ACT.crews({id:'cable'})");
assert.equal(ev('S.links[0].ready'), bulkReady);
assert.equal(ev('S.cash'), bulkCash);
// At sea crews cannot help: no crew buttons, and the action does nothing.
setup(ev);
ev("UI.sel={type:'link',id:'cable'};renderPanel();ACT.crews({id:'cable',all:1})");
assert.equal(dom.window.document.querySelector('#panelBody [data-act=crews]'), null);
assert.equal(ev('S.links[0].ready'), 1000);
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});
@ -149,19 +155,19 @@ test('one-click completion costs the same as repeated crew hires and advances pe
test('one-click completion is atomic when unaffordable and handles short or completed construction', () => {
const { ev, dom } = load();
try {
setup(ev);
ev("S.cash=30*10500000-1;UI.sel={type:'link',id:'cable'};renderPanel()");
setup(ev, false);
ev("S.cash=30*105000-1;UI.sel={type:'link',id:'cable'};renderPanel()");
const bulk = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all);
assert.equal(bulk.disabled, true);
ev("ACT.crews({id:'cable',all:1})");
assert.equal(ev('S.cash'), 30 * 10500000 - 1);
assert.equal(ev('S.cash'), 30 * 105000 - 1);
assert.equal(ev('S.links[0].ready'), 1000, 'no partial purchase');
ev("S.cash=10500000;S.links[0].ready=102;ACT.crews({id:'cable',all:1})");
ev("S.cash=105000;S.links[0].ready=102;ACT.crews({id:'cable',all:1})");
assert.equal(ev('S.cash'), 0);
assert.equal(ev('S.links[0].ready'), 101, 'two days remaining costs one normal hire');
assert.match(dom.window.document.body.textContent, /The cable is 1 day ahead\./);
ev("S.cash=10500000;S.day=101;ACT.crews({id:'cable',all:1})");
assert.equal(ev('S.cash'), 10500000, 'completed construction cannot be rushed');
assert.match(dom.window.document.body.textContent, /Construction is 1 day ahead\./);
ev("S.cash=105000;S.day=101;ACT.crews({id:'cable',all:1})");
assert.equal(ev('S.cash'), 105000, 'completed construction cannot be rushed');
ev("S.day=100;S.links[0].ready=1000;S.links[0].own=false;ACT.crews({id:'cable',all:1})");
assert.equal(ev('S.links[0].ready'), 1000, 'leased handovers cannot buy construction crews');
} finally { dom.window.close(); }