Puzzles: the chaos monkey acts out the N-1 star in every puzzle

When a build earns a new star the monkey snips each trench and cable in turn on the
map, and cities that lose traffic say how much; then the stars show. It can be let
loose again or skipped. Puzzle texts talk about the chaos monkey instead of a backhoe.
This commit is contained in:
Frederic Jung 2026-10-30 12:24:53 +01:00
parent cbb7ca8772
commit 9fc38fa4f4
No known key found for this signature in database
13 changed files with 134 additions and 40 deletions

View file

@ -81,7 +81,7 @@ const pzSig=()=>JSON.stringify([S.pops,S.links,S.pairMet||null,S.biz.map(b=>b.ro
/* ⭐ every flow delivered in full (circuits within their latency cap), and the twists; ⭐⭐ the year's spend within
budget; ⭐⭐⭐ N-1 under load: whichever single trench or cable is cut, every priority flow still gets all of its traffic
(best-effort flows may drop). The cut is routed by compute() like the real thing. */
function pzEval(){const sig=pzSig(),c0=UI.pzEv;if(c0&&c0.sig===sig)return c0.e;
function pzEval(){const sig=pzSig(),c0=UI.pzEv;if(c0&&(c0.sig===sig||UI.pzMk))return c0.e;// mid-scene the monkey's cuts are not the build
const P=S.pz,hot=UI.hotMap;compute();const R0=R,got=pzGot(),spend=pzSpend(),peak={},pk=()=>{for(const c in R.nodeLoad)peak[c]=Math.max(peak[c]||0,R.nodeLoad[c]);};pk();
const flows=P.dem.map((f,i)=>({f,i,g:got[i].g,ms:got[i].ms,full:pzFull(f,got[i]),fast:pzFast(f,got[i])}));
const tw=[];if(P.noSub)tw.push({k:'sub',ok:!S.links.some(l=>l.sub)});
@ -118,7 +118,7 @@ const pzToastsClear=()=>{$('toasts').textContent='';};
// The running game gets its usual save first and is kept in memory, set aside: save() keeps writing it to its slot
// (leaving the page mid-puzzle), and leaving the puzzle picks it up again.
function pzFlush(){save(true);UI.pzKeep=S;}
function pzBegin(def){if(!def)return;
function pzBegin(def){if(!def)return;pzMkStop();mkStop();
const go=()=>{const cs=pzCities(def);newGame(pzName(def),cs[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null;
S.pz={id:def.id,key:def.key||null,cities:cs,src:(def.src||[]).slice(),dem:def.dem.map(f=>({t:f.t,a:f.a,b:f.t==='l2'?f.b:null,g:f.g,ms:f.ms||0,be:!!f.be})),
via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null,rev:def.rev||1};
@ -130,7 +130,7 @@ function pzBegin(def){if(!def)return;
if(pzOn()){go();return;}
const live=!!(S&&UI.started&&!S.lost);UI.pzFrom=live?'game':'title';
if(live)pzFlush();go();}
function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false;
function pzLeave(){pzMkStop();mkStop();const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false;
if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null;
if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
// It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told.
@ -142,14 +142,14 @@ function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].
const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150);
cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();}
// ---------- building ----------
function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();}
function pzSnap(){pzMkStop();const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();}
function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI.sel.id))||(UI.sel.type==='city'&&!pzKind(UI.sel.id))))UI.sel=null;
compute();renderAll();pzCheck();}
// Stars count the moment they are earned.
// Every solved state is recorded, so a cheaper build at the same stars counts too.
// A new star below three is a cheer and a nudge, and play goes on; the results card opens at three stars, or when the
// player says they are done (the card's Finish button).
function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}return e;}
function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;const show=()=>{if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}};if(pzMkCan())pzMonkey(show);else show();return e;}
// The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend.
function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null};
if(e.stars<r.st||(e.stars===r.st&&r.sp!=null&&r.sp<=e.spend))return;

View file

@ -0,0 +1,23 @@
/* ---------- the chaos monkey in puzzles: the N-1 star, acted out ----------
The third star already asks whether the build survives any single cut (pzEval tries every trench and cable). When a
new star lands, and on request, the monkey plays that check on the map: it runs to each trench or cable, snips it,
and the cities that lose traffic say so. Only while the map is really being drawn: the stars never wait on it. */
const PZ_RUN=450,PZ_HOLD=550; // ms: the run to a tube, then how long its cut shows
const pzMkCan=()=>animOn()&&!UI.mapHid&&performance.now()-(UI.drawnAt||-1e9)<2000;
function pzMonkey(then){pzMkStop();const units=[...new Set(S.links.map(pzUnit))];if(!units.length){if(then)then();return;}
const c=S.pz.src[0]||S.pz.cities[0];UI.pzMk={units,i:-1,t:0,then,bad:0};if(CITY[c])mkStart(c);sfx('alert');pzMkStep();}
// Off to the next one: the tube it last snipped is whole again, the next one stays whole until it gets there.
function pzMkStep(){const m=UI.pzMk;if(!m||!pzOn())return;for(const l of S.links)l.cut=0;m.i++;if(m.i>=m.units.length){pzMkDone();return;}
const u=m.units[m.i];compute();renderAll();mkRun(S.links.find(l=>pzUnit(l)===u),PZ_RUN/MK_RUN);m.t=setTimeout(pzMkHit,PZ_RUN);}
function pzMkHit(){const m=UI.pzMk;if(!m||!pzOn())return;const ls=S.links.filter(l=>pzUnit(l)===m.units[m.i]),l0=ls[0];for(const l of ls)l.cut=1;compute();
const g=pzGot(),lost=[];S.pz.dem.forEach((f,i)=>{if(!f.be&&!pzFull(f,g[i]))lost.push({c:f.t==='l2'?f.b:f.a,g:Math.max(0,f.g-g[i].g)});});
floater((CITY[l0.a].x+CITY[l0.a].x+wrapDx(CITY[l0.a].x,CITY[l0.b].x))/2,(CITY[l0.a].y+CITY[l0.b].y)/2-26,tr('puzzles.monkey_snip'),'#FF8A3D');
for(const x of lost)floater(CITY[x.c].x,CITY[x.c].y-34,tr('puzzles.city_loses_g',{city:CITY[x.c].name,g:fmtG(x.g)}),'#FF4D5E');
if(UI.mk)UI.mk.bad=lost.length>0;if(lost.length)m.bad++;sfx(lost.length?'err':'click');renderAll();m.t=setTimeout(pzMkStep,lost.length?PZ_HOLD*2:PZ_HOLD);}
// The end: a cheer if nothing broke, a tantrum if something did, then whatever was waiting (the stars).
function pzMkDone(bad){const m=UI.pzMk;if(!m)return;clearTimeout(m.t);UI.pzMk=null;for(const l of S.links)l.cut=0;compute();
mkEnd(!(bad!=null?bad:m.bad),true);renderAll();if(m.then)m.then();}
// Skip: straight to the end; the verdict is already known.
function pzMkSkip(){if(UI.pzMk)pzMkDone(pzEval().n1?0:1);}
// Gone without a word: the build changed under it, or the puzzle closed.
function pzMkStop(){const m=UI.pzMk;if(!m)return;clearTimeout(m.t);UI.pzMk=null;for(const l of S.links)l.cut=0;mkStop();}

View file

@ -3,6 +3,9 @@
function pzWaveWhy(a,b,tier,r){if(r&&subWaveWhy(tier,r.km,r.sub))return tr('common.too_far_for_this_cable');if(!waveOk(a,b,tier))return tr('puzzles.needs_what',{what:waveNeed(tier)});return '';}
const pzPortsFree=c=>!S.pops[c]||portsUsed(c)+1<=portsMax(c)+1e-9;
Object.assign(ACT,{
// The chaos monkey acts out the N-1 check, or is told to get on with it.
pzMonkey:()=>{if(pzOn()&&pzEval().goal)pzMonkey();},
pzMkSkip:()=>{if(pzOn())pzMkSkip();},
// The puzzle list. The ruleset's title-screen door calls this.
puzzleMenu:()=>{if(S&&UI.started&&!pzOn())UI.nm=S.name;pzMenu();},
pzStart:({id})=>{const d=pzDef(id);if(!d||!pzPackOpen(d.pack))return;pzBegin(d);},

View file

@ -29,6 +29,7 @@ function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hi
const w=e.worst;
h+=!e.goal?`<div class="pzn1">🛡 ${tr('puzzles.n_1_deliver_everything_first')}</div>`:e.n1?`<div class="pzn1 on">🛡 ${tr('puzzles.survives_any_single_cut_under_load')}</div>`
:`<div class="pzn1 bad">⚠️ ${tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(w.u),g:fmtG(w.g)})}<br><small>${w.lost.map(x=>esc(pzFlowName(P.dem[x.i]))).join(', ')}</small></div>`;
if(UI.pzMk)h+=`<div class="btns">${btn('⏩ '+tr('puzzles.skip_the_monkey'),'pzMkSkip',{},'big')}</div>`;else if(e.goal)h+=`<div class="btns">${btn(tr('puzzles.let_the_chaos_monkey_loose'),'pzMonkey',{},'sm')}</div>`;
h+=`<div class="btns">${btn('↶ '+tr('puzzles.undo'),'pzUndo',{},'ghost sm',!(UI.pzHist&&UI.pzHist.length))}${btn(tr('puzzles.reset'),'pzReset',{},'ghost sm',!S.links.length&&!Object.keys(S.pops).length)}${(UI.pzTop||0)>0&&(UI.pzTop||0)<3?btn(tr('puzzles.finish_here'),'pzFinish',{},'sm'):''}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'ghost sm')}</div>`;
if(h!==UI._pzh){UI._pzh=h;morph(el,h);}}
// Trenches on a pair get numbers, cables their names, so parallel links say where they run.
@ -91,13 +92,13 @@ function pzLinkModal(a,b,keep){const kb=pzKind(b);
h+=`<h4 class="sub4">${tr('common.route')}</h4><div class="seg">${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} <small>${x.ms.toFixed(1)} ms${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}</small>`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}</div>`;
if(P.noSub&&r.sub)h+=`<p class="why">${tr('puzzles.the_sharks_say_no')}</p>`;
if(r.cab)h+=`<p class="note">${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}</p>`;
if(land)h+=`<div class="seg" style="margin-top:8px">${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}</div>`;
if(land)h+=`<div class="seg" style="margin-top:8px">${btn(tr('puzzles.diverse_route_40_survives_the_monkey'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_snip_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}</div>`;
if(pop)h+=`<p class="lead" style="margin-top:8px">${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}</p>`;
const full=[a,b].filter(c=>!pzPortsFree(c));if(full.length)h+=`<p class="why">${tr('puzzles.no_free_ports_in_list',{list:full.map(c=>esc(CITY[c].name)).join(', ')})}</p>`;
h+=`<div class="tiers">${PZ_TIERS.map(i=>{const why=pzWaveWhy(a,b,i,r),c=pzLinkCost(r,i,div)+pop;return `<button class="tierbtn" data-act="pzLink" data-args='{"tier":${i}}'${why||full.length||(P.noSub&&r.sub)?' disabled':''}><span class="sz">${LT[i].n}</span><span class="grow meta">${why?esc(why):pop?tr('puzzles.with_the_pop_price',{price:fmt$(c)}):''}</span><span class="pr num">${tr('puzzles.price_per_year',{price:fmt$(pzLinkCost(r,i,div))})}</span></button>`;}).join('')}</div>`;
openModal(h);}
// ---------- results ----------
function pzLine(e){return e.stars>=3?tr('puzzles.a_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?tr('puzzles.one_backhoe_away_from_a_very'):tr('puzzles.rock_solid_and_gold_plated_the');}
function pzLine(e){return e.stars>=3?tr('puzzles.a_chaos_monkey_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_monkey'):!e.n1?tr('puzzles.one_monkey_away_from_a_very'):tr('puzzles.rock_solid_and_gold_plated_the');}
// Stars still to win in this puzzle's pack, from the progress just saved.
function pzPackLeft(P){const d=pzDef(P.id);if(!d)return null;const p=pzLoad(),xs=PZ.filter(x=>x.pack===d.pack);return xs.length*3-xs.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);}
function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF'];let h='';

View file

@ -2883,8 +2883,8 @@
"progress.under_attack_now":"Under attack now",
"progress.your_score_peak_traffic":"Your score: peak traffic",
"progress.your_traffic_to_and_from_asia":"Your traffic to and from Asia",
"puzzles.a_backhoe_walks_into_your_network":"A backhoe walks into your network. Nothing happens.",
"puzzles.a_bigger_boat":"A Bigger Boat",
"puzzles.a_chaos_monkey_walks_into_your_network":"A chaos monkey walks into your network. Nothing happens.",
"puzzles.a_cut_on_where_drops_g":"A cut on {where} drops {g}",
"puzzles.a_different_route":"A different route",
"puzzles.a_diverse_route":"A diverse route (+40%)",
@ -2908,11 +2908,12 @@
"puzzles.carry_list":"Carry: {list}.",
"puzzles.carrying":"Carrying",
"puzzles.carrying_on_this_pair":"Carrying (all {n} links on this pair)",
"puzzles.city_loses_g":"{city} −{g}",
"puzzles.content_lives_in_list":"Content lives in {list}: eyeballs pull from the nearest.",
"puzzles.copied_paste_it_anywhere":"Copied! Paste it anywhere:<br>{t}",
"puzzles.de_kicks_sales_has_your_number":"DE-KICKS sales has your number. Connect Germany without Frankfurt.",
"puzzles.delivered":"Delivered",
"puzzles.diverse_route_40_survives_a_backhoe":"Diverse route (+40%, survives a backhoe)",
"puzzles.diverse_route_40_survives_the_monkey":"Diverse route (+40%, survives the chaos monkey)",
"puzzles.down_under_up_and_running":"Down Under, Up and Running",
"puzzles.drag_from_a_pink_pop_to":"Drag from a pink POP to another city to lease a wave",
"puzzles.drag_from_this_pop_onto_another":"Drag from this POP onto another puzzle city, or pick one here.",
@ -2939,15 +2940,17 @@
"puzzles.hub_cap":"Hub Cap",
"puzzles.includes_a_new_pop_in_city":"Includes a new POP in {city} ({price} for a year).",
"puzzles.installed":"installed",
"puzzles.it_works_finance_and_the_backhoe":"It works! Finance and the backhoe would like a word.",
"puzzles.it_works_finance_and_the_monkey":"It works! Finance and the chaos monkey would like a word.",
"puzzles.keep_building":"Keep building",
"puzzles.kiwi_fruit_salad":"Kiwi Fruit Salad",
"puzzles.latency":"Latency",
"puzzles.latency_caps":"latency caps",
"puzzles.lease_a_wave_to":"Lease a wave to",
"puzzles.let_the_chaos_monkey_loose":"🐒 Let the chaos monkey loose",
"puzzles.loading_this_week_s_puzzle":"Loading this week's puzzle…",
"puzzles.london_wants_half_a_terabit_your":"London wants half a terabit, and your routers came off eBuy.",
"puzzles.model_facts":"{cap} · {ports} ports · waves up to {wave}",
"puzzles.monkey_snip":"🐒 Snip!",
"puzzles.more_puzzles":"More puzzles",
"puzzles.n_1_club":"N-1 Club",
"puzzles.n_1_deliver_everything_first":"N-1: deliver everything first",
@ -2977,7 +2980,7 @@
"puzzles.not_through_frankfurt":"Not Through Frankfurt",
"puzzles.off_limits":"Off limits",
"puzzles.on_the_house":"On the house",
"puzzles.one_backhoe_away_from_a_very":"One backhoe away from a very long night. Add a second path for ⭐⭐⭐.",
"puzzles.one_monkey_away_from_a_very":"One chaos monkey away from a very long night. Add a second path for ⭐⭐⭐.",
"puzzles.one_ring_through_every_pop":"One ring through every POP",
"puzzles.one_very_big_island_and_a":"One very big island, and a lot of very empty fiber.",
"puzzles.open_a_pop_cost":"Open a POP · {cost}",
@ -3007,12 +3010,13 @@
"puzzles.same_cable_same_anchor":"Same cable as a link you have: one anchor takes both.",
"puzzles.same_puzzle_for_everyone_this_week":"Same puzzle for everyone this week",
"puzzles.same_trench_cheaper":"Same trench (cheaper)",
"puzzles.same_trench_cheaper_one_backhoe_cuts":"Same trench (cheaper, one backhoe cuts both)",
"puzzles.same_trench_cheaper_one_snip_cuts":"Same trench (cheaper, one snip cuts both)",
"puzzles.sao_paulo_to_miami_before_the":"São Paulo to Miami before the caipirinha gets warm.",
"puzzles.sea_to_shining_sea":"Sea to Shining Sea",
"puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es",
"puzzles.six_cities_a_few_gigs_each":"Six cities, a few gigs each, and a router with eight ports. Count before you dig.",
"puzzles.size":"Size",
"puzzles.skip_the_monkey":"Skip",
"puzzles.small_networks_real_traffic":"Small networks, real traffic",
"puzzles.spent_x":"Spent {x}",
"puzzles.spent_x_of_y":"Spent {x} / {y}",