From f4486ee9558c2e993f5390301f95cdb08a29cdee Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 10:54:25 +0100 Subject: [PATCH] Chaos monkey: a visitor that snips tubes in On-call and BGP at 3 a.m. Now and then a chaos monkey moves in for 120 to 240 days and snips a tube every couple of weeks, weak spots first, instead of the usual random outages. Outlast it without a customer noticing for a bonus and the Monkey-proof badge, or throw it a banana. Drawn on the map in shades; gameplay rule F4 with its test. --- .claude/skills/gameplay-rules/SKILL.md | 1 + CHANGELOG.md | 1 + site/i18n/de.js | 14 ++++ site/i18n/es.js | 14 ++++ site/i18n/fr.js | 14 ++++ site/i18n/it.js | 14 ++++ site/i18n/pt.js | 14 ++++ src/game/60-features/80-new-game.js | 2 +- src/game/80-simulation/50-sanitize.js | 4 + src/game/85-incidents/40-chaos-monkey.js | 52 +++++++++++++ src/game/88-days/10-day-tick.js | 4 +- src/game/88-days/20-badges.js | 1 + src/game/90-actions/60-links.js | 2 + src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/96-map/60-draw.js | 2 + src/game/96-map/87-chaos-monkey.js | 73 +++++++++++++++++ src/game/96-map/90-input.js | 1 + src/game/99-loop.js | 2 +- src/i18n/en.js | 14 ++++ tests/chaos-monkey.test.js | 99 ++++++++++++++++++++++++ tests/gameplay-rules.test.js | 21 +++++ 21 files changed, 347 insertions(+), 4 deletions(-) create mode 100644 src/game/85-incidents/40-chaos-monkey.js create mode 100644 src/game/96-map/87-chaos-monkey.js create mode 100644 tests/chaos-monkey.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 770d3ce..6e691fb 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -63,3 +63,4 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. | New players learn before they get punished. | | F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. | | F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. | +| F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. | diff --git a/CHANGELOG.md b/CHANGELOG.md index ebdfd49..2a605d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. - The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. - Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. - Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. diff --git a/site/i18n/de.js b/site/i18n/de.js index c255a30..a9aa838 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -68,8 +68,10 @@ "badges.lose_a_metro_ring_to_one":"Verliere einen Metro-Ring an einen einzigen Bagger.", "badges.lose_fiber_to_a_llama_herd":"Verliere Glasfaser an eine Lamaherde.", "badges.met_the_backhoe":"Den Bagger kennengelernt", +"badges.monkey_proof":"Affensicher", "badges.never_paid_list_price":"Nie den Listenpreis bezahlt", "badges.opt_out_of_3_auto_enrolled":"Kündige 3 automatisch gebuchte Zusatzleistungen.", +"badges.outlast_a_chaos_monkey_visit":"Überstehe einen Besuch des Chaos-Affen, ohne dass ein Kunde etwas merkt", "badges.over_the_mountains":"Über die Berge", "badges.paid_pnis_with_all_three_korean":"Bezahlte PNIs mit allen drei koreanischen Platzhirschen.", "badges.peer_at_an_ix_remotely":"Peere remote an einem IX.", @@ -453,6 +455,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/Monat · Lieferung innerhalb von {n} Tagen nach Unterschrift", "capacity_deals.what_price_mo_due_date":"{what} · {price}/Monat nach Lieferung · fällig am {date}", "capacity_deals.wholesale_waves":"Wholesale-Waves", +"chaos_monkey.arrived":"🐒 Ein Chaos-Affe ist in dein Netz gekommen!
Etwa {n} Tage lang kappt er absichtlich Leitungen, zuerst die ohne Ersatzweg. Übersteh es, ohne dass ein Kunde etwas merkt, und kassier einen Bonus.", +"chaos_monkey.banana":"🍌 Banane werfen {cost}", +"chaos_monkey.bribed":"🍌 Banane angenommen.
Der Chaos-Affe ist mit seinem Snack abgezogen. Dein Pager hat Pause.", +"chaos_monkey.card":"Kappt noch {n} Tage lang Leitungen. Bisher gekappt: {s}, von Kunden bemerkt: {hurt}.", +"chaos_monkey.loose":"Chaos-Affe los", +"chaos_monkey.rerouted":"🐒 Schnipp!
Der Chaos-Affe hat {a} ⇄ {b} gekappt, und der Verkehr ging einfach außen herum. Er wirkt enttäuscht.", +"chaos_monkey.snip_sprayed":"Der Chaos-Affe hat {a} ⇄ {b} mit etwas Klebrigem eingesprüht. Die Leitung ist down.", +"chaos_monkey.snip_to_see":"Der Chaos-Affe hat {a} ⇄ {b} gekappt, nur um zu sehen, was passiert.", +"chaos_monkey.snip_unplugged":"Der Chaos-Affe hat {a} ⇄ {b} ausgesteckt und grinst dich an.", +"chaos_monkey.survived":"🐒 Du hast den Chaos-Affen überstanden!
{n}-mal gekappt, und kein Kunde hat es gemerkt. Resilienz-Bonus: {cash}.", +"chaos_monkey.tap":"🐒 Er kappt absichtlich deine Leitungen, um zu beweisen, dass du es überstehst. Eine Banane würde ihn nach Hause schicken.", +"chaos_monkey.went_home":"🐒 Der Chaos-Affe ist nach Hause gegangen.
Gekappt: {n}. Von Kunden bemerkt: {hurt}. Wo es wehtat, hätte ein zweiter Weg dich gerettet.", "cities.270_million_people_on_17_000":"270 Millionen Menschen auf 17.000 Inseln. Mobile first und sehr hungrig nach Bandbreite.", "cities.a_capital_high_in_the_andes":"Eine Hauptstadt hoch in den Anden, knapp südlich des Äquators, die in US-Dollar zahlt. Vulkane an jedem Horizont.", "cities.a_capital_in_a_valley_under":"Eine Hauptstadt in einem Tal unter einem grünen Berg. Das nationale Stromnetz hatte schon ein paar berüchtigte schwarze Tage, also bring einen Generator mit.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 6a4af3e..d01b621 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -66,8 +66,10 @@ "badges.lose_a_metro_ring_to_one":"Pierde un anillo metropolitano por culpa de una sola retroexcavadora.", "badges.lose_fiber_to_a_llama_herd":"Pierde fibra por culpa de una manada de llamas.", "badges.met_the_backhoe":"Conoció a la retroexcavadora", +"badges.monkey_proof":"A prueba de monos", "badges.never_paid_list_price":"Nunca pagó precio de lista", "badges.opt_out_of_3_auto_enrolled":"Rechaza 3 complementos de alta automática.", +"badges.outlast_a_chaos_monkey_visit":"Aguanta una visita del mono del caos sin que ningún cliente lo note", "badges.over_the_mountains":"Sobre las montañas", "badges.paid_pnis_with_all_three_korean":"Paga PNIs a los tres operadores históricos coreanos.", "badges.peer_at_an_ix_remotely":"Haz peering en un IX de forma remota.", @@ -451,6 +453,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/mes · entregar en {n} días desde la firma", "capacity_deals.what_price_mo_due_date":"{what} · {price}/mes una vez entregado · vence el {date}", "capacity_deals.wholesale_waves":"Ondas al por mayor", +"chaos_monkey.arrived":"🐒 ¡Un mono del caos se ha colado en tu red!
Durante unos {n} días corta tubos a propósito, primero los que no tienen ruta de respaldo. Aguanta sin que ningún cliente lo note y te llevas un bonus.", +"chaos_monkey.banana":"🍌 Lanzar un plátano {cost}", +"chaos_monkey.bribed":"🍌 Plátano aceptado.
El mono del caos se fue con su merienda. Tu busca puede descansar.", +"chaos_monkey.card":"Cortando tubos {n} días más. Cortes hasta ahora: {s}, notados por clientes: {hurt}.", +"chaos_monkey.loose":"Mono del caos suelto", +"chaos_monkey.rerouted":"🐒 ¡Zas!
El mono del caos cortó {a} ⇄ {b} y el tráfico simplemente dio la vuelta. Parece decepcionado.", +"chaos_monkey.snip_sprayed":"El mono del caos roció {a} ⇄ {b} con algo pegajoso. Está caído.", +"chaos_monkey.snip_to_see":"El mono del caos cortó {a} ⇄ {b}, solo para ver qué pasaba.", +"chaos_monkey.snip_unplugged":"El mono del caos desenchufó {a} ⇄ {b} y te sonríe.", +"chaos_monkey.survived":"🐒 ¡Has aguantado al mono del caos!
{n} cortes y ningún cliente lo notó. Bonus de resiliencia: {cash}.", +"chaos_monkey.tap":"🐒 Corta tus tubos a propósito, para demostrar que puedes sobrevivir. Un plátano lo mandaría a casa.", +"chaos_monkey.went_home":"🐒 El mono del caos se fue a casa.
Cortes: {n}. Notados por clientes: {hurt}. Donde dolió, una segunda ruta te habría salvado.", "cities.270_million_people_on_17_000":"270 millones de personas en 17 000 islas. Móvil primero, y con muchísima hambre de ancho de banda.", "cities.a_capital_high_in_the_andes":"Una capital en lo alto de los Andes, justo al sur del ecuador, que paga en dólares estadounidenses. Volcanes en cada horizonte.", "cities.a_capital_in_a_valley_under":"Una capital en un valle bajo una montaña verde. La red eléctrica nacional ha tenido días malos famosos, así que trae un generador.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index b5e12d1..f2cfbad 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -66,8 +66,10 @@ "badges.lose_a_metro_ring_to_one":"Perds un anneau métropolitain à cause d’une seule pelleteuse.", "badges.lose_fiber_to_a_llama_herd":"Perds de la fibre à cause d’un troupeau de lamas.", "badges.met_the_backhoe":"Rencontre du troisième godet", +"badges.monkey_proof":"À l'épreuve des singes", "badges.never_paid_list_price":"Jamais au prix catalogue", "badges.opt_out_of_3_auto_enrolled":"Désactive 3 options souscrites d’office.", +"badges.outlast_a_chaos_monkey_visit":"Tiens bon face à une visite du singe du chaos sans qu'aucun client ne s'en aperçoive", "badges.over_the_mountains":"Par-delà les montagnes", "badges.paid_pnis_with_all_three_korean":"Des PNI payants avec les trois opérateurs historiques coréens.", "badges.peer_at_an_ix_remotely":"Fais du peering à distance sur un IX.", @@ -451,6 +453,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/mois · à livrer dans les {n} jours après la signature", "capacity_deals.what_price_mo_due_date":"{what} · {price}/mois une fois livré · échéance {date}", "capacity_deals.wholesale_waves":"Longueurs d'onde en gros", +"chaos_monkey.arrived":"🐒 Un singe du chaos s'est introduit dans ton réseau !
Pendant environ {n} jours, il coupe des tubes exprès, d'abord ceux sans chemin de secours. Tiens bon sans qu'aucun client ne s'en aperçoive et touche un bonus.", +"chaos_monkey.banana":"🍌 Lancer une banane {cost}", +"chaos_monkey.bribed":"🍌 Banane acceptée.
Le singe du chaos est reparti avec son goûter. Ton bipeur peut souffler.", +"chaos_monkey.card":"Coupe des tubes encore {n} jours. Coupures jusqu'ici : {s}, ressenties par les clients : {hurt}.", +"chaos_monkey.loose":"Singe du chaos en liberté", +"chaos_monkey.rerouted":"🐒 Clac !
Le singe du chaos a coupé {a} ⇄ {b}, et le trafic a simplement fait le tour. Il a l'air déçu.", +"chaos_monkey.snip_sprayed":"Le singe du chaos a aspergé {a} ⇄ {b} de quelque chose de collant. C'est en panne.", +"chaos_monkey.snip_to_see":"Le singe du chaos a coupé {a} ⇄ {b}, juste pour voir ce qui se passerait.", +"chaos_monkey.snip_unplugged":"Le singe du chaos a débranché {a} ⇄ {b} et te fait un grand sourire.", +"chaos_monkey.survived":"🐒 Tu as tenu face au singe du chaos !
{n} coupures et aucun client n'a rien vu. Bonus de résilience : {cash}.", +"chaos_monkey.tap":"🐒 Il coupe tes tubes exprès, pour prouver que tu peux y survivre. Une banane le renverrait chez lui.", +"chaos_monkey.went_home":"🐒 Le singe du chaos est rentré chez lui.
Coupures : {n}. Ressenties par les clients : {hurt}. Là où ça a fait mal, un deuxième chemin t'aurait sauvé.", "cities.270_million_people_on_17_000":"270 millions d’habitants sur 17 000 îles. Mobile first, et très gourmands en bande passante.", "cities.a_capital_high_in_the_andes":"Une capitale perchée dans les Andes, juste au sud de l’équateur, qui paie en dollars américains. Des volcans à chaque horizon.", "cities.a_capital_in_a_valley_under":"Une capitale dans une vallée au pied d’une montagne verte. Le réseau électrique national a connu quelques jours noirs célèbres : prévois un groupe électrogène.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 2afe831..bc48096 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -66,8 +66,10 @@ "badges.lose_a_metro_ring_to_one":"Perdi un anello metro per colpa di una sola ruspa.", "badges.lose_fiber_to_a_llama_herd":"Perdi la fibra per colpa di un branco di lama.", "badges.met_the_backhoe":"Incontro con la ruspa", +"badges.monkey_proof":"A prova di scimmia", "badges.never_paid_list_price":"Mai pagato il listino", "badges.opt_out_of_3_auto_enrolled":"Disattiva 3 add-on attivati d’ufficio.", +"badges.outlast_a_chaos_monkey_visit":"Resisti a una visita della scimmia del caos senza che nessun cliente se ne accorga", "badges.over_the_mountains":"Oltre le montagne", "badges.paid_pnis_with_all_three_korean":"PNI a pagamento con tutti e tre gli incumbent coreani.", "badges.peer_at_an_ix_remotely":"Fai peering da remoto su un IX.", @@ -451,6 +453,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/mese · da consegnare entro {n} giorni dalla firma", "capacity_deals.what_price_mo_due_date":"{what} · {price}/mese a consegna avvenuta · scadenza {date}", "capacity_deals.wholesale_waves":"Wave all'ingrosso", +"chaos_monkey.arrived":"🐒 Una scimmia del caos è entrata nella tua rete!
Per circa {n} giorni taglia tubi apposta, prima quelli senza un percorso di riserva. Resisti senza che nessun cliente se ne accorga e avrai un bonus.", +"chaos_monkey.banana":"🍌 Lancia una banana {cost}", +"chaos_monkey.bribed":"🍌 Banana accettata.
La scimmia del caos se n'è andata con la sua merenda. Il tuo cercapersone può riposare.", +"chaos_monkey.card":"Taglia tubi per altri {n} giorni. Tagli finora: {s}, notati dai clienti: {hurt}.", +"chaos_monkey.loose":"Scimmia del caos in libertà", +"chaos_monkey.rerouted":"🐒 Zac!
La scimmia del caos ha tagliato {a} ⇄ {b} e il traffico ha semplicemente girato intorno. Sembra delusa.", +"chaos_monkey.snip_sprayed":"La scimmia del caos ha spruzzato {a} ⇄ {b} con qualcosa di appiccicoso. È giù.", +"chaos_monkey.snip_to_see":"La scimmia del caos ha tagliato {a} ⇄ {b}, solo per vedere cosa succede.", +"chaos_monkey.snip_unplugged":"La scimmia del caos ha staccato {a} ⇄ {b} e ti sorride.", +"chaos_monkey.survived":"🐒 Hai resistito alla scimmia del caos!
{n} tagli e nessun cliente se n'è accorto. Bonus resilienza: {cash}.", +"chaos_monkey.tap":"🐒 Taglia i tuoi tubi apposta, per dimostrare che puoi sopravvivere. Una banana la rimanderebbe a casa.", +"chaos_monkey.went_home":"🐒 La scimmia del caos è tornata a casa.
Tagli: {n}. Notati dai clienti: {hurt}. Dove ha fatto male, un secondo percorso ti avrebbe salvato.", "cities.270_million_people_on_17_000":"270 milioni di persone su 17.000 isole. Mobile first, e affamatissime di banda.", "cities.a_capital_high_in_the_andes":"Una capitale in alto sulle Ande, appena a sud dell’equatore, che paga in dollari USA. Vulcani su ogni orizzonte.", "cities.a_capital_in_a_valley_under":"Una capitale in una valle sotto una montagna verde. La rete elettrica nazionale ha avuto qualche giornata nera famosa, quindi porta un generatore.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a5af6bb..88db3e9 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -66,8 +66,10 @@ "badges.lose_a_metro_ring_to_one":"Perca um anel metro para uma única retroescavadeira.", "badges.lose_fiber_to_a_llama_herd":"Perca fibra para um rebanho de lhamas.", "badges.met_the_backhoe":"Conheceu a retroescavadeira", +"badges.monkey_proof":"À prova de macaco", "badges.never_paid_list_price":"Nunca paguei preço de tabela", "badges.opt_out_of_3_auto_enrolled":"Cancele 3 add-ons ativados sem você pedir.", +"badges.outlast_a_chaos_monkey_visit":"Aguente uma visita do macaco do caos sem nenhum cliente perceber", "badges.over_the_mountains":"Por cima das montanhas", "badges.paid_pnis_with_all_three_korean":"PNIs pagos com as três incumbentes coreanas.", "badges.peer_at_an_ix_remotely":"Faça peering remoto num IX.", @@ -451,6 +453,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/mês · entregar em até {n} dias após assinar", "capacity_deals.what_price_mo_due_date":"{what} · {price}/mês após a entrega · prazo {date}", "capacity_deals.wholesale_waves":"Ondas no atacado", +"chaos_monkey.arrived":"🐒 Um macaco do caos entrou na sua rede!
Durante uns {n} dias, ele corta tubos de propósito, primeiro os que não têm rota de reserva. Aguente sem nenhum cliente perceber e ganhe um bônus.", +"chaos_monkey.banana":"🍌 Jogar uma banana {cost}", +"chaos_monkey.bribed":"🍌 Banana aceita.
O macaco do caos foi embora com o lanche. Seu pager pode descansar.", +"chaos_monkey.card":"Cortando tubos por mais {n} dias. Cortes até agora: {s}, sentidos pelos clientes: {hurt}.", +"chaos_monkey.loose":"Macaco do caos à solta", +"chaos_monkey.rerouted":"🐒 Zás!
O macaco do caos cortou {a} ⇄ {b} e o tráfego simplesmente deu a volta. Ele parece decepcionado.", +"chaos_monkey.snip_sprayed":"O macaco do caos borrifou {a} ⇄ {b} com algo grudento. Está fora do ar.", +"chaos_monkey.snip_to_see":"O macaco do caos cortou {a} ⇄ {b}, só para ver o que acontecia.", +"chaos_monkey.snip_unplugged":"O macaco do caos desligou {a} ⇄ {b} e está sorrindo para você.", +"chaos_monkey.survived":"🐒 Você aguentou o macaco do caos!
{n} cortes e nenhum cliente percebeu. Bônus de resiliência: {cash}.", +"chaos_monkey.tap":"🐒 Ele corta seus tubos de propósito, para provar que você aguenta. Uma banana o mandaria para casa.", +"chaos_monkey.went_home":"🐒 O macaco do caos foi para casa.
Cortes: {n}. Sentidos pelos clientes: {hurt}. Onde doeu, uma segunda rota teria salvado você.", "cities.270_million_people_on_17_000":"270 milhões de pessoas em 17.000 ilhas. Mobile first, e com muita fome de banda.", "cities.a_capital_high_in_the_andes":"Uma capital no alto dos Andes, logo ao sul do equador, que paga em dólar. Vulcões em todo horizonte.", "cities.a_capital_in_a_valley_under":"Uma capital num vale ao pé de uma montanha verde. A rede elétrica nacional já teve dias ruins famosos, então leve um gerador.", diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 0bad8cd..1d9d87b 100644 --- a/src/game/60-features/80-new-game.js +++ b/src/game/60-features/80-new-game.js @@ -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',capDeal: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}; + 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',capDeal: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}}; } diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 71cdda4..13652cc 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -13,6 +13,10 @@ function sanitize(s){ s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0); for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);} for(const k of ['survived','incidents','peak'])s.stats[k]=num(s.stats[k],0); + // The chaos monkey (2.0): saves without one get their first visit scheduled on the next day tick. + {const m=s.monkey&&typeof s.monkey==='object'&&!Array.isArray(s.monkey)?s.monkey:{},on=m.on?1:0,o={next:m.next==null?null:int(m.next,0,1e7,s.day+90),on}; + if(on){o.start=int(m.start,0,s.day,s.day);o.until=int(m.until,o.start,o.start+400,s.day+30);o.snip=int(m.snip,0,1e7,s.day+3);o.n=int(m.n,0,1e4,0);o.hurt=int(m.hurt,0,o.n,0);o.c=isCity(m.c)?m.c:isCity(s.home)?s.home:null;} + s.monkey=o;} for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object')p.bb.d=num(p.bb.d,0);else p.bb=null;} if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; opsSanitize(s); diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js new file mode 100644 index 0000000..09f93b2 --- /dev/null +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -0,0 +1,52 @@ +/* ---------- the chaos monkey: a visitor that breaks things on purpose ---------- + Like the real one (Netflix, 2011): something switches off random bits of production so you find out whether the + rest copes. Now and then, in On-call and BGP at 3 a.m. only, a monkey moves in for 120 to 240 days and snips a tube + every couple of weeks, preferring tubes with no other path round them. Its snips stand in for the usual random + failures while it is here, so the visit is a test, not a pile-on. Get through it without a customer noticing and + there is a bonus; a banana sends it home early. S.monkey: next (day of the next visit, null until the first tick), + on, start, until, snip (day of the next snip), n (snips), hurt (snips customers felt), c (city it last snipped by). */ +const MK_SNIPS=[N_('chaos_monkey.snip_unplugged'),N_('chaos_monkey.snip_sprayed'),N_('chaos_monkey.snip_to_see')]; +const mkSpicy=()=>rule('chaos')==='spicy'; +// Only the real game with real chaos: not Change Freeze (calm), Sandbox, puzzles or scenarios. +function mkElig(){return !!S&&S.mode!=='sandbox'&&S.mode!=='puzzle'&&!S.scn&&!S.lost&&['normal','spicy'].includes(rule('chaos'));} +const mkOn=()=>!!(S&&S.monkey&&S.monkey.on&&mkElig()); +const rint=(a,n)=>a+Math.floor(Math.random()*n); +// A quarter of a month's revenue to send it home; half a month's as the bonus for outlasting it. +const mkBananaCost=()=>Math.round(Math.min(1e6,Math.max(10000,(R.revMo||0)*0.25))/1000)*1000; +const mkBonus=()=>Math.round(Math.min(2e6,Math.max(20000,(R.revMo||0)*0.5))/1000)*1000; +// Is there another way between this tube's ends once its whole trench is gone? If not, it is a weak spot. +function mkWeak(l){const trc=l.trench||l.id,adj={}; + for(const x of S.links){if(x===l||(x.trench||x.id)===trc||linkDown(x))continue;(adj[x.a]||(adj[x.a]=[])).push(x.b);(adj[x.b]||(adj[x.b]=[])).push(x.a);} + const seen=new Set([l.a]),q=[l.a];while(q.length){const c=q.pop();if(c===l.b)return false;for(const n of adj[c]||[])if(!seen.has(n)){seen.add(n);q.push(n);}}return true;} +function mkTick(d){const M=S.monkey;if(!M)return; + if(!mkElig()){if(M.on)mkLeave('quiet');return;} + // The first visit is spread by the ASN, not the dice, so a game's other luck stays exactly as it was. + if(M.next==null)M.next=d+(mkSpicy()?180:270)+(S.asn||0)%120; + if(!M.on){if(dl.kind!=='vxc'&&!linkDown(l)).length<3){M.next=d+30;return;}mkArrive(d);return;} + if(d>=M.until){mkLeave();return;} + if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}} +function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121); + Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home}); + toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive'); + if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);} +function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));if(!live.length)return; + // Weak spots first: a sample keeps this cheap on big networks. + const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x])); + const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served; + hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));M.n++;M.c=l.a; + addInc({type:'cut',ref:trc,until:S.day+dur,msg:tr(pick(MK_SNIPS),{a:A,b:B}),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},''); + compute();const i=S.inc[S.inc.length-1],imp=Math.max(0,before-R.served);if(i)i.impact=imp; + const felt=before>1&&imp>=before*0.03;if(felt)M.hurt++;else S.stats.survived++; + toast(felt?`🐒 ${incTitle('cut')}
${esc(i?i.msg:'')}`:tr('chaos_monkey.rerouted',{a:A,b:B}),felt?'bad':'good',[],i?incOpen(i):null);sfx(felt?'err':'alert'); + if(typeof mkRun==='function'){if(!UI.mk&&CITY[M.c])mkStart(M.c);mkRun(l,1400,felt);}} +// why: 'banana' (bribed), 'quiet' (the rules or the game changed under it), or nothing (its time was up). +function mkLeave(why){const M=S.monkey,d=S.day,ok=!why&&M.n>0&&M.hurt===0;M.on=0;M.next=d+(mkSpicy()?rint(220,181):rint(360,361)); + // The usual failures were paused for the visit; give the NOC a breather before they start again. + S.nextFail=Math.max(S.nextFail,d+15); + if(why==='banana')toast(tr('chaos_monkey.bribed'),'good'); + else if(ok){const b=mkBonus();S.cash+=b;S.stats.mkSurv=(S.stats.mkSurv||0)+1;toast(tr('chaos_monkey.survived',{n:M.n,cash:fmt$(b)}),'goal');sfx('coin');track('monkey_survived');} + else if(!why)toast(tr('chaos_monkey.went_home',{n:M.n,hurt:M.hurt}),''); + if(typeof mkEnd==='function')mkEnd(ok,true);} +// The NOC tab's card while it is here. +function mkCard(){if(!mkOn())return '';const M=S.monkey,c=mkBananaCost(); + return `
🐒 ${tr('chaos_monkey.loose')}
${tr('chaos_monkey.card',{n:Math.max(1,M.until-S.day),s:M.n,hurt:M.hurt})}
${btn(tr('chaos_monkey.banana',{cost:fmt$(c)}),'mkBanana',{},'sm',S.cash
`;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 59ed88c..ef8be3c 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -63,7 +63,9 @@ function dayTick(){ // failures & events // Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never. let dirty=false;const cm=chaosMul(); - if(cm&&d>=S.nextFail){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} + // A visiting chaos monkey does the breaking instead (its snips replace these while it is here). + mkTick(d); + if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} // Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year). if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 0492fe1..37f33a3 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -68,6 +68,7 @@ const BADGES=[ {id:'toaster',i:'🍞',t:tr('common.toaster_wrangler'),d:tr('badges.weather_a_ddos_with_your_defences'),r:'c',ok:()=>(st().ddosHeld||0)>=1}, {id:'cleanpipe',i:'🚿',t:tr('common.clean_pipes'),d:tr('badges.turn_on_a_transit_clean_pipe'),r:'r',ok:()=>S.transit.some(t=>t.clean)}, {id:'lamb',i:'🐐',t:tr('common.sacrificial_lamb'),d:tr('badges.run_a_sacrificial_pni_choke_point'),r:'r',ok:()=>S.pni.some(p=>p.sacrif)}, + {id:'monkey',i:'🐒',t:tr('badges.monkey_proof'),d:tr('badges.outlast_a_chaos_monkey_visit'),r:'e',ok:()=>(st().mkSurv||0)>=1}, {id:'flood',i:'🌊',t:tr('badges.held_the_flood'),d:tr('badges.weather_a_multi_terabit_ddos'),r:'e',ok:()=>(st().ddosMonster||0)>=1}, {id:'skynot',i:'🤖',t:tr('common.skynot_smiles'),d:tr('badges.land_a_hackback_3000tm_that_actually'),r:'e',secret:true,ok:()=>(st().hackWin||0)>=1}, {id:'zero',i:'🕳️',t:tr('badges.zero_peers_given'),d:tr('badges.reach_tier_2_with_every_single'),r:'l',secret:true,ok:()=>isTier2()&&!Object.keys(S.peers).length&&!S.pni.length}, diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index 7c046d0..a564a7e 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -4,6 +4,8 @@ Object.assign(ACT,{ decomToggle:({city})=>{if(!S.pops[city])return;UI.decom=UI.decom||new Set();if(UI.decom.has(city))UI.decom.delete(city);else UI.decom.add(city);decomModal();}, decomGo:()=>{const sel=[...(UI.decom||[])].filter(c=>S.pops[c]);if(!sel.length||sel.length>=Object.keys(S.pops).length)return;closeModal();UI.decom=null;UI.sel=null;decommission(sel);sfx('alert');after();}, rmLink:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}{const l=S.links.find(x=>x.id===id),back=cabBack(l);if(back>0){S.cash+=back;toast(tr('links.name_is_called_off_the_cable',{name:esc(l.cname||tr('common.your_cable')),price:fmt$(back)}),'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; 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();}, diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index f679918..85e538d 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -50,7 +50,7 @@ function renderLeft(){checkLayer(); }else if(UI.left==='noc'){ h+=`
${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${btn(tr('common.connections'),'connOpen',{},'')}${btn(tr('common.traceroute'),'trace',{},'')}
`; h+=`

${tr('hud_and_panels.your_network_operations_center_every')}

`; - h+=opsCard(); + h+=opsCard()+mkCard(); // 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+=`
${incTitle(i.type)}
${esc(i.msg)}
${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)})}`:''}
${i.cost?`
${btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash`:''}
`;} h+=logSection();UI.logSeen=Date.now(); diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index f82dee0..a0d1f0c 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -86,6 +86,8 @@ function drawFrame(now){ CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; if(pzOn())for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); + // the chaos monkey (woken here after a reload, wherever it last snipped) + if(UI.mk)mkDraw(ks);else if(mkOn()&&!pzOn()&&CITY[S.monkey.c])mkStart(S.monkey.c); // floaters for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;} for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}} diff --git a/src/game/96-map/87-chaos-monkey.js b/src/game/96-map/87-chaos-monkey.js new file mode 100644 index 0000000..7919764 --- /dev/null +++ b/src/game/96-map/87-chaos-monkey.js @@ -0,0 +1,73 @@ +/* ---------- the chaos monkey, on the map ---------- + It hops from cut to cut, sprays chaos where it snips, and dances where a snip really hurt. It visits normal games + (85-incidents/40-chaos-monkey.js) and reviews Architect runs. Pure decoration on the animation clock: nothing + depends on it, and with animations off the monkey just sits at the cut. */ +const MK_RUN=0.62; // share of a review step the monkey spends running to the next cut +const MK_COLS=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF']; +// Where a link's middle is, in world coordinates (the shorter way round the date line). +const mkMid=l=>[(CITY[l.a].x+CITY[l.a].x+wrapDx(CITY[l.a].x,CITY[l.b].x))/2,(CITY[l.a].y+CITY[l.b].y)/2]; +function mkStart(c){const C=CITY[c];UI.mk={x:C.x,y:C.y,fx:C.x,fy:C.y,tx:C.x,ty:C.y,t0:animT,dur:1,face:1,mood:'run',spray:[],sprayAt:null,bad:false};} +// Off to the next cut: arrive, then spray. +function mkRun(l,dur,bad){const m=UI.mk;if(!m)return;const [x,y]=mkMid(l);m.fx=m.x;m.fy=m.y;m.tx=x;m.ty=y;m.t0=animT;m.dur=Math.max(1,dur*MK_RUN); + m.face=wrapDx(m.fx,x)<0?-1:1;m.mood='run';m.sprayAt=animT+m.dur;m.bad=!!bad;if(!animOn()){m.x=x;m.y=y;}} +function mkSpray(m){for(let i=0;i<(m.bad?26:16);i++){const a=Math.PI*2*i/(m.bad?26:16)+((i*37)%10)/10,v=0.05+((i*53)%10)/180; + m.spray.push({x:m.tx,y:m.ty,vx:Math.cos(a)*v,vy:Math.sin(a)*v-0.06,c:m.bad?(i%3?'#FF4D5E':'#FFD23F'):MK_COLS[i%MK_COLS.length],t:animT,s:i%4===0?(m.bad?'💥':'✂️'):null});}} +// It is over: a cheer when everything held, a tantrum where it broke; with bye it then leaves the map. +function mkEnd(ok,bye){const m=UI.mk;if(!m)return;m.mood=ok?'cheer':'dance';m.t0=animT;m.bye=bye?animT:0;} +function mkStop(){UI.mk=null;} +function mkDraw(ks){const m=UI.mk;if(!m)return;if(m.bye&&animT-m.bye>2600){mkStop();return;} + if(m.mood==='snip'&&animT-m.t0>1500){m.mood='stand';m.t0=animT;} + const p=Math.min(1,(animT-m.t0)/m.dur),e=p<0.5?2*p*p:1-Math.pow(-2*p+2,2)/2; + if(m.mood==='run'){m.x=m.fx+wrapDx(m.fx,m.tx)*e;m.y=m.fy+(m.ty-m.fy)*e;} + if(m.sprayAt!=null&&animT>=m.sprayAt){m.sprayAt=null;if(animOn())mkSpray(m);m.mood=m.bad?'dance':'snip';m.t0=animT;} + const sz=Math.round(36*Math.max(0.85,Math.min(1.4,Math.sqrt(cam.z)))); + // Hops while running, bounces on the spot otherwise. + const hop=m.mood==='run'&&p<1?Math.abs(Math.sin((animT-m.t0)/70))*sz*0.45:m.mood==='dance'?Math.abs(Math.sin((animT-m.t0)/90))*sz*0.6:m.mood==='cheer'?Math.abs(Math.sin((animT-m.t0)/120))*sz*0.35:0; + ctx.save();ctx.textAlign='center';ctx.textBaseline='middle'; + for(let i=m.spray.length-1;i>=0;i--){const q=m.spray[i],a=(animT-q.t)/900;if(a>1){m.spray.splice(i,1);continue;} + const dt=animT-q.t,wx=q.x+q.vx*dt/cam.z,wy=q.y+(q.vy*dt+0.00012*dt*dt)/cam.z; + for(const k of ks){const [sx,sy]=toS(wx,wy,k);ctx.globalAlpha=1-a;if(q.s){ctx.font=`${Math.round(sz*0.7)}px sans-serif`;ctx.fillText(q.s,sx,sy);}else{ctx.fillStyle=q.c;ctx.beginPath();ctx.arc(sx,sy,Math.max(2,sz*0.13*(1-a*0.5)),0,Math.PI*2);ctx.fill();}}} + ctx.globalAlpha=1;ctx.font=`${sz}px sans-serif`; + for(const k of ks){const [sx,sy]=toS(m.x,m.y,k);m.sx=sx;m.sy=sy-sz*0.6;m.r=sz*0.8;ctx.save();ctx.translate(sx,sy+sz*0.15); + ctx.fillStyle='rgba(30,38,64,.18)';ctx.beginPath();ctx.ellipse(0,0,sz*0.38,sz*0.12,0,0,Math.PI*2);ctx.fill(); + ctx.translate(0,-hop);const tilt=m.mood==='snip'?Math.sin((animT-m.t0)/60)*0.25:m.mood==='dance'?Math.sin((animT-m.t0)/80)*0.35:0;ctx.rotate(tilt);ctx.scale(m.face,1); + mkSprite(sz*1.25,animT-m.t0,m.mood==='run'&&p>=1?'stand':m.mood); + if(m.mood==='cheer'){ctx.scale(m.face,1);ctx.fillStyle='#000';ctx.fillText('🎉',sz*0.75,-sz*1.1);}ctx.restore();} + ctx.restore();} +// Our own monkey, drawn in the map's outline style, facing right with its feet at (0,0); s is its height. +// Shades on, spray can in hand: the arms and legs move with its mood. +function mkSprite(s,t,mood){const u=s/40,O='#1E2640',B='#A0673A',T='#F4CFA0',lw=Math.max(1.4,2*u),k=Math.sin(t/70); + ctx.lineJoin=ctx.lineCap='round';ctx.strokeStyle=O;ctx.lineWidth=lw; + const dot=(x,y,r,c)=>{ctx.fillStyle=c;ctx.beginPath();ctx.arc(x*u,y*u,r*u,0,Math.PI*2);ctx.fill();ctx.stroke();}; + const limb=(x1,y1,x2,y2,w)=>{ctx.beginPath();ctx.moveTo(x1*u,y1*u);ctx.lineTo(x2*u,y2*u);ctx.lineWidth=w*u+2*lw;ctx.strokeStyle=O;ctx.stroke();ctx.lineWidth=w*u;ctx.strokeStyle=B;ctx.stroke();ctx.lineWidth=lw;ctx.strokeStyle=O;}; + const run=mood==='run',up=mood==='cheer',wave=mood==='snip'||mood==='dance'; + // tail: a curl that sways + const sw=Math.sin(t/160)*3;ctx.beginPath();ctx.moveTo(-6*u,-9*u);ctx.bezierCurveTo(-19*u,-8*u,(-21+sw)*u,-26*u,(-13+sw)*u,-29*u);ctx.bezierCurveTo((-7+sw)*u,-31*u,(-6+sw)*u,-24*u,(-10+sw)*u,-24*u); + ctx.lineWidth=3*u+2*lw;ctx.stroke();ctx.lineWidth=3*u;ctx.strokeStyle=B;ctx.stroke();ctx.lineWidth=lw;ctx.strokeStyle=O; + // legs and feet + const g=run?5*k:mood==='dance'?3*k:0;limb(-3,-10,-4-g,-1.5,3.6);limb(4,-10,5+g,-1.5,3.6); + ctx.fillStyle=T;for(const x of [-4-g,5+g]){ctx.beginPath();ctx.ellipse((x+1)*u,-1*u,3*u,1.8*u,0,0,Math.PI*2);ctx.fill();ctx.stroke();} + // back arm, body, belly + const ba=up?[-10,-33]:wave?[-11,-25+2*k]:run?[-10,-14-3*k]:[-9,-13];limb(-4,-20,ba[0],ba[1],3.2);dot(ba[0],ba[1],2.2,T); + ctx.fillStyle=B;ctx.beginPath();ctx.ellipse(0,-15*u,9*u,10*u,0,0,Math.PI*2);ctx.fill();ctx.stroke(); + ctx.fillStyle=T;ctx.beginPath();ctx.ellipse(1.5*u,-14*u,5.5*u,7*u,0,0,Math.PI*2);ctx.fill(); + // head: ears, skull, face + dot(-6,-32,3.6,B);dot(10,-32,3.6,B);ctx.fillStyle=T;for(const x of [-6,10]){ctx.beginPath();ctx.arc(x*u,-32*u,1.9*u,0,Math.PI*2);ctx.fill();} + dot(2,-31,9,B);ctx.fillStyle=T;ctx.beginPath();ctx.arc(-1*u,-31.5*u,4*u,0,Math.PI*2);ctx.arc(5*u,-31.5*u,4*u,0,Math.PI*2);ctx.fill(); + ctx.beginPath();ctx.ellipse(2*u,-27.5*u,6.5*u,4.6*u,0,0,Math.PI*2);ctx.fill(); + // shades: two dark lenses on a bridge, with a glint + ctx.fillStyle=O;ctx.beginPath();ctx.ellipse(-1.2*u,-32.5*u,3.3*u,2.6*u,0,0,Math.PI*2);ctx.ellipse(5.4*u,-32.5*u,3.3*u,2.6*u,0,0,Math.PI*2);ctx.fill(); + ctx.beginPath();ctx.moveTo(1.5*u,-33.5*u);ctx.lineTo(2.7*u,-33.5*u);ctx.moveTo(-4.4*u,-33*u);ctx.lineTo(-7*u,-33.5*u);ctx.stroke(); + ctx.strokeStyle='#fff';ctx.lineWidth=Math.max(1,0.9*u);ctx.beginPath();ctx.moveTo(-2.6*u,-33.6*u);ctx.lineTo(-1.2*u,-34.3*u);ctx.moveTo(4*u,-33.6*u);ctx.lineTo(5.4*u,-34.3*u);ctx.stroke();ctx.strokeStyle=O;ctx.lineWidth=lw; + // mouth: a smirk, or a laugh when it breaks something + ctx.beginPath();if(mood==='dance'||up){ctx.fillStyle='#7A2633';ctx.ellipse(2.5*u,-26.5*u,2.6*u,2*u,0,0,Math.PI*2);ctx.fill();ctx.stroke();} + else{ctx.moveTo(-0.5*u,-27*u);ctx.quadraticCurveTo(3*u,-25*u,6*u,-28*u);ctx.stroke();} + // front arm with the spray can + const fa=up?[11,-34]:wave?[13,-27-2*k]:run?[11,-17+3*k]:[10,-14];limb(5,-20,fa[0],fa[1],3.2); + ctx.save();ctx.translate(fa[0]*u,fa[1]*u);ctx.rotate(wave?0.5:0); + ctx.fillStyle='#FF4F9A';ctx.beginPath();ctx.roundRect(-2.6*u,-8*u,5.2*u,9*u,1.2*u);ctx.fill();ctx.stroke(); + ctx.fillStyle='#FFD23F';ctx.fillRect(-2.6*u,-5*u,5.2*u,2*u);ctx.fillStyle='#C9D1E6';ctx.beginPath();ctx.roundRect(-1.6*u,-10.5*u,3.2*u,2.6*u,0.8*u);ctx.fill();ctx.stroke(); + if(wave){ctx.fillStyle='rgba(255,79,154,.45)';for(let i=0;i<4;i++){ctx.beginPath();ctx.arc((4+i*2.2)*u,(-11-i*1.4+Math.sin(t/40+i))*u,(0.9+i*0.4)*u,0,Math.PI*2);ctx.fill();}} + ctx.restore();dot(fa[0],fa[1],2.2,T);} +// Did a tap land on the monkey? (Where it was last drawn.) +const mkHit=(x,y)=>!!(UI.mk&&UI.mk.sx!=null&&Math.hypot(x-UI.mk.sx,y-UI.mk.sy)🐒 A chaos monkey got into your network!
For about {n} days it snips tubes on purpose, the ones without a backup path first. Ride it out with no customer noticing for a bonus.", +"chaos_monkey.banana":"🍌 Throw a banana {cost}", +"chaos_monkey.bribed":"🍌 Banana accepted.
The chaos monkey wandered off with its snack. Your pager can rest.", +"chaos_monkey.card":"Snipping tubes for {n} more days. Snips so far: {s}, felt by customers: {hurt}.", +"chaos_monkey.loose":"Chaos monkey on the loose", +"chaos_monkey.rerouted":"🐒 Snip!
The chaos monkey cut {a} ⇄ {b}, and traffic simply went round. It looks disappointed.", +"chaos_monkey.snip_sprayed":"The chaos monkey sprayed {a} ⇄ {b} with something sticky. It is down.", +"chaos_monkey.snip_to_see":"The chaos monkey cut {a} ⇄ {b}, just to see what would happen.", +"chaos_monkey.snip_unplugged":"The chaos monkey unplugged {a} ⇄ {b} and is grinning at you.", +"chaos_monkey.survived":"🐒 You outlasted the chaos monkey!
{n} snips and no customer noticed. Resilience bonus: {cash}.", +"chaos_monkey.tap":"🐒 It snips your tubes on purpose, to prove you can survive it. A banana would send it home.", +"chaos_monkey.went_home":"🐒 The chaos monkey went home.
Snips: {n}. Felt by customers: {hurt}. Where it hurt, a second path would have saved you.", "cities.270_million_people_on_17_000":"270 million people on 17,000 islands. Mobile first, and very hungry for bandwidth.", "cities.a_capital_high_in_the_andes":"A capital high in the Andes, just south of the equator, that pays in US dollars. Volcanoes on every horizon.", "cities.a_capital_in_a_valley_under":"A capital in a valley under a green mountain. The national grid has had some famous bad days, so bring a generator.", diff --git a/tests/chaos-monkey.test.js b/tests/chaos-monkey.test.js new file mode 100644 index 0000000..4089064 --- /dev/null +++ b/tests/chaos-monkey.test.js @@ -0,0 +1,99 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// A small network on a fixed seed: Frankfurt, Amsterdam, London and Paris in a ring, with a spur out to Zurich. +function net(preset) { + const { ev, errors, dom } = load(); + ev(`beginGame('Monkey Testers','fra',${JSON.stringify({ mode: 'normal', preset })});if(UI.pendGame)ACT.pitchSkip()`); + ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par','zrh'])ACT.buildPop({city:c})"); + ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1})"); + ev("for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['fra','zrh']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()"); + ev('for(let i=0;i<60;i++)dayTick();S.inc=[];for(const l of S.links)l.cut=0;compute()'); + return { ev, errors, dom }; +} +const link = (ev, a, b) => `S.links.find(l=>(l.a==='${a}'&&l.b==='${b}')||(l.a==='${b}'&&l.b==='${a}'))`; + +test('the chaos monkey visits On-call and BGP at 3 a.m., never Change Freeze or Sandbox', () => { + for (const [preset, ok] of [['oncall', true], ['bgp', true], ['freeze', false]]) { + const { ev, errors } = net(preset); + assert.equal(ev('mkElig()'), ok, preset); + ev('S.monkey.next=S.day;dayTick()'); + assert.equal(ev('!!S.monkey.on'), ok, preset); + assert.deepEqual(errors, []); + } + const { ev } = net('oncall'); + ev("S.mode='sandbox'"); + assert.equal(ev('mkElig()'), false); + ev("S.mode='normal';S.monkey.next=S.day;dayTick();S.scn={rules:{}}"); + assert.equal(ev('mkOn()'), false, 'never in a scenario'); +}); + +test('a visit lasts 120 to 240 days, snips every couple of weeks and pauses the usual failures', () => { + const { ev, errors } = net('oncall'); + ev('S.monkey.next=S.day;dayTick()'); + const len = ev('S.monkey.until-S.monkey.start'); + assert.ok(len >= 120 && len <= 240, `visit of ${len} days`); + ev('S.nextFail=S.day'); + const nf = ev('S.nextFail'); + ev('for(let i=0;i<60;i++)dayTick()'); + assert.ok(ev('S.monkey.n') >= 2, 'it snipped'); + assert.equal(ev('S.nextFail'), nf, 'no ordinary failure fired while it was here'); + assert.ok(ev("S.inc.some(i=>i.type==='cut')||S.stats.survived>0")); + // It leaves on time, and the ordinary failures wait a little before they start again. + ev('for(let i=0;i<200&&S.monkey.on;i++)dayTick()'); + assert.equal(ev('S.monkey.on'), 0); + assert.ok(ev('S.monkey.next>S.day+200')); + assert.ok(ev('S.nextFail>=S.day')); + assert.deepEqual(errors, []); +}); + +test('weak spots are tubes with no other way round', () => { + const { ev } = net('oncall'); + assert.equal(ev(`mkWeak(${link(ev, 'fra', 'zrh')})`), true); + assert.equal(ev(`mkWeak(${link(ev, 'fra', 'ams')})`), false); +}); + +test('outlasting it unnoticed pays a bonus and earns the badge; going home hurt pays nothing', () => { + const { ev, errors } = net('oncall'); + ev('S.monkey.next=S.day;dayTick();S.monkey.n=4;S.monkey.hurt=0;S.monkey.until=S.day+1'); + const cash = ev('S.cash'), bonus = ev('mkBonus()'); + ev('dayTick();checkBadges()'); + assert.equal(ev('S.monkey.on'), 0); + assert.equal(ev('S.stats.mkSurv'), 1); + assert.ok(ev('S.cash') >= cash + bonus - 1e6, 'bonus paid'); + assert.ok(ev("S.ach.monkey!==undefined")); + ev('S.monkey.next=S.day;dayTick();S.monkey.n=4;S.monkey.hurt=2;S.monkey.until=S.day+1;dayTick()'); + assert.equal(ev('S.stats.mkSurv'), 1, 'no bonus when customers felt it'); + assert.deepEqual(errors, []); +}); + +test('a banana sends it home early, for a price', () => { + const { ev, errors, dom } = net('bgp'); + ev("S.monkey.next=S.day;dayTick();UI.left='noc';renderLeft()"); + assert.ok(dom.window.document.querySelector('[data-act=mkBanana]'), 'the NOC card offers a banana'); + const cash = ev('S.cash'), cost = ev('mkBananaCost()'); + ev('ACT.mkBanana({})'); + assert.equal(ev('S.monkey.on'), 0); + assert.equal(ev('S.cash'), cash - cost); + assert.equal(ev('S.stats.mkSurv||0'), 0); + ev('S.cash=0;S.monkey.next=S.day;dayTick();ACT.mkBanana({})'); + assert.equal(ev('S.monkey.on'), 1, 'no banana without the cash'); + assert.deepEqual(errors, []); +}); + +test('saves keep the monkey; old and broken saves are repaired', () => { + const { ev, errors } = net('oncall'); + ev('S.monkey.next=S.day;dayTick();const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))'); + assert.equal(ev('S.monkey.on'), 1); + assert.ok(ev('S.monkey.until>S.day')); + ev("const o=JSON.parse(JSON.stringify(packSave(S)));delete o.monkey;S=migrate(o)"); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.monkey)')), { next: null, on: 0 }); + ev("const o=JSON.parse(JSON.stringify(packSave(S)));o.monkey={on:1,until:'soon',n:-3,hurt:99,c:''};S=migrate(o)"); + assert.equal(ev('S.monkey.n'), 0); + assert.equal(ev('S.monkey.hurt'), 0); + assert.equal(ev('S.monkey.c'), ev('S.home')); + assert.ok(ev('S.monkey.until>=S.monkey.start')); + ev('for(let i=0;i<5;i++)dayTick()'); + assert.deepEqual(errors, []); +}); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 76cf1ba..fb1603c 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -361,6 +361,27 @@ test('F3: a specialist path only brings customers you can already serve', () => assert.deepEqual(g.errors, []); }); +test('F4: the chaos monkey only visits On-call and BGP at 3 a.m., late, for 120 to 240 days, instead of the ordinary failures', () => { + for (const preset of ['freeze', 'oncall', 'bgp']) { + const g = load(); + g.ev(`beginGame('Monkey','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip()`); + g.ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()"); + g.ev('for(let i=0;i<2;i++)dayTick()'); + if (preset === 'freeze') { assert.equal(g.ev('mkElig()'), false, 'F4: never in Change Freeze'); continue; } + assert.ok(g.ev('S.monkey.next') >= 180, 'F4: not before day 180'); + g.ev('S.monkey.next=S.day;dayTick();S.nextFail=S.day'); + const len = g.ev('S.monkey.until-S.monkey.start'); + assert.ok(len >= 120 && len <= 240, `F4: a visit of ${len} days`); + g.ev('for(let i=0;i<40;i++)dayTick()'); + assert.ok(g.ev('S.nextFail') <= g.ev('S.day'), 'F4: no ordinary failure fired during the visit'); + assert.ok(g.ev("S.inc.filter(i=>i.type==='cut').every(i=>i.until-i.start<=(rule('chaos')==='spicy'?11:7))"), 'F4: snips heal within a week (spicy stretches by half)'); + assert.deepEqual(g.errors, []); + } + const g = load(); + g.ev("beginGame('Monkey','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.mode='sandbox'"); + assert.equal(g.ev('mkElig()'), false, 'F4: never in Sandbox'); +}); + test('no page errors while checking the rules', () => { assert.deepEqual(errors, []); });