From 13a29c2c2a7562a649e0cb1869d191e79dd20f2d Mon Sep 17 00:00:00 2001 From: Florian Krieger Date: Sun, 25 Oct 2026 15:38:10 +0100 Subject: [PATCH 01/64] Add on-demand single-link redundancy checks --- CHANGELOG.md | 2 ++ site/i18n/it.js | 13 +++++++++++++ site/index.html | 24 +++++++++++++++++++++--- tests/issues.test.js | 17 +++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c36434..bf32aa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Check a selected link’s redundancy against current demand: see disconnected endpoints, additional service loss and full fallback links without changing the live network. + ## [1.25.2] — 2026-10-25 - Tier 1 networks can lay their own subsea cable (#22). Pick two cities with a diff --git a/site/i18n/it.js b/site/i18n/it.js index 8a0542a..46aeda8 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2248,4 +2248,17 @@ "Replace ten of them and the cable pays for itself in about {n} months.":"Sostituiscine dieci e il cavo si ripaga in circa {n} mesi.", "Cuts still happen, anchors and sharks included, but the repair ship is yours to call.":"I tagli succedono lo stesso, ancore e squali compresi, ma la nave di riparazione la chiami tu.", "Lay the cable {price}":"Posa il cavo {price}", +"This backhoe wins.":"Questa ruspa vince.", +"Connected, but tight.":"Connesso, ma al limite.", +"One backhoe is not enough.":"Una ruspa non basta.", +"Redundancy check":"Verifica della ridondanza", +"No alternate backbone path connects these endpoints if this link fails.":"Se questo collegamento si interrompe, nessun percorso alternativo della dorsale collega questi estremi.", +"An alternate path exists, but current routing and capacity deliver less traffic.":"Esiste un percorso alternativo, ma con routing e capacità attuali viene consegnato meno traffico.", +"With current demand and routing, this link can fail without additional traffic loss.":"Con domanda e routing attuali, questo collegamento può interrompersi senza ulteriori perdite di traffico.", +"Additional traffic lost":"Ulteriore traffico perso", +"Service affected":"Servizio interessato", +"Full links during the test":"Collegamenti saturi durante il test", +"Snapshot only: one selected link fails. Other links on the same cable, trench or fabric stay up. Existing outages and routing rules still apply. No time, money or game state is changed.":"Solo un’istantanea: si interrompe il collegamento selezionato. Gli altri collegamenti sullo stesso cavo, scavo o fabric restano attivi. I guasti e le regole di routing esistenti si applicano comunque. Tempo, denaro e stato della partita non cambiano.", +"What happens if this link fails right now?":"Cosa succede se questo collegamento si interrompe adesso?", +"Check redundancy":"Verifica ridondanza", }; diff --git a/site/index.html b/site/index.html index 44a609b..ab5b4aa 100644 --- a/site/index.html +++ b/site/index.html @@ -427,6 +427,7 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #coach{top:auto !important;bottom:calc(var(--tabbar) + 8px);width:calc(100% - 16px);padding:7px 10px;font-size:13px} body.sheet-open #coach{bottom:calc(var(--tabbar) + 8px + min(62vh,520px))} #modal{align-items:end;padding:0} + #modal.link-check{bottom:var(--tabbar)} #modal .cta{position:sticky;bottom:calc(-16px - env(safe-area-inset-bottom,0px));z-index:1;background:var(--paper);margin:12px -16px 0 !important;padding:10px 16px calc(10px + env(safe-area-inset-bottom,0px));border-top:2px solid var(--line)} .title-art h1{font-size:34px}.title-art svg{width:54px;height:54px} .tagline{font-size:13.5px;margin:8px 0 10px} @@ -2443,6 +2444,7 @@ function checkGoals(){checkBadges(); /* ================= ACTIONS ================= */ function spend(c){if(S.cashNot enough cash.
Wait for revenue, or speed up time.'),'bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;} const ACT={ + linkCheck:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return;linkCheckModal(l);}, speed:({v})=>{v=+v;if(![0,0.5,1,2,4,8].includes(v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();}, help:()=>showHelp(), dash:()=>{if(!S)return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();}, @@ -2470,7 +2472,7 @@ const ACT={ tab:({t})=>{UI.tab=t;UI.confirm=null;renderPanel();}, leftTab:({t})=>{UI.left=t;UI.leftOpen=true;renderLeft();}, toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();}, - phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();}, + phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;if($('modal').classList.contains('link-check'))closeModal();haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();}, phonePlay:()=>{haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();}, phoneSpeed:()=>{haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();}, install:()=>{if(installEvt){installEvt.prompt();installEvt.userChoice.finally(()=>{installEvt=null;});return;} @@ -3041,9 +3043,25 @@ function vxcPanel(l){ return h; } function prefCtl(kind,id,cur){cur=cur||'normal';return `
${tr('Egress:')}${Object.keys(PREF).map(v=>btn(PREF[v],'setPref',{kind,id,v},cur===v?'pink sm':'ghost sm')).join('')}
`;} +// Trial routing is isolated from the live save, counters and scenic-route memory. +function linkTrial(id){const save=S,live=R,hot=UI.hotMap,cache=TE_CACHE; + try{S=JSON.parse(JSON.stringify(save));const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return null; + compute();const before=R;l.cut=S.day+1;compute(); + const allowed=new Set(Object.keys(S.pops).filter(popUp).concat(remoteCities())),adj={}; + for(const x of S.links)if(!linkDown(x)&&allowed.has(x.a)&&allowed.has(x.b)){(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];for(let i=0;i.01)losses.push({name:CITY[c].name,g});} + for(const b of S.biz)if(BIZ_T[b.type].l2){const g=Math.max(0,(before.l2[b.id]||0)-(R.l2[b.id]||0));if(g>.01)losses.push({name:b.name,g});} + const busy=S.links.filter(x=>x.id!==id&&!linkDown(x)&&capOf(x)>0&&(R.load[x.id]||0)/capOf(x)>=.995).map(x=>({name:CITY[x.a].name+' ⇄ '+CITY[x.b].name,g:R.load[x.id]||0,cap:capOf(x)})); + return {split:!seen.has(l.b),loss:losses.reduce((a,x)=>a+x.g,0),losses,busy,day:S.day}; + }finally{S=save;R=live;UI.hotMap=hot;TE_CACHE=cache;}} +function linkCheckModal(l){const t=linkTrial(l.id);if(!t)return; + const title=t.split?tr('This backhoe wins.'):t.loss>.01?tr('Connected, but tight.'):tr('One backhoe is not enough.'); + openModal(`

${tr('Redundancy check')}

${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)} · ${dateStr(t.day)}

${title}

${t.split?tr('No alternate backbone path connects these endpoints if this link fails.'):t.loss>.01?tr('An alternate path exists, but current routing and capacity deliver less traffic.'):tr('With current demand and routing, this link can fail without additional traffic loss.')}

${tr('Additional traffic lost')}${fmtG(t.loss)}
${t.losses.length?`

${tr('Service affected')}

${t.losses.map(x=>`
${esc(x.name)}−${fmtG(x.g)}
`).join('')}`:''}${t.busy.length?`

${tr('Full links during the test')}

${t.busy.slice(0,6).map(x=>`
${esc(x.name)}${fmtG(x.g)} / ${fmtG(x.cap)}
`).join('')}`:''}

${tr('Snapshot only: one selected link fails. Other links on the same cable, trench or fabric stay up. Existing outages and routing rules still apply. No time, money or game state is changed.')}

${btn(tr('Close'),'closeModal',{},'ghost')}
`,'link-check');} +function linkCheckControl(l){return `

${tr('Redundancy check')}

${tr('What happens if this link fails right now?')}

${btn(tr('Check redundancy'),'linkCheck',{id:l.id},'ghost sm',linkDown(l))}
`;} function trafficSection(l){ const rec=R.ef[edgeKey(l)],n=pairLinks(l.a,l.b).length; - let h=`

${tr("What's on this link")}

`; + let h=linkCheckControl(l)+`

${tr("What's on this link")}

`; if(!rec){return h+`

${tr('No traffic right now.')}

`;} const tot=Object.values(rec.net).reduce((a,b)=>a+b,0)||1; const nets=Object.entries(rec.net).sort((a,b)=>b[1]-a[1]); @@ -3297,7 +3315,7 @@ function toast(html,kind='',actions=[]){ const markLayer=()=>{UI.layerAt=performance.now();}; // Which layers are open: when that changes (a sheet, the dashboard, the bank, a selection), taps in flight are void. function checkLayer(){const q=id=>{const e=$(id);return e?(e.hidden?0:1):0;},sig=[q('modal'),q('dash'),q('bankBox'),UI.leftOpen?1:0,UI.left||'',UI.sel?UI.sel.type+UI.sel.id:'',UI.tab||''].join('|');if(sig!==UI._layer){UI._layer=sig;markLayer();}} -function openModal(html){if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;} +function openModal(html,cls=''){$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;} function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;} const NETWORK_NAMES=[ 'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom', diff --git a/tests/issues.test.js b/tests/issues.test.js index 13b30b8..06bfc03 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -539,3 +539,20 @@ test('#35 your own trench can light another fiber pair once a ROADMaster is full assert.equal(ev('S.links[0].pairs'), 4, 'saves are clamped to four pairs'); assert.deepEqual(errors, []); }); + +test('link redundancy trials distinguish a bridge, a full fallback and a healthy alternate path without changing the game',()=>{ + const {ev,errors}=load(); + ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}];S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0,trench:'main'}];compute();window.state=JSON.stringify(S);window.live=R;window.hot=UI.hotMap;window.cache=TE_CACHE"); + let t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,true);assert.equal(t.loss,80); + assert.equal(ev('JSON.stringify(S)'),ev('state'));assert.equal(ev('R===live&&UI.hotMap===hot&&TE_CACHE===cache'),true); + ev("S.links.push({id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0});compute()"); + t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,false);assert.equal(t.loss,70);assert.equal(t.busy.length,2); + ev("S.links[1].tier=1;S.links[2].tier=1;compute()");t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,false);assert.equal(t.loss,0); + ev("S.links[1].cut=S.day+5;compute()");assert.equal(ev("linkTrial('main').split"),true,'existing failures are respected');assert.equal(ev("linkTrial('a')"),null,'an already failed link is not tested'); + ev("S.links=S.links.slice(0,1);S.links.push({...S.links[0],id:'parallel'});compute()");assert.equal(ev("linkTrial('main').split"),false,'only the selected link fails even when a trench is shared');assert.equal(ev("linkTrial('main').loss"),0); + ev("S.links[0]={...S.links[0],kind:'df',sys:'roadm',ch:['tp16'],pairs:1,regen:0,ready:0,own:true};compute()");assert.equal(ev("linkTrial('main').loss"),0,'dark fiber is tested as one link'); + ev("window.innerWidth=360;ACT.linkCheck({id:'main'})");assert.match(ev("$('modalCard').textContent"),/One backhoe is not enough/);assert.equal(ev("$('modal').className"),'link-check');ev("ACT.phoneTab({t:'noc'})");assert.equal(ev("$('modal').hidden"),true); + ev("S.links[0]={...S.links[0],kind:'vxc',vt:1,prov:FABS[0].id};compute()");assert.equal(ev("linkTrial('main').loss"),0,'virtual circuits are tested individually'); + ev("window.saveRef=S;window.liveRef=R;window.originalCompute=compute;compute=()=>{throw Error('trial failed')}");assert.throws(()=>ev("linkTrial('main')"),/trial failed/);ev('compute=originalCompute');assert.equal(ev('S===saveRef&&R===liveRef'),true,'even a failed trial restores the live state'); + assert.deepEqual(errors,[]); +}); From af155f27bb504086376a474053dbaca3d3f88ac7 Mon Sep 17 00:00:00 2001 From: clayberF <49653677+clayberF@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:38:19 -0300 Subject: [PATCH 02/64] Calibrate city prices with PeeringDB and Hurricane Electric data CITY_PDB holds, per city, the carrier-neutral facilities and network presences from PeeringDB (within 50 km or same city name) and the ASN count of its country from bgp.he.net, pulled 2026-10-25. - Transit: the regional multiplier is scaled by competition, up to 1.8x where few networks are present. Hubs (1000+ presences) are unchanged, and hand-set markets (Korea, Belgian red tape) keep their price. - POPs: 1.25x to build and run with one or two facilities, 1.5x with none. - Offers: countries with 2000+ ASNs bring extra ISP customers. --- CHANGELOG.md | 2 ++ site/i18n/it.js | 1 + site/i18n/pt.js | 1 + site/index.html | 24 +++++++++++++++++++----- tests/regions.test.js | 16 ++++++++++++++++ 5 files changed, 39 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04b01be..e476617 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Prices now follow how connected each city really is, based on PeeringDB and Hurricane Electric data. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices. + ## [1.30.0] — 2026-10-26 - Twelve Pacific islands join the map: Honolulu, Guam, Koror, Majuro, Port Moresby, Honiara, Nouméa, Suva, Nuku’alofa, Apia, Pago Pago and Papeete. The cables across the Pacific now stop where they really land, and a POP on an island splits a long crossing into shorter hops that each carry more: California to Sydney goes from 400G to 1.6T per wave via Honolulu and Suva, Hong Kong and Manila to Los Angeles from 400G to 800G via Guam, and Santiago to Sydney from 400G to 800G via Tahiti. Twelve new cables, among them SEA-US Later, Echo-Chamber and Coral Sea Shanty, link the islands, and the old ones gain island stops. Only islands with a real exchange today get one: Honolulu, Guam, Suva, Nouméa and Honiara. Island telcos from Hawaiian Telecombo to Never Too Atoll join the networks, PacNOG meets in Suva every December, Guam, Port Moresby and Honiara have unreliable power, Tonga’s cable has a volcano for a neighbour, and a new scenario, Stepping Stones, asks you to hop the Pacific at 1.6T. diff --git a/site/i18n/it.js b/site/i18n/it.js index 47d9ec7..4a15669 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2585,4 +2585,5 @@ "The seabed off Tonga slid down a slope and took your {a}–{b} cable with it. The repair ship is coming from Papua New Guinea.":"Il fondale al largo di Tonga è franato giù per un pendio e si è portato via il tuo cavo {a}–{b}. La nave di riparazione arriva dalla Papua Nuova Guinea.", "Tonga hangs on one cable from Fiji. In 2022 an undersea volcano cut it, and the country was offline for weeks.":"Tonga è appesa a un solo cavo dalle Figi. Nel 2022 un vulcano sottomarino l’ha tranciato e il paese è rimasto offline per settimane.", "Tonga’s own telco. Lived through a volcano that cut its only cable, and jokes about it now.":"La telco di Tonga. È sopravvissuta a un vulcano che le ha tranciato l’unico cavo, e ora ci scherza su.", +"Few data centers: POPs {x}×":"Pochi data center: POP {x}×", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index b0f10d6..3d2e1f3 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2585,4 +2585,5 @@ "The seabed off Tonga slid down a slope and took your {a}–{b} cable with it. The repair ship is coming from Papua New Guinea.":"O fundo do mar perto de Tonga deslizou encosta abaixo e levou junto o seu cabo {a}–{b}. O navio de reparo está vindo de Papua-Nova Guiné.", "Tonga hangs on one cable from Fiji. In 2022 an undersea volcano cut it, and the country was offline for weeks.":"Tonga depende de um único cabo vindo de Fiji. Em 2022 um vulcão submarino o cortou, e o país ficou offline por semanas.", "Tonga’s own telco. Lived through a volcano that cut its only cable, and jokes about it now.":"A operadora de Tonga. Sobreviveu a um vulcão que cortou seu único cabo e hoje faz piada disso.", +"Few data centers: POPs {x}×":"Poucos data centers: POPs {x}×", }; diff --git a/site/index.html b/site/index.html index 35f84e6..47d0019 100644 --- a/site/index.html +++ b/site/index.html @@ -599,7 +599,7 @@ const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000; const SITE2_N=[tr('The Other Building'),tr('Campus B (the one with parking)'),tr('Across-the-River DC'),tr('The Annex'),tr('Suburban Mega-shed'),tr('The Cheaper One'),tr('Formerly a Shopping Mall'),tr('Bunker Two')]; const siteName=(c,s)=>s==='b'?SITE2_N[hstr(c)%SITE2_N.length]:CITY[c].dc; const BE_TAPE=30000; -const popCost=c=>POP_COST+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); +const popCost=c=>Math.round(POP_COST*(c&&CITY[c]?colo(c):1))+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); const CN_LIC=150000, CN_JV_MO=6000; // Scrubbing centers come in tiers by clean bandwidth. Always-on diverts instantly; on-demand is cheaper // but takes a couple of days to engage. A clean-pipe add-on on a transit scrubs upstream, per port. @@ -2125,7 +2125,7 @@ function compute(){ for(const e of E){if(e.k==='t')R2.useT[e.id]=(R2.useT[e.id]||0)+e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;} // money const C=R2.cost,V=R2.rev,pm=S.priceMul; - C.pops=Object.values(S.pops).reduce((a,p)=>a+POP_MO+((p.routers||1)-1)*ROUTER_MO+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0); + C.pops=Object.entries(S.pops).reduce((a,[c,p])=>a+popMo(c)+((p.routers||1)-1)*ROUTER_MO+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0); C.optical=S.links.filter(l=>l.kind==='df').reduce((a,l)=>a+(l.ready>S.day?0:ampCount(l.km)*AMP_MO*(l.own&&isRdm(l.sys)&&!l.sub?Math.max(1,l.pairs|0):1)+(l.regen|0)*REGEN_MO)+(l.spares?Math.round(150+(l.ch||[]).length*80):0),0); C.links=S.links.reduce((a,l)=>a+(l.mo||0),0); C.nni=(S.nni||[]).reduce((a,x)=>a+NNI[x.tier].mo,0); @@ -2305,7 +2305,19 @@ function spawnSpecial(t){const T=BIZ_T[t],mine=Object.keys(S.pops),lv=S.lvl||1; S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('a spare fiber pair in your {a}–{b} trench',{a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*0.9),reqs:[],exp:S.day+30});} } function cnOk(){return S.cnLic&&S.cnLic.state==='ok';} -function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.tape)return 1.5;return C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;} +/* Real-world calibration, pulled 2026-10-25 (Pacific islands 2026-10-26). Per city: [carrier-neutral facilities, network presences across them, + ASNs registered in its country]. Facilities and presences are PeeringDB facilities within 50 km or in the same city + (peeringdb.com/api/fac, net_count summed); ASNs per country are from bgp.he.net/report/world. */ +const CITY_PDB={sea:[37,539,33300],sjc:[57,1048,33300],dal:[59,969,33300],chi:[64,809,33300],ash:[86,1010,33300],nyc:[96,1322,33300],mia:[27,553,33300],sao:[70,1875,9693],lon:[100,2588,4027],ams:[69,2731,1827],fra:[56,2450,3705],par:[77,1528,2249],mrs:[8,273,2249],tor:[46,509,2595],bru:[33,328,443],oos:[5,22,443],bet:[16,174,152],mtl:[35,283,2595],kcy:[22,313,33300],cal:[15,127,2595],van:[13,214,2595],ott:[6,21,2595],lax:[44,939,33300],mex:[18,122,814],rek:[15,51,93],dub:[21,277,350],osl:[20,209,448],cph:[30,290,529],hel:[23,232,427],beg:[7,49,227],sof:[15,451,889],dxb:[8,135,231],mos:[49,632,6683],akl:[27,398,755],per:[12,248,3196],jkt:[98,3015,4108],mnl:[17,352,750],ber:[22,351,3705],ham:[26,228,3705],muc:[22,230,3705],zrh:[38,535,1209],nbo:[9,283,274],cai:[5,28,97],stg:[18,63,3705],sto:[31,539,1011],bcn:[13,159,1341],mad:[31,578,1341],lag:[13,279,304],jnb:[14,561,879],bom:[59,1050,6412],sin:[58,1271,782],hkg:[57,1107,1514],icn:[37,201,1197],pek:[10,15,6717],sha:[11,27,6717],tok:[58,917,1330],syd:[40,979,3196],for:[16,362,9693],rio:[33,577,9693],bsb:[14,108,9693],bhz:[13,40,9693],cwb:[11,79,9693],poa:[22,120,9693],aju:[4,3,9693],bel:[3,7,9693],bvb:[3,6,9693],cac:[4,6,9693],cpv:[4,12,9693],cpq:[19,65,9693],cgr:[4,4,9693],cau:[2,2,9693],cgb:[4,5,9693],cxj:[2,3,9693],fec:[5,4,9693],fln:[5,23,9693],igu:[5,26,124],gyn:[5,28,9693],jpa:[4,18,9693],ljd:[1,2,9693],ldb:[3,7,9693],mcp:[2,0,9693],mcz:[1,5,9693],mao:[7,15,9693],mgf:[4,9,9693],nat:[1,3,9693],pmw:[3,8,9693],pvh:[3,4,9693],rao:[6,3,9693],rec:[6,31,9693],rbr:[0,0,9693],ssa:[13,44,9693],ria:[2,2,9693],sjp:[2,4,9693],slz:[1,6,9693],the:[2,1,9693],vix:[6,30,9693],mvd:[1,2,53],asu:[3,8,124],cor:[2,29,1357],lpb:[1,2,71],uio:[9,16,287],mde:[2,18,598],ccs:[6,32,296],gua:[5,16,103],sjo:[8,6,128],qro:[11,144,814],mty:[5,27,814],gdl:[4,22,814],bue:[28,372,1357],scl:[36,274,450],lim:[12,156,267],bog:[16,195,598],pan:[8,26,158],del:[31,479,6412],maa:[20,374,6412],blr:[14,104,6412],hyd:[17,152,6412],tpe:[15,274,500],auh:[4,1,231],fuj:[1,49,231],cpt:[6,267,879],dkr:[2,4,23],abj:[5,11,32],acc:[7,78,124],dla:[3,14,34],fih:[7,19,57],lad:[8,27,79],cas:[2,2,39],alg:[0,0,16],tun:[2,0,30],jib:[3,19,5],add:[2,3,10],mba:[4,176,274],dar:[9,67,124],kla:[2,18,71],kgl:[5,14,34],mpm:[7,20,36],dur:[4,137,879],wdh:[1,2,22],lun:[4,3,24],hre:[1,0,37],gbe:[1,2,39],mel:[20,395,3196],bne:[21,277,3196],drw:[3,15,3196],osa:[19,229,1330],kul:[20,210,434],bkk:[32,397,675],sgn:[6,36,1068],khi:[7,15,488],dac:[30,107,2105],cbo:[1,0,33],waw:[25,855,2743],prg:[24,336,775],vie:[30,377,860],bud:[6,146,369],buh:[23,289,1424],tll:[7,80,256],ist:[28,334,1290],kyv:[33,506,2342],jed:[5,25,220],ruh:[8,29,220],doh:[6,29,31],mil:[29,728,1534],rom:[12,213,1534],pmo:[3,46,1534],lis:[9,129,187],ath:[6,108,307],atn:[42,589,33300],den:[28,310,33300],phx:[26,279,33300],bos:[31,209,33300],hou:[21,173,33300],slc:[22,202,33300],man:[29,353,4027],edi:[4,46,4027],bde:[0,0,4027],svg:[2,14,448],hnl:[7,33,33300],gum:[6,28,11],ror:[0,0,4],maj:[0,0,12],pom:[2,0,46],hir:[1,0,11],nou:[2,2,19],suv:[0,0,23],tbu:[0,0,5],apw:[0,0,11],ppg:[0,0,2],ppt:[0,0,6]}; +// Few networks in the building means few transit sellers to haggle with: up to 1.8× where almost nobody is present. +// Hand-set markets (Korea, Belgian red tape) keep their own price. +const txComp=c=>{const q=CITY_PDB[c];return q?clamp((1000/Math.max(q[1],10))**0.15,1,1.8):1;}; +// No neutral data center means building your own room: POPs cost more to build and to run. +const colo=c=>{const q=CITY_PDB[c];return !q?1:q[0]===0?1.5:q[0]<=2?1.25:1;}; +const popMo=c=>Math.round(POP_MO*colo(c)); +// Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. +const asnDense=c=>{const q=CITY_PDB[c];return !!q&&q[2]>=2000;}; +function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.tape)return 1.5;const base=C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;return Math.round(base*txComp(c)*10)/10;} const uaePair=(a,b)=>!!CITY[a].uae&&!!CITY[b].uae; const rainPair=(a,b)=>!!(CITY[a].rain||CITY[b].rain); const borderPair=(a,b)=>!!CITY[a].cc&&!!CITY[b].cc&&CITY[a].cc!==CITY[b].cc; @@ -2730,6 +2742,7 @@ function spawnOffer(){ if(lv>=3&&MEGA.some(m=>mine.includes(m.c)))types.push('ingest');if(lv>=4&&MEGA.some(m=>mine.includes(m.c)))types.push('aiwan','aiwan','mtrain');if(lv>=4&&S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('pairs'); if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor'); + const dense=mine.filter(asnDense);if(lv>=2&&dense.length)types.push('isp'); const fabC=mine.filter(c=>FABS.some(f=>f.cities.includes(c)));if(lv>=2&&fabC.length){types.push('fabip','fabip');if(mine.length>=2)types.push('fabl2');} const t=pick(types),T=BIZ_T[t]; if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;} @@ -2744,6 +2757,7 @@ function spawnOffer(){ let name=list.length?pick(list):(T.names?pick(T.names):'Startup #'+Math.floor(Math.random()*999)); S.usedNames.push(name); if(t==='provedor')city=pick(br); + if(t==='isp'&&dense.length&&Math.random()<0.5)city=pick(dense); if(t==='hft'){const fin=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'],mf=mine.filter(c=>fin.includes(c));city=mf.length?pick(mf):pick(mine);city2=pick(fin.filter(c=>c!==city));} const rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate; if(T.div&&!reqCan('diverse',{city,city2}))return; @@ -3314,12 +3328,12 @@ function renderPanel(){checkLayer(); function cityPanel(c){ const C=CITY[c],p=S.pops[c],ix=ixName(c),down=p&&p.down>S.day; let h=`
${REG[C.reg]} · ${esc(C.dc)}

${C.name}

-
${tr('{g} of eyeballs',{g:fmtG(eyeP(c))})}${regionMult(c)>1?`${tr('Transit {x}× pricier',{x:regionMult(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('Underserved: users grow 60% faster')+'':''}${ix?`${tr('IX: {ix}',{ix:esc(ix)})}`:''}${p?`${tr('Your POP')}`:''}${down?`DOWN`:''}
+
${tr('{g} of eyeballs',{g:fmtG(eyeP(c))})}${regionMult(c)>1?`${tr('Transit {x}× pricier',{x:regionMult(c)})}`:''}${colo(c)>1?`${tr('Few data centers: POPs {x}×',{x:colo(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('Underserved: users grow 60% faster')+'':''}${ix?`${tr('IX: {ix}',{ix:esc(ix)})}`:''}${p?`${tr('Your POP')}`:''}${down?`DOWN`:''}
`; if(!p){ h+=`
${C.note?`

${esc(C.note)}

`:''} ${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`

${tr('Open a POP here')}

${tr('A POP (point of presence) is your router in a rack here. Then connect it: lay fiber from one of your POPs, or buy transit right here.')}

- ${C.ru?`

${tr('Includes the mandatory government box in your rack: {cost} + {mo}/mo. It comes with its own listener.',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${btn(tr('Build POP {cost} + {mo}/mo',{cost:fmt$(popCost(c)),mo:fmt$(POP_MO)}),'buildPop',{city:c},'pink big',S.cash${tr('Includes the mandatory government box in your rack: {cost} + {mo}/mo. It comes with its own listener.',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${btn(tr('Build POP {cost} + {mo}/mo',{cost:fmt$(popCost(c)),mo:fmt$(popMo(c))}),'buildPop',{city:c},'pink big',S.cash${tr('Or drag from one of your routers to this city to lay fiber and build the POP in one go.')}

`}`; h+=offersHere(c); const trs=NETS.filter(n=>n.price&&n.pops.includes(c)); diff --git a/tests/regions.test.js b/tests/regions.test.js index 74a906a..5a3d8f8 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -634,5 +634,21 @@ test('Pacific islands: real landings, real exchanges only, and island hops carry assert.ok(ev('!!S.pops.hnl') && ev('S.lvl') >= 4); assert.equal(ev('scnProg().items.length'), 3); ev('cam.z=0.5;draw(0);cam.z=2;draw(0)'); + +test('prices follow real connectivity: thin markets cost more, hubs stay put', () => { + const { ev, errors } = load(); + start(ev); + assert.ok(ev('Object.keys(CITY_PDB).length') === ev('CITIES.length'), 'every city has real-world data'); + for (const c of ['fra', 'ams', 'lon', 'nyc']) assert.equal(ev(`txComp('${c}')`), 1, `${c} is a hub`); + assert.equal(ev("regionMult('sao')"), 1.6, 'São Paulo keeps the South American price'); + assert.ok(ev("regionMult('rbr')") > ev("regionMult('sao')") * 1.5, 'Rio Branco has few sellers'); + assert.ok(ev("txComp('rbr')") <= 1.8); + assert.equal(ev("colo('rbr')"), 1.5, 'no neutral data center'); + assert.equal(ev("popCost('rbr')"), ev('POP_COST') * 1.5); + assert.equal(ev("popMo('fra')"), ev('POP_MO')); + ev("ACT.buildPop({city:'rbr'});compute()"); + assert.ok(ev('R.cost.pops') >= ev("popMo('rbr')"), 'running cost uses the city rent'); + ev("selectCity('rbr')"); + assert.equal(ev('asnDense("sao")&&asnDense("nyc")&&!asnDense("kgl")'), true); assert.deepEqual(errors, []); }); From 6de56f79ebc7fa3eef1de62c55b1da80e70d8766 Mon Sep 17 00:00:00 2001 From: clayberF <49653677+clayberF@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:00:53 -0300 Subject: [PATCH 03/64] Calibration: drop a redundant guard and a one-caller helper --- site/index.html | 7 +++---- tests/regions.test.js | 4 +++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/site/index.html b/site/index.html index 47d0019..dcf523b 100644 --- a/site/index.html +++ b/site/index.html @@ -599,7 +599,7 @@ const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000; const SITE2_N=[tr('The Other Building'),tr('Campus B (the one with parking)'),tr('Across-the-River DC'),tr('The Annex'),tr('Suburban Mega-shed'),tr('The Cheaper One'),tr('Formerly a Shopping Mall'),tr('Bunker Two')]; const siteName=(c,s)=>s==='b'?SITE2_N[hstr(c)%SITE2_N.length]:CITY[c].dc; const BE_TAPE=30000; -const popCost=c=>Math.round(POP_COST*(c&&CITY[c]?colo(c):1))+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); +const popCost=c=>Math.round(POP_COST*colo(c))+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); const CN_LIC=150000, CN_JV_MO=6000; // Scrubbing centers come in tiers by clean bandwidth. Always-on diverts instantly; on-demand is cheaper // but takes a couple of days to engage. A clean-pipe add-on on a transit scrubs upstream, per port. @@ -2315,8 +2315,6 @@ const txComp=c=>{const q=CITY_PDB[c];return q?clamp((1000/Math.max(q[1],10))**0. // No neutral data center means building your own room: POPs cost more to build and to run. const colo=c=>{const q=CITY_PDB[c];return !q?1:q[0]===0?1.5:q[0]<=2?1.25:1;}; const popMo=c=>Math.round(POP_MO*colo(c)); -// Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. -const asnDense=c=>{const q=CITY_PDB[c];return !!q&&q[2]>=2000;}; function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.tape)return 1.5;const base=C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;return Math.round(base*txComp(c)*10)/10;} const uaePair=(a,b)=>!!CITY[a].uae&&!!CITY[b].uae; const rainPair=(a,b)=>!!(CITY[a].rain||CITY[b].rain); @@ -2742,7 +2740,8 @@ function spawnOffer(){ if(lv>=3&&MEGA.some(m=>mine.includes(m.c)))types.push('ingest');if(lv>=4&&MEGA.some(m=>mine.includes(m.c)))types.push('aiwan','aiwan','mtrain');if(lv>=4&&S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('pairs'); if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor'); - const dense=mine.filter(asnDense);if(lv>=2&&dense.length)types.push('isp'); + // Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. + const dense=mine.filter(c=>(CITY_PDB[c]||[])[2]>=2000);if(lv>=2&&dense.length)types.push('isp'); const fabC=mine.filter(c=>FABS.some(f=>f.cities.includes(c)));if(lv>=2&&fabC.length){types.push('fabip','fabip');if(mine.length>=2)types.push('fabl2');} const t=pick(types),T=BIZ_T[t]; if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;} diff --git a/tests/regions.test.js b/tests/regions.test.js index 5a3d8f8..41bc080 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -634,6 +634,8 @@ test('Pacific islands: real landings, real exchanges only, and island hops carry assert.ok(ev('!!S.pops.hnl') && ev('S.lvl') >= 4); assert.equal(ev('scnProg().items.length'), 3); ev('cam.z=0.5;draw(0);cam.z=2;draw(0)'); + assert.deepEqual(errors, []); +}); test('prices follow real connectivity: thin markets cost more, hubs stay put', () => { const { ev, errors } = load(); @@ -649,6 +651,6 @@ test('prices follow real connectivity: thin markets cost more, hubs stay put', ( ev("ACT.buildPop({city:'rbr'});compute()"); assert.ok(ev('R.cost.pops') >= ev("popMo('rbr')"), 'running cost uses the city rent'); ev("selectCity('rbr')"); - assert.equal(ev('asnDense("sao")&&asnDense("nyc")&&!asnDense("kgl")'), true); + assert.ok(ev("CITY_PDB.sao[2]>=2000&&CITY_PDB.nyc[2]>=2000&&CITY_PDB.kgl[2]<2000"), 'Brazil and the US are dense in ASNs, Rwanda is not'); assert.deepEqual(errors, []); }); From 8a25ebdb95bccf8d744256f666ddbe2a9731e962 Mon Sep 17 00:00:00 2001 From: Marvin Date: Mon, 26 Oct 2026 20:55:12 +0100 Subject: [PATCH 04/64] Custom routing metric for links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A link's routing metric could only be one of four presets (Prefer, Normal, Avoid, Backup only). Links now also get a Custom option, closer to how real networks tune IGP metrics: - Multiplier mode scales the distance cost, (km + 60) × 0.1 to 100. - Cost mode sets an exact cost, 1 to 65535 like an OSPF metric. The preset buttons stay plain. Picking Custom explains how a link's cost is worked out and lists what each preset comes to on that link. Choosing Custom starts from the current preset and switching modes keeps the effective cost, so nothing moves until the player changes the value. Like the presets, it applies to every link between the two cities. The cost formula lives in one helper, linkW(), used by compute() and the traceroute paths. Custom links store mk/mv, which sanitize() repairs and clamps; old saves load unchanged. The link panel skips its daily re-render while the number field has focus, and Enter applies the value. Tests cover routing equivalence with the presets, rerouting by cost, mode switching, input clamping, saves, and the panel at desktop and phone width. French, Italian and Portuguese for the new strings. Perf on the big network: no change beyond noise, routing identical to main. --- CHANGELOG.md | 2 + site/i18n/fr.js | 11 ++++- site/i18n/it.js | 11 ++++- site/i18n/pt.js | 11 ++++- site/index.html | 34 +++++++++++---- tests/game.test.js | 102 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 161 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 648e743..fe661d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Links can now use a custom routing metric, set either as a multiplier or as an exact cost. Pick Custom under Routing metric to fine-tune where your traffic goes; it explains how a link's cost is worked out and what each preset comes to on that link. + ## [1.31.0] — 2026-10-26 - Series of Tubes now speaks French. The game follows your browser's language the first time, and you can switch to Français under Settings or on the title screen. diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 1b4c2ba..0bb9742 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1604,7 +1604,6 @@ "Going to customers in":"Vers les clients de", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Plus gros contributeur : {egress} à {city}. Passe-le en « Secours seul », donne aux clients une sortie plus proche (peering, cache, transit local) ou augmente la métrique de ce lien.", "Routing metric":"Métrique de routage", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"Tes routeurs choisissent le chemin le moins coûteux. Augmente la métrique pour pousser le trafic vers d’autres chemins. « Secours seul » le laisse au repos tant que le reste fonctionne. S’applique à tous les liens entre ces deux villes.", "Behind the Great Firewall":"Derrière le Grand Pare-feu", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"La Chine continentale joue selon ses propres règles. {list} et d’autres services étrangers y sont bloqués, donc les utilisateurs atteignent surtout des réseaux chinois. Le trafic qui passe la frontière perd environ {pct} en filtrage et congestion, sauf s’il emprunte une route premium : du transit CN-Too ou un circuit transfrontalier premium (tous deux vendus uniquement à Hong Kong), ou un PNI avec un réseau chinois. Le revenu par utilisateur est plus faible ici.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Les réseaux étrangers ont besoin d’une coentreprise locale et d’une licence d’opérateur pour construire ici.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"via un courtier en capacité", "List it with a capacity broker they keep 10%":"La confier à un courtier en capacité il garde 10 %", "Nothing spare to sell on this fiber right now.":"Rien à vendre sur cette fibre pour l’instant.", +"Custom":"Perso", +"Multiplier":"Multiplicateur", +"Cost":"Coût", +"Set":"Appliquer", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Coût sur ce lien : {w}. Autorisé : de {lo} à {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"Tes routeurs choisissent le chemin le moins coûteux. Augmente la métrique pour pousser le trafic vers d’autres chemins. « Secours seul » le laisse au repos tant que le reste fonctionne. Choisis Perso pour fixer ton propre multiplicateur ou coût. S’applique à tous les liens entre ces deux villes.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"Le coût d’un lien, c’est sa longueur en km plus 60, fois un multiplicateur. Le trafic prend le chemin au coût total le plus bas.", +"Presets on this link: {list}.":"Préréglages sur ce lien : {list}.", +"Cost: the exact number, whatever the distance.":"Coût : le nombre exact, quelle que soit la distance.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Multiplicateur : il multiplie le coût de la distance, donc un lien plus long coûte toujours plus.", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index 6bf8565..fdc589d 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1603,7 +1603,6 @@ "Going to customers in":"Diretto ai clienti a", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Fonte principale: {egress} a {city}. Impostala su “Solo backup”, dai ai clienti un’uscita più vicina (peering, una cache, transit locale) o alza la metrica di questo link.", "Routing metric":"Metrica di routing", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"I tuoi router scelgono il percorso a costo minore. Alza la metrica per spingere il traffico su altri percorsi. “Solo backup” lo lascia a riposo finché il resto funziona. Vale per tutti i link tra queste due città.", "Behind the Great Firewall":"Dietro il Great Firewall", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"La Cina continentale gioca con regole tutte sue. {list} e altri servizi stranieri qui sono bloccati, quindi gli utenti raggiungono soprattutto reti cinesi. Il traffico che attraversa il confine perde circa il {pct} tra filtri e congestione, a meno che non viaggi su una rotta premium: transit CN-Too o un circuito transfrontaliero premium (entrambi venduti solo a Hong Kong), oppure un PNI con una rete cinese. Qui i ricavi per utente sono più bassi.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Per costruire infrastrutture qui, le reti straniere hanno bisogno di una joint venture locale e di una licenza operativa.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"tramite un broker di capacità", "List it with a capacity broker they keep 10%":"Mettila in vendita con un broker di capacità trattiene il 10%", "Nothing spare to sell on this fiber right now.":"Per ora non c’è niente da vendere su questa fibra.", +"Custom":"Personalizzata", +"Multiplier":"Moltiplicatore", +"Cost":"Costo", +"Set":"Imposta", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Costo su questo link: {w}. Ammessi: da {lo} a {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"I tuoi router scelgono il percorso a costo minore. Alza la metrica per spingere il traffico su altri percorsi. “Solo backup” lo lascia a riposo finché il resto funziona. Scegli Personalizzata per impostare il tuo moltiplicatore o costo. Vale per tutti i link tra queste due città.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"Il costo di un link è la sua lunghezza in km più 60, per un moltiplicatore. Il traffico prende il percorso col costo totale più basso.", +"Presets on this link: {list}.":"Preset su questo link: {list}.", +"Cost: the exact number, whatever the distance.":"Costo: il numero esatto, a prescindere dalla distanza.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Moltiplicatore: scala il costo della distanza, così un link più lungo costa comunque di più.", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 9c443f5..9f4950d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1602,7 +1602,6 @@ "Going to customers in":"Indo para clientes em", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Maior fonte: {egress} em {city}. Coloque em “Só backup”, dê aos clientes uma saída mais próxima (peering, um cache, transit local) ou aumente a métrica deste link.", "Routing metric":"Métrica de roteamento", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"Seus routers escolhem o caminho de menor custo. Aumente a métrica para empurrar o tráfego para outros caminhos. “Só backup” deixa o link ocioso a menos que nada mais funcione. Vale para todos os links entre essas duas cidades.", "Behind the Great Firewall":"Atrás do Great Firewall", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"A China continental joga com regras próprias. {list} e outros serviços estrangeiros são bloqueados aqui, então os usuários acessam principalmente redes chinesas. O tráfego que cruza a fronteira perde cerca de {pct} com filtragem e congestionamento, a menos que vá por uma rota premium: transit CN-Too ou um circuito transfronteiriço premium (ambos vendidos só em Hong Kong), ou um PNI com uma rede chinesa. A receita por usuário aqui é menor.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Redes estrangeiras precisam de uma joint venture local e de uma licença de operação para construir infraestrutura aqui.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"por um corretor de capacidade", "List it with a capacity broker they keep 10%":"Anunciar com um corretor de capacidade ele fica com 10%", "Nothing spare to sell on this fiber right now.":"Nada sobrando para vender nesta fibra por enquanto.", +"Custom":"Personalizada", +"Multiplier":"Multiplicador", +"Cost":"Custo", +"Set":"Aplicar", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Custo neste link: {w}. Permitido: de {lo} a {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"Seus routers escolhem o caminho de menor custo. Aumente a métrica para empurrar o tráfego para outros caminhos. “Só backup” deixa o link ocioso a menos que nada mais funcione. Escolha Personalizada para definir seu próprio multiplicador ou custo. Vale para todos os links entre essas duas cidades.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"O custo de um link é seu comprimento em km mais 60, vezes um multiplicador. O tráfego segue o caminho de menor custo total.", +"Presets on this link: {list}.":"Predefinições neste link: {list}.", +"Cost: the exact number, whatever the distance.":"Custo: o número exato, seja qual for a distância.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Multiplicador: multiplica o custo da distância, então um link mais longo continua custando mais.", }; diff --git a/site/index.html b/site/index.html index 9334e32..a125165 100644 --- a/site/index.html +++ b/site/index.html @@ -315,6 +315,7 @@ label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-t input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 12px;font-family:var(--display);font-weight:800;font-size:18px;background:var(--soft)} .network-name{display:flex;flex-wrap:wrap;align-items:center;gap:8px} .network-name input.t{flex:1 1 240px;width:auto;min-width:0} +.metric-in{display:flex;gap:6px;align-items:center;margin-top:6px}.metric-in input.t{flex:1 1 120px;width:auto;min-width:0;font-size:16px;padding:4px 10px} .plug{display:flex;gap:12px;align-items:center;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;margin:10px 0 4px;background:var(--soft);box-shadow:0 3px 0 var(--ink);color:var(--ink);text-decoration:none} .plug:hover{background:#FFF6D6}.plug .pi{font-size:30px;line-height:1}.plug b{font-family:var(--display);font-size:16px}.plug .meta{display:block;margin-top:2px}.plug .go{margin-left:auto;font-weight:900;white-space:nowrap} .starts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} @@ -719,6 +720,10 @@ const NNI=[{n:'10G',g:10,mo:500},{n:'100G',g:100,mo:1200}]; const VXC=[{n:'10G',g:10,m:1},{n:'50G',g:50,m:2.4},{n:'100G',g:100,m:3.6}]; const vxcMo=(km,sub,t)=>Math.round((150+km*0.12)*VXC[t].m*(sub?2:1)); const MET={prefer:{l:tr('Prefer'),f:0.5},normal:{l:tr('Normal'),f:1},avoid:{l:tr('Avoid'),f:4},backup:{l:tr('Backup only'),f:60}}; +// Custom metrics: a multiplier on the distance cost (f) or an absolute IGP cost (w), capped like an OSPF metric. +const MET_LIM={f:[0.1,100],w:[1,65535]}; +const clampM=(k,v)=>{const [lo,hi]=MET_LIM[k];v=Math.min(hi,Math.max(lo,v));return k==='w'?Math.round(v):Math.round(v*100)/100;}; +const linkW=l=>l.metric==='custom'?(l.mk==='w'?l.mv:(l.km+60)*l.mv):(l.km+60)*MET[l.metric||'normal'].f; const PREF={high:tr('Prefer'),normal:tr('Normal'),low:tr('Backup only')}; const edgeKey=l=>l.aString(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x'; function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={}; - for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=(l.km+60)*MET[l.metric||'normal'].f;(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);} + for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=linkW(l);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);} const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};} function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[]; @@ -1924,7 +1929,7 @@ function compute(){ const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]); const edges={},TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={}; for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.ae.w,wLat=e=>e.lat+0.05; @@ -2202,7 +2207,7 @@ function sanitize(s){ 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'; const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); - s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);if(l.metric&&!own(MET,l.metric))l.metric='normal';return l;}); + s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);if(l.metric==='custom'){if(l.mk!=='w')l.mk='f';l.mv=clampM(l.mk,num(l.mv,l.mk==='w'?l.km+60:1));}else{if(l.metric&&!own(MET,l.metric))l.metric='normal';delete l.mk;delete l.mv;}return l;}); const degO=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null; s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.lacp=degO(t.lacp),t.site=['a','b','ab'].includes(t.site)?t.site:'a',t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t.clean=!!t.clean,t)); s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=lag(x.n),x.sacrif=!!x.sacrif,x)); @@ -3039,7 +3044,13 @@ const ACT={ upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='vxc'||!VXC[t]||t<=l.vt)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>NNI[pt.tier].g){toast(tr('Fabric port in {city} is full.',{city:CITY[c].name}),'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();}, cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();}, setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();}, - setMetric:({id,v})=>{if(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();}, + setMetric:({id,v})=>{if(v!=='custom'&&!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return; + // Switching to custom starts from the current preset's factor, so nothing moves until the player edits it. + for(const x of pairLinks(l.a,l.b)){if(v==='custom'){if(x.metric!=='custom'){x.mk='f';x.mv=MET[x.metric||'normal'].f;}}else{delete x.mk;delete x.mv;}x.metric=v;}sfx('click');after();}, + metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l||l.metric!=='custom')return; + for(const x of pairLinks(l.a,l.b))if(x.metric==='custom'&&x.mk!==k){const w=linkW(x);x.mk=k;x.mv=clampM(k,k==='w'?w:w/(x.km+60));}sfx('click');after();}, + metricSet:({id})=>{const l=S.links.find(x=>x.id===id),t=$('metIn');if(!l||l.metric!=='custom'||!t)return;const v=parseFloat(String(t.value).replace(',','.'));if(!Number.isFinite(v)){sfx('err');return;} + t.blur();for(const x of pairLinks(l.a,l.b))if(x.metric==='custom'){x.mk=l.mk;x.mv=clampM(l.mk,v);}sfx('click');after();}, goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();}, custGo:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b)return;$('dash').hidden=true;ACT.focusCity({city:b.city});UI.tab='cust';renderPanel();}, listMore:({k})=>{if(k!=='conn'&&k!=='cust')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;renderDash();}, @@ -3373,6 +3384,8 @@ function renderPanel(){checkLayer(); const P=$('panel'); if(!S||!UI.sel){P.hidden=true;return;} P.hidden=false; + // Don't wipe a half-typed custom metric on the daily re-render. + const fe=document.activeElement;if(fe&&fe.id==='metIn'&&UI.sel.type!=='city'&&fe.dataset.id===UI.sel.id)return; const scrollEl=$('panelBody').querySelector('.scroll');const st=scrollEl?scrollEl.scrollTop:0; const html=UI.sel.type==='city'?cityPanel(UI.sel.id):linkPanel(UI.sel.id);if(html===UI._ph&&!P.hidden&&$('panelBody').firstChild)return;UI._ph=html;morph($('panelBody'),html); const ns=$('panelBody').querySelector('.scroll');if(ns)ns.scrollTop=st; @@ -3563,8 +3576,15 @@ function trafficSection(l){ if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`

${tr("Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.",{egress:esc(d.lab),city:CITY[d.city].name})}

`;} return h+`
`; } -function metricSection(l){const cur=l.metric||'normal'; - return `

${tr('Routing metric')}

${tr('Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},cur===k?'pink sm':'ghost sm')).join('')}
`;} +function metricSection(l){const cur=l.metric||'normal',base=l.km+60,sel=k=>cur===k?'pink sm':'ghost sm'; + let h=`

${tr('Routing metric')}

${tr('Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},sel(k))).join('')}${btn(tr('Custom'),'setMetric',{id:l.id,v:'custom'},sel('custom'))}
`; + if(cur==='custom'){const k=l.mk,[lo,hi]=MET_LIM[k],md=m=>k===m?'pink sm':'ghost sm'; + const pre=Object.keys(MET).map(m=>`${MET[m].l} ×${MET[m].f} = ${Math.round(base*MET[m].f)}`).join(', '); + h+=`

${tr('A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.')} ${tr('Presets on this link: {list}.',{list:pre})}

+
${btn(tr('Multiplier'),'metricMode',{id:l.id,k:'f'},md('f'))}${btn(tr('Cost'),'metricMode',{id:l.id,k:'w'},md('w'))}
+
${btn(tr('Set'),'metricSet',{id:l.id},'pink sm')}
+

${k==='w'?tr('Cost: the exact number, whatever the distance.'):tr('Multiplier: scales the distance cost, so a longer link still costs more.')} ${tr('Cost on this link: {w}. Allowed: {lo} to {hi}.',{w:Math.round(linkW(l)),lo:k==='w'?lo:'×'+lo,hi:k==='w'?hi:'×'+hi})}

`;} + return h+'
';} function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2; let h=`

${tr('Behind the Great Firewall')}

${tr('Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.',{list:CN_BLOCKED.slice(0,4).map(esc).join(', '),pct:pct(loss)})}

`; if(st==='none')h+=`

${tr('Foreign networks need a local joint venture and an operating license to build infrastructure here.')}

${btn(tr('Apply for a license {price} + {mo}/mo · ~45 days',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO)}),'applyCn',{},'pink',S.cash{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false}); -addEventListener('keydown',e=>{if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}}); +addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}}); /* ---------- click delegation ---------- */ let pressing=false; diff --git a/tests/game.test.js b/tests/game.test.js index 6bbdadc..1502f83 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -405,3 +405,105 @@ test('#117 several scrubbing centers: nearest first, spill to the next, and far assert.equal(ev("S.scrubs.some(x=>x.city==='lon')"), false); assert.deepEqual(errors, []); }); + +// Custom routing metrics: a fra–ams–par triangle where the direct fra–par link is normally shortest. +const triangle = (ev) => { + ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + ev("for(const c of ['ams','par'])ACT.buildPop({city:c});const L=(a,b)=>{UI.via=null;openLinkModal(a,b);ACT.buildLink({tier:1});closeModal();};L('fra','ams');L('ams','par');L('fra','par');compute()"); + ev("window.FP=S.links.find(l=>(l.a==='fra'&&l.b==='par')||(l.a==='par'&&l.b==='fra')).id;window.hops=()=>JSON.stringify(trPaths('fra').path('par').map(h=>h.l.id))"); +}; + +test('a custom multiplier routes exactly like the matching preset', () => { + const { ev, errors } = load(); + triangle(ev); + assert.equal(ev("hops()"), JSON.stringify([ev("FP")]), 'direct link wins by default'); + ev("ACT.setMetric({id:FP,v:'avoid'})"); + const avoid = ev("JSON.stringify({h:hops(),load:R.load,served:R.served})"); + ev("ACT.setMetric({id:FP,v:'custom'})"); + const l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.metric, 'custom'); + assert.equal(l.mk, 'f'); + assert.equal(l.mv, 4, 'custom starts from the preset it replaces'); + assert.equal(ev("JSON.stringify({h:hops(),load:R.load,served:R.served})"), avoid); + ev("ACT.setMetric({id:FP,v:'normal'})"); + assert.equal(ev("'mk' in S.links.find(l=>l.id===FP)||'mv' in S.links.find(l=>l.id===FP)"), false, 'presets drop the custom fields'); + assert.deepEqual(errors, []); +}); + +test('an absolute custom cost steers the path, and switching modes keeps the cost', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'})"); + const l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.mk, 'w'); + assert.equal(l.mv, Math.round(l.km + 60), 'switching to cost keeps the effective metric'); + ev("ACT.selLink({id:FP});renderAll();$('metIn').value='65535';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 65535); + assert.ok(!JSON.parse(ev("hops()")).includes(ev("FP")), 'a huge cost sends traffic round via Amsterdam'); + ev("renderAll();$('metIn').value='1';ACT.metricSet({id:FP})"); + assert.equal(ev("hops()"), JSON.stringify([ev("FP")])); + ev("ACT.metricMode({id:FP,k:'f'})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 0.1, 'converted back to a multiplier, clamped to the minimum'); + assert.deepEqual(errors, []); +}); + +test('custom metric input is validated and clamped', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.selLink({id:FP});renderAll()"); + ev("$('metIn').value='';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 1, 'empty input changes nothing'); + ev("renderAll();$('metIn').value='9999';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 100); + ev("renderAll();$('metIn').value='0';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 0.1); + ev("ACT.metricMode({id:FP,k:'x'});ACT.setMetric({id:FP,v:'bogus'})"); + assert.equal(ev("S.links.find(l=>l.id===FP).metric"), 'custom'); + assert.deepEqual(errors, []); +}); + +test('custom metrics survive a save, and broken ones are repaired', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'});S.links.find(l=>l.id===FP).mv=777;S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + let l = ev("S.links.find(l=>l.id===FP)"); + assert.deepEqual([l.metric, l.mk, l.mv], ['custom', 'w', 777]); + ev("Object.assign(S.links.find(l=>l.id===FP),{mk:'zz',mv:'lots'});S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + l = ev("S.links.find(l=>l.id===FP)"); + assert.deepEqual([l.metric, l.mk, l.mv], ['custom', 'f', 1]); + ev("Object.assign(S.links.find(l=>l.id===FP),{metric:'custom',mk:'w',mv:1e9});S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 65535); + // An old save: preset metric, no custom fields at all. + ev("const x=S.links.find(l=>l.id===FP);x.metric='avoid';delete x.mk;delete x.mv;S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.metric, 'avoid'); + assert.ok(!('mk' in l) && !('mv' in l)); + assert.equal(JSON.parse(ev("hops()")).length, 2, 'the old save still routes, avoiding the direct link'); + assert.deepEqual(errors, []); +}); + +test('preset buttons stay plain, and Custom explains the numbers, also on phones', () => { + const { ev, dom, errors } = load(); + triangle(ev); + for (const w of [1280, 390]) { + ev(`window.innerWidth=${w};ACT.setMetric({id:FP,v:'normal'});ACT.selLink({id:FP});renderAll()`); + const doc = dom.window.document; + const btns = [...doc.querySelectorAll('#panel [data-act="setMetric"]')]; + assert.equal(btns.length, 5); + const km = ev("S.links.find(l=>l.id===FP).km"); + assert.deepEqual(btns.map(b => b.textContent), ['Prefer', 'Normal', 'Avoid', 'Backup only', 'Custom']); + assert.equal(doc.getElementById('metIn'), null); + assert.doesNotMatch(doc.getElementById('panel').textContent, /times a multiplier/); + ev("ACT.setMetric({id:FP,v:'custom'})"); + assert.ok(doc.getElementById('metIn'), `custom editor at ${w}px`); + assert.ok(doc.querySelector('#panel [data-act="metricMode"]')); + const txt = doc.getElementById('panel').textContent; + assert.match(txt, /times a multiplier/); + assert.match(txt, new RegExp(`Normal ×1 = ${Math.round(km + 60)}, Avoid ×4 = ${Math.round((km + 60) * 4)}`)); + assert.match(txt, /Multiplier: scales the distance cost/); + assert.match(txt, /Cost on this link/); + ev("ACT.metricMode({id:FP,k:'w'})"); + assert.match(doc.getElementById('panel').textContent, /Cost: the exact number/); + } + assert.deepEqual(errors, []); +}); From 744b769000792679b7bdf145e5d302b16dfc70c1 Mon Sep 17 00:00:00 2001 From: Filip Hruska Date: Tue, 27 Oct 2026 10:13:07 +0000 Subject: [PATCH 05/64] Rework DDoS generation, mitigation accounting and NOC reporting Scale normal attacks with network demand, level and gaming exposure, with randomized sizes, durations, overlapping attacks and distributed ingress. Set average sizes to three times the non-gaming baseline at one gaming customer and eight times at fifty. Keep Flood Season escalating after its challenge ends. Add gaming-specific vectors, Memcached amplification and ACK floods. Account for upstream scrubbing, Flowspec and shared scrubbing capacity in sequence. Show precise mitigation totals and one destination-based scrubbing detour in existing live attack cards. Keep each source-to-scrubbing route distinct in link traffic breakdowns, including the source label, Open button and map highlight. Include deterministic tests, old-save migration and translations. --- CHANGELOG.md | 28 ++ site/i18n/fr.js | 29 +- site/i18n/it.js | 29 +- site/i18n/pt.js | 29 +- site/index.html | 265 ++++++++----- tests/game.test.js | 520 ++++++++++++++++++++++++++ tests/helpers/reference-allocation.js | 4 +- tests/modes.test.js | 26 +- tests/routing-reference.test.js | 1 + tests/services.test.js | 24 ++ 10 files changed, 823 insertions(+), 132 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5d320..df9f47c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,34 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels, Open buttons or map highlights. + +- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. Local scrubbing adds no backbone-haul line, and distributed ingress no longer produces unrelated or repeated latency messages. + +- The NOC no longer shows the generic attack-rate note for networks without gaming customers. + +- Gaming customers now scale normal-mode DDoS sizes from three times the no-gaming average with one customer to eight times with 50. Adding more gamers continues to increase attack sizes, while frequency still rises gradually toward seven attacks per week. Flood Season keeps its existing escalation. + +- Normal-mode DDoS attacks now vary much more in size, with a 2% chance of a much larger flood. The long-run average still scales with demand, customer level and gaming customers; Flood Season keeps its existing size distribution and escalation. + +- Game server and cloud gaming customers now carry a “Gaming attracts attacks” note on their offers and customer lists, so you can see the DDoS risk before signing them. + +- Live attacks now show how much traffic Flowspec actually drops at the ingress routers. Routers without TCAM no longer claim to filter attacks, mixed router capabilities are called out, and Flowspec drops are counted separately from other edge filters. + +- Normal networks without gaming customers now average half a DDoS attack per week, with attacks ten times smaller than the ordinary baseline. Gaming customers gradually raise attack sizes and the expected rate toward seven attacks per week as your level and customer count grow. The size calculation accounts for the smaller RackNet and TeamSpooked floods so signing a gamer increases the overall average size. Flood Season keeps its separate escalation. + +- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec, and their size stays within one third of the ordinary attack range at your current scale. + +- Gaming customers bring larger, longer and more frequent DDoS attacks as your level and customer count grow, with overlapping floods, at most 14 starts in any seven days and durations up to seven days. Attacks arrive across transit and peering ports in different regions, following normal traffic shares. Attack bandwidth grows with the whole network, with no fixed bandwidth ceiling. + +- Flood Season keeps sending larger, more frequent attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off. + +- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through in its existing status lines. Bandwidth uses the usual Gbps and Tbps units, with no duplicate summary. “After upstream scrubbing” appears only while upstream scrubbing is active. Scrubbing lines show the city, current use and compact capacity, such as “Scrubbing in Frankfurt: 30.2 Gbps / 100G”. + +- DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center. + +- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter needs other defences. + - Pick a peering policy in the peering inbox: Open to all, Selective or Closed. Open accepts every request and keeps the route servers; Selective gets fewer requests but you answer them yourself and request peers at each exchange, without route servers; Closed gets no requests, and customers hear you are hard to reach. The inbox also gets a button to raise all max-prefix limits at once. - Brazil is slimmer: 15 small cities that sat right next to bigger ones are gone from new games, leaving 25 in Brazil. A small city no longer crowds a bigger one in the same country unless it is a cable landing or a capital. Saved games keep their POPs in those cities, and the Order and Progress scenario now asks for 15 IX.brrr ports instead of 20. ## [1.33.0] — 2026-10-27 diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c06021c..7fcfb8f 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -923,10 +923,7 @@ "Live attack: {city}":"Attaque en cours : {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · {n} j restants", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"Blackholé : les déchets ont disparu, et {city} aussi. L’attaque a obtenu ce qu’elle voulait.", -"Reaching your network: {g}":"Ce qui atteint ton réseau : {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing à la demande en cours de redirection, actif dans {n} j", -"{tier} scrubbing in {city} is cleaning it":"Le scrubbing {tier} à {city} le nettoie", -"{net} is scrubbing it upstream (clean-pipe)":"{net} le nettoie en amont (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contenu sur ton PNI sacrificiel {net}", "IX blackhole on ✓":"Blackhole IX actif ✓", "IX blackhole ~half honour it":"Blackhole IX ~la moitié le respecte", @@ -935,10 +932,7 @@ "Sacrificial choke ✓":"Goulot sacrificiel ✓", "Make sacrificial contains floods · ½ capacity":"Rendre sacrificiel contient les floods · ½ capacité", "No scrubbing center":"Pas de centre de scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"Flowspec sur ton {model} élimine le trafic {vec} en bordure", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"Flowspec sur ton {model} rogne le trafic {vec}, mais sa TCAM est petite", -"Your {model} here has no Flowspec TCAM":"Ton {model} ici n’a pas de TCAM Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec ne peut pas arrêter un {vec} (couche applicative)", +"Flowspec cannot catch {vec}":"Flowspec ne peut pas arrêter {vec}", "Stop blackholing":"Arrêter le blackholing", "Blackhole the target (RTBH)":"Blackholer la cible (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2604,8 +2598,6 @@ "Attack hauled to scrubbing in {city}":"Attaque acheminée vers le scrubbing de {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Veut un centre de scrubbing sur son continent, pour que les attaques ne traversent pas un océan", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Ton backbone ne peut en acheminer que {g} jusqu’à {city} : le reste n’est pas nettoyé", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"Le scrubbing {tier} à {city} le nettoie, acheminé par ton backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"Tes centres de scrubbing sont pleins : {g} passent quand même", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Les attaques vont vers ton centre de scrubbing le plus proche. D’ici, c’est {city}, à {km} km : le flot traverse ton backbone aller et retour, ce qui ajoute de la latence, et ce que tes liens ne peuvent pas porter n’est pas nettoyé. Un centre ici nettoie les attaques sur place.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"les attaques sur {city} sont acheminées vers {to} pour le scrubbing : +{ms} ms", "Scrubbing centers":"Centres de scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"{n} limites max-prefix relevées.
{k} d’entre elles étaient des fuites de routes. Elles sont dans le NOC maintenant.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"{n} limites max-prefix relevées.
Que de la croissance, aucune fuite. Chanceux.", "Off while your peering policy is {pol}":"Désactivé tant que votre politique de peering est {pol}", +"Memcached amplification":"Amplification Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtres en bordure : {g} supprimés", +"{g} is leaking through":"{g} passent encore", +"Attack fully mitigated":"Attaque entièrement neutralisée", +"Scrubbing centers unavailable or at capacity":"Centres de scrubbing indisponibles ou saturés", +"Distributed ingress":"Arrivée distribuée", +", across {n} transit and peering ports":", via {n} ports de transit et de peering", +"No scrubbing needed after edge mitigation":"Aucun scrubbing nécessaire après la protection en bordure", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing à {city} : {used} / {capacity}", +"This attack: {g}":"Cette attaque : {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Trafic de scrubbing acheminé par ton backbone : {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Après le scrubbing en amont : {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Aucun filtrage Flowspec : les routeurs d’entrée n’ont pas de TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec supprime {g} ; certains routeurs d’entrée n’ont pas de TCAM", +"Flowspec dropping: {g}":"Flowspec supprime {g}", +"Gaming attracts attacks":"Le gaming attire les attaques", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index be339b0..ef9450b 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -924,10 +924,7 @@ "Live attack: {city}":"Attacco in corso: {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · {n}g rimasti", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"In buco nero: la spazzatura è sparita, e anche {city}. L’attacco ha ottenuto ciò che voleva.", -"Reaching your network: {g}":"Arriva alla tua rete: {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing on-demand in deviazione, attivo tra {n}g", -"{tier} scrubbing in {city} is cleaning it":"Lo scrubbing {tier} a {city} lo sta pulendo", -"{net} is scrubbing it upstream (clean-pipe)":"{net} lo sta ripulendo a monte (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contenuto sulla tua PNI sacrificale {net}", "IX blackhole on ✓":"Blackhole IX attivo ✓", "IX blackhole ~half honour it":"Blackhole IX ~metà lo rispetta", @@ -936,10 +933,7 @@ "Sacrificial choke ✓":"Strozzatura sacrificale ✓", "Make sacrificial contains floods · ½ capacity":"Rendi sacrificale contiene i flood · ½ capacità", "No scrubbing center":"Nessun centro di scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"Il Flowspec sul tuo {model} sta scartando {vec} all’edge", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"Il Flowspec sul tuo {model} lima {vec}, ma la sua TCAM è piccola", -"Your {model} here has no Flowspec TCAM":"Il tuo {model} qui non ha TCAM per il Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec non può fermare un {vec} (livello applicativo)", +"Flowspec cannot catch {vec}":"Flowspec non può fermare {vec}", "Stop blackholing":"Togli il buco nero", "Blackhole the target (RTBH)":"Metti il bersaglio in buco nero (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2607,8 +2601,6 @@ "Attack hauled to scrubbing in {city}":"Attacco portato allo scrubbing di {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Vuole un centro di scrubbing nel suo continente, così gli attacchi non attraversano un oceano", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Il tuo backbone riesce a portarne solo {g} a {city}: il resto non viene pulito", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"Lo scrubbing {tier} a {city} lo sta pulendo, portato lì sul tuo backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"I tuoi centri di scrubbing sono pieni: {g} passano lo stesso", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Gli attacchi vanno al tuo centro di scrubbing più vicino. Da qui è {city}, a {km} km: il flusso viaggia sul tuo backbone fin lì e ritorno, il che aggiunge latenza, e quello che i tuoi link non riescono a portare non viene pulito. Un centro qui pulisce gli attacchi sul posto.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"gli attacchi su {city} vengono portati a {to} per lo scrubbing: +{ms} ms", "Scrubbing centers":"Centri di scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"Alzati {n} limiti max-prefix.
{k} erano route leak. Ora sono nel NOC.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"Alzati {n} limiti max-prefix.
Tutta crescita, nessun leak. Fortuna.", "Off while your peering policy is {pol}":"Spento finché la tua politica di peering è {pol}", +"Memcached amplification":"Amplificazione Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtri al bordo: {g} scartati", +"{g} is leaking through":"{g} superano le difese", +"Attack fully mitigated":"Attacco completamente mitigato", +"Scrubbing centers unavailable or at capacity":"Centri di scrubbing non disponibili o al completo", +"Distributed ingress":"Ingresso distribuito", +", across {n} transit and peering ports":", su {n} porte di transit e peering", +"No scrubbing needed after edge mitigation":"Nessuno scrubbing necessario dopo la mitigazione al bordo", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing a {city}: {used} / {capacity}", +"This attack: {g}":"Questo attacco: {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Traffico di scrubbing trasportato sul tuo backbone: {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Dopo lo scrubbing a monte: {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Nessun filtraggio Flowspec: i router di ingresso non hanno TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec scarta {g}; alcuni router di ingresso non hanno TCAM", +"Flowspec dropping: {g}":"Flowspec scarta {g}", +"Gaming attracts attacks":"Il gaming attira attacchi", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 215579b..9479de2 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -924,10 +924,7 @@ "Live attack: {city}":"Ataque ao vivo: {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · faltam {n}d", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"Em blackhole: o lixo sumiu, e {city} também. O ataque conseguiu o que queria.", -"Reaching your network: {g}":"Chegando na sua rede: {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing on-demand desviando, ativo em {n}d", -"{tier} scrubbing in {city} is cleaning it":"O scrubbing {tier} em {city} está limpando", -"{net} is scrubbing it upstream (clean-pipe)":"{net} está limpando upstream (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contido no seu PNI sacrificial com {net}", "IX blackhole on ✓":"Blackhole IX ativo ✓", "IX blackhole ~half honour it":"Blackhole IX ~metade respeita", @@ -936,10 +933,7 @@ "Sacrificial choke ✓":"Gargalo sacrificial ✓", "Make sacrificial contains floods · ½ capacity":"Tornar sacrificial contém floods · ½ capacidade", "No scrubbing center":"Sem centro de scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"O Flowspec no seu {model} está descartando {vec} na borda", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"O Flowspec no seu {model} reduz {vec}, mas a TCAM é pequena", -"Your {model} here has no Flowspec TCAM":"Seu {model} aqui não tem TCAM para Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec não pega um {vec} (camada de aplicação)", +"Flowspec cannot catch {vec}":"Flowspec não consegue filtrar {vec}", "Stop blackholing":"Parar blackhole", "Blackhole the target (RTBH)":"Blackhole no alvo (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2607,8 +2601,6 @@ "Attack hauled to scrubbing in {city}":"Ataque levado ao scrubbing em {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Quer um centro de scrubbing no próprio continente, para que os ataques não atravessem um oceano", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Seu backbone só consegue levar {g} até {city}: o resto não é limpo", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"O scrubbing {tier} em {city} está limpando, levado pelo seu backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"Seus centros de scrubbing estão cheios: {g} passam direto", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Os ataques vão para o seu centro de scrubbing mais próximo. Daqui é {city}, a {km} km: a enxurrada viaja pelo seu backbone até lá e volta, o que aumenta a latência, e o que seus links não conseguem levar não é limpo. Um centro aqui limpa os ataques na hora.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"os ataques em {city} são levados a {to} para scrubbing: +{ms} ms", "Scrubbing centers":"Centros de scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"{n} limites de max-prefix aumentados.
{k} deles eram vazamentos de rotas. Estão no NOC agora.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"{n} limites de max-prefix aumentados.
Tudo crescimento, nenhum vazamento. Sorte.", "Off while your peering policy is {pol}":"Desligado enquanto sua política de peering for {pol}", +"Memcached amplification":"Amplificação Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtros de borda descartando: {g}", +"{g} is leaking through":"{g} estão passando", +"Attack fully mitigated":"Ataque totalmente mitigado", +"Scrubbing centers unavailable or at capacity":"Centros de scrubbing indisponíveis ou lotados", +"Distributed ingress":"Entrada distribuída", +", across {n} transit and peering ports":", por {n} portas de transit e peering", +"No scrubbing needed after edge mitigation":"Scrubbing desnecessário após a mitigação na borda", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing em {city}: {used} / {capacity}", +"This attack: {g}":"Este ataque: {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Tráfego de scrubbing levado pelo seu backbone: {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Após o scrubbing upstream: {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Sem filtragem Flowspec: os roteadores de entrada não têm TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec descarta {g}; alguns roteadores de entrada não têm TCAM", +"Flowspec dropping: {g}":"Flowspec descarta {g}", +"Gaming attracts attacks":"Gaming atrai ataques", }; diff --git a/site/index.html b/site/index.html index c003a61..b9c7a6f 100644 --- a/site/index.html +++ b/site/index.html @@ -637,9 +637,13 @@ const FS_RES=[1,0.4,0.15]; const DDOS_VEC={ dns:{n:tr('DNS reflection'),fs:true}, ntp:{n:tr('NTP amplification'),fs:true}, + memcached:{n:tr('Memcached amplification'),fs:true}, + ack:{n:tr('ACK flood'),fs:false}, cldap:{n:tr('CLDAP flood'),fs:true}, syn:{n:tr('SYN flood'),fs:true}, http:{n:tr('HTTP flood'),fs:false}, + racknet:{n:tr('RackNet'),fs:false,gaming:true}, + teamspooked:{n:tr('TeamSpooked'),fs:false,gaming:true}, }; const MYIX_COST=80000, MYIX_MO=3000, MYIX_FEE=1500, START_CASH=200000; // Your own exchange's switching fabric. Bigger fabrics carry more and attract more members. @@ -1441,7 +1445,7 @@ const initials=n=>n.name.replace(/[^A-Za-z ]/g,'').split(' ').filter(Boolean).ma /* ================= BUSINESSES ================= */ const BIZ_T={ dia:{l:tr('Enterprise DIA'),opts:[1,2,5,10],rate:600}, - game:{l:tr('Game servers'),opts:[5,10,20,40],rate:120}, + game:{l:tr('Game servers'),gaming:true,opts:[5,10,20,40],rate:120}, host:{l:tr('Hosting'),opts:[10,20,40,80],rate:60}, isp:{l:tr('Downstream ISP (buys transit)'),opts:[100,200,400,800],rate:15,lv:2}, l2vpn:{l:tr('L2VPN circuit'),opts:[1,10,40,100],rate:0,l2:true,km:1,lv:1}, @@ -1466,7 +1470,7 @@ const BIZ_T={ pairs:{l:tr('Hundreds of fiber pairs'),opts:[1],rate:0,fiber:true,mega:true,lv:4,names:['A Hyperscaler Who Shall Not Be Named','Planet-Scale AI WAN Team','The Fiber-Hungry Giant','Project Very Long Glass']}, esport:{l:tr('Esports world final'),opts:[400,800,1600,3200],rate:0,event:true,lv:5,names:['League of Lag Finals','Counter-Ping Major','Fortnightly World Cup','Dota Two Many Viewers','Rocket Leak Championship','Street Frighter Evo']}, sov:{l:tr('Sovereign cloud region'),opts:[400,800,1600],rate:0,l2:true,div:true,km:0.6,lv:6,names:['Gaia-Ex Sovereign Cloud','Bundeswolke (Very Secure)','Le Cloud Souverain','Datenschutz Deluxe','Your Data Stays Here, Probably','A Cloud With a Flag on It','Data Residency Is a State of Mind']}, - cgame:{l:tr('Cloud gaming platform'),opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, + cgame:{l:tr('Cloud gaming platform'),gaming:true,opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, metav:{l:tr('Metaverse platform'),opts:[1600,3200,6400],rate:35,lv:9,names:['Meh-taverse','Second Second Life','Horizon Worlds Apart','The Oasis (Ready Player Done)','Legs Finally Shipped Inc.','Decentra-landlocked']}, agi:{l:tr('AGI lab (allegedly)'),opts:[12800,25600],rate:0,l2:true,div:true,mega:true,km:0.4,lv:11,names:['Almost General Intelligence Inc.','Superintelligence Pending','The Lab That Said Two More Years','Paperclip Maximizer Labs','Deep Thought Two','Benevolent Overlord Research']}, mars:{l:tr('Mars mission ground station'),opts:[100,200,400],rate:0,l2:true,lat:true,km:4,lv:13,names:['Red Planet Relay','Ares Ground Segment','Olympus Mons Uplink','Mars or Bust Mission Control','Interplanetary Ping Society','Light-Minute Logistics','RFC 1149 Avian Carriers (Mars Division)']}, @@ -1794,7 +1798,7 @@ function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSO function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, ltv:2,t1v:2,auV:1,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:{}, - done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; + 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',won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; } /* ================= HELPERS ================= */ @@ -2133,7 +2137,7 @@ function teOptimize(){const L=[tr('# Suggested by the optimizer from live traffi return L.join('\n');} // Ready-made RouteScripts, filled in from the live network. Players load them from the help; the AI button picks them too. const teUps=()=>[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S.transit.filter(t=>t.net===n).map(t=>NET[n].price*regionMult(t.city)))})).sort((a,b)=>a.p-b.p); -const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>!!(S.ev.ddos&&S.ev.ddos.until>S.day); +const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>ddosAll().length>0; const teSad=()=>S.biz.some(b=>!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&!BIZ_T[b.type].event&&sfOf(R,b.city)<0.95); const TE_RECIPES=[ {id:'shield',n:N_('Shields Up'),d:N_('For a DDoS: drop the junk at the edge and keep business customers first. It costs a little real traffic, so remove it when the attack is over.'),fit:()=>teAtk()?9:0.3, @@ -2235,18 +2239,18 @@ function compute(){ // ok() cannot change during one compute, so ask each exit once per network, not once per flow and rank. // okBy[net] lists the exits that reach it in E's order, like E.filter(e=>e.ok(net)). const okBy={};for(const id of NET_IDS)okBy[id]=[]; - const ekN={};for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;} + R2.ingressPorts={};const ekN={};for(const e of E){e.ek=e.k+':'+e.id;if(e.k!=='c'){const p=R2.ingressPorts[e.ek]||(R2.ingressPorts[e.ek]={k:e.k,id:e.id,city:e.city,lab:e.lab,cap:0,traffic:0});p.cap+=e.cap;}ekN[e.ek]=(ekN[e.ek]||0)+1;} // dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last. for(const e of E){e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}} for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];if(okBy[n.id].some(e=>e.rank>0&&e.k!=='t')){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id];}} const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net)); const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1); // Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index). - const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j];flows.push({c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j});}; + const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j],f={c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j};flows.push(f);return f;}; // Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give). const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}} // Traffic shares by network index, and their sums, for each share table (and with Russia's throttle). - const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'),HAUL=[];R2.haul=[]; + const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'),scrubRoom={},atkBy={},junkGroups=[],bhCities=new Set(ddosAll().filter(a=>a.bh).map(a=>a.city));R2.haul=[];R2.ddos=[];for(const a of ddosAll())for(const part of ddosSlices(a))(atkBy[part.city]||(atkBy[part.city]=[])).push(part); for(const c of Object.keys(S.pops)){ const p=S.pops[c],ci=CIDX[c],cn=cnCity(c),SH=cn?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cn&&ev.golden>day?1.4:1);const biz=bizBw[c]??0;const d0=eye+biz; // Goggle video is throttled in Russia (#70): people there get half of it, so they ask for half. It is not @@ -2255,26 +2259,18 @@ function compute(){ const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?sa[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf; R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d; for(let j=0;jday?ev.ddos:null; - const rtbh=!!(atk&&atk.bh), edge=!!(atk&&TRX&&TRX.blackhole&&!rtbh); + const attacks=atkBy[c]||[],rtbh=bhCities.has(c),edge=!!(attacks.length&&TRX&&TRX.blackhole&&!rtbh); let dd=0; - if(atk&&!rtbh){let mult=1;const en=atk.entry||{}; - if(DDOS_VEC[atk.vec]&&DDOS_VEC[atk.vec].fs){const cap=fsAt(atk.city);if(cap)mult=Math.min(mult,FS_RES[cap]);} - if(en.k==='t'){const t=S.transit.find(x=>x.id===en.id);if(t&&t.clean)mult=Math.min(mult,0.1);} - if(atk.ixbh&&hasIxAt(atk.city))mult=Math.min(mult,0.5); - if(edge)mult=0; - // Scrubbing is used when it beats the edge tools; floods for a center in another city are hauled after the circuits below. - const sp=edge?null:scrubPlan(atk); - if(sp&&scrubIdeal(sp)x.id===en.id);if(p&&p.sacrif)dd=Math.min(dd,liveCap(pniG(p),p.city,p.site,p.n)*0.9);}} + for(const atk of attacks){const m=ddosMitigation(atk,{},bhCities.has((atk.parent||atk).city),false);R2.ddos.push(m);dd+=m.leak; + const group={m,flows:[]};junkGroups.push(group); + if(atk.entries?.length){for(const q of m.ingress){const f=flow(c,ci,cn,0,q.g,false,true);f.pin=q.entry.k+':'+q.entry.id;group.flows.push({f,share:m.leak>0?q.g/m.leak:0});}} + else for(let j=0;jm.attack.city===c))m.offline=true;continue;} const bh=rtbh||edge; - if(dd>0)for(let j=0;jn+a.gbps,0)+d*0.1;if(rtbh)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d; R2.cityBlocked=R2.cityBlocked||{}; const mtuH=ev.pmtud&&ev.pmtud.until>day?ev.pmtud:null,kr=CITY[c].kr; for(let j=0;jday&&n.id==='fbk'?0.8:1);if(a<=0)continue; @@ -2337,18 +2333,28 @@ function compute(){ if((b.reqs||[]).includes('diverse')){const k=b.city+'>'+b.city2;R2.div[b.id]=divMemo[k]??(divMemo[k]=disjointI(b.city,b.city2));}} /* A flood for a scrubbing center elsewhere rides the backbone there, with the victim's own traffic (#117). What the links cannot carry is not scrubbed and lands on the city after all. */ - for(const H of HAUL){const A=H.c,B=H.to,Ai=CIDX[A],Bi=CIDX[B];let h=0,ms=null; - if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][Bi]0?H.a*take/want:0;ms=path.reduce((x,e)=>x+e.lat,0)*2; - const ek='scrub:'+B;R2.egDesc[ek]={lab:labOf(N_('Attack hauled to scrubbing in {city}'),'city',CITY[B].name),city:A,k:'l2'}; - for(const i of ni)if(HAS[i])nodeTake(i,take);for(const l of path){l.res-=take;l.ld+=take;carry(l,ek,NN,Ai,take);}} - R2.haul.push({city:A,to:B,tier:H.tier,a:H.a,h,ms});const left=(H.a-h)*0.85;if(left>1e-6)for(let j=0;j0?scrubPlan(atk,m.leak,scrubRoom,(x,want)=>{const B=x.city,Bi=CIDX[B];if(A===B)return want;let h=0,ms=null; + if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][Bi]0?want*take/total:0;ms=path.reduce((n,e)=>n+e.lat,0)*2; + // Sources sharing a center need separate labels in link breakdowns and map highlights. + const ek='scrub:'+A+'>'+B;R2.egDesc[ek]={lab:labOf(N_('Attack hauled to scrubbing in {city}'),'city',CITY[B].name),city:A,k:'l2'}; + for(const i of ni)if(HAS[i])nodeTake(i,take);for(const l of path){l.res-=take;l.ld+=take;carry(l,ek,NN,Ai,take);}} + R2.haul.push({city:A,to:B,tier:x.tier||0,a:want,h,ms,attack:atk.id});return h;}):null; + if(m.sp){m.leak=m.sp.leak; + // The card describes the victim's nearest center, separately from distributed ingress hauling above. + const c=(atk.parent||atk).city;let near=scrubNear.get(c);if(near===undefined){near=null; + for(const x of S.scrubs)if(popUp(x.city)&&SPD[c]&&SPD[c][CIDX[x.city]]n+e.lat,0);if(!near||ms{const key=src*NC+dst,c0=teCache.get(key); if(c0===false)return null;if(c0&&c0.path.every(l=>l.res>1e-3)&&c0.ni.every(i=>!HAS[i]||NRES[i]>1e-3))return c0; const {D,P}=dijkstra(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3),dst); if(D[dst]===Infinity||D[dst]>2*base+60){teCache.set(key,false);return null;} const Q=walkI(P,src,dst);teCache.set(key,Q);return Q;}; + const ingressE={};for(const e of E)(ingressE[e.ek]||(ingressE[e.ek]=[])).push(e); const base=e=>e.pref==='low'?4:e.rank; // LOCAL_PREF on an upstream moves it ahead of or behind the other transits, never ahead of peering (#96). const eff=(e,n)=>{let r=base(e);if(TR){if(e.k==='t'&&TR.up[e.net])r=TR.up[e.net]==='prefer'?2.9:3.5;if(e.prep)r=4.4;if(e.k!=='c'&&TR.drain.has(e.city))r=4.6;const o=TR.net[n];if(o){if(o.prefer===e.k)r=0.5;else if(o.avoid===e.k)r=4.5;}}return r;}; @@ -2374,7 +2380,7 @@ function compute(){ const ek=e.ek,nr=f.nr,ci=f.ci;if(!e.told||e.dup){R2.egDesc[ek]=e.desc;e.told=true;} for(const l of path){l.res-=amt;l.ld+=amt;carry(l,ek,nr,ci,amt);} e.used+=amt;f.rem-=amt; - if(!f.junk){let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn; + if(!f.junk){if(e.k!=='c')R2.ingressPorts[ek].traffic+=amt;let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn; if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);} SRV[f.ci]+=ok;R2.served+=ok;if(f.bz)R2.bizSrv[f.c]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok; // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then @@ -2406,8 +2412,9 @@ function compute(){ // Index loops in here: plain for…of allocates an iterator per loop until V8 has optimised compute(). for(let fi=0,FN=flows.length;fix&&typeof x==='object'&&isCity(x.city)&&s.pops[x.city]&&!seen.has(x.city)&&seen.add(x.city)).map(x=>({city:x.city,tier:int(x.tier,0,SCRUB_TIERS.length-1,0)}));} s.scrubMode=s.scrubMode==='ondemand'?'ondemand':'always'; - if(s.ev&&s.ev.ddos){const a=s.ev.ddos; - if(!a||typeof a!=='object'||!isCity(a.city)||!own(DDOS_VEC,a.vec))delete s.ev.ddos; - else{a.gbps=num(a.gbps,2);a.until=num(a.until,s.day);a.bh=!!a.bh;a.ixbh=!!a.ixbh;a.start=num(a.start,s.day); - if(!a.entry||typeof a.entry!=='object')a.entry={k:'edge',lab:''};else{a.entry.lab=String(a.entry.lab||'').slice(0,60);a.entry.id=a.entry.id==null?undefined:String(a.entry.id).slice(0,40);}}} + // Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it. + const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!s.pops[a.city]||!own(DDOS_VEC,a.vec))return null; + a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.ixbh=!!a.ixbh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+7); + if(Array.isArray(a.entries)){a.entries=a.entries.filter(en=>en&&['t','ix','p'].includes(en.k)&&isCity(en.city)&&typeof en.id==='string'&&Number.isFinite(+en.share)&&+en.share>0).slice(0,3000).map(en=>({k:en.k,id:en.id.slice(0,40),city:en.city,lab:String(en.lab||'').slice(0,60),share:+en.share}));const sum=a.entries.reduce((n,en)=>n+en.share,0);if(Number.isFinite(sum)&&sum>0)for(const en of a.entries)en.share/=sum;else delete a.entries;}else delete a.entries; + a.sla=Array.isArray(a.sla)?a.sla.filter(x=>typeof x==='string').slice(0,s.biz.length):[]; + if(!a.entry||typeof a.entry!=='object')a.entry={k:'edge',lab:''};else{a.entry.lab=String(a.entry.lab||'').slice(0,60);a.entry.id=a.entry.id==null?undefined:String(a.entry.id).slice(0,40);}return a;}; + const attacks=[s.ev.ddos,...(Array.isArray(s.ev.ddosMore)?s.ev.ddosMore:[])].map(repairAttack).filter(Boolean).slice(0,14); + if(attacks.length)s.ev.ddos=attacks[0];else delete s.ev.ddos;s.ev.ddosMore=attacks.slice(1); + s.ddosStarts=(Array.isArray(s.ddosStarts)?s.ddosStarts:attacks.map(a=>a.start)).filter(d=>typeof d==='number'||typeof d==='string').map(Number).filter(d=>Number.isFinite(d)&&d>s.day-7&&d<=s.day).sort((a,b)=>a-b).slice(-14); s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews; if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} return s;} @@ -2623,6 +2635,7 @@ function bizSfOf(r,c){const d=r.bizDem&&r.bizDem[c];return teRules()&&teRules(). function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);} function bHas(o){return bCities(o).every(c=>S.pops[c]);} function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day⚠️ ${tr('Gaming attracts attacks')}`:'';} function bTerms(o){const T=BIZ_T[o.type]; if(T.event){const live=S.day>=o.start;return tr('{bw} extra for {d} days, {when} · pays {fee} when it is over',{bw:fmtG(o.bw),d:o.dur,when:live?tr('day {n} of {d}',{n:S.day-o.start+1,d:o.dur}):tr('starting in {n}d',{n:o.start-S.day}),fee:fmt$(o.fee)});} if(T.sdwan)return tr('{n} sites: {list} · {bw} per site · {price}/mo',{n:o.sites.length,list:o.sites.map(c=>CITY[c].name).join(', '),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)}); @@ -2753,59 +2766,83 @@ function lagsN(){const o=[];for(const t of S.transit)if((t.n||1)>=2&&!(t.down>S. for(const p of S.pni)if((p.n||1)>=2)o.push({k:'p',id:p.id,o:p,n:p.n,lab:tr('PNI LAG with {name} in {city}',{name:NET[p.net].name,city:CITY[p.city].name})}); for(const x in S.ixp){const n=(S.ixn||{})[x]||1;if(n>=2&&!S.myIx[x])o.push({k:'ix',id:x,n,lab:ixNamesCity(x)?tr('{ix} LAG',{ix:ixName(x)}):tr('{ix} LAG in {city}',{ix:ixName(x),city:CITY[ixCity(x)].name})});}return o;} // Where the junk comes in: one of the city's live uplinks, or just "the edge" if it has none yet. +// The primary slot remains compatible with older saves; every system uses the full live set. +function ddosAll(s=S,live=true){return [s.ev.ddos,...(s.ev.ddosMore||[])].filter(a=>a&&(!live||a.until>s.day));} +const ddosFind=id=>ddosAll().find(a=>id===undefined||a.id===id); +function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);S.ev.ddos=left[0]||null;S.ev.ddosMore=left.slice(1);} +function ddosExpire(){for(const a of ddosAll(S,false))if(a.until<=S.day||!S.pops[a.city]){ddosDone(a);ddosDrop(a);}} +function ddosEntries(){const ports=Object.values(R.ingressPorts||{}).filter(p=>p.cap>0),busy=ports.some(p=>p.traffic>1e-6),weight=p=>busy?p.traffic:p.cap,total=ports.reduce((n,p)=>n+weight(p),0); + return total>0?ports.filter(p=>weight(p)>0).map(p=>({k:p.k,id:p.id,city:p.city,lab:p.lab,share:weight(p)/total})):[];} +function ddosSlices(a){if(!a.entries?.length)return [a];const groups={}; + for(const en of a.entries){const c=S.pops[en.city]?en.city:a.city;(groups[c]||(groups[c]=[])).push(en);} + return Object.entries(groups).map(([city,entries])=>({...a,parent:a,city,entries,gbps:a.gbps*entries.reduce((n,en)=>n+en.share,0)}));} +const ddosCities=a=>[...new Set([a.city,...(a.entries||[]).map(en=>en.city)])].filter(c=>S.pops[c]); +const ddosHasIx=a=>ddosCities(a).some(hasIxAt); +const ddosSf=a=>Math.min(1,...ddosCities(a).map(c=>sfOf(R,c))); +function ddosReport(a){const ms=(R.ddos||[]).filter(m=>m.attack===a||m.attack.parent===a);if(!ms.length)return ddosMitigation(a); + const parts={};for(const m of ms)for(const x of m.sp?.parts||[]){const q=parts[x.city]||(parts[x.city]={city:x.city,tier:x.tier,a:0,cleaned:0});q.a+=x.a;q.cleaned+=x.cleaned;} + return {attack:a,blackhole:ms.some(m=>m.blackhole),upstream:ms.some(m=>m.upstream),reaching:ms.reduce((n,m)=>n+m.reaching,0),flowspec:ms.reduce((n,m)=>n+m.flowspec,0),fsMissing:ms.some(m=>m.fsMissing),filtered:ms.reduce((n,m)=>n+m.filtered,0),sp:Object.keys(parts).length?{parts:Object.values(parts)}:null,near:ms.find(m=>m.near)?.near||null,leak:ms.reduce((n,m)=>n+m.leak,0)};} function ddosEntry(c){const o=[]; for(const t of S.transit)if(t.city===c&&!(t.down>S.day))o.push({k:'t',id:t.id,lab:tr('{net} transit',{net:NET[t.net].name})}); for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined)o.push({k:'ix',id:x,lab:tr('{ix} peering',{ix:ixName(x)})}); for(const p of S.pni)if(p.city===c)o.push({k:'p',id:p.id,lab:tr('PNI with {net}',{net:NET[p.net].name})}); return o.length?pick(o):{k:'edge',lab:''};} -// Flowspec capability of the router in a city: 0 none, 1 basic, 2 full. The flood is filtered where the -// victim POP's own router has the TCAM for it. +// Flowspec capability at each ingress POP: 0 none, 1 basic, 2 full. const fsAt=c=>{const p=S.pops[c];return p?(RG[p.rgen||0].fs||0):0;}; -// Scrubbing residual for an attack: clean up to the center's capacity (to 15%), overflow leaks. On-demand +// Scrubbing removes attack traffic up to the center's capacity; overflow leaks. On-demand // does nothing for the first couple of days while traffic is being diverted. -function scrubEngaged(atk){return hasScrub()&&(S.scrubMode==='always'||(S.day-(atk.start||S.day))>=SCRUB_DELAY);} +function scrubEngaged(atk){return hasScrub()&&(S.scrubMode==='always'||(S.day-(atk.start??S.day))>=SCRUB_DELAY);} // Several centers (#117): the flood goes to the nearest working one, and what it cannot take spills to the next. // A center in another city only helps if the backbone can carry the flood there; routing works that out. -const scrubFar=c=>{const a=S.ev&&S.ev.ddos;return a&&a.until>S.day&&a.city===c&&(R.haul||[]).find(q=>q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS)||null;}; -function scrubPlan(atk){if(!scrubEngaged(atk))return null;const c=atk.city;let g=atk.gbps||0;const parts=[]; - for(const x of S.scrubs.filter(x=>popUp(x.city)&&(x.city===c||pathExists(c,x.city))).sort((a,b)=>(a.city===c?0:kmBetween(c,a.city))-(b.city===c?0:kmBetween(c,b.city)))){if(g<=0)break;const a=Math.min(g,SCRUB_TIERS[x.tier||0].g);parts.push({city:x.city,tier:x.tier||0,a});g-=a;} +const scrubFar=c=>ddosAll().some(a=>ddosCities(a).includes(c))&&(R.haul||[]).find(q=>q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS)||null; +function scrubPlan(atk,g=atk.gbps||0,room={},take=null){if(!scrubEngaged(atk))return null;const c=atk.city;const parts=[]; + for(const x of S.scrubs.filter(x=>popUp(x.city)&&(x.city===c||pathExists(c,x.city))).sort((a,b)=>(a.city===c?0:kmBetween(c,a.city))-(b.city===c?0:kmBetween(c,b.city)))){if(g<=0)break;const cap=SCRUB_TIERS[x.tier||0].g,a=Math.min(g,room[x.city]??cap);if(a<=0)continue;const cleaned=take?take(x,a):a;room[x.city]=(room[x.city]??cap)-cleaned;parts.push({city:x.city,tier:x.tier||0,a,cleaned});g-=cleaned;} return parts.length?{parts,leak:g}:null;} -// What still lands on the city if every haul gets through: 15% of what is scrubbed, plus whatever no center can take. -const scrubIdeal=p=>p?p.parts.reduce((s,x)=>s+x.a*0.15,0)+p.leak:Infinity; +// One accounting pipeline for routing and the NOC: upstream -> edge -> scrubbing -> leakage. +function ddosMitigation(a,room={},blackhole=a.bh,plan=true){const entries=a.entries?.length?a.entries:[{...(a.entry||{}),share:1}],total=entries.reduce((n,en)=>n+en.share,0),ingress=[]; + let upstream=false,reaching=0,g=0,flowspec=0,fsMissing=false; + for(const en of entries){const t=en.k==='t'?S.transit.find(x=>x.id===en.id):null,p=en.k==='p'?S.pni.find(x=>x.id===en.id):null,clean=!!(t&&t.clean); + upstream=upstream||clean;let part=blackhole?0:a.gbps*en.share/total*(clean?0.1:1);reaching+=part; + if(DDOS_VEC[a.vec]?.fs){const cap=fsAt(S.pops[en.city]?en.city:a.city),before=part;part*=FS_RES[cap];flowspec+=before-part;if(cap===0&&before>0)fsMissing=true;} + if(a.ixbh&&hasIxAt(a.city))part*=0.5; + if(p&&p.sacrif)part=Math.min(part,liveCap(pniG(p),p.city,p.site,p.n)*0.9); + if(teRules()?.blackhole&&!blackhole)part=0; + g+=part;ingress.push({entry:en,g:part});} + const filtered=reaching-g,sp=plan&&g>0?scrubPlan(a,g,room):null; + return {attack:a,blackhole,upstream,reaching,flowspec,fsMissing,filtered,ingress,sp,leak:sp?sp.leak:g};} // The NOC's live attack view: what is hitting you, what each tool would do about it right now, and the buttons. -function ddosPanel(){ - const a=S&&S.ev&&S.ev.ddos;if(!a||a.until<=S.day||!S.pops[a.city])return ''; - const V=DDOS_VEC[a.vec]||{n:'?',fs:false},cap=fsAt(a.city),model=RG[(S.pops[a.city].rgen||0)].n,en=a.entry||{}; - const cleanT=en.k==='t'?S.transit.find(x=>x.id===en.id):null, sacP=en.k==='p'?S.pni.find(x=>x.id===en.id):null; - let mult=1; - if(V.fs&&cap)mult=Math.min(mult,FS_RES[cap]); - if(cleanT&&cleanT.clean)mult=Math.min(mult,0.1); - if(a.ixbh&&hasIxAt(a.city))mult=Math.min(mult,0.5); - const sp=scrubPlan(a),useS=!!sp&&scrubIdeal(sp)(R.haul||[]).find(q=>q.city===a.city&&q.to===x.city); - let land=a.bh?0:useS?sp.parts.reduce((t,x)=>{const q=x.city===a.city?null:hl(x);return t+x.a*0.15+(q?(q.a-q.h)*0.85:0);},sp.leak):a.gbps*mult; - if(sacP&&sacP.sacrif)land=Math.min(land,liveCap(PORT[sacP.tier].g,sacP.city,sacP.site,sacP.n)*0.9); - land=Math.round(land); - const fsLine=!V.fs?'— '+tr('Flowspec cannot catch an {vec} (application layer)',{vec:esc(V.n)}) - :cap>=2?'✓ '+tr('Flowspec on your {model} is dropping {vec} at the edge',{model:esc(model),vec:esc(V.n)}) - :cap===1?'~ '+tr('Flowspec on your {model} trims {vec}, but its TCAM is small',{model:esc(model),vec:esc(V.n)}) - :'— '+tr('Your {model} here has no Flowspec TCAM',{model:esc(model)}); - const scrOne=x=>{const T=SCRUB_TIERS[x.tier],q=x.city===a.city?null:hl(x); - return q&&q.hS.pops[a.city]).map(ddosOne).join(''):'';} +function ddosOne(a){ + const V=DDOS_VEC[a.vec]||{n:'?',fs:false},en=a.entry||{}; + const sacP=en.k==='p'?S.pni.find(x=>x.id===en.id):null; + const m=ddosReport(a),sp=m.sp,hl=x=>{const qs=(R.haul||[]).filter(q=>q.to===x.city&&q.attack===a.id);return qs.length?{a:qs.reduce((n,q)=>n+q.a,0),h:qs.reduce((n,q)=>n+q.h,0)}:null;}; + const landLine=m.blackhole?'~ '+tr('Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.',{city:esc(CITY[a.city].name)}) + :m.upstream?'✓ '+tr('After upstream scrubbing: {g}',{g:fmtG(m.reaching)}):''; + const fsLine=!V.fs?'— '+tr('Flowspec cannot catch {vec}',{vec:esc(V.n)}) + :m.flowspec<=1e-6?'— '+tr('No Flowspec filtering: ingress routers have no TCAM') + :m.fsMissing?'~ '+tr('Flowspec dropping: {g}; some ingress routers have no TCAM',{g:fmtG(m.flowspec)}) + :'✓ '+tr('Flowspec dropping: {g}',{g:fmtG(m.flowspec)}); + const used=c=>(R.ddos||[m]).reduce((n,q)=>n+(q.sp?.parts||[]).filter(x=>x.city===c).reduce((t,x)=>t+x.cleaned,0),0); + const scrOne=x=>{const T=SCRUB_TIERS[x.tier],q=hl(x),total=used(x.city); + return (x.cleaned>1e-6?'✓ ':'~ ')+tr('Scrubbing in {city}: {used} / {capacity}',{city:esc(CITY[x.city].name),used:fmtG(total),capacity:T.n}) + +(total>x.cleaned+1e-6?' · '+tr('This attack: {g}',{g:fmtG(x.cleaned)}):'') + +(q&&q.h~ '+tr('Your backbone can only haul {g} of it to {city}: the rest is not scrubbed',{g:fmtG(q.h),city:esc(CITY[x.city].name)}):'');}; const scrLine=!hasScrub()?'— '+tr('No scrubbing center') - :!scrubEngaged(a)?'… '+tr('On-demand scrubbing diverting, live in {n}d',{n:Math.max(1,SCRUB_DELAY-(S.day-(a.start||S.day)))}) - :!sp?'— '+tr('No scrubbing center') - :sp.parts.map(scrOne).join('
')+(sp.leak>0.5?'
~ '+tr('Your scrubbing centers are full: {g} leaks past',{g:fmtG(sp.leak)}):''); - const entryLine=cleanT&&cleanT.clean?'✓ '+tr('{net} is scrubbing it upstream (clean-pipe)',{net:esc(NET[cleanT.net].name)}) - :sacP&&sacP.sacrif?'✓ '+tr('Contained on your sacrificial {net} PNI',{net:esc(NET[sacP.net].name)}):''; + :!scrubEngaged(a)?'… '+tr('On-demand scrubbing diverting, live in {n}d',{n:Math.max(1,SCRUB_DELAY-(S.day-(a.start??S.day)))}) + :!sp?'— '+(m.leak<=1e-6?tr('No scrubbing needed after edge mitigation'):tr('Scrubbing centers unavailable or at capacity')) + :sp.parts.map(scrOne).join('
'); + const haulLine=m.near&&m.near.ms>0&&sp?.parts.some(x=>x.cleaned>1e-6)?'✓ '+tr('Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)',{city:esc(CITY[a.city].name),to:esc(CITY[m.near.city].name),ms:m.near.ms.toFixed(1)}):''; + const entryLine=sacP&&sacP.sacrif?'✓ '+tr('Contained on your sacrificial {net} PNI',{net:esc(NET[sacP.net].name)}):''; let h=`
🚨 ${tr('Live attack: {city}',{city:esc(CITY[a.city].name)})}
${tr('{size} · {vec}{entry} · {n}d left',{size:fmtG(a.gbps),vec:esc(V.n),entry:a.entry&&a.entry.lab?' · '+esc(a.entry.lab):'',n:a.until-S.day})}
-
${a.bh?tr('Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.',{city:esc(CITY[a.city].name)}):tr('Reaching your network: {g}',{g:fmtG(land)})}
+ ${landLine?`
${landLine}
`:''} + ${m.blackhole?'':`
${fsLine}
${entryLine?`
${entryLine}
`:''} + ${m.filtered-m.flowspec>1e-6?`
✓ ${tr('Edge filters dropping: {g}',{g:fmtG(m.filtered-m.flowspec)})}
`:''}
${scrLine}
-
${fsLine}
${entryLine?`\n
${entryLine}
`:''} -
${a.bh?btn(tr('Stop blackholing'),'unrtbh',{},'ghost sm'):btn(tr('Blackhole the target (RTBH)'),'rtbh',{},'red sm')}${hasIxAt(a.city)&&!a.bh?btn(a.ixbh?tr('IX blackhole on ✓'):tr('IX blackhole ~half honour it'),'ixbh',{},a.ixbh?'green sm':'sm'):''}${btn(tr('HackBack 3000™ $20k'),'hackback',{},'sm',S.cash<20000)}
+ ${haulLine?`
${haulLine}
`:''} +
${m.leak>1e-6?'~ '+tr('{g} is leaking through',{g:fmtG(m.leak)}):'✓ '+tr('Attack fully mitigated')}
`} +
${m.blackhole?btn(tr('Stop blackholing'),'unrtbh',{id:a.id},'ghost sm'):btn(tr('Blackhole the target (RTBH)'),'rtbh',{id:a.id},'red sm')}${ddosHasIx(a)&&!m.blackhole?btn(a.ixbh?tr('IX blackhole on ✓'):tr('IX blackhole ~half honour it'),'ixbh',{id:a.id},a.ixbh?'green sm':'sm'):''}${btn(tr('HackBack 3000™ $20k'),'hackback',{id:a.id},'sm',S.cash<20000)}

${tr('RTBH is free and instant, but it drops everything to the victim, attack and customer alike. An IX blackhole keeps the customer up but only about half the members honour it. HackBack 3000™ by Skynot AI sometimes ends it, and sometimes flattens an innocent and earns you a fine.')}

`; return h;} function fireFailure(){ @@ -2817,7 +2854,7 @@ function fireFailure(){ if(S.transit.some(t=>!(t.down>S.day)))opts.push(['transit',3]); if(Object.keys(S.ixp).length)opts.push(['ixloop',2]); if(S.transit.length&&S.day>60)opts.push(['leak',2]); - if(S.day>40&&!scnRule('ddos'))opts.push(['ddos',2]); // Flood Season brings its own + // DDoS has its own schedule, so other incidents cannot bypass the weekly limit. if(fabsUsed.length)opts.push(['fabric',1.5]); const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0&&!linkDown(l));if(lit.length)opts.push(['amp',1.5+lit.length*0.3],['optic',1.5+lit.length*0.3]); opts.push(['funny',4]); @@ -2921,27 +2958,49 @@ function fireFailure(){ else{const paused=pref('pauseIncident')&&autoPause();toast(`${incTitle(type)}
${esc(last.msg)}${paused?`
${tr('Game paused.')}`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('Rush repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));} sfx('alert'); } -// A DDoS attack: mostly short, modest spikes; now and then a "botnet of toasters" monster into the terabits. -// In Flood Season (scenario rule ddos) they come more often, a third are monsters, and they grow over the year. -function ddosAttack(){const type='ddos',fl=scnRule('ddos'),grow=fl?1+S.day/180:1;if(S.ev.ddos&&S.ev.ddos.until>S.day)ddosDone(S.ev.ddos); - const c=pick(Object.keys(S.pops)),vec=pick(Object.keys(DDOS_VEC)),V=DDOS_VEC[vec]; - const monster=Math.random()<(fl?0.33:0.15),base=Math.max(R.cityDem[c]||0,4); - const gbps=Math.round((monster?800+Math.random()*2600:2+Math.random()*Math.max(18,base*0.9))*grow); - const dur=2+Math.floor(Math.random()*4),entry=ddosEntry(c); - S.ev.ddos={city:c,vec,gbps,until:S.day+dur,entry,bh:false,start:S.day}; +const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0); +const ddosVectors=()=>Object.keys(DDOS_VEC).filter(k=>!DDOS_VEC[k].gaming||gamingCount()>0); +// Expected starts per week in normal play; the rolling 14-start limit is a separate ceiling. +// Spread gaming exposure over dozens of customers, including the first, rather than switching baselines. +const ddosRate=()=>0.5+6.5*(1-Math.exp(-gamingCount()/50*(1+Math.max(1,S.lvl||1)/LEVELS.length))); +const ddosPressure=()=>1-Math.exp(-(.01+Math.max(0,(S.lvl||1)-1)/12+gamingCount()/10+(scnRule('ddos')?.2+S.day/365:0))); +// Normalize the vector mix so smaller gaming-only floods do not lower the advertised overall mean. +function ddosSizeMean(){const stage=Math.max(1,S.lvl||1)/LEVELS.length,games=gamingCount(),fl=scnRule('ddos'); + const base=Math.max(10,(R.demand||0)*4/3*stage,fl?1400:0); + if(fl)return base*(1+0.2*games/(games+10))*(1+S.day/365); + // Relative to no gaming: 3x at one customer, 8x at 50, approaching the existing 12x balance. + const mean=base*(games?1.2-0.9*Math.pow(4/9,(games-1)/49):0.1),vectors=ddosVectors(),weight=vectors.reduce((n,k)=>n+(DDOS_VEC[k].gaming?1/3:1),0)/vectors.length; + return mean/weight;} +// Normal rolls: 98% uniform 0.2–2, 2% uniform 8–12. Their mean is 1.278, so spikes do not inflate the balance. +const ddosSizeMax=()=>ddosSizeMean()*(scnRule('ddos')?1.5:12/1.278); +function ddosSize(vec){const fl=scnRule('ddos'),r=Math.random(),roll=fl?1/3+r*2/3:(r<.98?.2+1.8*r/.98:8+4*(r-.98)/.02)/12; + const raw=ddosSizeMax()*(DDOS_VEC[vec].gaming?1/3:1)*roll; + return fl?Math.max(2,Math.floor(raw)):Math.max(0.001,Math.floor(raw*1000)/1000);} +function ddosTick(){if(S.mode==='sandbox')return;if(scnRule('ddos')){let next=+S.scn.nextDdos||3,n=0; + while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next40||gamingCount())for(let i=0;i<2;i++)if(Math.random()d>S.day-7&&d<=S.day);if(S.ddosStarts.length>=14||!Object.keys(S.pops).length)return;S.ddosStarts.push(S.day); + const c=pick(Object.keys(S.pops)),vec=pick(ddosVectors()),V=DDOS_VEC[vec]; + const gbps=ddosSize(vec); + const dur=1+Math.floor(Math.random()*(1+6*ddosPressure())),entry=ddosEntry(c); + const entries=ddosEntries(),a={id:uid(),city:c,vec,gbps,until:S.day+dur,entry:entries.length>1?{k:'distributed',lab:tr('Distributed ingress')}:entries[0]||entry,entries,bh:false,start:S.day}; + if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a); const soaked=(V.fs&&fsAt(c))||hasScrub(); - const how=entry&&entry.lab?tr(', in via {e}',{e:entry.lab}):''; + const how=entries.length>1?tr(', across {n} transit and peering ports',{n:entries.length}):entry&&entry.lab?tr(', in via {e}',{e:entry.lab}):''; const msg=tr('A {size} {vec} attack is hitting {city}{how}.',{size:fmtG(gbps),vec:V.n,city:CITY[c].name,how})+' '+(soaked?tr('Your mitigation is eating most of it.'):tr('Junk traffic is eating your capacity. Open the NOC to fight back.')); - if(fl)S.ev.ddos.who=pick(FLOOD_WHO); - addInc({type,ref:c,until:S.day+dur,msg:fl?msg+' '+tr('Attacker: {who}.',{who:tr(S.ev.ddos.who)}):msg,cost:0}); + if(fl)a.who=pick(FLOOD_WHO); + addInc({type,ref:c,atk:a.id,until:S.day+dur,msg:fl?msg+' '+tr('Attacker: {who}.',{who:tr(a.who)}):msg,cost:0}); if(soaked){S.stats.survived++;S.stats.ddosHeld=(S.stats.ddosHeld||0)+1;if(gbps>=1000)S.stats.ddosMonster=(S.stats.ddosMonster||0)+1;} - compute(); - toast(`${incTitle('ddos')}: ${esc(CITY[c].name)}
${esc(msg)}${fl?`
${esc(tr('Attacker: {who}.',{who:tr(S.ev.ddos.who)}))}`:''}`,soaked?'goal':'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:c}); + if(recompute){compute();a.worst=ddosSf(a);} + toast(`${incTitle('ddos')}: ${esc(CITY[c].name)}
${esc(msg)}${fl?`
${esc(tr('Attacker: {who}.',{who:tr(a.who)}))}`:''}`,soaked?'goal':'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:c}); sfx('alert');} // When an attack is over: was it held? Held means the city under attack got at least 97% of its traffic every day. -function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pops[a.city])a.worst=sfOf(R,a.city);const ok=(a.worst===undefined?1:a.worst)>=0.97; +function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pops[a.city])a.worst=ddosSf(a);const ok=(a.worst===undefined?1:a.worst)>=0.97; if(ok){S.stats.ddosOk=(S.stats.ddosOk||0)+1;if(a.gbps>=1000)S.stats.ddosOkBig=(S.stats.ddosOkBig||0)+1;}else S.stats.ddosLost=(S.stats.ddosLost||0)+1; if(scnRule('ddos')){const who=tr(a.who||FLOOD_WHO[0]);toast(ok?tr('Flood held: {g}.
{who} gave up and went back to mining crypto.',{g:fmtG(a.gbps),who:who.charAt(0).toUpperCase()+who.slice(1)}):tr('That one got through: {g}.
{city} sank to {p}. Somewhere, {who} is very proud of itself.',{g:fmtG(a.gbps),city:CITY[a.city]?CITY[a.city].name:tr('Your network'),p:pct(a.worst||0),who}),ok?'goal':'bad');}} +const floodGap=()=>Math.max(0.05,(3+Math.random()*5)/(Math.sqrt(1+S.day/180)*(1+gamingCount()/10+Math.max(0,(S.lvl||1)-1)/12))); const FLOOD_WHO=[N_('a botnet of 40,000 smart toasters'),N_('every unpatched baby monitor in Europe'),N_('a gaming clan that lost one match'),N_('a fridge that achieved sentience and chose violence'),N_('a crypto bro shorting your stock'),N_('a teenager with a stolen credit card and a grudge'),N_('a rival ISP’s “stress test”'),N_('ten thousand smart light bulbs, blinking in unison'),N_('a printer. Just one printer. Nobody knows how'),N_('a botnet run from a cloud you also host'),N_('somebody who did not like your network name'),N_('the internet-connected kettles of a whole country')]; function incTitle(t){return {ring:tr('Metro ring cut'),site:tr('Site outage'),cut:tr('Fiber cut'),crash:tr('Router crash'),power:tr('Power outage'),transit:tr('Upstream outage'),ixloop:tr('IX meltdown'),leak:tr('Route leak'),ddos:tr('DDoS attack'),fabric:tr('Fabric outage'),depeer:tr('Peering spat'),fatwave:tr('Fat-fingered wave'),label:tr('Patch panel mishap'),mtu:tr('MTU mismatch'),krroute:tr('Rerouted via Hong Kong'),ctrlplane:tr('Control plane meltdown'),lacp:tr('LACP trouble'),loss:tr('Packet loss'),pmtud:tr('PMTUD black hole'),oops:tr('Oops'),cleaner:tr('Vacuum incident'),maxpfx:tr('Max-prefix meltdown'),prepend:tr('Prepend-ageddon'),rpki:tr('RPKI invalid'),amp:tr('Amplifier failure'),roadmff:tr('Fat-fingered ROADM'),optic:tr('Dead optic'),maint:tr('Maintenance window'),ac:tr('Cooling failure'),hijack:tr('BGP hijack'),shutdown:tr('Government shutdown'),redsea:tr('Geopolitical cable cut')}[t]||tr('Incident');} const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop','maxpfx'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic']; @@ -2956,7 +3015,7 @@ function clearInc(i){ else if(TDOWN.includes(T)){const t=S.transit.find(x=>x.id===i.ref);if(t)t.down=remainUntil(x=>TDOWN.includes(x.type)&&x.ref===i.ref);} else if(T==='rpki'||T==='hijack'){if(!S.inc.some(x=>x.type==='rpki'||x.type==='hijack'))S.ev.rpki=null;} else if(T==='leak'){S.ev.leak=null;} - else if(T==='ddos'){const a=S.ev.ddos;if(a&&a.city===i.ref&&(a.start===undefined||a.start===i.start)){ddosDone(a);S.ev.ddos=null;}} + else if(T==='ddos'){const a=ddosAll(S,false).find(a=>i.atk?a.id===i.atk:a.city===i.ref&&(a.start===undefined||a.start===i.start));if(a){ddosDone(a);ddosDrop(a);}} else if(T==='fabric'){if(S.ev.fab)S.ev.fab[i.ref]=remainUntil(x=>x.type==='fabric'&&x.ref===i.ref);} else if(T==='mtu'){const l=S.links.find(x=>x.id===i.ref);if(l)l.deg=remainUntil(x=>x.type==='mtu'&&x.ref===i.ref);} else if(T==='loss'){const l=S.links.find(x=>x.id===i.ref);if(l&&!S.inc.some(x=>x.type==='loss'&&x.ref===i.ref))l.loss=null;} @@ -3034,8 +3093,9 @@ function dayTick(){ if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved); {const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('You are no longer Tier 1.
Because {why}. Your Tier 1 badge stays; win the status back to show it again.',{why:t1Why()}),'bad');S.t1Now=t1;} if(S.grace&&S.grace.until===d){toast(tr('The courtesy route has ended.
New networks you have not connected to are now only reachable through your own peering and transit.'),'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}]);} - {const a=S.ev.ddos;if(a&&a.until>d&&R&&S.pops[a.city])a.worst=Math.min(a.worst===undefined?1:a.worst,sfOf(R,a.city));} - if(scnRule('ddos')&&!(S.scn.done||S.scn.failed)&&d>=(+S.scn.nextDdos||3)&&!(S.ev.ddos&&S.ev.ddos.until>d)){ddosAttack();S.scn.nextDdos=d+3+Math.floor(Math.random()*5);} + for(const a of ddosAll(S,false))if(a.until>=d&&R&&S.pops[a.city])a.worst=Math.min(a.worst===undefined?1:a.worst,ddosSf(a)); + ddosExpire(); + ddosTick(); if(R&&R.demand>0)S.stats.clean=R.served/R.demand>=0.995?(S.stats.clean||0)+1:0; if(S.scn&&S.scn.id==='redsea')S.stats.asiaRun=asiaG()>=RS_G?(S.stats.asiaRun||0)+1:0; if(S.ev.php===d)toast(tr('The internet is back.
Half of it, anyway. Everything was patched in a hurry and nobody learned anything.'),'good'); @@ -3050,6 +3110,7 @@ function dayTick(){ if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);} else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));} compute(); + for(const a of ddosAll())a.worst=Math.min(a.worst??1,ddosSf(a)); for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();} S.cash+=(R.revMo-R.costMo)/30; S.stats.peak=Math.max(S.stats.peak,R.served); @@ -3059,9 +3120,9 @@ function dayTick(){ if(l.ready===d){toast(`${l.own?tr('Your fiber is finished: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('Dark fiber handed over: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name})}
${(l.ch||[]).length?tr('Channels are lighting up now.'):tr('It is dark. Add optics to light it up.')}`,'goal',[{l:tr('Open'),act:'selLink',args:{id:l.id}}]);sfx('coin');} if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+extra);toast(tr('Construction delay: +{n} days
{why} ({a}–{b})',{n:extra,why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('Archaeologists found a Roman bathhouse on your route.'),tr('A protected hamster species lives along the right-of-way.'),tr('The railway changed its mind about the easement.'),tr('The drilling crew hit a granite boulder the size of a bus.'),tr('A town council wants a public hearing. About the color of the manhole covers.'),tr('Somebody else’s gas main was exactly where the map said it was not.'),tr('The permit office lost your permit. And then the replacement.')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}} // DDoS protection SLA: if a protected customer's own city is hit and still goes down, you pay out (once per attack). - if(S.ev.ddos&&S.ev.ddos.until>d){const a=S.ev.ddos; - for(const b of S.biz)if(b.type==='scrub'&&b.city===a.city&&b.slaFor!==a.start&&sfOf(R,b.city)<0.85){ - b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; + for(const a of ddosAll()){ + for(const b of S.biz)if(b.type==='scrub'&&ddosCities(a).includes(b.city)&&!(a.sla||[]).includes(b.id)&&(a.id||b.slaFor!==a.start)&&sfOf(R,b.city)<0.85){ + (a.sla||(a.sla=[])).push(b.id);b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; toast(tr('SLA breach: {name}.
The attack on {city} got through and your protected customer went down. You owe {pen} in SLA credits.',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} // businesses mood for(const b of S.biz.slice()){if(eventTick(b,d))continue;b.pm=b.mood;const sf=bizSf(b),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b); @@ -3425,10 +3486,10 @@ const ACT={ rmScrub:({city})=>{if(!S.scrubs.some(x=>x.city===city))return;if(UI.confirm!=='scrub:'+city){UI.confirm='scrub:'+city;renderAll();return;}S.scrubs=S.scrubs.filter(x=>x.city!==city);if(!hasScrub())S.scrubMode='always';UI.confirm=null;after();}, cleanPipe:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.clean=!t.clean;toast(t.clean?tr('Clean-pipe add-on enabled on {net}.
They scrub a flood before it reaches your port here, for {mo}/mo.',{net:NET[t.net].name,mo:fmt$(cleanMo(t))}):tr('Clean-pipe add-on removed from {net}.',{net:NET[t.net].name}),t.clean?'good':'');after();}, sacrif:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;p.sacrif=!p.sacrif;toast(p.sacrif?tr('{net} PNI is now a sacrificial choke point.
A flood from there dies on the small port instead of inside your network, but legit traffic over it runs at half capacity.',{net:NET[p.net].name}):tr('{net} PNI is back to normal.',{net:NET[p.net].name}),p.sacrif?'good':'');after();}, - ixbh:()=>{const a=S.ev.ddos;if(!a){toast(tr('No attack to blackhole right now.'),'');return;}if(!hasIxAt(a.city)){toast(tr('No IX in {city} to announce a blackhole to.',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('IX blackhole announced in {city}.
About half the members honour the /32 and drop the junk. The customer stays up.',{city:CITY[a.city].name}):tr('IX blackhole withdrawn.'),a.ixbh?'good':'');sfx('alert');after();}, - rtbh:()=>{const a=S.ev.ddos;if(!a){toast(tr('No attack to blackhole right now.'),'');return;}a.bh=true;S.stats.rtbh=(S.stats.rtbh||0)+1;toast(tr('RTBH announced.
You blackholed the target in {city}. The flood stops, and so does everyone there.',{city:CITY[a.city].name}),'bad');sfx('alert');after();}, - unrtbh:()=>{const a=S.ev.ddos;if(!a||!a.bh)return;a.bh=false;toast(tr('Blackhole withdrawn.
{city} is reachable again. Brace for the junk.',{city:CITY[a.city].name}),'');after();}, - hackback:()=>{const a=S.ev.ddos;if(!a||a.until<=S.day){toast(tr('Nothing to hack back right now.'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1; + ixbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('No attack to blackhole right now.'),'');return;}if(!ddosHasIx(a)){toast(tr('No IX in {city} to announce a blackhole to.',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('IX blackhole announced in {city}.
About half the members honour the /32 and drop the junk. The customer stays up.',{city:ddosCities(a).filter(hasIxAt).map(c=>CITY[c].name).join(', ')}):tr('IX blackhole withdrawn.'),a.ixbh?'good':'');sfx('alert');after();}, + rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('No attack to blackhole right now.'),'');return;}a.bh=true;S.stats.rtbh=(S.stats.rtbh||0)+1;toast(tr('RTBH announced.
You blackholed the target in {city}. The flood stops, and so does everyone there.',{city:CITY[a.city].name}),'bad');sfx('alert');after();}, + unrtbh:({id}={})=>{const a=ddosFind(id);if(!a)return;for(const x of ddosAll())if(x.city===a.city)x.bh=false;toast(tr('Blackhole withdrawn.
{city} is reachable again. Brace for the junk.',{city:CITY[a.city].name}),'');after();}, + hackback:({id}={})=>{const a=ddosFind(id);if(!a||a.until<=S.day){toast(tr('Nothing to hack back right now.'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1; if(Math.random()<0.35){a.until=S.day;a.bh=false;S.stats.hackWin=(S.stats.hackWin||0)+1;toast(tr('HackBack 3000™ strikes back!
Skynot AI traced the botnet and politely bricked it. The attack on {city} stops cold.',{city:CITY[a.city].name}),'goal');sfx('coin');} else{const fine=15000+Math.floor(Math.random()*35000);S.cash-=fine;S.stats.vigilante=(S.stats.vigilante||0)+1; toast(tr('HackBack 3000™ hit the wrong target.
{who} A regulator sends you a {fine} fine, and the attack rolls on.',{who:pick([tr("Skynot AI flattened a grandma's internet-connected fridge."),tr('You counter-flooded a hospital in a country you cannot pronounce.'),tr('The botnet was already someone else’s botnet. They are furious.')]),fine:fmt$(fine)}),'bad');sfx('err');} @@ -3697,7 +3758,7 @@ function renderLeft(){checkLayer(); {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('Customer level {lv}: {name}',{lv,name:LEVELS[lv-1].n})}
${nx?tr('Next: {req} unlocks {what}',{req:nx.req,what:lc1(nx.unlock)}):tr('Every customer type is unlocked. Go get those terabits.')}
`;} if(!S.offers.length)h+=`

${tr('No open offers right now. Businesses look for networks with POPs in their city. New ones pop up every few weeks.')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); - h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('{n} special requirement','{n} special requirements',o.reqs.length)}`:''}
${reqList(o)} + h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('{n} special requirement','{n} special requirements',o.reqs.length)}`:''}
${bRisk(o)}${reqList(o)}
${has?btn(tr('Accept'),'accept',{id:o.id},'green sm'):btn(tr('Go there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('Decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('Needs a POP in {cities}',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }else if(UI.left==='noc'){ h+=`
${btn(tr('Open NOC dashboard'),'dash',{},'pink')}${btn(tr('Connections'),'connOpen',{},'')}${btn(tr('Traceroute'),'trace',{},'')}
`; @@ -3781,7 +3842,7 @@ function cityPanel(c){ h+=`

${tr('Business customers')}

`; const bz=S.biz.filter(b=>bCities(b).includes(c)); if(!bz.length)h+=`

${tr('No businesses yet. Offers pop up as $ bubbles on the map.')}

`; - for(const b of bz)h+=`
${esc(b.name)}
${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · ${b.sites?tr('carrying {g} per site',{g:fmtG(R.l2[b.id]||0)}):tr('carrying {g}',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('fiber is down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('serving {v}',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('needs a scrubbing center')+'':''}${S.day-(b.since||0)<15?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('Really drop?'):tr('Drop'),'dropBiz',{id:b.id},'ghost sm')}
`; + for(const b of bz)h+=`
${esc(b.name)}
${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · ${b.sites?tr('carrying {g} per site',{g:fmtG(R.l2[b.id]||0)}):tr('carrying {g}',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('fiber is down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('serving {v}',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('needs a scrubbing center')+'':''}${S.day-(b.since||0)<15?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('Really drop?'):tr('Drop'),'dropBiz',{id:b.id},'ghost sm')}
`; h+=`
`+offersHere(c); }else if(UI.tab==='up'){ h+=portNote(c)+latNote(c); @@ -3973,7 +4034,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('Offers here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('They need the full internet. Your reach is {pct}.',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('Needs your own scrubbing center (Infra tab).')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('Needs a POP in {cities} too.',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('Accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('No'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('Offers here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('They need the full internet. Your reach is {pct}.',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('Needs your own scrubbing center (Infra tab).')}
`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`
${tr('Needs a POP in {cities} too.',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('Accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('No'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} @@ -4031,8 +4092,8 @@ const SCN_PROG={stg:()=>[{l:tr('Reach'),v:R.reach,max:0.45,txt:`${pct(R.reach)} darien:()=>[...['bog','lim','scl','sao'].map(c=>pChk(tr('POP in {city}',{city:CITY[c].name}),!!S.pops[c])),pSrv(150)], gangnam:()=>[pReach(),pSrv(200)], fttb:()=>[...AU_BB.map(c=>pChk(tr('Broadband in {city}',{city:CITY[c].name}),!!(S.pops[c]&&S.pops[c].bb))),{l:tr('Cables overseas'),v:Math.min(2,auExits()),max:2,txt:`${auExits()} / 2`}], - flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,a=S.ev.ddos&&S.ev.ddos.until>S.day?S.ev.ddos:null; - return [{l:tr('Floods held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('Terabit floods held'),v:big,max:5,txt:`${big} / 5`},{l:tr('Floods that got through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(a?[{l:tr('Under attack now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`}]:[]);},baltic:()=>[{l:tr('Days in a row with 99.5% served'),v:S.stats.clean||0,max:90,txt:tr('{n} of {m}',{n:S.stats.clean||0,m:90})}]}; + flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll(); + return [{l:tr('Floods held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('Terabit floods held'),v:big,max:5,txt:`${big} / 5`},{l:tr('Floods that got through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('Under attack now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`})));},baltic:()=>[{l:tr('Days in a row with 99.5% served'),v:S.stats.clean||0,max:90,txt:tr('{n} of {m}',{n:S.stats.clean||0,m:90})}]}; function scnProg(){const sc=S&&S.scn;if(!sc)return null; if(sc.id==='weekly')return {goal:tr('Serve as much traffic as you can in one year.'),items:[{l:tr('Your score: peak traffic'),v:0,max:0,txt:fmtG(S.stats.peak||0)}],f:Math.min(1,S.day/sc.days)}; const def=SCN.find(x=>x.id===sc.id),fn=SCN_PROG[sc.id];if(!def)return null;let items=[];try{items=fn?fn():[];}catch(e){items=[];} @@ -4110,7 +4171,7 @@ function custSection(){const F=UI.kf||{};let h=`
b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' ▲':' ▼'; const sorts=[['mood',tr('Happiness')],['mo',tr('Per month')],['name',tr('Name')],['city',tr('Where')]]; h+=`
${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; - h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `
${esc(b.name)} ${esc(BIZ_T[b.type].l)}
${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); + h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `
${esc(b.name)} ${esc(BIZ_T[b.type].l)}
${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); return h+listMore('cust',rows.length,n=>trn('+{n} more customer','+{n} more customers',n))+`
`;} /* ---------- connections overview (#31, #33, #38) ---------- Every transit port, PNI, IX port, cache and fabric port in one list, filterable by type, city and diff --git a/tests/game.test.js b/tests/game.test.js index e6d0d16..1047b19 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -2,6 +2,15 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load, seed } = require('./harness'); +test('daily DDoS spawns share one routing calculation and score their first active day', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.day=50;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();window.__compute=compute;window.__random=Math.random;window.__computes=0;compute=()=>{window.__computes++;window.__compute()};Math.random=()=>0;dayTick();compute=window.__compute;Math.random=window.__random"); + assert.equal(ev('ddosAll().length'), 2, 'both daily spawn opportunities were used'); + assert.equal(ev('window.__computes'), 1, 'daily spawns do not reroute the whole network individually'); + assert.ok(ev('ddosAll().every(a=>a.worst===ddosSf(a))'), 'first-day service is recorded after routing'); + assert.deepEqual(errors, []); +}); + test('page boots to the title screen without errors', () => { const { ev, errors } = load(); assert.equal(ev("document.getElementById('modal').hidden"), false); @@ -197,6 +206,52 @@ test('Flowspec is a router-model capability, and each tool answers a flood', () assert.deepEqual(errors, []); }); +test('a distributed SYN flood reports actual Flowspec drops and sends only the remainder to scrubbing', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.scrubs=[{city:'fra',tier:0}];S.scrubMode='always';S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'edge',city:'fra',share:1}]};compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2); + assert.match(ev('ddosPanel()'), /— No Flowspec filtering: ingress routers have no TCAM/); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 30\.2 Gbps \/ 100G/); + assert.doesNotMatch(ev('ddosPanel()'), /✓ Flowspec|After upstream scrubbing|Reaching your network/); + for (const [router, dropped, scrubbed] of [[1,18.12,12.08], [3,25.67,4.53]]) { + ev(`S.pops.fra.rgen=${router};compute()`); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-dropped)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-scrubbed)<1e-9); + assert.match(ev('ddosPanel()'), new RegExp('✓ Flowspec dropping: '+dropped.toFixed(1).replace('.', '\\.')+' Gbps')); + assert.match(ev('ddosPanel()'), new RegExp('Scrubbing in Frankfurt: '+scrubbed.toFixed(1).replace('.', '\\.')+' Gbps / 100G')); + assert.doesNotMatch(ev('ddosPanel()'), /no TCAM|Edge filters dropping/); + } + ev("S.ev.ddos.vec='ack';compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2); + assert.match(ev('ddosPanel()'), /— Flowspec cannot catch ACK flood/); + assert.deepEqual(errors, []); +}); + +test('Flowspec accounts for each ingress router, upstream cleaning and other edge filters separately', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.pops.nyc.rgen=3;S.transit=[{id:'tf',city:'fra',net:'cog',tier:1},{id:'tn',city:'nyc',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:0},{city:'nyc',tier:0}];S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.5},{k:'t',id:'tn',city:'nyc',share:0.5}]};compute()"); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-12.835)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)')-17.365)<1e-9); + assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 12\.8 Gbps; some ingress routers have no TCAM/); + assert.match(ev('ddosPanel()'), /Scrubbing in Frankfurt: 15\.1 Gbps \/ 100G/); + assert.match(ev('ddosPanel()'), /Scrubbing in New York: 2\.3 Gbps \/ 100G/); + assert.equal(ev('ddosMitigation(S.ev.ddos).flowspec'), ev('ddosReport(S.ev.ddos).flowspec'), 'uncached reports also filter at the ingress instead of the target'); + ev('S.transit[1].clean=true;compute()'); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).reaching')-16.61)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-1.2835)<1e-9); + assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 16\.6 Gbps/); + assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 1\.3 Gbps/); + ev("S.pops.fra.rgen=3;S.ixp={fra:1,nyc:1};S.ev.ddos.ixbh=true;compute()"); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-14.1185)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).flowspec')-1.24575)<1e-9); + assert.match(ev('ddosPanel()'), /✓ Flowspec dropping: 14\.1 Gbps/); + assert.match(ev('ddosPanel()'), /✓ Edge filters dropping: 1\.2 Gbps/); + assert.ok(ev('Math.abs(ddosReport(S.ev.ddos).reaching-ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)-ddosReport(S.ev.ddos).leak)<1e-9')); + assert.deepEqual(errors, []); +}); + test('RTBH blackholes the victim, and HackBack 3000 is a gamble', () => { const { ev } = load(); ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=120;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()"); @@ -478,3 +533,468 @@ test('the broadband panel shows what homes in that city really pay, not the base assert.ok(ev("cityPanel('del')").includes(rev + '/mo'), `revenue line matches what the month pays (${rev})`); assert.deepEqual(errors, []); }); + + +test('Memcached amplification and ACK flood are available without gaming customers and respect Flowspec', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});RG[0].fs=2"); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('DDOS_VEC.memcached.fs'), true); + assert.equal(ev('DDOS_VEC.ack.fs'), false); + ev("S.ev.ddos={city:'fra',vec:'ack',gbps:300,until:S.day+3,start:S.day};compute()"); + const ack = ev('R.served'); + assert.match(ev('ddosPanel()'), /ACK flood/); + assert.doesNotMatch(ev('ddosPanel()'), /application layer/); + ev("S.ev.ddos.vec='memcached';compute()"); + assert.ok(ev('R.served') > ack, 'Flowspec filters Memcached but cannot filter ACK'); + for (const vec of ['memcached', 'ack']) { + ev(`const old=Math.random;Math.random=()=>(${['dns','ntp','memcached','ack'].indexOf(vec)}+0.1)/ddosVectors().length;ddosAttack();Math.random=old`); + assert.equal(ev('ddosAll().at(-1).vec'), vec, 'the generator can select each new vector'); + } + assert.deepEqual(errors, []); +}); + + +test('DDoS accounting conserves attack bandwidth through upstream, edge and local scrubbing', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.bb.d=100;S.scrubs=[{city:'fra',tier:1}];S.transit[0].clean=true;S.ev.ddos={city:'fra',vec:'http',gbps:1842,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute()"); + assert.ok(Math.abs(ev('R.ddos[0].reaching') - 184.2) < 1e-9); + assert.equal(ev('R.ddos[0].sp.parts[0].cleaned'), ev('R.ddos[0].reaching')); + assert.equal(ev('R.ddos[0].leak'), 0, 'the 1T center cleans the upstream remainder'); + assert.doesNotMatch(ev('ddosPanel()'), /842 Gbps of attack traffic leaks/); + ev('S.transit[0].clean=false;compute()'); + assert.equal(ev('R.ddos[0].reaching'), 1842); + assert.equal(ev('R.ddos[0].leak'), 842); + for (const setup of ["S.transit[0].clean=true", "RG[0].fs=2;S.ev.ddos.vec='dns'", "S.scrubs=[]"]) { + ev(setup+';compute()'); + assert.ok(ev('Math.abs(R.ddos[0].reaching-R.ddos[0].filtered-(R.ddos[0].sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0)-R.ddos[0].leak)<1e-9')); + assert.ok(ev('R.ddos[0].leak<=R.ddos[0].reaching')); + } + // On-demand diversion must also work for an attack which began on day zero. + ev("S.scrubs=[{city:'fra',tier:1}];S.scrubMode='ondemand';S.day=2;compute()"); + assert.equal(ev('R.ddos[0].leak'), 0); + assert.deepEqual(errors, []); +}); + + +test('the NOC integrates DDoS mitigation totals into each live attack card without duplicate summaries on phones', () => { + const { ev, errors, dom } = load(); + ev('ACT.start({})'); + Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true }); + ev("S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.transit[0].clean=true;S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={city:'fra',vec:'http',gbps:3840,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute();UI.left='noc';UI.leftOpen=true;renderLeft()"); + const card = () => dom.window.document.querySelector('[data-act="rtbh"], [data-act="unrtbh"]').closest('.inc'); + const text = () => card().textContent; + assert.match(card().querySelector('.nm').textContent, /🚨 Live attack: Frankfurt/); + assert.equal(dom.window.document.querySelector('.ddos-stats'), null, 'use the existing attack card'); + assert.doesNotMatch(text(), /DDoS mitigation status|Attack size:|3840 Gbps|This attack:/); + assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'the attack size appears once'); + assert.match(text(), /✓ After upstream scrubbing: 384 Gbps/); + assert.equal(text().match(/After upstream scrubbing/g).length, 1, 'show the upstream remainder once'); + assert.doesNotMatch(text(), /Reaching your network|reaching your network|Upstream scrubbing active/); + assert.match(text(), /✓ Scrubbing in Frankfurt: 384 Gbps \/ 1T/); + assert.match(text(), /✓ Attack fully mitigated/); + ev('S.transit[0].clean=false;compute();renderLeft()'); + assert.doesNotMatch(text(), /After upstream scrubbing|Reaching your network/); + assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'inactive upstream scrubbing does not repeat the attack size'); + assert.match(text(), /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T/); + assert.match(text(), /~ 2\.84 Tbps is leaking through/); + assert.equal(text().match(/leaking through/g).length, 1, 'show the mitigation outcome once'); + assert.doesNotMatch(text(), /Upstream scrubbing|Attack fully mitigated|leaks past mitigation/); + ev("S.transit[0].clean=true;S.pops.fra.rgen=3;S.ev.ddos.vec='dns';compute();renderLeft()"); + assert.match(text(), /✓ Flowspec dropping: 326 Gbps/); + assert.doesNotMatch(text(), /Edge filters dropping/); + assert.match(text(), /✓ Scrubbing in Frankfurt: 57\.6 Gbps \/ 1T/); + assert.match(text(), /✓ Attack fully mitigated/); + ev('ACT.rtbh();renderLeft()'); + assert.match(text(), /~ Blackholed: the junk is gone, and so is Frankfurt/); + assert.equal(text().match(/Blackholed:/g).length, 1); + assert.doesNotMatch(text(), /After upstream scrubbing|reaching your network|scrubbing in Frankfurt|Attack fully mitigated|leaking through/i); + assert.ok(card().querySelector('[data-act="unrtbh"]'), 'the existing controls stay in the card'); + assert.deepEqual(errors, []); +}); + +test('overlapping floods share scrubbing capacity, have separate controls, and finish independently', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:700,start:0,until:3};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:700,start:0,until:5}];compute();UI.left='noc';UI.leftOpen=true;renderLeft()"); + assert.equal(ev('R.ddos.length'), 2); + assert.equal(ev('R.ddos.reduce((n,m)=>n+(m.sp?.parts.reduce((v,x)=>v+x.cleaned,0)||0),0)'), 1000); + assert.equal(ev('R.ddos.reduce((n,m)=>n+m.leak,0)'), 400, 'one center cannot spend its capacity twice'); + const cards = [...dom.window.document.querySelectorAll('[data-act="rtbh"]')].map(b=>b.closest('.inc')); + assert.equal(cards.length, 2); + assert.match(cards[1].textContent, /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T · This attack: 300 Gbps/); + ev("ACT.rtbh({id:'two'})"); + assert.equal(ev("S.ev.ddos.bh||false"), false, 'the selected attack gets the control'); + assert.equal(ev('S.ev.ddosMore[0].bh'), true); + assert.ok(ev('R.ddos.every(m=>m.leak===0)'), 'blackholing a target city drops every flood to it'); + ev("ACT.unrtbh({id:'one'});const old=Math.random;Math.random=()=>0.1;ACT.hackback({id:'two'});Math.random=old"); + assert.equal(ev('ddosAll().length'), 1, 'hack-back ends only the selected attack'); + ev('S.day=3;ddosExpire();compute()'); + assert.equal(ev('ddosAll().length'), 0); + assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2, 'both attacks scored once'); + ev('ddosExpire()'); + assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2); + assert.deepEqual(errors, []); +}); + +test('overlapping DDoS saves round trip and legacy attacks migrate safely', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.ev.ddos={city:'fra',vec:'dns',gbps:'80',until:7,start:0};delete S.ev.ddosMore;delete S.ddosStarts;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('ddosAll().length'), 1); + assert.equal(ev('S.ev.ddos.gbps'), 80); + assert.equal(ev('S.ev.ddosMore.length'), 0); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]); + ev("S.ev.ddosMore=[{id:'overlap',city:'fra',vec:'ack',gbps:50,until:5,start:0,sla:['customer']},null,{city:'bad',vec:'dns'}, {city:'fra',vec:'unknown'}];S.ddosStarts=[0,'bad',Infinity,-9,99];S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('ddosAll().length'), 2); + assert.equal(ev('S.ev.ddosMore[0].id'), 'overlap'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('R.ddos.length'), 2); + assert.deepEqual(errors, []); +}); + +test('simultaneous attacks each bill their protected customer only once', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.biz=[{id:'protected',name:'Shield',city:'fra',type:'scrub',bw:5,rate:900,mood:100,since:0,reqs:[]}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:6000,start:0,until:7};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:6000,start:0,until:7}];compute();dayTick()"); + assert.equal(ev('S.stats.sla'), 2, 'same-day attacks have separate SLA identities'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));dayTick()'); + assert.equal(ev('S.stats.sla'), 2, 'reloading does not pay the same credits twice'); + assert.deepEqual(errors, []); +}); + +test('DDoS frequency rises with level and signed gaming customers, with a rolling weekly ceiling', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.day=50;S.lvl=1;S.biz=[]"); + const base = ev('ddosRate()'); + assert.equal(base, 0.5); + ev('S.lvl=13'); + assert.equal(ev('ddosRate()'), base, 'level alone does not increase the non-gaming rate'); + ev("S.biz=[{type:'game',city:'fra'}];S.lvl=1"); + const early = ev('ddosRate()'); + ev('S.lvl=13'); + const level = ev('ddosRate()'); + ev("S.biz=Array.from({length:20},(_,i)=>({type:i%2?'cgame':'game',city:'fra'}))"); + const gaming = ev('ddosRate()'); + assert.ok(base < early && early < level && level < gaming && gaming <= 7); + ev("S.offers=Array.from({length:50},()=>({type:'game'}));S.biz=[];S.lvl=1"); + assert.equal(ev('ddosRate()'), base, 'unsigned offers do not attract attacks'); + // Force every random spawn opportunity, then verify each rolling seven-day window. + ev('window.__starts=[];window.__oldRandom=Math.random;Math.random=()=>0'); + for (let day = 50; day < 66; day++) { + ev(`S.day=${day};ddosTick();window.__starts.push(...ddosAll().filter(a=>a.start===S.day).map(a=>a.start))`); + assert.ok(ev('S.ddosStarts.length') <= 14); + } + ev('Math.random=window.__oldRandom'); + const starts = JSON.parse(ev('JSON.stringify(window.__starts)')); + for (let day = 50; day < 66; day++) assert.ok(starts.filter(d=>d>day-7&&d<=day).length <= 14); + assert.ok(starts.length > 14, 'the allowance renews as starts leave the rolling window'); + ev('for(let i=0;i<30;i++)ddosAttack()'); + assert.equal(ev('S.ddosStarts.length'), 14, 'manual and incident starts cannot bypass the cap'); + assert.deepEqual(errors, []); +}); + +test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood Season scaling', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.lvl=13;R.demand=150000;S.biz=[]'); + assert.equal(ev('ddosSizeMean()'), 20000); + ev("S.scn={id:'flood',rules:{ddos:true}};S.day=365"); + assert.equal(ev('ddosSizeMean()'), 400000); + ev('S.day=730'); + assert.equal(ev('ddosSizeMean()'), 600000, 'Flood Season keeps growing after completion'); + ev('S.scn=null;R.demand=300000'); + assert.equal(ev('ddosSizeMean()'), 40000, 'larger networks can draw still larger attacks'); + ev('S.lvl=1'); + const early = ev('ddosSizeMax()'); + ev('S.lvl=13'); + const late = ev('ddosSizeMax()'); + ev("S.biz=[{type:'game',city:'fra'}]"); + assert.ok(early < late && late < ev('ddosSizeMax()')); + // Fixed quantiles show longer durations as both level and gaming exposure rise. + ev('window.__oldRandom=Math.random;Math.random=()=>0.95;S.lvl=1;S.biz=[];ddosAttack();window.__earlyDur=ddosAll().at(-1).until-S.day;S.lvl=13;S.biz=Array.from({length:40},()=>({type:\'game\',city:\'fra\',bw:0,rate:0}));ddosAttack();Math.random=window.__oldRandom'); + assert.ok(ev('ddosAll().at(-1).until-S.day') > ev('window.__earlyDur')); + assert.equal(ev('ddosAll().at(-1).until-S.day'), 7); + assert.deepEqual(errors, []); +}); + +test('distributed attacks follow normal transit and peering traffic across regions', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].rgen=3;S.pops[c].bb={d:c==='fra'?100:300}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}];S.pni=[{id:'pf',city:'fra',net:'ggl',tier:1}];S.ixp={nyc:1};S.rs={nyc:true};compute();window.__normal=JSON.stringify(R.ingressPorts);ddosAttack()"); + const normal = JSON.parse(ev('window.__normal')); + const entries = JSON.parse(ev('JSON.stringify(ddosAll()[0].entries)')); + const total = Object.values(normal).reduce((n,p)=>n+p.traffic,0); + assert.ok(entries.some(p=>p.k==='t') && entries.some(p=>p.k==='p') && entries.some(p=>p.k==='ix')); + assert.deepEqual([...new Set(entries.map(p=>p.city))].sort(), ['fra','nyc']); + for (const en of entries) assert.ok(Math.abs(en.share-normal[en.k+':'+en.id].traffic/total)<1e-9); + assert.ok(Math.abs(entries.reduce((n,en)=>n+en.share,0)-1)<1e-9); + assert.match(ev('ddosPanel()'), /Live attack:/); + assert.doesNotMatch(ev('ddosPanel()'), /ports: .*regions:/, 'keep regional detail out of the live attack card'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('S.ev.ddos.entries.length'), entries.length, 'distributed shares survive a save round trip'); + assert.deepEqual(errors, []); +}); + +test('distributed ingress applies upstream scrubbing only to its own port and uses regional centers', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].rgen=3;S.pops[c].bb={d:100}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2,clean:true},{id:'tn',city:'nyc',net:'cog',tier:2}];S.scrubs=[{city:'fra',tier:0}];S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.25},{k:'t',id:'tn',city:'nyc',share:0.75}]};compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 775); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 750); + assert.equal(ev('R.useT.tn'), 400, 'the uncleaned flood fills its own ingress port'); + assert.ok(ev('R.useT.tf') < 200, 'it cannot spill into the cleaned port'); + assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 775 Gbps/); + assert.match(ev('ddosPanel()'), /~ 750 Gbps is leaking through/); + ev("S.scrubs.push({city:'nyc',tier:1});compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 25\.0 Gbps \/ 100G/); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in New York: 750 Gbps \/ 1T/); + assert.deepEqual(errors, []); +}); + +test('scrubbing hauls retain their real source on each link when several cities use one center', () => { + const { ev, errors, dom } = load(); + ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['prg','ber'])ACT.buildPop({city:c}); + for(const c in S.pops)S.pops[c].rgen=3; + S.links=[{id:'fp1',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100}, + {id:'fp2',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100}, + {id:'fb',a:'fra',b:'ber',kind:'wave',tier:2,km:420,mo:100}, + {id:'pb',a:'prg',b:'ber',kind:'wave',tier:2,km:280,mo:100}]; + S.transit=[{id:'tp',city:'prg',net:'cog',tier:2},{id:'tb',city:'ber',net:'cog',tier:2}]; + S.scrubs=[{city:'fra',tier:1}]; + S.ev.ddos={id:'spread',city:'ber',vec:'ack',gbps:100,start:0,until:7, + entries:[{k:'t',id:'tp',city:'prg',share:.5},{k:'t',id:'tb',city:'ber',share:.5}]};compute()`); + const sources = id => JSON.parse(ev(`JSON.stringify(Object.entries(R.ef[edgeKey(S.links.find(l=>l.id==='${id}'))].eg) + .filter(([key])=>key.startsWith('scrub:')).map(([key,g])=>({city:R.egDesc[key].city,g})).sort((a,b)=>a.city.localeCompare(b.city)))`)); + assert.equal(ev('R.load.pb||0'), 0, 'Berlin does not feed the Prague link'); + assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']); + assert.deepEqual(sources('fb').map(x=>x.city), ['ber']); + assert.ok(sources('fp1')[0].g>0 && sources('fb')[0].g>0); + assert.ok(Math.abs(sources('fp1')[0].g-ev('R.load.fp1+R.load.fp2'))<1e-9, 'the grouped record covers both parallel links exactly'); + ev("selectLink('fp1');draw(0)"); + const row = [...dom.window.document.querySelectorAll('#panelBody .row')].find(x=>x.querySelector('.nm')?.textContent==='Attack hauled to scrubbing in Frankfurt'); + assert.ok(row); + assert.match(row.querySelector('.meta').textContent, /^Prague · /); + assert.equal(JSON.parse(row.querySelector('[data-act="goEgress"]').dataset.args).city, 'prg'); + assert.deepEqual(JSON.parse(ev('JSON.stringify([...UI.feed])')), ['prg'], 'the map highlights the same source as the inspected link'); + row.querySelector('[data-act="goEgress"]').click(); + assert.equal(ev('UI.sel.id'), 'prg', 'Open goes to the actual source city'); + // Reordering ingress and adding an overlapping flood must not change the attribution. + ev("S.ev.ddos.entries.reverse();S.ev.ddosMore=[{...S.ev.ddos,id:'overlap',gbps:20,entries:S.ev.ddos.entries.slice().reverse()}];compute()"); + assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']); + assert.deepEqual(sources('fb').map(x=>x.city), ['ber']); + // When Berlin's direct link fails, its haul really does join Prague's route. + ev('S.links.find(l=>l.id==="fb").cut=S.day+1;compute()'); + assert.ok(ev('R.load.pb')>0); + assert.deepEqual(sources('fp1').map(x=>x.city), ['ber','prg']); + assert.deepEqual(sources('pb').map(x=>x.city), ['ber']); + assert.ok(Math.abs(sources('fp1').reduce((n,x)=>n+x.g,0)-ev('R.load.fp1+R.load.fp2'))<1e-9, 'shared-path totals still equal the actual link load'); + assert.deepEqual(errors, []); +}); + +function setupScrubLatency(ev) { + ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['par','nyc','ams'])ACT.buildPop({city:c}); + for(const c in S.pops)S.pops[c].rgen=RG.findIndex(g=>g.fs===1); + S.links=[{id:'pf',a:'par',b:'fra',kind:'wave',tier:3,km:620/1.3,mo:100}, + {id:'fn',a:'fra',b:'nyc',kind:'wave',tier:3,km:6000,mo:100}, + {id:'fa',a:'fra',b:'ams',kind:'wave',tier:3,km:200,mo:100}]; + S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}]; + S.scrubs=[{city:'fra',tier:0},{city:'par',tier:0}]; + S.ev.ddos={id:'par-flood',city:'par',vec:'dns',gbps:33.8,start:0,until:7, + entries:[{k:'t',id:'tf',city:'fra',share:0.65},{k:'t',id:'tn',city:'nyc',share:0.35}]};compute()`); +} + +test('distributed ingress does not give a locally protected victim a remote scrubbing latency', () => { + const { ev, errors, dom } = load(); + setupScrubLatency(ev); + assert.ok(ev("R.haul.some(q=>q.city==='nyc'&&q.to==='par'&&q.ms>60)"), 'the remote ingress still travels to its scrubbing center'); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'both centers clean the distributed flood'); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-20.28)<1e-9); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0); + Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true }); + ev("UI.left='noc';UI.leftOpen=true;renderLeft()"); + const text = dom.window.document.getElementById('left').textContent; + assert.match(text, /Live attack: Paris/); + assert.match(text, /Scrubbing in Frankfurt: 8\.8 Gbps/); + assert.match(text, /Scrubbing in Paris: 4\.7 Gbps/); + assert.doesNotMatch(text, /Scrubbing traffic hauled over your backbone|\+\d+(\.\d+)? ms/); + // A local center is still nearest when it is full and other centers take overflow. + ev("S.ev.ddos.vec='ack';S.ev.ddos.gbps=300;compute()"); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + assert.deepEqual(errors, []); +}); + +test('each attack shows only the nearest scrubbing detour using precise one-way link latency', () => { + const { ev, errors } = load(); + setupScrubLatency(ev); + ev("for(const c in S.pops)S.pops[c].rgen=3;S.scrubs=[{city:'fra',tier:0},{city:'ams',tier:0}];S.ev.ddos.vec='ack';S.ev.ddos.gbps=230;compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'capacity spills between centers'); + const card = ev('ddosOne(S.ev.ddos)'); + assert.equal((card.match(/Scrubbing traffic hauled over your backbone/g)||[]).length, 1); + assert.match(card, /✓ Scrubbing traffic hauled over your backbone: Paris → Frankfurt \(\+3\.1 ms\)/); + // An overlapping attack has its own victim and nearest center. + ev("S.ev.ddosMore=[{id:'other',city:'ams',vec:'ack',gbps:10,start:0,until:7,entries:[{k:'t',id:'tn',city:'nyc',share:1}]}];compute()"); + assert.doesNotMatch(ev('ddosOne(S.ev.ddosMore[0])'), /Scrubbing traffic hauled over your backbone/); + assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Frankfurt \(\+3\.1 ms\)/); + // Ignore a failed nearby center and use the live path to Amsterdam. + ev("S.pops.fra.down=10;S.links.push({id:'pa',a:'par',b:'ams',kind:'wave',tier:3,km:2000,mo:100});S.ev.ddos.entries=[{k:'edge',city:'par',share:1}];compute()"); + assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Amsterdam \(\+13\.0 ms\)/); + ev('S.ev.ddos.bh=true;compute()'); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + ev('S.ev.ddos.bh=false;S.scrubMode="ondemand";compute()'); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + assert.deepEqual(errors, []); +}); + +test('a constrained remote haul leaves scrubbing capacity for the next overlapping flood', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc'])S.pops[c].rgen=3;S.links=[{id:'thin',a:'nyc',b:'fra',kind:'wave',tier:1,km:6000,mo:100}];S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'far',city:'nyc',vec:'http',gbps:600,start:0,until:7};S.ev.ddosMore=[{id:'near',city:'fra',vec:'http',gbps:900,start:0,until:7}];compute()"); + const clean = JSON.parse(ev('JSON.stringify(R.ddos.map(m=>({id:m.attack.id,clean:m.sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0,leak:m.leak})))')); + assert.equal(clean.find(m=>m.id==='near').clean, 900); + assert.ok(clean.find(m=>m.id==='far').clean <= 100); + assert.ok(clean.reduce((n,m)=>n+m.clean,0) <= 1000); + for (const m of clean) assert.equal(m.clean+m.leak, m.id==='near'?900:600); + assert.deepEqual(errors, []); +}); + +test('distributed attack statistics survive an ingress outage and corrupted saved shares', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'a',city:'fra',share:0.25},{k:'t',id:'b',city:'nyc',share:0.75}]};S.pops.nyc.down=5;compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 1000); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 1000); + ev("S.ev.ddos.entries.push({k:'t',id:'bad',city:'unknown',share:5},{k:'t',id:'bad2',city:'fra',share:-1});S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + assert.equal(ev('S.ev.ddos.entries.length'), 2); + assert.equal(ev('S.ev.ddos.entries.reduce((n,en)=>n+en.share,0)'), 1); + assert.deepEqual(errors, []); +}); + +test('RackNet and TeamSpooked require signed gaming customers, bypass Flowspec, and stay within a third of the current size range', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=13;S.pops.fra.bb={d:150000};ACT.buyTransit({city:'fra',net:'cog',tier:2});compute()"); + assert.equal(ev("ddosVectors().includes('racknet')||ddosVectors().includes('teamspooked')"), false); + ev("S.offers=[{type:'game'}]"); + assert.equal(ev("ddosVectors().includes('racknet')"), false, 'an unsigned offer does not introduce gaming attacks'); + ev("S.biz=[{type:'game',id:'gamer',name:'Gamer',city:'fra',bw:0,rate:0}];compute()"); + for (const vec of ['racknet','teamspooked']) { + assert.equal(ev(`DDOS_VEC.${vec}.fs`), false); + const sizeMax = ev('ddosSizeMax()/3'); + ev(`const old=Math.random;let n=0;Math.random=()=>n++===1?(ddosVectors().indexOf('${vec}')+0.5)/ddosVectors().length:0.999999;ddosAttack();Math.random=old`); + assert.equal(ev('ddosAll().at(-1).vec'), vec); + assert.ok(ev('ddosAll().at(-1).gbps') <= sizeMax); + assert.ok(ev('ddosAll().at(-1).gbps') > sizeMax*(1-0.00002), 'the upper randomized quantile approaches the one-third limit, including rare spikes'); + } + ev("S.biz[0].type='cgame'"); + assert.equal(ev("ddosVectors().includes('teamspooked')"), true, 'cloud gaming also attracts these vectors'); + ev('S.biz=[]'); + assert.equal(ev("ddosVectors().includes('teamspooked')"), false); + assert.equal(ev('ddosAll().length'), 2, 'existing attacks finish naturally after the gaming customer leaves'); + assert.deepEqual(errors, []); +}); + +test('normal DDoS starts average half an attack per week without gaming and never exceed a seven-per-week expected rate', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.day=50'); + const checks = JSON.parse(ev(` + const oldAttack=ddosAttack,oldRandom=Math.random,out=[]; + try { + for(const [level,games] of [[1,0],[13,0],[1,1],[13,1],[13,10],[13,1000]]){ + S.lvl=level;S.biz=Array.from({length:games},()=>({type:'game'})); + let starts=0,draw=0;ddosAttack=()=>{starts++};Math.random=()=>((draw++)+0.5)/14000; + for(let day=0;day<7000;day++)ddosTick(); + out.push({level,games,expected:ddosRate(),observed:starts/1000}); + } + } finally {ddosAttack=oldAttack;Math.random=oldRandom;} + JSON.stringify(out) + `)); + for(const row of checks){ + assert.ok(Math.abs(row.observed-row.expected)<=0.0011, JSON.stringify(row)); + if(row.games===0)assert.equal(row.observed,0.5); + else assert.ok(row.expected>0.5&&row.expected<=7); + } + assert.ok(checks[3].expected>checks[2].expected, 'level increases gaming frequency'); + assert.ok(checks[4].expected>checks[3].expected, 'more gaming customers increase frequency'); + assert.ok(checks[3].expected<0.8, 'one gaming customer does not suddenly add several attacks per week, even at the last level'); + assert.deepEqual(errors, []); +}); + +test('normal attack sizes match the one- and fifty-gamer targets while frequency rises gradually', () => { + const { ev, errors } = load(); + ev('ACT.start({})'); + const samples = JSON.parse(ev(` + const oldRandom=Math.random,out=[]; + try { + for(const [level,demand] of [[1,0],[3,1850],[LEVELS.length,LV_REQ.at(-1).pk]]){ + const counts=[]; + for(const games of [0,1,2,5,10,20,50,100,1000]){ + S.lvl=level;S.biz=Array.from({length:games},(_,i)=>({id:'g'+i,type:i%2?'cgame':'game',city:'fra',bw:0,rate:0})); + const vectors=ddosVectors();let sum=0; + for(let i=0;idraw++===1?(i+0.5)/vectors.length:roll; + ddosAttack(false);sum+=weight*S.ev.ddos.gbps; + } + counts.push({games,mean:sum/vectors.length,rate:ddosRate()}); + } + out.push({level,demand,counts}); + } + } finally {Math.random=oldRandom;} + JSON.stringify(out) + `)); + for(const row of samples){ + const [plain,first]=row.counts,fifty=row.counts.find(c=>c.games===50),hundred=row.counts.find(c=>c.games===100),many=row.counts.at(-1); + assert.ok(Math.abs(first.mean-plain.mean*3)<0.003, 'the first gamer triples the overall mean, allowing only bandwidth rounding: '+JSON.stringify(row)); + assert.ok(Math.abs(fifty.mean-plain.mean*8)<0.01, 'fifty gamers bring eightfold sizes, allowing only bandwidth rounding'); + assert.ok(hundred.mean>first.mean*3, 'growth continues across dozens of gaming customers'); + assert.ok(hundred.mean>plain.mean*10 && hundred.mean6 && many.rate<=7); + for(let i=1;irow.counts[i-1].mean, 'each sampled count increases actual spawned attack sizes'); + assert.ok(row.counts[i].rate>row.counts[i-1].rate, 'each sampled count increases frequency'); + } + } + assert.ok(Math.abs(samples[0].counts[0].mean-1)<0.001, 'the minimum-demand baseline still permits small attacks'); + assert.ok(Math.abs(samples[1].counts[0].mean-740/13)<0.001, 'the 1.85 Tbps non-gaming example keeps its average'); + assert.ok(Math.abs(samples[2].counts[0].mean-samples[2].demand*4/3/10)<0.001); + assert.deepEqual(errors, []); +}); + +test('normal attack sizes cover a broad ordinary range and a two-percent large tail without raising the mean', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.lvl=3;S.biz=[];R.demand=1850'); + const distribution = JSON.parse(ev(` + const oldRandom=Math.random,ordinary=[],large=[];let sum=0; + try { + for(let i=0;i<10000;i++){ + Math.random=()=>(i+0.5)/10000; + const g=ddosSize('syn');sum+=g;(g>100?large:ordinary).push(g); + } + } finally {Math.random=oldRandom;} + JSON.stringify({ordinary:{n:ordinary.length,min:Math.min(...ordinary),max:Math.max(...ordinary)}, + large:{n:large.length,min:Math.min(...large),max:Math.max(...large),near500:large.some(g=>g>=490&&g<=510)},mean:sum/10000}) + `)); + assert.equal(distribution.ordinary.n, 9800); + assert.equal(distribution.large.n, 200); + assert.ok(distribution.ordinary.min>=8.9 && distribution.ordinary.min<10); + assert.ok(distribution.ordinary.max>85 && distribution.ordinary.max<=89.1); + assert.ok(distribution.ordinary.max/distribution.ordinary.min>9.9); + assert.ok(distribution.large.min>=356 && distribution.large.max<=535); + assert.ok(distribution.large.near500, 'the example network can occasionally face a roughly 500 Gbps flood'); + assert.ok(Math.abs(distribution.mean-740/13)<0.001, 'the rare tail preserves the previous 56.923 Gbps average'); + // Verify that real spawns use both bands, not just the standalone sampler. + for (const [roll,minimum,maximum] of [[0.49,8.9,89.1],[0.99,356,535]]) { + ev(`S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=1850;const old=Math.random;let n=0;Math.random=()=>{const i=n++;return i===1?(ddosVectors().indexOf('syn')+0.5)/ddosVectors().length:i===2?${roll}:0.5};try{ddosAttack()}finally{Math.random=old}`); + assert.equal(ev('S.ev.ddos.vec'), 'syn'); + assert.ok(ev('S.ev.ddos.gbps')>=minimum && ev('S.ev.ddos.gbps')<=maximum); + } + assert.deepEqual(errors, []); +}); + +test('Flood Season retains its existing size quantiles and escalation when normal attacks gain rare spikes', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.scn={id:'flood',rules:{ddos:true}};S.lvl=3;S.biz=[];R.demand=1850"); + for (const [day,expected] of [[0,[700,1400,2099]],[365,[1400,2800,4199]],[730,[2100,4200,6299]]]) { + ev(`S.day=${day}`); + const actual = JSON.parse(ev("const old=Math.random;let sizes;try{sizes=[0,0.5,0.999999].map(r=>{Math.random=()=>r;return ddosSize('syn')})}finally{Math.random=old}JSON.stringify(sizes)")); + assert.deepEqual(actual, expected); + } + assert.deepEqual(errors, []); +}); diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index a5c557c..52e6af4 100644 --- a/tests/helpers/reference-allocation.js +++ b/tests/helpers/reference-allocation.js @@ -5,8 +5,8 @@ module.exports = ` for(f of flows){ if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue; Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++; - const candidates=E.filter(e=>e.usede.used(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]); for(let i=0;i1e-6;){ let j=i+1;while(j= 3, 'starts with bigger gear unlocked'); // a few weeks in: several attacks start on their own schedule let n = 0; - for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('!!(S.ev.ddos&&S.ev.ddos.start===S.day)')) n++; } + for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('ddosAll().some(a=>a.start===S.day)')) n++; } assert.ok(n >= 4, `attacks keep coming (${n} in 40 days)`); assert.ok(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)') >= 3, 'finished attacks are scored'); // scoring: held only if service stayed at 97%+ @@ -468,3 +468,27 @@ test('RouteScript: help, ready-made scripts and the AI button', () => { ev("UI.dtab='overview';renderAll()"); assert.deepEqual(errors, []); }); + + +test('Flood Season keeps attacking and escalating after both success and timeout', () => { + for (const outcome of ['done', 'failed']) { + const { ev, errors, dom } = load(); + ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9"); + if (outcome === 'done') ev('S.stats.ddosOk=20;S.stats.ddosOkBig=5;S.day=100'); + else ev('S.day=365'); + ev('scnTick(S.day)'); + assert.ok(ev(`!!S.scn.${outcome}`)); + assert.ok([...dom.window.document.querySelectorAll('#modal [data-act="closeModal"]')].some(b=>b.textContent==='Keep playing')); + ev('ACT.closeModal();S.scn.nextDdos=S.day+1;dayTick()'); + assert.equal(ev('S.ev.ddos.start'), ev('S.day'), 'Keep playing still spawns attacks'); + const before = ev('S.day'); + ev('S.scn.nextDdos=S.day+1;S.day+=8;dayTick()'); + assert.ok(ev('ddosAll().at(-1).start') > before, 'subsequent attacks keep coming'); + const gaps = JSON.parse(ev('const old=Math.random;Math.random=()=>0.5;S.day=0;const early=floodGap();S.day=1000;const late=floodGap();Math.random=old;JSON.stringify([early,late])')); + assert.ok(gaps[1] < gaps[0], 'frequency keeps increasing with scenario age'); + const sizes = JSON.parse(ev('const old=Math.random;Math.random=()=>0.9;S.day=0;ddosAttack();const early=ddosAll().at(-1).gbps;S.day=1000;ddosAttack();const late=ddosAll().at(-1).gbps;Math.random=old;JSON.stringify([early,late])')); + assert.ok(sizes[1] > sizes[0], 'intensity keeps increasing with scenario age'); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); diff --git a/tests/routing-reference.test.js b/tests/routing-reference.test.js index 8742007..8a239ad 100644 --- a/tests/routing-reference.test.js +++ b/tests/routing-reference.test.js @@ -38,6 +38,7 @@ test('indexed routing matches the simple allocation loop across network changes' "S.te.script='prefer transit Cogentle\\nprepend transit Cogentle 2\\nprotect customers'", "S.ev.rpki={nets:['ggl','nfx'],until:S.day+3};S.ev.depeer=S.day+3", "S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}", + "S.ev.ddos.entries=[{k:'t',id:'transit0',city:'fra',share:.4},{k:'t',id:'transit4',city:'nyc',share:.6}]", "S.links[0].eqDown=S.day+2;S.links[1].cut=S.day+2;S.links[2].loss={until:S.day+2,f:0.5}", "S.links[4].chFail={until:S.day+2,o:'tp16'};S.links[6].ch.push('zr4');S.links[8].regen=2", "S.day+=4;S.pni.splice(0,20);S.caches.splice(0,10);S.transit[0].pref='high'", diff --git a/tests/services.test.js b/tests/services.test.js index 5379cdc..9ba8bc5 100644 --- a/tests/services.test.js +++ b/tests/services.test.js @@ -9,6 +9,30 @@ function network(ev) { ev("const L=(a,b,t,v)=>{UI.via=v||null;openLinkModal(a,b);ACT.buildLink({tier:t});};L('fra','ams',3);L('fra','par',3);L('ams','lon',2,'uly');closeModal()"); } +test('gaming offers and signed customers show their DDoS risk in Deals, city panels and customer lists', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.offers=['game','cgame','host'].map(type=>({id:type,city:'fra',name:type,bw:5,rate:100,reqs:[],exp:S.day+30,type}));UI.left='deals';UI.leftOpen=true;renderLeft()"); + const notes = (root, action) => { + const buttons = [...root.querySelectorAll(`[data-act="${action}"]`)]; + assert.equal(buttons.length, 3); + for (const button of buttons) { + const id = JSON.parse(button.dataset.args).id; + const count = (button.closest('.row').textContent.match(/Gaming attracts attacks/g)||[]).length; + assert.equal(count, id==='game'||id==='cgame'?1:0, `risk note for ${id}`); + } + }; + assert.equal(ev('gamingCount()'), 0, 'offers disclose future risk before signing'); + notes(dom.window.document.getElementById('leftBody'), 'accept'); + ev("selectCity('fra');ACT.tab({t:'cust'})"); + notes(dom.window.document.getElementById('panelBody'), 'accept'); + ev("for(const id of ['game','cgame','host'])ACT.accept({id});UI.tab='cust';renderPanel()"); + assert.equal(ev('gamingCount()'), 2, 'the note uses the same customer classification as the attack calculation'); + notes(dom.window.document.getElementById('panelBody'), 'dropBiz'); + ev('ACT.custOpen({})'); + notes(dom.window.document.getElementById('custSec'), 'custGo'); + assert.deepEqual(errors, []); +}); + test('event networks pay in full when the crowd is served, nothing up front', () => { const { ev, errors } = load(); seed(ev, 4); From 925e7c1798eb335aa2b85ea157f68f1d6507c160 Mon Sep 17 00:00:00 2001 From: Filip Hruska Date: Tue, 27 Oct 2026 10:15:33 +0000 Subject: [PATCH 06/64] rewrite changelog --- CHANGELOG.md | 31 +++++++------------------------ 1 file changed, 7 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df9f47c..0294568 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,36 +6,19 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels, Open buttons or map highlights. - -- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. Local scrubbing adds no backbone-haul line, and distributed ingress no longer produces unrelated or repeated latency messages. - -- The NOC no longer shows the generic attack-rate note for networks without gaming customers. - -- Gaming customers now scale normal-mode DDoS sizes from three times the no-gaming average with one customer to eight times with 50. Adding more gamers continues to increase attack sizes, while frequency still rises gradually toward seven attacks per week. Flood Season keeps its existing escalation. - -- Normal-mode DDoS attacks now vary much more in size, with a 2% chance of a much larger flood. The long-run average still scales with demand, customer level and gaming customers; Flood Season keeps its existing size distribution and escalation. - +- Attacks are now more common and dynamic in nature to bring some more excitement. +- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels. +- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. - Game server and cloud gaming customers now carry a “Gaming attracts attacks” note on their offers and customer lists, so you can see the DDoS risk before signing them. - - Live attacks now show how much traffic Flowspec actually drops at the ingress routers. Routers without TCAM no longer claim to filter attacks, mixed router capabilities are called out, and Flowspec drops are counted separately from other edge filters. - -- Normal networks without gaming customers now average half a DDoS attack per week, with attacks ten times smaller than the ordinary baseline. Gaming customers gradually raise attack sizes and the expected rate toward seven attacks per week as your level and customer count grow. The size calculation accounts for the smaller RackNet and TeamSpooked floods so signing a gamer increases the overall average size. Flood Season keeps its separate escalation. - -- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec, and their size stays within one third of the ordinary attack range at your current scale. - -- Gaming customers bring larger, longer and more frequent DDoS attacks as your level and customer count grow, with overlapping floods, at most 14 starts in any seven days and durations up to seven days. Attacks arrive across transit and peering ports in different regions, following normal traffic shares. Attack bandwidth grows with the whole network, with no fixed bandwidth ceiling. - +- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec and require dedicated mitigation. - Flood Season keeps sending larger, more frequent attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off. - -- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through in its existing status lines. Bandwidth uses the usual Gbps and Tbps units, with no duplicate summary. “After upstream scrubbing” appears only while upstream scrubbing is active. Scrubbing lines show the city, current use and compact capacity, such as “Scrubbing in Frankfurt: 30.2 Gbps / 100G”. - +- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through. - DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center. - -- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter needs other defences. - +- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation. - Pick a peering policy in the peering inbox: Open to all, Selective or Closed. Open accepts every request and keeps the route servers; Selective gets fewer requests but you answer them yourself and request peers at each exchange, without route servers; Closed gets no requests, and customers hear you are hard to reach. The inbox also gets a button to raise all max-prefix limits at once. - Brazil is slimmer: 15 small cities that sat right next to bigger ones are gone from new games, leaving 25 in Brazil. A small city no longer crowds a bigger one in the same country unless it is a cable landing or a capital. Saved games keep their POPs in those cities, and the Order and Progress scenario now asks for 15 IX.brrr ports instead of 20. + ## [1.33.0] — 2026-10-27 - Australia arrives: start in Sydney on hard mode. Expensive transit, a national network that keeps 45% of every broadband bill, real Australian exchanges and carriers, Adelaide, Canberra, Hobart and the South Island of New Zealand, new cables, very Australian outages and a new scenario, Fibre to the Basement. Older saves with Australian POPs are told once what changed. From 66ae4be72d5bfaa8a47dfef372ed3ca5beca395a Mon Sep 17 00:00:00 2001 From: LookedPath <2457111+LookedPath@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:30:20 +0000 Subject: [PATCH 07/64] Add editable optic counts to fiber link panels --- CHANGELOG.md | 2 + site/i18n/es.js | 4 ++ site/i18n/fr.js | 4 ++ site/i18n/it.js | 4 ++ site/i18n/pt.js | 4 ++ src/game/90-actions/88-optic-counts.js | 27 +++++++++ src/game/93-ui/70-link-panels.js | 2 +- src/game/93-ui/75-optic-counts.js | 20 +++++++ src/i18n/en.js | 4 ++ src/styles/35-optic-counts.css | 4 ++ tests/optic-counts.test.js | 81 ++++++++++++++++++++++++++ 11 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 src/game/90-actions/88-optic-counts.js create mode 100644 src/game/93-ui/75-optic-counts.js create mode 100644 src/styles/35-optic-counts.css create mode 100644 tests/optic-counts.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 3465c68..5a1b699 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf. + - Yellow progress bars are slim again, like the green and red ones, instead of padded boxes. - São Paulo's exchange is now called IX.brrr São Paulo, like every other Brazilian exchange (#166). - Sponsor a conference: some peering meetings sell sponsorships, and while the glow lasts more customers from that region come knocking (#168). diff --git a/site/i18n/es.js b/site/i18n/es.js index f7dea85..23f66b0 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2348,6 +2348,10 @@ "notifications.n_min_ago":{"one":"hace {n} min","other":"hace {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Nada en los últimos 10 minutos.", "notifications.show_all_n":"Mostrar las {n}", +"optic_counts.apply_price":"Aplicar · {price}", +"optic_counts.count_for_model":"Número de canales {model}", +"optic_counts.only_n_channels_free":"Solo quedan {n} canales libres en esta fibra.", +"optic_counts.target_count":"Cantidad deseada", "own_cable.a_and_b":"{a} y {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"Una flota pesquera está faenando justo donde necesitas tender.", "own_cable.a_leased_wave_wave_on_this":"Una onda {wave} alquilada en esta ruta cuesta {price}/mes.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4342c28..d9a31c3 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2348,6 +2348,10 @@ "notifications.n_min_ago":{"one":"il y a {n} min","other":"il y a {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Rien ces 10 dernières minutes.", "notifications.show_all_n":"Tout afficher ({n})", +"optic_counts.apply_price":"Appliquer · {price}", +"optic_counts.count_for_model":"Nombre de canaux {model}", +"optic_counts.only_n_channels_free":"Il ne reste que {n} canaux libres sur cette fibre.", +"optic_counts.target_count":"Quantité souhaitée", "own_cable.a_and_b":"{a} et {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"Une flotte de chalutiers drague pile là où tu dois poser.", "own_cable.a_leased_wave_wave_on_this":"Une longueur d’onde {wave} louée sur ce parcours coûte {price}/mois.", diff --git a/site/i18n/it.js b/site/i18n/it.js index db5ff27..1054518 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2348,6 +2348,10 @@ "notifications.n_min_ago":{"one":"{n} min fa","other":"{n} min fa"}, "notifications.nothing_in_the_last_10_minutes":"Niente negli ultimi 10 minuti.", "notifications.show_all_n":"Mostra tutte e {n}", +"optic_counts.apply_price":"Applica · {price}", +"optic_counts.count_for_model":"Numero di canali {model}", +"optic_counts.only_n_channels_free":"Su questa fibra sono liberi solo {n} canali.", +"optic_counts.target_count":"Quantità desiderata", "own_cable.a_and_b":"{a} e {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"Una flotta di pescherecci sta strascicando proprio dove devi posare.", "own_cable.a_leased_wave_wave_on_this":"Una wave da {wave} in affitto su questa tratta costa {price}/mese.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index b474374..f0f4baf 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2348,6 +2348,10 @@ "notifications.n_min_ago":{"one":"há {n} min","other":"há {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Nada nos últimos 10 minutos.", "notifications.show_all_n":"Mostrar todas as {n}", +"optic_counts.apply_price":"Aplicar · {price}", +"optic_counts.count_for_model":"Número de canais {model}", +"optic_counts.only_n_channels_free":"Só há {n} canais livres nesta fibra.", +"optic_counts.target_count":"Quantidade desejada", "own_cable.a_and_b":"{a} e {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"Uma frota pesqueira está arrastando redes bem onde você precisa lançar.", "own_cable.a_leased_wave_wave_on_this":"Uma wave de {wave} alugada nesta rota custa {price}/mês.", diff --git a/src/game/90-actions/88-optic-counts.js b/src/game/90-actions/88-optic-counts.js new file mode 100644 index 0000000..62d1e91 --- /dev/null +++ b/src/game/90-actions/88-optic-counts.js @@ -0,0 +1,27 @@ +// Quote the whole change before spending: shelf optics still need regen cards. +function opticCountCost(l,o,n){ + const add=Math.max(0,n-(l.ch||[]).filter(k=>k===o).length),sp=Math.min(add,spareN(o)),r=REGEN_CH*(l.regen|0),c=optCost(o); + return sp*Math.round(c*r)+(add-sp)*Math.round(c*(1+r)); +} +Object.assign(ACT,{ + setChCount:({id,o,n})=>{ + const l=S.links.find(x=>x.id===id); + if(!l||l.kind!=='df'||!own(OPT,o)||!Number.isSafeInteger(n)||n<0||n>chMax(l))return; + const old=(l.ch||[]).filter(k=>k===o).length,d=n-old; + if(!d)return; + if(d>0){ + const why=chWhy(l,o); + if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + const free=chMax(l)-(l.ch||[]).length-soldSlots(l); + if(d>free){toast(tr('optic_counts.only_n_channels_free',{n:free}),'bad');sfx('err');return;} + if(!portGate(l.a,d)||!portGate(l.b,d)||!spend(opticCountCost(l,o,n)))return; + const sp=Math.min(d,spareN(o));if(sp)S.spares[o]-=sp; + (l.ch=l.ch||[]).push(...Array(d).fill(o)); + }else{ + let left=-d;l.ch=l.ch.filter(k=>k!==o||left--<=0); + S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)-d; + } + if(UI.opticCounts)delete UI.opticCounts[JSON.stringify([id,o])]; + after(); + }, +}); diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 19b6eb7..e37ea26 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -81,7 +81,7 @@ function dfPanel(l){ if(l.own&&l.sub)h+=subUpgradePanel(l); for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k); const md=optMode(k,l),cc=chCost(l,k),sp=spareN(k); - h+=`
${O.n} ${optModes(k,l).map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')}
${esc(O.blurb)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${sp?` · ${trn('link_panels.n_spare_on_the_shelf',sp)}`:''}
${md&&!md.full?`
⚠️ ${tr('link_panels.runs_at_g_per_channel_on',{g:fmtG(md.g)})} ${!l.sub&®enNeed(k,l)>(l.regen|0)?trn('link_panels.n_regen_site_would_bring_it',regenNeed(k,l),{g:fmtG(O.g)}):''}
`:''}${why?`
${esc(why)}
`:''}
${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(sp?`+ ${cc?tr('link_panels.spare_price',{price:fmt$(cc)}):tr('common.spare')}`:`+ ${fmt$(cc)}`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash`;} + h+=`
${O.n} ${optModes(k,l).map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')}
${esc(O.blurb)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${sp?` · ${trn('link_panels.n_spare_on_the_shelf',sp)}`:''}
${md&&!md.full?`
⚠️ ${tr('link_panels.runs_at_g_per_channel_on',{g:fmtG(md.g)})} ${!l.sub&®enNeed(k,l)>(l.regen|0)?trn('link_panels.n_regen_site_would_bring_it',regenNeed(k,l),{g:fmtG(O.g)}):''}
`:''}${why?`
${esc(why)}
`:''}${opticCountControl(l,k,n)}
${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(sp?`+ ${cc?tr('link_panels.spare_price',{price:fmt$(cc)}):tr('common.spare')}`:`+ ${fmt$(cc)}`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash`;} {const st=Object.keys(OPT).filter(k=>spareN(k)>0);h+=`

${tr('link_panels.unplugged_optics_go_on_the_spares')}

`; {const used=[...new Set(l.ch||[])].filter(k=>OPT[k]&&OPT[k].lvl<=lvl());if(used.length)h+=`
${used.map(k=>btn(tr('link_panels.stock_a_spare_optic_price',{optic:OPT[k].n,price:fmt$(optCost(k))}),'buySpare',{o:k},'ghost sm',S.cash=64)).join('')}

${tr('link_panels.spares_bought_now_are_already_paid')}

`;}if(st.length)h+=`

${tr('common.spares_shelf')}

`+st.map(k=>`
${spareN(k)} × ${OPT[k].n}
${btn(tr('link_panels.sell_one_price',{price:fmt$(spareValue(k))}),'sellSpare',{o:k},'ghost sm')}
`).join('');} const rg=l.regen|0,rgAdd=REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH); diff --git a/src/game/93-ui/75-optic-counts.js b/src/game/93-ui/75-optic-counts.js new file mode 100644 index 0000000..35fe1cf --- /dev/null +++ b/src/game/93-ui/75-optic-counts.js @@ -0,0 +1,20 @@ +function opticCountControl(l,o,n){ + const key=JSON.stringify([l.id,o]);let draft=UI.opticCounts&&UI.opticCounts[key]; + if(draft&&draft.base!==n){delete UI.opticCounts[key];draft=null;} + const v=draft?draft.n:n,value=draft?draft.value:n; + const price=Number.isSafeInteger(v)&&v>=0&&v<=chMax(l)?opticCountCost(l,o,v):0; + return `
`; +} +document.addEventListener('input',e=>{ + const f=e.target.closest('form.optic-count');if(!f||!S)return; + const l=S.links.find(x=>x.id===f.dataset.link),o=f.dataset.optic,n=f.elements.count.valueAsNumber; + if(!l||!own(OPT,o))return; + UI.opticCounts=UI.opticCounts||{};UI.opticCounts[JSON.stringify([l.id,o])]={base:(l.ch||[]).filter(k=>k===o).length,n,value:e.target.value}; + e.target.setAttribute('value',e.target.value); + f.querySelector('button').textContent=tr('optic_counts.apply_price',{price:fmt$(Number.isSafeInteger(n)&&n>=0&&n<=chMax(l)?opticCountCost(l,o,n):0)}); +}); +document.addEventListener('submit',e=>{ + const f=e.target.closest('form.optic-count');if(!f)return;e.preventDefault(); + if(!S||!f.reportValidity()||!$('modal').hidden)return; + ACT.setChCount({id:f.dataset.link,o:f.dataset.optic,n:f.elements.count.valueAsNumber}); +}); diff --git a/src/i18n/en.js b/src/i18n/en.js index 86aae1c..2d9cd0b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2349,6 +2349,10 @@ "notifications.n_min_ago":{"one":"{n} min ago","other":"{n} min ago"}, "notifications.nothing_in_the_last_10_minutes":"Nothing in the last 10 minutes.", "notifications.show_all_n":"Show all {n}", +"optic_counts.apply_price":"Apply · {price}", +"optic_counts.count_for_model":"Number of {model} channels", +"optic_counts.only_n_channels_free":"Only {n} channels are free on this fiber.", +"optic_counts.target_count":"Target count", "own_cable.a_and_b":"{a} and {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"A fishing fleet is trawling exactly where you need to lay.", "own_cable.a_leased_wave_wave_on_this":"A leased {wave} wave on this route costs {price}/mo.", diff --git a/src/styles/35-optic-counts.css b/src/styles/35-optic-counts.css new file mode 100644 index 0000000..6690821 --- /dev/null +++ b/src/styles/35-optic-counts.css @@ -0,0 +1,4 @@ +.optic-count{display:flex;flex-wrap:wrap;align-items:end;gap:8px;margin-top:8px} +.optic-count label{display:flex;flex-direction:column;gap:3px;font-size:12px;font-weight:800} +.optic-count input.t{width:88px;font-size:16px;min-height:44px} +.optic-count .b{min-height:44px} diff --git a/tests/optic-counts.test.js b/tests/optic-counts.test.js new file mode 100644 index 0000000..1e85f3f --- /dev/null +++ b/tests/optic-counts.test.js @@ -0,0 +1,81 @@ +const test=require('node:test'); +const assert=require('node:assert/strict'); +const {load}=require('./harness'); +function setup(ev,sub=false){ev(`ACT.start({});S.cash=1e9;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0; + S.pops.fra.rgen=mainRG(4);S.pops.fra.routers=16;S.pops.ams={...S.pops.fra}; + S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sub:${sub},sys:'roadm',km:400,ch:[],ready:0,day:0,cut:0,mo:1}]; + UI.sel={type:'link',id:'fiber'};renderPanel();`);} +const count=ev=>ev('S.links[0].ch.length'); +for(const sub of [false,true])test(`typed counts buy and remove optics on ${sub?'subsea':'land'} fiber`,()=>{ + const {ev,dom,errors}=load();try{ + setup(ev,sub);const doc=dom.window.document; + const f=doc.querySelector('form.optic-count[data-optic="zr4"]'),input=f.elements.count; + input.focus();input.value='5';input.dispatchEvent(new dom.window.Event('input',{bubbles:true})); + const cost=ev("5*chCost(S.links[0],'zr4')"),cash=ev('S.cash'); + assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`))); + ev('S.day++;renderPanel()'); + assert.equal(doc.activeElement,input,'tick preserves the focused field');assert.equal(input.value,'5'); + assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`))); + f.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true})); + assert.equal(count(ev),5);assert.equal(cash-ev('S.cash'),cost); + ev("ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),2);assert.equal(ev('S.spares.zr4'),3); + const before=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),5);assert.equal(ev('S.cash'),before);assert.equal(ev('S.spares.zr4'),0); + ev("ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(count(ev),0);assert.equal(ev('S.spares.zr4'),5); + assert.deepEqual(errors,[]); + }finally{dom.window.close();} +}); +test('batch price matches individual channel purchases with spares, regen cards and tariffs',()=>{ + const {ev,dom}=load();try{setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20"); + const expected=ev("2*Math.round(optCost('zr4')*REGEN_CH*2)+3*Math.round(optCost('zr4')*(1+REGEN_CH*2))"); + assert.equal(ev("opticCountCost(S.links[0],'zr4',5)"),expected); + const cash=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(cash-ev('S.cash'),expected); + setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20");const cash2=ev('S.cash'); + ev("for(let i=0;i<5;i++)ACT.addCh({id:'fiber',o:'zr4'})");assert.equal(cash2-ev('S.cash'),expected); + }finally{dom.window.close();} +}); +test('unaffordable batches, port limits and invalid input never partially change state',()=>{ + const {ev,dom}=load();try{setup(ev);ev('S.cash=1'); + ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),0);assert.equal(ev('S.cash'),1); + ev('S.cash=1e9;S.pops.ams.routers=1');const max=ev("Math.floor(portsMax('ams')-portsUsed('ams'))"); + ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${max+1}})`);assert.equal(count(ev),0);assert.equal(ev('S.cash'),1e9); + ev('S.pops.ams.routers=16'); + for(const n of ['NaN','Infinity','-1','1.5','65',"'3'"]){ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${n}})`);assert.equal(count(ev),0);} + ev("ACT.setChCount({id:'missing',o:'zr4',n:2});ACT.setChCount({id:'fiber',o:'missing',n:2})");assert.equal(ev('S.cash'),1e9); + }finally{dom.window.close();} +}); +test('channel reservations and reach, line-system, level and router compatibility still apply',()=>{ + const {ev,dom}=load();try{setup(ev); + ev("S.links[0].ch=Array(63).fill('zr8');ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),63); + setup(ev);ev("S.biz.push({type:'wwave',link:'fiber',slots:63});ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.links[0].km=20000;ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.links[0].sys='lite';ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.lvl=1;S.done={};ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.pops.ams.rgen=0;ACT.setChCount({id:'fiber',o:'tp32',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.links[0].ch=['zr4','zr8','zr4'];ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(ev("JSON.stringify(S.links[0].ch)"),'["zr8"]'); + }finally{dom.window.close();} +}); +test('plus and minus buttons work alongside typed counts',()=>{ + const {ev,dom,errors}=load();try{setup(ev);const doc=dom.window.document; + const plus=()=>[...doc.querySelectorAll('[data-act="addCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4'); + const minus=()=>[...doc.querySelectorAll('[data-act="rmCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4'); + const input=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input'); + plus().click();assert.equal(count(ev),1);assert.equal(input().value,'1'); + input().value='4';input().dispatchEvent(new dom.window.Event('input',{bubbles:true})); + input().form.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true})); + assert.equal(count(ev),4);minus().click();assert.equal(count(ev),3);assert.equal(input().value,'3'); + plus().click();assert.equal(count(ev),4);assert.equal(input().value,'4');assert.deepEqual(errors,[]); + }finally{dom.window.close();} +}); + +test('draft counts and quotes stay together when reopening a panel or using shortcuts',()=>{ + const {ev,dom}=load();try{setup(ev);const doc=dom.window.document; + const field=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input'); + field().value='5';field().dispatchEvent(new dom.window.Event('input',{bubbles:true})); + ev("UI.sel=null;renderPanel();$('panelBody').innerHTML='';UI.sel={type:'link',id:'fiber'};renderPanel()"); + assert.equal(field().value,'5'); + ev("ACT.addCh({id:'fiber',o:'zr4'});ACT.rmCh({id:'fiber',o:'zr4'})"); + assert.equal(field().value,'0');assert.ok(field().form.querySelector('button').textContent.includes(ev('fmt$(0)'))); + field().value='';field().dispatchEvent(new dom.window.Event('input',{bubbles:true}));ev('S.day++;renderPanel()'); + assert.equal(field().value,'','empty in-progress entry survives a tick'); + }finally{dom.window.close();} +}); From 4932b3f93a786fb29c574a374d9eebf65ceecfec Mon Sep 17 00:00:00 2001 From: logfro Date: Wed, 28 Oct 2026 01:44:17 +0100 Subject: [PATCH 08/64] Add bulk PNI ordering across networks and POPs Add two actions to the NOC Traffic tab: - Order PNIs with one network at every shared POP. - Order PNIs with all eligible networks at every shared POP, including long-tail peers. Both actions offer a selectable port size and preview new connections, upgrades, total setup costs, additional monthly charges and blocked sites. Upgrade smaller PNIs while preserving larger connections, pending orders and existing LAG members. Reserve router capacity across the batch and account for pending speed and LAG augments to avoid overbooking ports. Require the full setup budget before placing any orders. Reuse normal peering policies, minimum port sizes and provisioning delays, then recompute and save once for the entire batch. Keep large global previews compact with collapsible network and blocked-connection lists. Translate the new UI into all five supported languages and add tests for single-network and global ordering, capacity, budgets, repeated clicks, save migration, and mobile keyboard interaction. Validation: - Build and translation checks pass. - 308 of 309 tests pass. The existing subsea reach test also fails on origin/main because the Windows locale uses a dot as the thousands separator where the assertion expects a comma. - Chromium desktop and phone checks pass with the supplied save. - Big-network benchmark against origin/main: dashboard tabs take 16.8 -> 17.6 ms on desktop and 77.1 -> 80.7 ms on a simulated phone (median of 15 runs). Routing results are identical, with no slowdowns beyond the benchmark's noise threshold. --- CHANGELOG.md | 2 + site/i18n/es.js | 20 +++ site/i18n/fr.js | 20 +++ site/i18n/it.js | 20 +++ site/i18n/pt.js | 20 +++ src/game/70-rules/35-pni-orders.js | 23 +++ .../90-actions/40-sites-peering-caches.js | 12 +- src/game/94-dashboard/60-dashboard.js | 3 +- src/game/95-modals/35-pni-all.js | 19 +++ src/i18n/en.js | 20 +++ tests/pni-all.test.js | 155 ++++++++++++++++++ tests/pni-global.test.js | 135 +++++++++++++++ 12 files changed, 442 insertions(+), 7 deletions(-) create mode 100644 src/game/70-rules/35-pni-orders.js create mode 100644 src/game/95-modals/35-pni-all.js create mode 100644 tests/pni-all.test.js create mode 100644 tests/pni-global.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0094b5d..40263ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Order PNIs with one network or every network at all shared POPs from the NOC Traffic tab: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. + ## [1.35.0] — 2026-10-27 - Series of Tubes now speaks Spanish. The game follows your browser's language the first time, and you can switch to Spanish under Settings or on the title screen. diff --git a/site/i18n/es.js b/site/i18n/es.js index 16f2a3c..06a16dd 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Probaron un peer remoto una vez. Osciló durante un lanzamiento de producto. Nunca más.", "pitcairn.uk_grant_mo":"Subvención británica {mo}/mes", "pitcairn.uk_grant_mo_once_islanders":"Subvención británica {mo}/mes cuando los isleños estén en línea", +"pni_all.additional_per_month":"Coste mensual adicional", +"pni_all.all_at_port":"Peering con todas las redes · {port}", +"pni_all.delivery_and_traffic_charges":"Los plazos de entrega varían según la red. También se aplican cargos de peering basados en el tráfico cuando corresponda.", +"pni_all.n_blocked_connections":{"one":"{n} conexión no disponible","other":"{n} conexiones no disponibles"}, +"pni_all.n_blocked_pops":{"one":"{n} POP no disponible","other":"{n} POP no disponibles"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existente o pedido pendiente se mantiene sin cambios.","other":"{n} PNI existentes o pedidos pendientes se mantienen sin cambios."}, +"pni_all.n_networks":{"one":"{n} red","other":"{n} redes"}, +"pni_all.n_of_total_connections":"{n} / {total} conexiones", +"pni_all.n_of_total_pops":"{n} / {total} POP en común", +"pni_all.n_orders_with_net":{"one":"{n} pedido de PNI realizado con {net}. Sin cambios: {kept}; no disponibles: {blocked}.","other":"{n} pedidos de PNI realizados con {net}. Sin cambios: {kept}; no disponibles: {blocked}."}, +"pni_all.new_and_upgrades":"Nuevos: {fresh} · Ampliaciones: {up}", +"pni_all.no_shared_locations":"No hay POP en común disponibles.", +"pni_all.no_shared_pops":"No tienes POP en común con esta red.", +"pni_all.order_missing_and_upgrade_smaller":"Pide los PNI que faltan y amplía los más pequeños en los POP en común. Los PNI mayores y los pedidos pendientes se mantienen sin cambios. Se omiten los POP no disponibles.", +"pni_all.peer_all_networks":"Peering con todas las redes en todos los POP", +"pni_all.peer_at_port":"Peering en todos los POP · {port}", +"pni_all.peer_on_all_pops":"Peering en todos los POP", +"pni_all.pni_size":"Capacidad del PNI", +"pni_all.setup_total":"Coste total de instalación", +"pni_all.traffic_charges_apply":"También se aplican cargos de tráfico de {price} por Gbps.", "pnis.a_new_region_is_coming_online":"Pronto se pondrá en marcha una región nueva. Lleva poniéndose en marcha pronto desde 2019.", "pnis.about_n_days_to_go_nothing":"Faltan unos {n} días. No queda más que esperar, o perseguirlo.", "pnis.augment_with_net_delivered_in_city":"Ampliación con {net} entregada en {city}.
Ahora {port}.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4e674bf..882a336 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Ils ont essayé un peer distant, une fois. Il a flappé pendant un lancement de produit. Plus jamais.", "pitcairn.uk_grant_mo":"Subvention britannique {mo}/mois", "pitcairn.uk_grant_mo_once_islanders":"Subvention britannique {mo}/mois une fois les insulaires en ligne", +"pni_all.additional_per_month":"Coût mensuel supplémentaire", +"pni_all.all_at_port":"Peering avec tous les réseaux · {port}", +"pni_all.delivery_and_traffic_charges":"Les délais de livraison varient selon le réseau. Des frais de peering liés au trafic s'appliquent aussi lorsque le réseau l'exige.", +"pni_all.n_blocked_connections":{"one":"{n} connexion indisponible","other":"{n} connexions indisponibles"}, +"pni_all.n_blocked_pops":{"one":"{n} POP indisponible","other":"{n} POP indisponibles"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existant ou commande en attente reste inchangé.","other":"{n} PNI existants ou commandes en attente restent inchangés."}, +"pni_all.n_networks":{"one":"{n} réseau","other":"{n} réseaux"}, +"pni_all.n_of_total_connections":"{n} / {total} connexions", +"pni_all.n_of_total_pops":"{n} / {total} POP en commun", +"pni_all.n_orders_with_net":{"one":"{n} commande de PNI passée avec {net}. Inchangés : {kept} ; indisponibles : {blocked}.","other":"{n} commandes de PNI passées avec {net}. Inchangés : {kept} ; indisponibles : {blocked}."}, +"pni_all.new_and_upgrades":"Nouveaux : {fresh} · Augmentations : {up}", +"pni_all.no_shared_locations":"Aucun POP en commun disponible.", +"pni_all.no_shared_pops":"Tu n'as aucun POP en commun avec ce réseau.", +"pni_all.order_missing_and_upgrade_smaller":"Commande les PNI manquants et augmente la capacité des plus petits dans les POP en commun. Les PNI plus grands et les commandes en attente restent inchangés. Les POP indisponibles sont ignorés.", +"pni_all.peer_all_networks":"Peering avec tous les réseaux sur tous les POP", +"pni_all.peer_at_port":"Peering sur tous les POP · {port}", +"pni_all.peer_on_all_pops":"Peering sur tous les POP", +"pni_all.pni_size":"Capacité du PNI", +"pni_all.setup_total":"Coût total d'installation", +"pni_all.traffic_charges_apply":"Des frais de trafic de {price} par Gbps s'appliquent également.", "pnis.a_new_region_is_coming_online":"Une nouvelle région arrive bientôt. Elle arrive bientôt depuis 2019.", "pnis.about_n_days_to_go_nothing":"Encore environ {n} jours. Rien à faire qu’attendre, ou relancer.", "pnis.augment_with_net_delivered_in_city":"Extension avec {net} livrée à {city}.
Désormais {port}.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 83a3693..6ad0307 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Hanno provato un peer remoto, una volta. Ha flappato durante il lancio di un prodotto. Mai più.", "pitcairn.uk_grant_mo":"Contributo UK {mo}/mese", "pitcairn.uk_grant_mo_once_islanders":"Contributo UK {mo}/mese quando gli isolani saranno online", +"pni_all.additional_per_month":"Costo mensile aggiuntivo", +"pni_all.all_at_port":"Peering con tutte le reti · {port}", +"pni_all.delivery_and_traffic_charges":"I tempi di consegna variano secondo la rete. Si applicano anche costi di peering basati sul traffico, dove previsti.", +"pni_all.n_blocked_connections":{"one":"{n} connessione non disponibile","other":"{n} connessioni non disponibili"}, +"pni_all.n_blocked_pops":{"one":"{n} POP non disponibile","other":"{n} POP non disponibili"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI esistente o ordine in attesa resta invariato.","other":"{n} PNI esistenti o ordini in attesa restano invariati."}, +"pni_all.n_networks":{"one":"{n} rete","other":"{n} reti"}, +"pni_all.n_of_total_connections":"{n} / {total} connessioni", +"pni_all.n_of_total_pops":"{n} / {total} POP in comune", +"pni_all.n_orders_with_net":{"one":"{n} ordine PNI effettuato con {net}. Invariati: {kept}; non disponibili: {blocked}.","other":"{n} ordini PNI effettuati con {net}. Invariati: {kept}; non disponibili: {blocked}."}, +"pni_all.new_and_upgrades":"Nuovi: {fresh} · Upgrade: {up}", +"pni_all.no_shared_locations":"Nessun POP in comune disponibile.", +"pni_all.no_shared_pops":"Non hai POP in comune con questa rete.", +"pni_all.order_missing_and_upgrade_smaller":"Ordina i PNI mancanti e potenzia quelli più piccoli nei POP in comune. I PNI più grandi e gli ordini in attesa restano invariati. I POP non disponibili vengono saltati.", +"pni_all.peer_all_networks":"Peering con tutte le reti su tutti i POP", +"pni_all.peer_at_port":"Peering su tutti i POP · {port}", +"pni_all.peer_on_all_pops":"Peering su tutti i POP", +"pni_all.pni_size":"Capacità PNI", +"pni_all.setup_total":"Costo totale di attivazione", +"pni_all.traffic_charges_apply":"Si applicano anche costi di traffico di {price} per Gbps.", "pnis.a_new_region_is_coming_online":"Una nuova region arriverà presto. Arriva presto dal 2019.", "pnis.about_n_days_to_go_nothing":"Mancano circa {n} giorni. Non resta che aspettare, o sollecitare.", "pnis.augment_with_net_delivered_in_city":"Ampliamento con {net} consegnato a {city}.
Ora {port}.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index cd40592..e3fd3ba 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Tentaram um peer remoto uma vez. Ele flapou durante um lançamento de produto. Nunca mais.", "pitcairn.uk_grant_mo":"Subsídio do Reino Unido {mo}/mês", "pitcairn.uk_grant_mo_once_islanders":"Subsídio do Reino Unido {mo}/mês quando os ilhéus estiverem online", +"pni_all.additional_per_month":"Custo mensal adicional", +"pni_all.all_at_port":"Peering com todas as redes · {port}", +"pni_all.delivery_and_traffic_charges":"Os prazos de entrega variam conforme a rede. Também se aplicam custos de peering baseados no tráfego, quando exigidos.", +"pni_all.n_blocked_connections":{"one":"{n} ligação indisponível","other":"{n} ligações indisponíveis"}, +"pni_all.n_blocked_pops":{"one":"{n} POP indisponível","other":"{n} POPs indisponíveis"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existente ou pedido pendente permanece inalterado.","other":"{n} PNIs existentes ou pedidos pendentes permanecem inalterados."}, +"pni_all.n_networks":{"one":"{n} rede","other":"{n} redes"}, +"pni_all.n_of_total_connections":"{n} / {total} ligações", +"pni_all.n_of_total_pops":"{n} / {total} POPs em comum", +"pni_all.n_orders_with_net":{"one":"{n} pedido de PNI feito com {net}. Inalterados: {kept}; indisponíveis: {blocked}.","other":"{n} pedidos de PNI feitos com {net}. Inalterados: {kept}; indisponíveis: {blocked}."}, +"pni_all.new_and_upgrades":"Novos: {fresh} · Upgrades: {up}", +"pni_all.no_shared_locations":"Não há POPs em comum disponíveis.", +"pni_all.no_shared_pops":"Não tens POPs em comum com esta rede.", +"pni_all.order_missing_and_upgrade_smaller":"Pede os PNIs em falta e aumenta os mais pequenos nos POPs em comum. Os PNIs maiores e os pedidos pendentes ficam inalterados. Os POPs indisponíveis são ignorados.", +"pni_all.peer_all_networks":"Peering com todas as redes em todos os POPs", +"pni_all.peer_at_port":"Peering em todos os POPs · {port}", +"pni_all.peer_on_all_pops":"Peering em todos os POPs", +"pni_all.pni_size":"Capacidade do PNI", +"pni_all.setup_total":"Custo total de instalação", +"pni_all.traffic_charges_apply":"Também se aplicam custos de tráfego de {price} por Gbps.", "pnis.a_new_region_is_coming_online":"Uma nova região vai entrar no ar em breve. Ela está entrando no ar em breve desde 2019.", "pnis.about_n_days_to_go_nothing":"Faltam cerca de {n} dias. Não há nada a fazer além de esperar, ou cobrar.", "pnis.augment_with_net_delivered_in_city":"Ampliação com {net} entregue em {city}.
Agora {port}.", diff --git a/src/game/70-rules/35-pni-orders.js b/src/game/70-rules/35-pni-orders.js new file mode 100644 index 0000000..c364a8e --- /dev/null +++ b/src/game/70-rules/35-pni-orders.js @@ -0,0 +1,23 @@ +/* Single and bulk orders share the same checks, prices and provisioning. */ +function pniQuote(city,net,tier,reserved=0){tier=+tier;const g1=tier===-1;if(g1)tier=0; + if(!S||!S.pops[city]||!isNet(net)||!NET[net].pops.includes(city)||!Number.isInteger(tier)||!PORT[tier]||(g1&&!pniG1(net)))return null; + const ex=S.pni.find(p=>p.city===city&&p.net===net); + if(ex&&(g1||!pniOn(ex)||ex.up||(!(ex.g1&&tier===0)&&tier<=ex.tier)))return null; + const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1),slots=ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier); + let why='';if(!portOk(city,tier))why=tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}); + else{const r=peerOk(net,'pni',city);if(!r.ok)why=tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)}); + else if(!g1&&tier0&&portsUsed(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(portsUsed(city)+reserved),m:portsMax(city)});} + return {city,net,tier,g1,ex,cost,slots,why};} +function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net); + if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1; + if(ex)ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead}); + return lead;} +function pniBatch(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null; + const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0; + // Pending augments and earlier orders in this batch already own their future ports. + for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)); + for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city); + const q=pniQuote(city,n.id,tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots; + mo+=pniMo({net:n.id,tier:q.tier,g1:q.g1,n:q.ex&&q.ex.n},0)-(q.ex?pniMo(q.ex,0):0);} + return {shared,orders,blocked,kept,cost,mo};} diff --git a/src/game/90-actions/40-sites-peering-caches.js b/src/game/90-actions/40-sites-peering-caches.js index 05783be..cf4da86 100644 --- a/src/game/90-actions/40-sites-peering-caches.js +++ b/src/game/90-actions/40-sites-peering-caches.js @@ -12,13 +12,13 @@ Object.assign(ACT,{ unpeer:({city,net})=>{delete S.peers[net+'@'+city];after();}, peerAll:({city})=>{if(!isIx(city)||S.ixp[city]===undefined)return;const set=ixSessions(city);let n=0;for(const id of ixMembers(city))if(!set.has(id)&&peerOk(id,'ix',city).ok){S.peers[id+'@'+city]=true;n++;}if(!n)return;toast(trn('sites_peering_caches.n_new_session_at_ix_small',n,{ix:esc(ixName(city))}),'good',[],{a:'city',v:ixCity(city)});sfx('build');after();}, tailTog:()=>{UI.tailOpen=!UI.tailOpen;renderLeft();}, - pni:({city,net,tier})=>{tier=+tier;const g1=tier===-1;if(g1){if(!pniG1(net))return;tier=0;}if(!S.pops[city]||!NET[net]||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const r=peerOk(net,'pni',city);if(!r.ok){toast(tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)}),'bad');sfx('err');after();return;} - if(!g1&&tierp.city===city&&p.net===net);if(ex&&(g1||!pniOn(ex)||ex.up))return;if(ex&&!(ex.g1&&tier===0)&&tier<=ex.tier)return; - const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1);if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(cost))return;if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1; - // Nothing is instant: a cross-connect takes weeks, and the big networks quote months for a new PNI or an augment. - const lead=pniLead(net);if(ex)ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead}); + pni:({city,net,tier})=>{const q=pniQuote(city,net,tier);if(!q)return;if(q.why){toast(q.why,'bad');sfx('err');after();return;}if(!spend(q.cost))return;const lead=pniPlace(q); toast(tr('sites_peering_caches.pni_with_net_ordered_eta_a',{net:esc(NET[net].name),eta:pniWhen(lead),dc:esc(siteName(city,'a'))}),'good');after();}, + pniAllOpen:({net})=>{pniAllModal(net);}, + pniAllSize:({v})=>{if(!UI.pniAll)return;pniAllModal(UI.pniAll.net,+v);$('modalCard').querySelector('[data-chg="pniAllSize"]')?.focus();}, + pniAll:({net,tier})=>{const b=pniBatch(net,tier);if(!b||!b.orders.length)return;if(!spend(b.cost))return; + for(const q of b.orders)pniPlace(q);UI.pniAll=null;closeModal(); + toast(trn('pni_all.n_orders_with_net',b.orders.length,{net:esc(net===null?tr('common.all_networks'):NET[net].name),kept:b.kept,blocked:b.blocked.length}),'good');after();}, pniChase:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||(pniOn(p)&&!p.up))return;const r=Math.random(); if(r<0.15){if(p.up)p.up.ready=Math.max(S.day+1,p.up.ready-30);else p.ready=Math.max(S.day+1,p.ready-30);toast(tr('sites_peering_caches.your_account_manager_found_the_order'),'good');} else toast(pick([tr('sites_peering_caches.it_is_with_the_provisioning_team'),tr('sites_peering_caches.we_are_waiting_on_the_colo'),tr('sites_peering_caches.your_ticket_was_merged_into_another'),tr('sites_peering_caches.could_you_resend_the_loa_you'),tr('sites_peering_caches.your_account_manager_is_on_paternity')]));after();}, diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 5bb0282..85e9c64 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -18,8 +18,9 @@ function renderDash(){checkLayer(); {const k=UI.dashSort||'traffic',dir=UI.dashDir||-1,val=x=>k==='name'?x.n.name.toLowerCase():k==='asn'?x.n.asn:k==='type'?x.n.type:k==='cost'?x.cost:k==='lost'?x.lost:x.t;nets.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||b.t-a.t;});} if(DT==='cust')h+=custSection(); if(DT==='conn')h+=connSection(); + if(DT==='traffic')h+=`
${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'pink sm')}
`; if(DT==='traffic')h+=`

${tr('dashboard.traffic_by_network_asn')}

${tr('dashboard.where_your_users_traffic_comes_from')}

${['c','p','ix','t'].map(k=>`${EGC[k][0]}`).join('')}
${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>``).join('')} - ${nets.map(({n,e,t,want})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}
`; + ${nets.map(({n,e,t,want})=>{return `${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?`
${btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm')}
`:''}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}`;}).join('')}
`; if(DT==='traffic'){const top=transitTop(S.transit.map(t=>t.id),8);if(top.length)h+=`

${tr('dashboard.who_your_transit_carries')}

${tr('dashboard.the_networks_you_pay_transit_to')}

${top.map(([id,v])=>`
${logo(NET[id])}
${esc(NET[id].name)} AS${NET[id].asn} · ${fmtG(v)} · ${tr('dashboard.about_price_mo',{price:fmt$((R.cost.transit||0)*v/tT)})}
${esc(offTransitHint(id))}
${btn(tr('common.where_6276'),'netFocus',{id},'ghost sm')}
`).join('')}
`;} const ls=S.links.filter(l=>capOf(l)>0).map(l=>({l,u:(R.load[l.id]||0)/capOf(l)})).sort((a,b)=>b.u-a.u).slice(0,8); const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6); diff --git a/src/game/95-modals/35-pni-all.js b/src/game/95-modals/35-pni-all.js new file mode 100644 index 0000000..69f228e --- /dev/null +++ b/src/game/95-modals/35-pni-all.js @@ -0,0 +1,19 @@ +function pniAllModal(net,tier=1){const b=pniBatch(net,tier);if(!b)return;UI.pniAll={net,tier}; + const all=net===null,n=NET[net],port=tier===-1?'1G':PORT[tier].n,up=b.orders.filter(q=>q.ex).length,byNet={}; + if(all)for(const q of b.orders)(byNet[q.net]||(byNet[q.net]=[])).push(q.city); + const controls=`
${btn(all?tr('pni_all.all_at_port',{port}):tr('pni_all.peer_at_port',{port}),'pniAll',{net,tier},'pink',!b.orders.length||S.cash`; + const blocked=b.blocked.map(q=>`

${all?esc(NET[q.net].name)+' · ':''}${esc(CITY[q.city].name)}: ${q.why}

`).join(''); + openModal(`
${all?tr('common.all_networks'):`AS${n.asn} · ${esc(n.name)}`}

${all?tr('pni_all.peer_all_networks'):tr('pni_all.peer_on_all_pops')}

+

${tr('pni_all.order_missing_and_upgrade_smaller')}

+
+
${tr('pni_all.new_and_upgrades',{fresh:b.orders.length-up,up})}${all?tr('pni_all.n_of_total_connections',{n:b.orders.length,total:b.shared.length}):tr('pni_all.n_of_total_pops',{n:b.orders.length,total:b.shared.length})}
+
${tr('pni_all.setup_total')}${fmt$(b.cost)}
+
${tr('pni_all.additional_per_month')}${tr('common.price_mo',{price:fmt$(b.mo)})}
+ ${all?`

${tr('pni_all.delivery_and_traffic_charges')}

`:n.perG?`

${tr('pni_all.traffic_charges_apply',{price:fmt$(n.perG)})}

`:''} + ${S.cash${tr('interface.not_enough_cash_wait_for_revenue')}

`:''} + ${all?controls:''} + ${all&&b.orders.length?`
${trn('pni_all.n_networks',Object.keys(byNet).length)}${Object.entries(byNet).map(([id,cities])=>`
${esc(NET[id].name)}${trn('save.n_pop',cities.length)}

${cities.map(c=>esc(CITY[c].name)).join(' · ')}

`).join('')}
`:b.orders.length?`

${b.orders.map(q=>esc(CITY[q.city].name)).join(' · ')}

${pniEta(net)}

`:''} + ${b.kept?`

${trn('pni_all.n_existing_or_pending_unchanged',b.kept)}

`:''} + ${b.blocked.length?(all?`
${trn('pni_all.n_blocked_connections',b.blocked.length)}${blocked}
`:`

${trn('pni_all.n_blocked_pops',b.blocked.length)}

${blocked}`):''} + ${!b.shared.length?`

${all?tr('pni_all.no_shared_locations'):tr('pni_all.no_shared_pops')}

`:''} + ${all?'':controls}`);} diff --git a/src/i18n/en.js b/src/i18n/en.js index b26cc57..64c4e7f 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2582,6 +2582,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Tried a remote peer once. It flapped during a product launch. Never again.", "pitcairn.uk_grant_mo":"UK grant {mo}/mo", "pitcairn.uk_grant_mo_once_islanders":"UK grant {mo}/mo once the islanders are online", +"pni_all.additional_per_month":"Additional monthly cost", +"pni_all.all_at_port":"Peer all networks · {port}", +"pni_all.delivery_and_traffic_charges":"Delivery times vary by network. Traffic-based peering charges also apply where required.", +"pni_all.n_blocked_connections":{"one":"{n} blocked connection","other":"{n} blocked connections"}, +"pni_all.n_blocked_pops":{"one":"{n} blocked POP","other":"{n} blocked POPs"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} existing PNI or pending order stays unchanged.","other":"{n} existing PNIs or pending orders stay unchanged."}, +"pni_all.n_networks":{"one":"{n} network","other":"{n} networks"}, +"pni_all.n_of_total_connections":"{n} / {total} connections", +"pni_all.n_of_total_pops":"{n} / {total} shared POPs", +"pni_all.n_orders_with_net":{"one":"{n} PNI order placed with {net}. Unchanged: {kept}; blocked: {blocked}.","other":"{n} PNI orders placed with {net}. Unchanged: {kept}; blocked: {blocked}."}, +"pni_all.new_and_upgrades":"New: {fresh} · Upgrades: {up}", +"pni_all.no_shared_locations":"No shared POPs are available.", +"pni_all.no_shared_pops":"You have no POPs in common with this network.", +"pni_all.order_missing_and_upgrade_smaller":"Orders missing PNIs and upgrades smaller ones at your shared POPs. Larger PNIs and pending orders stay unchanged. Unavailable POPs are skipped.", +"pni_all.peer_all_networks":"Peer all networks on all POPs", +"pni_all.peer_at_port":"Peer on all POPs · {port}", +"pni_all.peer_on_all_pops":"Peer on all POPs", +"pni_all.pni_size":"PNI size", +"pni_all.setup_total":"Total setup cost", +"pni_all.traffic_charges_apply":"Traffic charges of {price} per Gbps also apply.", "pnis.a_new_region_is_coming_online":"A new region is coming online soon. It has been coming online soon since 2019.", "pnis.about_n_days_to_go_nothing":"About {n} days to go. Nothing to do but wait, or chase it.", "pnis.augment_with_net_delivered_in_city":"Augment with {net} delivered in {city}.
Now {port}.", diff --git a/tests/pni-all.test.js b/tests/pni-all.test.js new file mode 100644 index 0000000..c6ba3b0 --- /dev/null +++ b/tests/pni-all.test.js @@ -0,0 +1,155 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev, cities = []) { + ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0"); + for (const city of cities) ev(`ACT.buildPop({city:'${city}'})`); + ev('for(const p of Object.values(S.pops))p.rgen=RG.length-1;compute()'); +} + +test('bulk PNIs add missing shared POPs and upgrade smaller ports once, preserving existing orders and LAGs', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams', 'lon', 'par', 'nyc', 'sjc', 'sao']); + ev(`S.pni.push( + {id:'small',net:'drz',city:'fra',tier:0,n:2,site:'ab',pref:'high'}, + {id:'big',net:'drz',city:'ams',tier:2}, + {id:'equal',net:'drz',city:'lon',tier:1}, + {id:'pending',net:'drz',city:'par',tier:0,ready:S.day+20}, + {id:'augment',net:'drz',city:'nyc',tier:0,up:{tier:1,n:1,ready:S.day+20}});compute()`); + const before = ev('JSON.stringify(S)'); + assert.deepEqual(JSON.parse(ev("JSON.stringify((b=>({shared:b.shared.length,orders:b.orders.length,kept:b.kept,cost:b.cost,mo:b.mo}))(pniBatch('drz',1)))")), + { shared: 6, orders: 2, kept: 4, cost: 6750, mo: 650 }); + assert.equal(ev('JSON.stringify(S)'), before, 'preview does not change the save'); + const cash = ev('S.cash'); + const existing = JSON.parse(ev("JSON.stringify(S.pni.filter(p=>p.id!=='small'))")); + ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('window.afterCount'), 1, 'one recompute/render/save for the whole batch'); + assert.equal(ev('S.cash'), cash - 6750); + assert.equal(ev('S.pni.length'), 6); + assert.equal(ev("S.pni.filter(p=>p.city==='sao'||p.city==='tok').length"), 0, 'only shared owned POPs'); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pni.filter(p=>['big','equal','pending','augment'].includes(p.id)))")), existing); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2); + assert.equal(ev("S.pni.find(p=>p.id==='small').site"), 'ab'); + assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high'); + assert.ok(ev("S.pni.find(p=>p.city==='sjc').ready>S.day"), 'new PNIs still take time'); + ev("ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('S.cash'), cash - 6750, 'repeat clicks neither charge nor duplicate'); + assert.equal(ev('window.afterCount'), 1); + ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));S.day=Math.max(...S.pni.map(p=>p.up?p.up.ready:p.ready||0));pniDay(S.day);compute()'); + assert.equal(ev("S.pni.find(p=>p.id==='small').tier"), 1, 'augment survives save migration and delivers'); + assert.equal(ev("S.pni.find(p=>p.city==='sjc').tier"), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('bulk PNIs skip router speed, port capacity and policy restrictions with city-specific reasons', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams', 'lon', 'ash']); + ev(`S.pops.fra.rgen=0;S.pops.ams.rgen=1; + S.caches=Array.from({length:portsMax('ams')},()=>({id:uid(),city:'ams',net:'cfl'})); + while(['ams','lon'].some(c=>snub('msf',c)?.all))S.asn++; + compute();R.demTo.msf=1e4;ACT.pniAllOpen({net:'msf'});ACT.pniAllSize({v:'2'})`); + assert.equal(ev("pniBatch('msf',2).orders.length"), 1); + assert.equal(ev("pniBatch('msf',2).blocked.length"), 3); + const text = dom.window.document.getElementById('modalCard').textContent; + assert.match(text, /Frankfurt.*router can't take a 400G/s); + assert.match(text, /Amsterdam.*No free router ports/s); + assert.match(text, /Ashburn.*capacity|Ashburn.*sold out/s); + const cash = ev('S.cash'); + ev("ACT.pniAll({net:'msf',tier:2})"); + assert.equal(ev('S.pni.length'), 1); + assert.equal(ev('S.pni[0].city'), 'lon'); + assert.equal(ev('S.cash'), cash - 3500); + assert.match(ev("S.log[0].t"), /blocked: 3/); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('insufficient funds refuse the entire eligible batch and execution rechecks a stale preview', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams']); + ev("S.cash=pniBatch('drz',1).cost-1;ACT.pniAllOpen({net:'drz'})"); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + const cash = ev('S.cash'); + ev("ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0); + ev("S.cash=1e8;ACT.pniAllOpen({net:'drz'});delete S.pops.ams;S.pops.fra.rgen=0;ACT.pniAll({net:'drz',tier:2})"); + assert.equal(ev('S.cash'), 1e8); + assert.equal(ev('S.pni.length'), 0, 'deleted POPs and unsupported speeds are rechecked on click'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('bulk PNI actions reject invalid networks, sizes, minimum ports, traffic thresholds and non-shared locations', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev('S.pops.fra.rgen=0'); + const cash = ev('S.cash'); + for (const net of ['missing', '__proto__', 'drz', 'nfx']) { + for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:'${net}',tier:${tier}})`); + } + ev("ACT.pniAll({net:'nfx',tier:0});R.demTo.nfx=0;ACT.pniAll({net:'nfx',tier:1})"); + assert.equal(ev('S.pni.length'), 0); + assert.equal(ev('S.cash'), cash); + ev("delete S.pops.fra;ACT.pniAllOpen({net:'drz'});ACT.pniAll({net:'drz',tier:1})"); + assert.match(dom.window.document.getElementById('modalCard').textContent, /no POPs in common/); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('Doitsche 1G bulk orders and 10G augments keep paid-peering fees and conference delivery rules', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams']); + ev("S.conf={until:S.day+10,reg:'EU'};Math.random=()=>0.5"); + const cash = ev('S.cash'); + assert.equal(ev("pniBatch('dtk',-1).cost"), 2400); + assert.equal(ev("pniBatch('dtk',-1).mo"), ev('2*(PORT[0].pni/2+NET.dtk.paidFee)')); + ev("ACT.pniAll({net:'dtk',tier:-1})"); + assert.equal(ev('S.cash'), cash - 2400); + assert.equal(ev('S.stats.beerPni'), 1); + assert.equal(ev('S.pni.every(p=>p.g1&&pniG(p)===1&&p.ready===S.day+15)'), true); + ev('S.day+=15;pniDay(S.day);compute()'); + assert.equal(ev("pniBatch('dtk',0).mo"), 200, 'upgrades add port costs, without charging the peering fee twice'); + ev("ACT.pniAll({net:'dtk',tier:0});S.day=Math.max(...S.pni.map(p=>p.up.ready));pniDay(S.day)"); + assert.equal(ev('S.pni.every(p=>!p.g1&&pniG(p)===10)'), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('Traffic row buttons and size selection work by DOM events on phones in every language', () => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { dom, ev, errors } = load(lang === 'en' ? {} : { lang }); + setup(ev); + dom.window.innerWidth = 360; + ev("ACT.launchBB({city:'fra'});ACT.dash();ACT.dashTab({k:'traffic'})"); + const doc = dom.window.document; + const buttons = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')]; + assert.ok(buttons.length > 0, lang); + assert.equal(buttons.some(b => JSON.parse(b.dataset.args).net === '_tail'), false); + const cash = ev('S.cash'); + buttons.find(b => JSON.parse(b.dataset.args).net === 'cfl').click(); + assert.equal(doc.getElementById('modal').hidden, false, lang); + let select = doc.querySelector('#modalCard select'); + assert.equal(select.closest('label').textContent.includes(ev("tr('pni_all.pni_size')")), true, lang); + select.focus(); + select.value = '0'; + select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + select = doc.querySelector('#modalCard select'); + assert.equal(select.value, '0', lang); + assert.equal(doc.activeElement, select, 'size changes preserve keyboard focus'); + const submit = doc.querySelector('#modalCard [data-act="pniAll"]'); + assert.equal(JSON.parse(submit.dataset.args).tier, 0, lang); + assert.equal(submit.disabled, false, lang); + assert.equal(ev('S.cash'), cash, 'opening or changing the preview spends nothing'); + submit.click(); + assert.equal(doc.getElementById('modal').hidden, true, lang); + assert.equal(ev("S.pni.some(p=>p.net==='cfl'&&p.city==='fra'&&p.tier===0)"), true, lang); + assert.equal(ev('S.cash'), cash - 1750, lang); + assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); diff --git a/tests/pni-global.test.js b/tests/pni-global.test.js new file mode 100644 index 0000000..e175ed2 --- /dev/null +++ b/tests/pni-global.test.js @@ -0,0 +1,135 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=RG.length-1;compute()"); +} + +test('global PNIs cover every eligible network and shared POP, including the long tail, in one transaction', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev(`ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG.length-1; + S.pni.push({id:'small',net:'cfl',city:'fra',tier:0,n:2,site:'ab',pref:'high'}, + {id:'big',net:'drz',city:'ams',tier:2}, + {id:'pending',net:'nfx',city:'fra',tier:1,ready:S.day+30}); + compute();for(const n of NETS)R.demTo[n.id]=1e4`); + const before = ev('JSON.stringify(S)'); + const batch = JSON.parse(ev('JSON.stringify(pniBatch(null,1))')); + assert.equal(ev('JSON.stringify(S)'), before, 'global preview changes no game state'); + assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'fra' && q.ex)); + assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'ams' && !q.ex)); + assert.ok(batch.orders.some(q => ev(`NET['${q.net}'].tail`)), 'small networks are included'); + assert.equal(batch.orders.some(q => q.net === 'drz' && q.city === 'ams'), false, 'no downgrade'); + assert.equal(batch.orders.some(q => q.net === 'nfx' && q.city === 'fra'), false, 'keep pending orders'); + const cash = ev('S.cash'); + ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:null,tier:1})"); + assert.equal(ev('window.afterCount'), 1); + assert.equal(ev('S.cash'), cash - batch.cost); + assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length); + assert.equal(ev('new Set(S.pni.map(p=>p.net+"@"+p.city)).size'), ev('S.pni.length')); + assert.equal(ev("S.pni.every(p=>S.pops[p.city]&&NET[p.net].pops.includes(p.city))"), true); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2, 'LAG members stay together'); + assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high'); + assert.equal(ev("S.pni.find(p=>p.id==='big').tier"), 2); + assert.equal(ev('Object.keys(S.pops).every(c=>portsUsed(c)<=portsMax(c))'), true); + ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));compute()'); + assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.tier"), 1); + const count = ev('S.pni.length'); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.cash'), cash - batch.cost, 'repeat clicks spend nothing'); + assert.equal(ev('S.pni.length'), count); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('global PNIs share the available router ports, including four 10G breakouts per slot', () => { + for (const [tier, count] of [[1, 1], [0, 4]]) { + const { dom, ev, errors } = load(); + setup(ev); + ev("S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'}));compute()"); + assert.equal(ev(`pniBatch(null,${tier}).orders.length`), count); + assert.ok(ev(`pniBatch(null,${tier}).blocked.some(q=>/No free router ports/.test(q.why))`)); + ev(`ACT.pniAll({net:null,tier:${tier}})`); + assert.equal(ev('S.pni.length'), count); + assert.equal(ev("portsUsed('fra')"), 8); + const cash = ev('S.cash'); + ev(`ACT.pniAll({net:null,tier:${tier}})`); + assert.equal(ev('S.cash'), cash); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); + +test('global planning reserves ports for pending speed and LAG augments without mutating the save', () => { + for (const [tier, n] of [[1, 1], [0, 4]]) { + const { dom, ev, errors } = load(); + setup(ev); + ev(`S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'})); + S.pni=[{id:'pending',city:'fra',net:'cfl',tier:0,n:1,up:{tier:${tier},n:${n},ready:S.day+30}}];compute()`); + const state = ev('JSON.stringify(S)'); + assert.equal(ev('pniBatch(null,0).orders.length'), 0); + assert.equal(ev('pniBatch(null,1).orders.length'), 0); + assert.equal(ev('JSON.stringify(S)'), state); + const cash = ev('S.cash'); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.pni.length'), 1); + assert.equal(ev('S.cash'), cash); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); + +test('global PNIs require the full budget and reject unsupported sizes and an empty POP list', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev('S.cash=pniBatch(null,1).cost-1;ACT.pniAllOpen({net:null})'); + const cash = ev('S.cash'); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0, 'no partial purchase'); + for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:null,tier:${tier}})`); + ev('ACT.pniAll({tier:1});S.pops={};ACT.pniAllOpen({net:null})'); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0); + assert.match(dom.window.document.getElementById('modalCard').textContent, /No shared POPs/); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the global Traffic button preserves scope, keyboard focus and translations on phones', () => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { dom, ev, errors } = load(lang === 'en' ? {} : { lang }); + setup(ev); + dom.window.innerWidth = 360; + ev("ACT.dash();ACT.dashTab({k:'traffic'})"); + const doc = dom.window.document; + const button = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')].find(b => JSON.parse(b.dataset.args).net === null); + assert.ok(button, lang); + button.click(); + assert.equal(doc.querySelector('#modalCard h2').textContent, ev("tr('pni_all.peer_all_networks')"), lang); + const cash = ev('S.cash'); + const select = doc.querySelector('#modalCard select'); + assert.equal([...select.options].some(o => o.value === '-1'), false, '1G is not available for all networks'); + select.focus(); + select.value = '0'; + select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + assert.equal(doc.activeElement, doc.querySelector('#modalCard select')); + const submit = doc.querySelector('#modalCard [data-act="pniAll"]'); + assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0 }, lang); + assert.equal(submit.disabled, false, lang); + assert.ok(doc.querySelectorAll('#modalCard details').length > 0, 'long lists are collapsed'); + assert.equal(ev('S.cash'), cash, 'preview does not buy anything'); + assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang); + const cost = ev('pniBatch(null,0).cost'); + submit.click(); + assert.equal(doc.getElementById('modal').hidden, true, lang); + assert.equal(ev('S.cash'), cash - cost, lang); + assert.ok(ev('new Set(S.pni.map(p=>p.net)).size') > 1, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); From abe92fe3b13c2493950ac36aeb238bfade0c86d3 Mon Sep 17 00:00:00 2001 From: logfro Date: Wed, 28 Oct 2026 02:19:30 +0100 Subject: [PATCH 09/64] Add real-time sales automation and automatic paid repairs Add independent toggles for auto-accept in Deals and auto-pay repairs in NOC. Save both settings and default them off for older or malformed saves. Check sales every five wall-clock seconds regardless of game speed, and show a small countdown on Accept buttons in Deals, city offers and fiber broker offers. Only sign when all requirements, locations, equipment and service capacity are ready. Trial the added demand before accepting it, protect healthy existing customers and account for booked future events. Use the existing paid repair action for affordable active incidents, including slow router reboots. Skip expired incidents, removed equipment, DDoS attacks and repairs that were already rushed. Pause both automations with the game, hidden pages and open dialogs. Translate the controls into all five supported languages and cover timing, countdowns, capacity, budgets, repair payments, persistence, mobile controls and trial rollback with deterministic tests. Chromium checks verify about five real seconds at both 0.5x and 8x game speed and exercise the supplied large save without changing the save file. --- CHANGELOG.md | 3 + site/i18n/es.js | 5 + site/i18n/fr.js | 5 + site/i18n/it.js | 5 + site/i18n/pt.js | 5 + src/game/60-features/80-new-game.js | 2 +- src/game/60-features/90-automation.js | 30 +++ src/game/80-simulation/50-sanitize.js | 1 + src/game/90-actions/50-customers.js | 5 +- src/game/93-ui/40-hud-and-panels.js | 4 +- src/game/93-ui/70-link-panels.js | 4 +- src/game/99-loop.js | 1 + src/i18n/en.js | 5 + tests/automation.test.js | 319 ++++++++++++++++++++++++++ 14 files changed, 388 insertions(+), 6 deletions(-) create mode 100644 src/game/60-features/90-automation.js create mode 100644 tests/automation.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0094b5d..3f87e28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Toggle auto-accept in Deals to check ready sales every five real seconds, including their requirements and available service capacity, with a countdown beside each Accept button. +- Toggle auto-pay repairs in the NOC to pay for affordable rush repairs automatically while the game runs. + ## [1.35.0] — 2026-10-27 - Series of Tubes now speaks Spanish. The game follows your browser's language the first time, and you can switch to Spanish under Settings or on the title screen. diff --git a/site/i18n/es.js b/site/i18n/es.js index 16f2a3c..4fd30a4 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -12,6 +12,11 @@ "action_helpers.too_far_even_at_its_slowest":"Demasiado lejos incluso en su ajuste más lento: aquí un tramo óptico mide {span} km y el alcance es de {max} km. Añade un sitio regenerador (Sistema de línea).", "action_helpers.unlocks_at_customer_level_n":"Se desbloquea en el nivel de cliente {n}.", "actions.your_router_can_t_take_a":"Tu router no admite un puerto de {port}.
Mejóralo en la pestaña Infra.", +"automation.auto_accept_sales":"Ventas automáticas: {state}", +"automation.auto_pay_repairs":"Reparaciones pagadas auto: {state}", +"automation.next_auto_check":"Tiempo hasta la próxima comprobación automática de requisitos.", +"automation.repairs_when_affordable":"Mientras juegas, paga automáticamente las reparaciones urgentes disponibles si hay fondos suficientes.", +"automation.sales_every_five_seconds":"Cada 5 segundos mientras juegas, acepta solo ofertas cuyos requisitos se cumplan y tengan capacidad de servicio disponible.", "badges.a_petabit_a_second":"Un petabit por segundo", "badges.a_secret_badge":"Una insignia secreta", "badges.attend_a_conference":"Asiste a una conferencia.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4e674bf..7280f8a 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -12,6 +12,11 @@ "action_helpers.too_far_even_at_its_slowest":"Trop loin, même au débit le plus lent : ici une portée optique fait {span} km et l’optique va jusqu’à {max} km. Ajoute un site de régénération (Système de ligne).", "action_helpers.unlocks_at_customer_level_n":"Se débloque au niveau client {n}.", "actions.your_router_can_t_take_a":"Ton routeur ne supporte pas de port {port}.
Mets-le à niveau dans l’onglet Infra.", +"automation.auto_accept_sales":"Ventes automatiques : {state}", +"automation.auto_pay_repairs":"Réparations payées auto : {state}", +"automation.next_auto_check":"Temps avant la prochaine vérification automatique des conditions.", +"automation.repairs_when_affordable":"Pendant le jeu, paie automatiquement les réparations urgentes disponibles si les fonds suffisent.", +"automation.sales_every_five_seconds":"Toutes les 5 secondes pendant le jeu, accepte uniquement les offres dont les conditions sont remplies et la capacité de service disponible.", "badges.a_petabit_a_second":"Un pétabit par seconde", "badges.a_secret_badge":"Un badge secret", "badges.attend_a_conference":"Participe à une conférence.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 83a3693..312e1b0 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -12,6 +12,11 @@ "action_helpers.too_far_even_at_its_slowest":"Troppo lontano anche alla velocità più bassa: qui una tratta ottica è di {span} km e l’ottica arriva a {max} km. Aggiungi un sito di rigenerazione (Sistema di linea).", "action_helpers.unlocks_at_customer_level_n":"Si sblocca al livello cliente {n}.", "actions.your_router_can_t_take_a":"Il tuo router non regge una porta {port}.
Aggiornalo nella scheda Infra.", +"automation.auto_accept_sales":"Vendite automatiche: {state}", +"automation.auto_pay_repairs":"Riparazioni a pagamento auto: {state}", +"automation.next_auto_check":"Tempo fino alla prossima verifica automatica dei requisiti.", +"automation.repairs_when_affordable":"Durante il gioco, paga automaticamente le riparazioni urgenti disponibili se hai abbastanza fondi.", +"automation.sales_every_five_seconds":"Ogni 5 secondi durante il gioco, accetta solo le offerte con requisiti soddisfatti e capacità di servizio disponibile.", "badges.a_petabit_a_second":"Un petabit al secondo", "badges.a_secret_badge":"Un badge segreto", "badges.attend_a_conference":"Partecipa a una conferenza.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index cd40592..49b342f 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -12,6 +12,11 @@ "action_helpers.too_far_even_at_its_slowest":"Longe demais até na configuração mais lenta: um span óptico aqui tem {span} km e ela alcança {max} km. Adicione um site de regeneração (Line system).", "action_helpers.unlocks_at_customer_level_n":"Desbloqueia no nível de cliente {n}.", "actions.your_router_can_t_take_a":"Seu router não aguenta uma porta {port}.
Faça upgrade na aba Infra.", +"automation.auto_accept_sales":"Vendas automáticas: {state}", +"automation.auto_pay_repairs":"Reparações pagas auto: {state}", +"automation.next_auto_check":"Tempo até à próxima verificação automática dos requisitos.", +"automation.repairs_when_affordable":"Durante o jogo, paga automaticamente as reparações urgentes disponíveis quando há fundos suficientes.", +"automation.sales_every_five_seconds":"A cada 5 segundos durante o jogo, aceita apenas ofertas com os requisitos cumpridos e capacidade de serviço disponível.", "badges.a_petabit_a_second":"Um petabit por segundo", "badges.a_secret_badge":"Um badge secreto", "badges.attend_a_conference":"Participe de uma conferência.", diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 2fa348b..5ae1c21 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,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:{}, + ltv:2,t1v:3,auV:1,autoSales:false,autoRepair:false,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:{}, done:{},inc:[],ev:{},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,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; } diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js new file mode 100644 index 0000000..e8130b9 --- /dev/null +++ b/src/game/60-features/90-automation.js @@ -0,0 +1,30 @@ +/* Optional operators use the same sales and repair actions as the player. */ +const AUTO_SALES_MS=5000; +function autoSalesSeconds(now=performance.now()){if(!S||!S.autoSales)return null; + const left=UI.autoGame===S&&autoActive()?AUTO_SALES_MS-(now-UI.autoSalesAt):AUTO_SALES_MS; + return Math.max(1,Math.min(AUTO_SALES_MS/1000,Math.ceil(left/1000)));} +function autoAcceptLabel(){return tr('common.accept')+(S.autoSales?` (${autoSalesSeconds()})`:'');} +function renderAutoCountdown(now=performance.now()){const n=autoSalesSeconds(now);if(UI.autoCount===n)return;UI.autoCount=n; + for(const el of document.querySelectorAll('[data-auto-sales]'))el.textContent=n===null?'':`(${n})`;} +function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};} +function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null; + const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; + if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null; + if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id; + if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;} + const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day); + // Trial the added demand before signing; failed trials leave the live game untouched. + try{S={...S,biz:S.biz}; + // shortcut: future events reserve capacity together; use per-date trials if separate bookings must share capacity. + if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();} + const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); + return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null; + }finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}} +function autoActive(){return !!(S&&UI.started&&!S.lost&&UI.speed&&$('modal').hidden&&document.visibilityState==='visible');} +function automationTick(now){if(UI.autoGame!==S){UI.autoGame=S;UI.autoSalesAt=now;} + if(!autoActive()){UI.autoSalesAt=now;return;} + if(S.autoRepair&&S.inc.length){purgeInc();for(const i of S.inc.slice()){if(!autoActive())break; + if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&i.cost<=S.cash&&!(i.slow&&i.rushed))ACT.fixInc({id:i.id});}} + if(!S.autoSales||!autoActive()){UI.autoSalesAt=now;return;}if(now-UI.autoSalesAt{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;}; // A capacity broker finds a buyer at once and keeps 10% of the monthly price. const o=fiberOffer(t,l,nm,0.9);o.broker=true;S.offers.push(o);toast(tr('customers.listed_with_a_capacity_broker_name',{name:esc(o.name),what:esc(o.what)}),'good');sfx('click');after();}, - accept:({id})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} + autoToggle:({k})=>{if(k!=='autoSales'&&k!=='autoRepair')return;S[k]=!S[k];if(k==='autoSales'){UI.autoGame=S;UI.autoSalesAt=performance.now();}sfx('click');after();}, + accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;const customer=auto?(S.autoSales&&autoOffer(o)):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)=o.start){toast(tr('customers.too_late_the_event_has_already'),'bad');return;} // A carrier renting more alien waves on a fiber it already rents grows its contract, like a real order for extra waves, @@ -12,7 +13,7 @@ Object.assign(ACT,{ const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name); if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots); floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;} - S.offers=S.offers.filter(x=>x!==o);S.biz.push({id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined}); + S.offers=S.offers.filter(x=>x!==o);S.biz.push(customer); floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();}, decline:({id})=>{S.offers=S.offers.filter(x=>x.id!==id);after();}, dropBiz:({id})=>{const b0=S.biz.find(x=>x.id===id);if(!b0)return;if(BIZ_T[b0.type].event&&S.day>=b0.start){toast(tr('customers.the_event_is_already_running_the'),'bad');sfx('err');return;}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();}, diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 2a98394..2f599cf 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -37,16 +37,18 @@ function renderLeft(){checkLayer(); h+=GOALS.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `
${d?'✓':''}
${esc(g.t)}
${c||!d?`
${esc(g.d)}
`:''}${!d&&g.r?`
${tr('hud_and_panels.reward_cash',{cash:fmt$(g.r)})}
`:''}
`;}).join(''); h+=badgeGrid(); }else if(UI.left==='deals'){ + h+=`

${tr('automation.sales_every_five_seconds')}

`; {const st=custStats();if(st.n)h+=`
${tr('common.your_customers')} ${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}
${st.unhappy?`
${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}
`:''}
${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}
`;} h+=confSection(); {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}
${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}
`;} if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${reqList(o)} -
${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} +
${has?btn(autoAcceptLabel(),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }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+=`

${tr('automation.repairs_when_affordable')}

`; // 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/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 19b6eb7..5cba29a 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -76,7 +76,7 @@ function dfPanel(l){ if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l); h+=`

${tr('link_panels.selling_spare_capacity')}

${tr('link_panels.other_carriers_rent_what_you_do')}

${tr('common.free_channels')}${fc} / ${chMax(l)}
${sold.map(b=>`
${esc(b.name)}
${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}
`).join('')} - ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(tr('common.accept'),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}
`;} + ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(autoAcceptLabel(),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}`;} h+=`

${tr('common.optics')}

${tr('link_panels.each_channel_is_a_pair_of')}

`; if(l.own&&l.sub)h+=subUpgradePanel(l); for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k); @@ -93,7 +93,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(autoAcceptLabel(),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 7f1b386..70a4e5d 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -10,6 +10,7 @@ function frame(now){ if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();} if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}} + try{automationTick(now);renderAutoCountdown();}catch(e){tickErr(e);} if(UI.speed&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ const t=animOn()?animT:0; if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;} diff --git a/src/i18n/en.js b/src/i18n/en.js index b26cc57..bdc2a00 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -13,6 +13,11 @@ "action_helpers.too_far_even_at_its_slowest":"Too far even at its slowest setting: an optical span here is {span} km and it reaches {max} km. Add a regen site (Line system).", "action_helpers.unlocks_at_customer_level_n":"Unlocks at customer level {n}.", "actions.your_router_can_t_take_a":"Your router can't take a {port} port.
Upgrade it in the Infra tab.", +"automation.auto_accept_sales":"Auto-accept sales: {state}", +"automation.auto_pay_repairs":"Auto-pay repairs: {state}", +"automation.next_auto_check":"Time until the next automatic requirements check.", +"automation.repairs_when_affordable":"While playing, automatically pay for available rush repairs when you can afford them.", +"automation.sales_every_five_seconds":"Every 5 seconds while playing, accept only offers whose requirements and service capacity are ready.", "badges.a_petabit_a_second":"A Petabit a Second", "badges.a_secret_badge":"A secret badge", "badges.attend_a_conference":"Attend a conference.", diff --git a/tests/automation.test.js b/tests/automation.test.js new file mode 100644 index 0000000..b613873 --- /dev/null +++ b/tests/automation.test.js @@ -0,0 +1,319 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});compute()"); +} +function offer(ev, id, extra = {}) { + ev(`S.offers.push(${JSON.stringify({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`); +} + +test('auto-accept waits five real seconds at every game speed and the toggle stops it', () => { + for (const speed of [0.5, 1, 2, 4, 8]) { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'first'); + ev("ACT.autoToggle({k:'autoSales'});UI.autoSalesAt=1000"); + const start = ev('UI.autoSalesAt'); + ev(`UI.speed=${speed};automationTick(${start + 4999})`); + assert.equal(ev('S.biz.length'), 0, speed); + ev(`automationTick(${start + 5000})`); + assert.equal(ev('S.biz[0].id'), 'first', speed); + offer(ev, 'second'); + ev(`automationTick(${start + 9999})`); + assert.equal(ev('S.biz.length'), 1, speed); + ev(`automationTick(${start + 10000})`); + assert.equal(ev('S.biz.length'), 2, speed); + ev("ACT.autoToggle({k:'autoSales'})"); + offer(ev, 'off'); + ev(`automationTick(${start + 20000});ACT.accept({id:'off',auto:true})`); + assert.equal(ev('S.biz.length'), 2, speed); + assert.equal(ev('S.offers[0].id'), 'off', speed); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); + +test('Accept buttons share a real-time countdown in Deals, city offers and fiber broker offers', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + offer(ev, 'waiting', { reqs: ['gen'] }); + ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';UI.leftOpen=true;renderAll()"); + assert.equal(dom.window.document.querySelectorAll('[data-auto-sales]').length, 0); + ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); + const counts = () => [...dom.window.document.querySelectorAll('[data-auto-sales]')]; + assert.ok(counts().length >= 2, 'Deals and the city panel both show it'); + assert.ok(counts().every(el => el.textContent === '(5)')); + ev('testNow=2001;renderAutoCountdown()'); + assert.ok(counts().every(el => el.textContent === '(4)')); + ev('testNow=3000;UI.speed=8;renderAutoCountdown()'); + assert.ok(counts().every(el => el.textContent === '(3)')); + ev('UI.speed=0.5;renderAll();renderAutoCountdown()'); + assert.ok(counts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone'); + assert.match(dom.window.document.querySelector('#leftBody [data-act="accept"]').textContent, /Accept \(3\)/); + ev("ACT.buildPop({city:'ams'});S.links.push({id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:[],own:true,km:450,ready:0,cut:0,mo:1})"); + offer(ev, 'broker', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 1, what: 'One wave' }); + ev("compute();UI.sel={type:'link',id:'fiber'};renderPanel()"); + const broker = dom.window.document.querySelector('#panelBody [data-act="accept"] [data-auto-sales]'); + assert.ok(broker); + assert.equal(broker.textContent, '(3)'); + ev('testNow=6000;automationTick(testNow);renderAutoCountdown()'); + assert.equal(ev("S.biz.some(b=>b.id==='ready')"), true); + assert.equal(ev("S.offers.some(o=>o.id==='waiting')"), true, 'the countdown does not bypass requirements'); + assert.ok(counts().every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown'); + ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); + assert.equal(counts().length, 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('auto-accept leaves unready and expired offers alone without failure notifications', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'generator', { reqs: ['gen'] }); + offer(ev, 'missing-pop', { city: 'ams' }); + offer(ev, 'scrub', { type: 'scrub' }); + offer(ev, 'expired', { exp: 0 }); + offer(ev, 'ipv6', { reqs: ['ipv6'] }); + const log = ev('S.log.length'); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('S.offers.length'), 5); + assert.equal(ev('S.log.length'), log, 'no repeated failed manual-action toasts'); + ev('S.pops.fra.gen=true;compute();automationTick(10000)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.biz[0].id'), 'generator'); + // Manual acceptance keeps its existing sign-now, provision-later behavior. + ev("ACT.accept({id:'scrub'})"); + assert.equal(ev("S.biz.some(b=>b.id==='scrub')"), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the trial includes new bandwidth and later offers cannot overbook earlier accepted sales', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'one', { bw: 60 }); + offer(ev, 'two', { bw: 60 }); + const state = ev('JSON.stringify(S)'); + ev('window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap'); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + assert.equal(ev('JSON.stringify(S)'), state); + assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.offers[0].id'), 'two'); + assert.ok(ev('bizSf(S.biz[0])') >= 0.95); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('auto-accept checks actual circuits, latency and NNI capacity', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;compute()"); + offer(ev, 'circuit', { type: 'hft', city2: 'ams', bw: 10, latMax: 50, reqs: ['lat'] }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'POPs alone are not a circuit'); + ev("S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.offers[0].latMax=0.1'); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'latency budget must pass'); + ev("S.offers=[];window.fabric=FABS.find(f=>f.cities.includes('fra')).id;ACT.buyNni({city:'fra',prov:fabric,tier:0})"); + const prov = ev('fabric'); + const bandwidth = ev('NNI[0].g * 0.75'); + offer(ev, 'fabric-one', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] }); + offer(ev, 'fabric-two', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] }); + // Transit has enough headroom, so the second rejection is the shared NNI port. + ev("S.transit[0].tier=4;compute();S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)"); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.offers[0].id'), 'fabric-two'); + assert.ok(ev("nniUsed('fra',fabric)<=NNI[0].g")); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('new circuits do not take service away from healthy signed customers', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});S.transit[0].city='ams';compute()"); + offer(ev, 'existing', { bw: 80 }); + ev("ACT.accept({id:'existing'})"); + offer(ev, 'new-circuit', { type: 'l2vpn', city2: 'ams', bw: 50 }); + assert.equal(ev('bizWhy(S.biz[0]).length'), 0); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + assert.ok(ev('bizSf(S.biz[0])') >= 0.95, 'failed preview leaves the old routing result intact'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('fiber sales check live equipment and free spectrum, and repeated carrier orders still merge', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(14).fill('zr4'),km:450,sub:false,ready:0,cut:0,mo:1}];S.biz=[{id:'old',name:'Same Carrier',type:'wwave',city:'fra',city2:'ams',link:'fiber',bw:1,rate:1000,slots:1,reqs:[],mood:100,since:0}];compute()"); + offer(ev, 'full', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 2 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev("S.offers[0].slots=1;S.offers[0].name='Same Carrier';S.links[0].eqDown=10;compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'a broken amplifier prevents a wave sale'); + ev('S.links[0].eqDown=0;compute();S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.biz[0].slots'), 2); + assert.equal(ev('S.biz[0].rate'), 1600); + assert.equal(ev('freeCh(S.links[0])'), 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('capacity pair sales need completed infrastructure and reserve it for the accepted contract', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev("ACT.buildPop({city:'ams'});S.links=[{id:'own',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1}];compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz[0].link'), 'own'); + assert.equal(ev('capPend(S.biz[0])'), true, 'normal delivery handover still happens on a game day'); + offer(ev, 'second-pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'the same trench cannot be promised twice'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('future event demand is tested before signing, with booked events reserving headroom', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'event', { type: 'event', bw: 80, rate: 0, start: 10, dur: 3, fee: 5000, exp: 9 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz[0].start'), 10, 'the trial does not move the actual event date'); + assert.equal(ev('R.cityDem.fra'), 0); + offer(ev, 'too-large', { bw: 30 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev('S.offers[0].bw=10'); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + assert.equal(ev('S.biz[0].start'), 10); + assert.equal(ev('R.cityDem.fra'), 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('failed capacity trials restore game, routing and map state even when compute throws', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + ev("window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap;window.originalCompute=compute;window.compute=()=>{throw new Error('trial failed')}"); + assert.throws(() => ev('autoOffer(S.offers[0])'), /trial failed/); + assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true); + ev('window.compute=originalCompute'); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('S.offers.length'), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('auto-pay rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its toggle', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev(`S.cash=10000;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,chFail:{i:0,until:10},mo:1}]; + S.pops.fra.down=8;S.inc=[ + {id:'amp',type:'amp',ref:'fiber',until:10,cost:30000,msg:'Broken amp'}, + {id:'optic',type:'optic',ref:'fiber',until:10,cost:5000,msg:'Broken optic'}, + {id:'slow',type:'crash',ref:'fra',until:8,cost:2000,slow:true,msg:'Slow boot'}, + {id:'orphan',type:'amp',ref:'gone',until:10,cost:299,msg:'Removed equipment'}, + {id:'expired',type:'amp',ref:'fiber',until:0,cost:1000,msg:'Expired'}, + {id:'ddos',type:'ddos',ref:'fra',until:10,cost:1000,msg:'Attack'}]; + S.autoRepair=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(1)`); + assert.equal(ev('S.cash'), 3000); + assert.equal(ev("S.inc.some(i=>i.id==='optic')"), false); + assert.equal(ev('S.links[0].chFail'), null); + assert.equal(ev("S.inc.find(i=>i.id==='slow').rushed"), true); + assert.equal(ev("S.inc.find(i=>i.id==='slow').until"), 1); + assert.equal(ev("S.inc.find(i=>i.id==='slow').cost"), 0); + assert.equal(ev('S.pops.fra.down'), 1); + ev('automationTick(2)'); + assert.equal(ev('S.cash'), 3000, 'no duplicate rush payment'); + ev('S.cash=40000;automationTick(3)'); + assert.equal(ev('S.cash'), 10000); + assert.equal(ev('S.links[0].eqDown'), 0); + assert.equal(ev("S.inc.some(i=>i.id==='amp')"), false); + ev("ACT.autoToggle({k:'autoRepair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});automationTick(4)"); + assert.equal(ev('S.cash'), 10000); + assert.equal(ev("S.inc.some(i=>i.id==='new')"), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('automation pauses with the game, dialogs, hidden pages and game over', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'paused'); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;UI.speed=0;automationTick(5000)'); + assert.equal(ev('S.biz.length'), 0); + ev('UI.speed=1;automationTick(9999)'); + assert.equal(ev('S.biz.length'), 0, 'resume starts a fresh five-second wait'); + ev("openModal('

Menu

');automationTick(10000);closeModal()"); + ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'hidden'});automationTick(15000)"); + ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'visible'});S.lost=true;automationTick(20000);S.lost=false;automationTick(24999)"); + assert.equal(ev('S.biz.length'), 0); + ev('automationTick(25000)'); + assert.equal(ev('S.biz.length'), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the frame loop repairs new incidents without waiting for the sales timer', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev(`S.autoRepair=true;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,mo:1}]; + window.originalDay=dayTick;window.dayTick=()=>{S.links[0].eqDown=10;S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'Broken amp'})}; + window.cashBefore=S.cash;last=0;acc=DAY_MS;frame(16);window.dayTick=originalDay`); + assert.equal(ev('S.cash'), ev('cashBefore-1000')); + assert.equal(ev('S.inc.length'), 0); + assert.equal(ev('S.links[0].eqDown'), 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('toggles persist, old and malformed saves default off, and the timer resets for another game', () => { + const { ev, dom, errors } = load(); + setup(ev); + assert.equal(ev('S.autoSales||S.autoRepair'), false); + ev("ACT.autoToggle({k:'autoSales'});ACT.autoToggle({k:'autoRepair'});save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')))"); + assert.equal(ev('S.autoSales&&S.autoRepair'), true); + ev("delete S.autoSales;delete S.autoRepair;S=migrate(S)"); + assert.equal(ev('S.autoSales||S.autoRepair'), false); + ev("S.autoSales='true';S.autoRepair=1;S=migrate(S);ACT.autoToggle({k:'cash'})"); + assert.equal(ev('S.autoSales||S.autoRepair'), false); + ev('UI.autoGame=S;UI.autoSalesAt=0;S=migrate(JSON.parse(JSON.stringify(S)));S.autoSales=true;compute()'); + offer(ev, 'imported'); + ev('automationTick(100000)'); + assert.equal(ev('S.biz.length'), 0, 'an imported game does not inherit another game timer'); + ev('automationTick(105000)'); + assert.equal(ev('S.biz.length'), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('both toggle buttons work by keyboard-compatible DOM events on phones in every language', () => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); + setup(ev); + dom.window.innerWidth = 360; + for (const [tab, key] of [['deals', 'autoSales'], ['noc', 'autoRepair']]) { + ev(`ACT.leftTab({t:'${tab}'});renderAll()`); + const button = [...dom.window.document.querySelectorAll('#leftBody [data-act="autoToggle"]')].find(b => JSON.parse(b.dataset.args).k === key); + assert.ok(button, lang); + assert.equal(button.getAttribute('aria-pressed'), 'false', lang); + button.focus(); + button.click(); + const updated = dom.window.document.querySelector('#leftBody [data-act="autoToggle"]'); + assert.equal(updated.getAttribute('aria-pressed'), 'true', lang); + assert.equal(ev(`S.${key}`), true, lang); + assert.doesNotMatch(dom.window.document.getElementById('leftBody').textContent, /automation\./, lang); + } + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); From dd82737af8ebbe88bd5130616cbecbd7f5590439 Mon Sep 17 00:00:00 2001 From: logfro Date: Wed, 28 Oct 2026 02:55:12 +0100 Subject: [PATCH 10/64] Show auto-accept countdowns only for ready offers Hide the countdown when an offer has unmet requirements, missing locations, expired terms or insufficient service capacity. Keep manual acceptance available with its existing behavior. Share capacity previews across the Deals, city and fiber views, reuse them between automatic checks, and invalidate them after actions or incidents. Check changing requirements immediately and always perform a fresh full validation before automatically signing a contract. Add regression tests for blocked offers, requirements becoming fulfilled or unfulfilled, capacity changes and preview reuse. All 17 automation tests pass; the full independent branch passes 314 of 315 tests, with only the pre-existing locale-dependent subsea formatting failure remaining. --- CHANGELOG.md | 2 +- src/game/60-features/90-automation.js | 12 +++-- src/game/90-actions/90-action-helpers.js | 2 +- src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/70-link-panels.js | 4 +- tests/automation.test.js | 56 +++++++++++++++++++++--- 6 files changed, 64 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f87e28..07cdb6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Toggle auto-accept in Deals to check ready sales every five real seconds, including their requirements and available service capacity, with a countdown beside each Accept button. +- Toggle auto-accept in Deals to check ready sales every five real seconds, including their requirements and available service capacity, with a countdown beside eligible Accept buttons. - Toggle auto-pay repairs in the NOC to pay for affordable rush repairs automatically while the game runs. ## [1.35.0] — 2026-10-27 diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js index e8130b9..8a2b0e8 100644 --- a/src/game/60-features/90-automation.js +++ b/src/game/60-features/90-automation.js @@ -3,9 +3,15 @@ const AUTO_SALES_MS=5000; function autoSalesSeconds(now=performance.now()){if(!S||!S.autoSales)return null; const left=UI.autoGame===S&&autoActive()?AUTO_SALES_MS-(now-UI.autoSalesAt):AUTO_SALES_MS; return Math.max(1,Math.min(AUTO_SALES_MS/1000,Math.ceil(left/1000)));} -function autoAcceptLabel(){return tr('common.accept')+(S.autoSales?` (${autoSalesSeconds()})`:'');} -function renderAutoCountdown(now=performance.now()){const n=autoSalesSeconds(now);if(UI.autoCount===n)return;UI.autoCount=n; - for(const el of document.querySelectorAll('[data-auto-sales]'))el.textContent=n===null?'':`(${n})`;} +function autoCountdownReady(o){if(!S||!S.autoSales||!o||!(o.exp>S.day)||!bCities(o).every(popUp)||!reqOk(o))return false; + const inc=S.inc.map(i=>i.id).join('|');let c=UI.autoReady; + // Share capacity trials between views and keep them until the next check, action or incident. + if(!c||c.s!==S||c.at!==UI.autoSalesAt||c.inc!==inc||c.event!==S.nextEvent)c=UI.autoReady={s:S,at:UI.autoSalesAt,inc,event:S.nextEvent,offers:new Map()}; + if(!c.offers.has(o))c.offers.set(o,!!autoOffer(o));return c.offers.get(o);} +function autoAcceptLabel(o){return tr('common.accept')+(S.autoSales?` ${autoCountdownReady(o)?`(${autoSalesSeconds()})`:''}`:'');} +function renderAutoCountdown(now=performance.now()){const n=autoSalesSeconds(now);if(UI.autoCount===n&&UI.autoCountResult===R)return;UI.autoCount=n;UI.autoCountResult=R; + const offers=new Map((S?S.offers:[]).map(o=>[o.id,o])); + for(const el of document.querySelectorAll('[data-auto-sales]'))el.textContent=n!==null&&autoCountdownReady(offers.get(el.dataset.autoSales))?`(${n})`:'';} function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};} function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null; const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 67c8055..14e5aad 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -20,7 +20,7 @@ function chWhy(l,o){const O=OPT[o];if(O.lvl>lvl())return tr('action_helpers.unlo if((l.ch||[]).length+soldSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)}); for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&RG[p.rgen||0].clsinnerWidth>760&&innerWidth<=1200; function selectLink(id){UI.sel={type:'link',id};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;$('panel').classList.remove('full');renderPanel();renderLeft();} function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;const P=$('panel');if(P)P.classList.remove('full');if(!S.pops[c])UI.tab='cust';renderPanel();} diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 2f599cf..5070f9d 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -44,7 +44,7 @@ function renderLeft(){checkLayer(); if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${reqList(o)} -
${has?btn(autoAcceptLabel(),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} +
${has?btn(autoAcceptLabel(o),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }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')}

`; diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 5cba29a..3d15925 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -76,7 +76,7 @@ function dfPanel(l){ if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l); h+=`

${tr('link_panels.selling_spare_capacity')}

${tr('link_panels.other_carriers_rent_what_you_do')}

${tr('common.free_channels')}${fc} / ${chMax(l)}
${sold.map(b=>`
${esc(b.name)}
${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}
`).join('')} - ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(autoAcceptLabel(),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}
`;} + ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(autoAcceptLabel(off),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}`;} h+=`

${tr('common.optics')}

${tr('link_panels.each_channel_is_a_pair_of')}

`; if(l.own&&l.sub)h+=subUpgradePanel(l); for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k); @@ -93,7 +93,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(autoAcceptLabel(),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(autoAcceptLabel(o),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} diff --git a/tests/automation.test.js b/tests/automation.test.js index b613873..5ae9473 100644 --- a/tests/automation.test.js +++ b/tests/automation.test.js @@ -44,14 +44,16 @@ test('Accept buttons share a real-time countdown in Deals, city offers and fiber assert.equal(dom.window.document.querySelectorAll('[data-auto-sales]').length, 0); ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); const counts = () => [...dom.window.document.querySelectorAll('[data-auto-sales]')]; - assert.ok(counts().length >= 2, 'Deals and the city panel both show it'); - assert.ok(counts().every(el => el.textContent === '(5)')); + const readyCounts = () => counts().filter(el => el.dataset.autoSales === 'ready'); + assert.ok(readyCounts().length >= 2, 'Deals and the city panel both show it'); + assert.ok(readyCounts().every(el => el.textContent === '(5)')); + assert.ok(counts().filter(el => el.dataset.autoSales === 'waiting').every(el => el.textContent === ''), 'unmet requirements have no countdown'); ev('testNow=2001;renderAutoCountdown()'); - assert.ok(counts().every(el => el.textContent === '(4)')); + assert.ok(readyCounts().every(el => el.textContent === '(4)')); ev('testNow=3000;UI.speed=8;renderAutoCountdown()'); - assert.ok(counts().every(el => el.textContent === '(3)')); + assert.ok(readyCounts().every(el => el.textContent === '(3)')); ev('UI.speed=0.5;renderAll();renderAutoCountdown()'); - assert.ok(counts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone'); + assert.ok(readyCounts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone'); assert.match(dom.window.document.querySelector('#leftBody [data-act="accept"]').textContent, /Accept \(3\)/); ev("ACT.buildPop({city:'ams'});S.links.push({id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:[],own:true,km:450,ready:0,cut:0,mo:1})"); offer(ev, 'broker', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 1, what: 'One wave' }); @@ -62,13 +64,55 @@ test('Accept buttons share a real-time countdown in Deals, city offers and fiber ev('testNow=6000;automationTick(testNow);renderAutoCountdown()'); assert.equal(ev("S.biz.some(b=>b.id==='ready')"), true); assert.equal(ev("S.offers.some(o=>o.id==='waiting')"), true, 'the countdown does not bypass requirements'); - assert.ok(counts().every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown'); + offer(ev, 'next-ready'); + ev('renderAll();renderAutoCountdown()'); + assert.ok(counts().filter(el => el.dataset.autoSales === 'next-ready').every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown'); ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); assert.equal(counts().length, 0); assert.deepEqual(errors, []); dom.window.close(); }); +test('only ready offers get a countdown, including after requirements or capacity change', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + offer(ev, 'needs-generator', { reqs: ['gen'] }); + offer(ev, 'too-big', { bw: 1000 }); + offer(ev, 'expired', { exp: 0 }); + ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); + const count = id => dom.window.document.querySelector(`#leftBody [data-auto-sales="${id}"]`).textContent; + assert.equal(count('ready'), '(5)'); + assert.equal(count('needs-generator'), ''); + assert.equal(count('too-big'), ''); + assert.equal(count('expired'), ''); + ev('S.pops.fra.gen=true;after()'); + assert.equal(count('needs-generator'), '(5)', 'becoming eligible shows the timer'); + ev('S.pops.fra.gen=false;compute();renderAutoCountdown()'); + assert.equal(count('needs-generator'), '', 'a requirement becoming false hides it immediately'); + ev("S.offers.find(o=>o.id==='too-big').bw=2;after()"); + assert.equal(count('too-big'), '(5)', 'actions invalidate the capacity preview'); + ev('testNow=6000;automationTick(testNow);renderAutoCountdown()'); + assert.equal(ev("S.offers.some(o=>o.id==='needs-generator')"), true, 'acceptance checks requirements again'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('readiness trials are shared between views and are not repeated for every redraw', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';window.originalAutoOffer=autoOffer;window.trials=0;window.autoOffer=o=>{trials++;return originalAutoOffer(o)};ACT.autoToggle({k:'autoSales'})"); + assert.equal(ev('trials'), 1); + ev('renderAll();compute();renderAll();renderAutoCountdown()'); + assert.equal(ev('trials'), 1, 'ordinary routing refreshes reuse the preview'); + ev('after()'); + assert.equal(ev('trials'), 2, 'a real action refreshes readiness'); + ev('window.autoOffer=originalAutoOffer'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + test('auto-accept leaves unready and expired offers alone without failure notifications', () => { const { ev, dom, errors } = load(); setup(ev); From 2f5a924d6af83781d3678ae7bb4323d023b1663d Mon Sep 17 00:00:00 2001 From: Charles Miller Date: Wed, 28 Oct 2026 09:51:37 +0000 Subject: [PATCH 11/64] Add bulk IX peering and PoP redundancy utilities --- CHANGELOG.md | 2 + site/i18n/es.js | 19 +++ site/i18n/fr.js | 19 +++ site/i18n/it.js | 19 +++ site/i18n/pt.js | 19 +++ src/game/70-rules/95-utilities.js | 15 +++ src/game/90-actions/88-utilities.js | 15 +++ src/game/90-actions/89-game-and-settings.js | 1 + src/game/93-ui/50-city-panel.js | 1 + src/game/93-ui/55-utilities.js | 19 +++ src/i18n/en.js | 19 +++ tests/utilities.test.js | 137 ++++++++++++++++++++ 12 files changed, 285 insertions(+) create mode 100644 src/game/70-rules/95-utilities.js create mode 100644 src/game/90-actions/88-utilities.js create mode 100644 src/game/93-ui/55-utilities.js create mode 100644 tests/utilities.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index fb42726..6cb683f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Utilities join route servers and request eligible peers across every joined IX, and install missing PoP redundancy hardware in one purchase. + ## [1.36.0] — 2026-10-28 - You can put a link on standby, so one of two links between the same cities sits idle as a backup (#122). It carries traffic only when the other links are full or down, so its capacity is never wasted, and the map draws it dashed while it waits. The routing metric still applies to every link between the two cities. diff --git a/site/i18n/es.js b/site/i18n/es.js index 0c9a6df..7235f4c 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3064,4 +3064,23 @@ "tutorial.your_customers_want_the_whole":"Tus clientes quieren todo internet. Abre la pestaña Tránsito y compra un puerto a un operador.", "tutorial.your_router_is_live_press_launch":"Tu router está activo. Pulsa «Lanzar banda ancha» para vender internet a la gente de tu ciudad.", "ui.n_d_left":"quedan {n} d", +"utilities.hardware_note":"Solo hardware: reparte los servicios entre ambas ubicaciones y comprueba enlaces diversos y la capacidad del router restante para una protección completa ante fallos.", +"utilities.install_missing":"Instalar el hardware que falta", +"utilities.ix_peering":"Peering IX en toda la red", +"utilities.join_route_servers":"Unirse a todos los route servers ({n})", +"utilities.kit_complete":"Todos los componentes del kit están instalados.", +"utilities.kit_cost":"Pago único: {cost} · Coste mensual adicional: {mo}", +"utilities.kit_installed":"Kit de redundancia instalado en {city}.", +"utilities.peer_counts":"{ready} elegibles · {existing} existentes · {blocked} no disponibles", +"utilities.peering_note":"Solicita peers elegibles en cada IX al que te hayas unido. Se omiten las sesiones existentes, incluidos los peers del route server. Los rechazos y umbrales de tráfico siguen vigentes. No se compran puertos ni PNI de pago.", +"utilities.peers_requested":"Se han establecido {n} nuevas sesiones de peering IX.", +"utilities.quote_changed":"El presupuesto ha cambiado. Revisa el nuevo precio e inténtalo de nuevo.", +"utilities.redundancy_kit":"Kit de redundancia del POP", +"utilities.request_all":"Solicitar todos los peers elegibles ({n})", +"utilities.route_server_note":"Los peers de los route servers requieren una política de peering abierta. Las sesiones existentes siguen activas; no se compran puertos.", +"utilities.route_servers_joined":"Te has unido a {n} route servers.", +"utilities.second_site":"Segunda ubicación", +"utilities.title":"Utilidades", +"utilities.two_routers":"Al menos dos routers", +"utilities.view_pop":"Ver POP", }; diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 05ae35c..d4b87c0 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3064,4 +3064,23 @@ "tutorial.your_customers_want_the_whole":"Tes clients veulent tout Internet. Ouvre l’onglet Transit et achète un port chez un opérateur.", "tutorial.your_router_is_live_press_launch":"Ton routeur est en ligne. Appuie sur « Lancer le haut débit » pour vendre Internet aux habitants de ta ville.", "ui.n_d_left":"encore {n} j", +"utilities.hardware_note":"Matériel uniquement : répartis les services entre les deux sites et vérifie la diversité des liaisons et la capacité du routeur restant pour une protection complète contre les pannes.", +"utilities.install_missing":"Installer le matériel manquant", +"utilities.ix_peering":"Peering IX sur tout le réseau", +"utilities.join_route_servers":"Rejoindre tous les route servers ({n})", +"utilities.kit_complete":"Tous les composants du kit sont installés.", +"utilities.kit_cost":"Coût initial : {cost} · Coût mensuel supplémentaire : {mo}", +"utilities.kit_installed":"Kit de redondance installé à {city}.", +"utilities.peer_counts":"{ready} éligibles · {existing} existants · {blocked} indisponibles", +"utilities.peering_note":"Demande les peers éligibles sur chaque IX rejoint. Les sessions existantes, y compris via le route server, sont ignorées. Les refus et seuils de trafic restent applicables. Aucun port ni PNI payant ne sera acheté.", +"utilities.peers_requested":"{n} nouvelles sessions de peering IX établies.", +"utilities.quote_changed":"Le devis a changé. Vérifie le nouveau prix et réessaie.", +"utilities.redundancy_kit":"Kit de redondance du POP", +"utilities.request_all":"Demander tous les peers éligibles ({n})", +"utilities.route_server_note":"Les peers des route servers nécessitent une politique de peering ouverte. Les sessions existantes restent activées ; aucun port ne sera acheté.", +"utilities.route_servers_joined":"{n} route servers rejoints.", +"utilities.second_site":"Deuxième site", +"utilities.title":"Utilitaires", +"utilities.two_routers":"Au moins deux routeurs", +"utilities.view_pop":"Voir le POP", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index 92ca041..c6beb8c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3064,4 +3064,23 @@ "tutorial.your_customers_want_the_whole":"I tuoi clienti vogliono tutta internet. Apri la scheda Transit e compra una porta da un carrier.", "tutorial.your_router_is_live_press_launch":"Il tuo router è acceso. Premi “Lancia la banda larga” per vendere internet alla gente della tua città.", "ui.n_d_left":"ancora {n}g", +"utilities.hardware_note":"Solo hardware: distribuisci i servizi tra le due sedi e verifica percorsi diversi e capacità del router superstite per una protezione completa dai guasti.", +"utilities.install_missing":"Installa l’hardware mancante", +"utilities.ix_peering":"Peering IX su tutta la rete", +"utilities.join_route_servers":"Unisciti a tutti i route server ({n})", +"utilities.kit_complete":"Tutti i componenti del kit sono installati.", +"utilities.kit_cost":"Una tantum: {cost} · Costo mensile aggiuntivo: {mo}", +"utilities.kit_installed":"Kit di ridondanza installato a {city}.", +"utilities.peer_counts":"{ready} idonei · {existing} esistenti · {blocked} non disponibili", +"utilities.peering_note":"Richiedi i peer idonei in ogni IX a cui partecipi. Le sessioni esistenti, inclusi i peer del route server, vengono saltate. Rifiuti e soglie di traffico restano validi. Non vengono acquistate porte o PNI a pagamento.", +"utilities.peers_requested":"Stabilite {n} nuove sessioni di peering IX.", +"utilities.quote_changed":"Il preventivo è cambiato. Controlla il nuovo prezzo e riprova.", +"utilities.redundancy_kit":"Kit di ridondanza del POP", +"utilities.request_all":"Richiedi tutti i peer idonei ({n})", +"utilities.route_server_note":"I peer dei route server richiedono una politica di peering aperta. Le sessioni esistenti restano attive; non vengono acquistate porte.", +"utilities.route_servers_joined":"Collegati {n} route server.", +"utilities.second_site":"Seconda sede", +"utilities.title":"Utilità", +"utilities.two_routers":"Almeno due router", +"utilities.view_pop":"Mostra POP", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 6e219ea..cb05f6d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3064,4 +3064,23 @@ "tutorial.your_customers_want_the_whole":"Seus clientes querem a internet inteira. Abra a aba Transit e compre uma porta de uma operadora.", "tutorial.your_router_is_live_press_launch":"Seu router está no ar. Aperte “Lançar banda larga” para vender internet ao pessoal da sua cidade.", "ui.n_d_left":"faltam {n}d", +"utilities.hardware_note":"Apenas hardware: distribui os serviços pelos dois locais e verifica ligações diversas e capacidade do router restante para proteção completa contra falhas.", +"utilities.install_missing":"Instalar hardware em falta", +"utilities.ix_peering":"Peering IX em toda a rede", +"utilities.join_route_servers":"Aderir a todos os route servers ({n})", +"utilities.kit_complete":"Todos os componentes do kit estão instalados.", +"utilities.kit_cost":"Custo único: {cost} · Custo mensal adicional: {mo}", +"utilities.kit_installed":"Kit de redundância instalado em {city}.", +"utilities.peer_counts":"{ready} elegíveis · {existing} existentes · {blocked} indisponíveis", +"utilities.peering_note":"Solicita peers elegíveis em todos os IX a que aderiste. As sessões existentes, incluindo peers do route server, são ignoradas. Recusas e limites de tráfego continuam a aplicar-se. Não são compradas portas nem PNI pagos.", +"utilities.peers_requested":"Estabelecidas {n} novas sessões de peering IX.", +"utilities.quote_changed":"O orçamento mudou. Verifica o novo preço e tenta novamente.", +"utilities.redundancy_kit":"Kit de redundância do POP", +"utilities.request_all":"Solicitar todos os peers elegíveis ({n})", +"utilities.route_server_note":"Os peers dos route servers exigem uma política de peering aberta. As sessões existentes continuam ativas; não são compradas portas.", +"utilities.route_servers_joined":"Adesão a {n} route servers concluída.", +"utilities.second_site":"Segundo local", +"utilities.title":"Utilitários", +"utilities.two_routers":"Pelo menos dois routers", +"utilities.view_pop":"Ver POP", }; diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js new file mode 100644 index 0000000..3d99f22 --- /dev/null +++ b/src/game/70-rules/95-utilities.js @@ -0,0 +1,15 @@ +/* Utilities: plan from live state, then apply a whole batch with one recompute. */ +function utilityRouteServers(){return S?Object.keys(S.ixp).filter(ix=>isIx(ix)&&!S.myIx[ix]&&!S.rs[ix]):[];} +function utilityKit(city){const p=S&&S.pops[city];if(!p)return null; + const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0; + return {gen,site,router,cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), + mo:(gen?GEN_MO:0)+(site?SITE2_MO:0)+(router?routerMo(g):0)};} +function utilityPeers(){if(!S)return [];return Object.keys(S.ixp).filter(isIx).map(ix=>{ + const sessions=ixSessions(ix),requests=[],blocked=[];let existing=0; + for(const id of ixMembers(ix)){ + // Existing but temporarily down sessions must not be repeatedly requested. + if(sessions.has(id)||S.peers[id+'@'+ix]){existing++;continue;} + const chk=peerOk(id,'ix',ix);if(chk.ok)requests.push(id);else blocked.push({id,why:chk.why}); + } + return {ix,requests,blocked,existing}; +});} diff --git a/src/game/90-actions/88-utilities.js b/src/game/90-actions/88-utilities.js new file mode 100644 index 0000000..05b6615 --- /dev/null +++ b/src/game/90-actions/88-utilities.js @@ -0,0 +1,15 @@ +Object.assign(ACT,{ + utilities:({city}={})=>{if(S)utilitiesModal(city);}, + utilityPick:()=>{if(S&&$('utilityCity'))utilitiesModal($('utilityCity').value);}, + utilityRouteServers:({city}={})=>{if(!S)return;const ids=utilityRouteServers();for(const ix of ids)S.rs[ix]=true; + if(ids.length){sfx('build');after();}utilitiesModal(city,tr('utilities.route_servers_joined',{n:ids.length}));}, + utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||!q.cost)return; + // Prices can change while a modal is open. Refresh the quote before spending more. + if(q.cost!==+cost){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} + if(!spend(q.cost))return;const p=S.pops[city]; + if(q.gen)p.gen=true;if(q.site){p.site2=true;p.site2Day=S.day;}if(q.router)p.routers=2; + after();const msg=tr('utilities.kit_installed',{city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + utilityPeers:({city}={})=>{if(!S)return;const rows=utilityPeers();let n=0; + for(const row of rows)for(const id of row.requests){S.peers[id+'@'+row.ix]=true;n++;} + if(n){sfx('build');after();}utilitiesModal(city,tr('utilities.peers_requested',{n}));}, +}); diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 3ec2894..4774cf6 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -23,6 +23,7 @@ Object.assign(ACT,{ ${btn(tr('game_and_settings.scenarios_amp_weekly_challenge'),'scenarios',{},'ghost')} ${btn(tr('common.how_to_play'),'help',{},'ghost')} ${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''} + ${btn(tr('utilities.title'),'utilities',{},'')} ${btn(tr('common.settings'),'settings',{},'ghost')} ${btn(tr('common.start_a_new_network'),'resetAsk',{},'red')} ${chatHtml()}${issueHtml()}`);}, diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 853d518..71360d8 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -67,6 +67,7 @@ function cityPanel(c){ ${have.length?btn(tr('common.remove'),'rmCache',{id:(have.find(x=>x.site==='b')||have[0]).id},'ghost sm'):''}${btn(have.length?tr('common.box'):tr('common.request'),'cache',{city:c,net:n.id},'sm',!ok)}${S.pops[c].site2&&have.length?(()=>{const nb=have.filter(x=>x.site==='b').length,na=have.length-nb;return `
${tr('city_panel.boxes_a_in_a_b_in',{a:na,b:nb})}${na?btn(tr('city_panel.move_one_to_b'),'cacheSite',{city:c,net:n.id,s:'b'},'ghost sm'):''}${nb?btn(tr('city_panel.move_one_to_a'),'cacheSite',{city:c,net:n.id,s:'a'},'ghost sm'):''}
`;})():''}`;} h+=`
`; }else{ + h+=utilityKitHtml(c); const ls=S.links.filter(l=>l.a===c||l.b===c); const rt=p.routers||1,g=p.rgen||0,G=RG[g],nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||nodeCap(c),Ni=g===mainRG(G.cls)?mainRG(G.cls+1):-1,N=Ni>=0?RG[Ni]:null,pu=portsUsed(c),pm=portsMax(c); h+=`

${tr('common.routers')}

${tr('city_panel.the_model_sets_your_fastest')}

diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js new file mode 100644 index 0000000..3ed1e15 --- /dev/null +++ b/src/game/93-ui/55-utilities.js @@ -0,0 +1,19 @@ +function utilityKitHtml(city,modal=false){const q=utilityKit(city);if(!q)return '';const p=S.pops[city]; + const row=(label,have)=>`
${label}${have?tr('common.installed'):tr('common.none_304f')}
`; + return `

${tr('utilities.redundancy_kit')}

+ ${row(tr('common.backup_generator'),p.gen)}${row(tr('utilities.second_site'),p.site2)}${row(tr('utilities.two_routers'),(p.routers||1)>=2)} + ${q.cost?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.install_missing'),'utilityKit',{city,cost:q.cost,modal},'pink',S.cash`:`

${tr('utilities.kit_complete')}

`} +

${tr('utilities.hardware_note')}

`;} +function utilitiesModal(city,message){if(!S)return;const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); + city=S.pops[city]?city:UI.sel&&UI.sel.type==='city'&&S.pops[UI.sel.id]?UI.sel.id:S.pops[S.home]?S.home:cities[0]; + const rows=utilityPeers(),n=rows.reduce((v,r)=>v+r.requests.length,0),rs=utilityRouteServers().length; + openModal(`

${tr('utilities.title')}

+ ${message?`

${esc(message)}

`:''} +

${tr('utilities.ix_peering')}

${tr('utilities.peering_note')}

+
${btn(tr('utilities.join_route_servers',{n:rs}),'utilityRouteServers',{city},'pink',!rs)}${btn(tr('utilities.request_all',{n}),'utilityPeers',{city},'',!n)}
+

${tr('utilities.route_server_note')}

+ ${ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

${btn(tr('common.peering_policy'),'inbox',{},'ghost sm')}`:''} + ${rows.map(r=>`
${esc(ixName(r.ix))} · ${tr('utilities.peer_counts',{ready:r.requests.length,existing:r.existing,blocked:r.blocked.length})} + ${r.blocked.map(b=>`

${esc(NET[b.id].name)}: ${esc(b.why)}

`).join('')}
`).join('')}
+ ${cities.length?`
${btn(tr('utilities.view_pop'),'utilityPick',{},'sm')}
${utilityKitHtml(city,true)}`:''}`); +} diff --git a/src/i18n/en.js b/src/i18n/en.js index b8fd360..c25a5c2 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3065,4 +3065,23 @@ "tutorial.your_customers_want_the_whole":"Your customers want the whole internet. Open the Transit tab and buy a port from a carrier.", "tutorial.your_router_is_live_press_launch":"Your router is live. Press “Launch broadband” to sell internet to the people of your city.", "ui.n_d_left":"{n}d left", +"utilities.hardware_note":"Hardware only: assign services across both sites and check diverse links and surviving router capacity for full failover protection.", +"utilities.install_missing":"Install missing hardware", +"utilities.ix_peering":"Network-wide IX peering", +"utilities.join_route_servers":"Join all route servers ({n})", +"utilities.kit_complete":"All kit components are installed.", +"utilities.kit_cost":"One-off: {cost} · Additional monthly cost: {mo}", +"utilities.kit_installed":"Redundancy kit installed in {city}.", +"utilities.peer_counts":"{ready} eligible · {existing} existing · {blocked} unavailable", +"utilities.peering_note":"Request eligible peers at every IX you have joined. Existing sessions, including route-server peers, are skipped. Refusals and traffic thresholds still apply. No ports or paid PNIs are purchased.", +"utilities.peers_requested":"Established {n} new IX peering sessions.", +"utilities.quote_changed":"The quote changed. Review the new price and try again.", +"utilities.redundancy_kit":"PoP redundancy kit", +"utilities.request_all":"Request all eligible peers ({n})", +"utilities.route_server_note":"Route-server peers require an Open peering policy. Existing sessions stay enabled; no ports are bought.", +"utilities.route_servers_joined":"Joined {n} route servers.", +"utilities.second_site":"Second site", +"utilities.title":"Utilities", +"utilities.two_routers":"At least two routers", +"utilities.view_pop":"View PoP", }; diff --git a/tests/utilities.test.js b/tests/utilities.test.js new file mode 100644 index 0000000..1e86ee5 --- /dev/null +++ b/tests/utilities.test.js @@ -0,0 +1,137 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(t, opts) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;UI.speed=0;compute()"); + return h; +} + +test('redundancy kit matches normal purchases, including cash, monthly costs and save reload', t => { + const a = setup(t), b = setup(t); + const quote = JSON.parse(a.ev("JSON.stringify(utilityKit('fra'))")); + const cash = a.ev('S.cash'), monthly = a.ev('R.costMo'); + a.ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})"); + b.ev("ACT.addGen({city:'fra'});ACT.addSite({city:'fra'});ACT.addRouter({city:'fra'})"); + for (const expr of ['S.pops.fra', 'R.cost']) + assert.deepEqual(JSON.parse(a.ev(`JSON.stringify(${expr})`)), JSON.parse(b.ev(`JSON.stringify(${expr})`))); + assert.equal(a.ev('S.cash'), cash - quote.cost); + assert.equal(a.ev('S.cash'), b.ev('S.cash')); + assert.equal(a.ev('R.costMo'), monthly + quote.mo); + const before = a.ev('JSON.stringify(S)'); + a.ev("ACT.utilityKit({city:'fra',cost:0})"); + assert.equal(a.ev('JSON.stringify(S)'), before, 'repeat does not buy more hardware'); + a.ev("save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));compute()"); + assert.equal(a.ev('S.pops.fra.gen && S.pops.fra.site2 && S.pops.fra.routers===2'), true); + assert.deepEqual(a.errors, []); + assert.deepEqual(b.errors, []); +}); + +test('kit is all-or-nothing, rejects stale quotes and handles missing PoPs', t => { + const { ev, errors } = setup(t); + ev("window.quote=utilityKit('fra').cost;S.cash=quote-1"); + const before = ev('JSON.stringify(S.pops.fra)'); + ev("ACT.utilityKit({city:'fra',cost:quote})"); + assert.equal(ev('JSON.stringify(S.pops.fra)'), before); + assert.equal(ev('S.cash'), ev('quote-1')); + ev("S.cash=1e8;ACT.utilityKit({city:'fra',cost:quote+1,modal:true})"); + assert.equal(ev('JSON.stringify(S.pops.fra)'), before); + assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/); + ev("ACT.utilityKit({city:'not-a-city',cost:0});ACT.utilityKit({city:'ams',cost:0})"); + assert.deepEqual(errors, []); +}); + +test('kit buys only missing components and preserves extra routers and service placement', t => { + const { ev, errors } = setup(t); + ev("S.pops.fra.routers=4;S.pops.fra.gen=true;S.pops.fra.rgen=3;S.transit.push({id:'test',city:'fra',net:'cog',tier:0,site:'a'});compute()"); + const cash = ev('S.cash'); + assert.equal(ev("utilityKit('fra').cost"), ev('SITE2_COST')); + ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})"); + assert.equal(ev('S.cash'), cash - ev('SITE2_COST')); + assert.equal(ev('S.pops.fra.routers'), 4); + assert.equal(ev('S.pops.fra.rgen'), 3); + assert.equal(ev('S.transit[0].site'), 'a'); + assert.deepEqual(errors, []); +}); + +test('bulk peering covers rival IXs, respects policy and is idempotent', t => { + const { ev, errors } = setup(t); + ev("ACT.buildPop({city:'ams'});ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0});ACT.buyIx({city:'ams~3',tier:0});ACT.rs({city:'ams'});compute()"); + const expected = JSON.parse(ev("JSON.stringify(utilityPeers().flatMap(r=>r.requests.map(id=>id+'@'+r.ix)))")); + assert.ok(expected.length > 0); + assert.ok(expected.some(k => k.endsWith('@ams~3'))); + const blocked = JSON.parse(ev("JSON.stringify(utilityPeers().flatMap(r=>r.blocked.map(b=>b.id+'@'+r.ix)))")); + assert.ok(blocked.length > 0); + const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), pnis = ev('JSON.stringify(S.pni)'); + ev('ACT.utilityPeers()'); + for (const k of expected) assert.equal(ev(`S.peers[${JSON.stringify(k)}]`), true, k); + for (const k of blocked) assert.equal(ev(`!!S.peers[${JSON.stringify(k)}]`), false, k); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('JSON.stringify(S.ixp)'), ports); + assert.equal(ev('JSON.stringify(S.pni)'), pnis); + const peers = ev('JSON.stringify(S.peers)'); + ev('ACT.utilityPeers()'); + assert.equal(ev('JSON.stringify(S.peers)'), peers); + assert.equal(ev('utilityPeers().reduce((n,r)=>n+r.requests.length,0)'), 0); + assert.deepEqual(errors, []); +}); + +test('bulk peering skips disconnected IXs, route server coverage and existing down sessions', t => { + const { ev, errors } = setup(t); + assert.equal(ev('utilityPeers().length'), 0); + ev("ACT.utilityPeers();ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'});S.peers['ggl@fra']=true;compute()"); + assert.equal(ev("utilityPeers()[0].requests.includes('drz')"), false); + assert.equal(ev("utilityPeers()[0].requests.includes('ggl')"), false); + ev("ACT.cancelIx({city:'fra',sure:1,ok:1});ACT.utilityPeers()"); + assert.equal(ev('utilityPeers().length'), 0); + assert.deepEqual(errors, []); +}); + +test('utilities are available from the menu and PoP Infra in every language', t => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { ev, dom, errors } = setup(t, lang === 'en' ? {} : { lang }); + ev('ACT.menu()'); + assert.ok(dom.window.document.querySelector('[data-act="utilities"]'), lang); + ev("selectCity('fra');ACT.tab({t:'links'})"); + assert.ok(dom.window.document.querySelector('#panelBody [data-act="utilityKit"]'), lang); + ev('ACT.utilities()'); + assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra'); + assert.ok(!dom.window.document.querySelector('#modalCard').textContent.includes('utilities.'), lang); + assert.deepEqual(errors, [], lang); + } +}); + +test('join all route servers preserves existing sessions and covers rival and remote IX ports', t => { + const { ev, errors } = setup(t); + ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'});window.fabric=FABS.find(f=>f.cities.includes('fra')&&f.cities.includes('ams')).id;S.links.push({id:'remote',a:'fra',b:'ams',kind:'vxc',prov:fabric,vt:1,km:kmBetween('fra','ams'),sub:false,mo:0,cut:0,day:S.day});ACT.buyIx({city:'ams',tier:0});ACT.buyIx({city:'ams~3',tier:0});compute()"); + assert.equal(ev("isRemote('ams')"), true); + assert.deepEqual(JSON.parse(ev('JSON.stringify(utilityRouteServers().sort())')), ['ams', 'ams~3']); + const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), peers = ev('JSON.stringify(S.peers)'); + ev('ACT.utilityRouteServers()'); + assert.equal(ev("S.rs.fra && S.rs.ams && S.rs['ams~3']"), true); + assert.equal(ev("ixSessions('ams').has('drz')"), true); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('JSON.stringify(S.ixp)'), ports); + assert.equal(ev('JSON.stringify(S.peers)'), peers); + const rs = ev('JSON.stringify(S.rs)'); + ev('ACT.utilityRouteServers()'); + assert.equal(ev('JSON.stringify(S.rs)'), rs, 'repeat never toggles a session off'); + assert.equal(ev('utilityRouteServers().length'), 0); + assert.deepEqual(errors, []); +}); + +test('route-server batch leaves peering policy and player-owned exchanges alone', t => { + const { ev, errors } = setup(t); + ev('ACT.utilityRouteServers()'); + assert.equal(ev('Object.keys(S.rs).length'), 0, 'does not join an IX without a port'); + ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.inboxPol({p:'closed'});ACT.utilityRouteServers()"); + assert.equal(ev('ppol()'), 'closed'); + assert.equal(ev('S.rs.fra'), true); + assert.equal(ev("ixSessions('fra').has('drz')"), false, 'does not bypass closed policy'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Off while your peering policy/); + ev("S.myIx.fra={members:[],fab:0};S.rs.fra=false;ACT.utilityRouteServers()"); + assert.equal(ev('S.rs.fra'), false, 'owned exchange has no join-route-server control'); + assert.deepEqual(errors, []); +}); From 0f1db884c22beca0b7dfe44015e49d2f021a6a71 Mon Sep 17 00:00:00 2001 From: Charles Miller Date: Wed, 28 Oct 2026 10:51:54 +0000 Subject: [PATCH 12/64] Balance PoP caches and request missing caches per site --- CHANGELOG.md | 2 +- site/i18n/es.js | 14 +++- site/i18n/fr.js | 14 +++- site/i18n/it.js | 14 +++- site/i18n/pt.js | 14 +++- src/game/70-rules/95-utilities.js | 11 ++- src/game/90-actions/88-utilities.js | 12 ++- src/game/93-ui/55-utilities.js | 10 ++- src/i18n/en.js | 14 +++- tests/utilities-caches.test.js | 109 ++++++++++++++++++++++++++++ 10 files changed, 187 insertions(+), 27 deletions(-) create mode 100644 tests/utilities-caches.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cb683f..8f40c93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Utilities join route servers and request eligible peers across every joined IX, and install missing PoP redundancy hardware in one purchase. +- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. ## [1.36.0] — 2026-10-28 diff --git a/site/i18n/es.js b/site/i18n/es.js index 7235f4c..c94e3b2 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3064,19 +3064,25 @@ "tutorial.your_customers_want_the_whole":"Tus clientes quieren todo internet. Abre la pestaña Tránsito y compra un puerto a un operador.", "tutorial.your_router_is_live_press_launch":"Tu router está activo. Pulsa «Lanzar banda ancha» para vender internet a la gente de tu ciudad.", "ui.n_d_left":"quedan {n} d", -"utilities.hardware_note":"Solo hardware: reparte los servicios entre ambas ubicaciones y comprueba enlaces diversos y la capacidad del router restante para una protección completa ante fallos.", -"utilities.install_missing":"Instalar el hardware que falta", +"utilities.apply_kit":"Aplicar kit de redundancia", +"utilities.cache_moves":"Cachés que mover: {n} (equilibradas por proveedor)", +"utilities.cache_note":"Solicita una caché por proveedor elegible en cada ubicación existente. Se conservan las cachés actuales; los proveedores siguen exigiendo tráfico suficiente.", +"utilities.cache_ports":"Se necesitan {need} puertos libres de router; disponibles: {free}. No se solicita nada hasta que haya espacio para todas.", +"utilities.cache_quote":"{n} cachés nuevas · Hardware gratuito · Coste mensual adicional: {mo}", +"utilities.caches_requested":"Se han instalado {n} cachés en {city}.", "utilities.ix_peering":"Peering IX en toda la red", "utilities.join_route_servers":"Unirse a todos los route servers ({n})", -"utilities.kit_complete":"Todos los componentes del kit están instalados.", +"utilities.kit_applied":"Redundancia actualizada en {city}.", +"utilities.kit_balanced":"Hardware instalado y cachés equilibradas.", "utilities.kit_cost":"Pago único: {cost} · Coste mensual adicional: {mo}", -"utilities.kit_installed":"Kit de redundancia instalado en {city}.", "utilities.peer_counts":"{ready} elegibles · {existing} existentes · {blocked} no disponibles", "utilities.peering_note":"Solicita peers elegibles en cada IX al que te hayas unido. Se omiten las sesiones existentes, incluidos los peers del route server. Los rechazos y umbrales de tráfico siguen vigentes. No se compran puertos ni PNI de pago.", "utilities.peers_requested":"Se han establecido {n} nuevas sesiones de peering IX.", "utilities.quote_changed":"El presupuesto ha cambiado. Revisa el nuevo precio e inténtalo de nuevo.", "utilities.redundancy_kit":"Kit de redundancia del POP", +"utilities.redundancy_note":"Las cachés existentes se equilibran por proveedor. Reparte por separado las conexiones IX, PNI y transit entre ubicaciones y comprueba enlaces diversos y capacidad de reserva de los routers.", "utilities.request_all":"Solicitar todos los peers elegibles ({n})", +"utilities.request_caches":"Solicitar las cachés que faltan ({n})", "utilities.route_server_note":"Los peers de los route servers requieren una política de peering abierta. Las sesiones existentes siguen activas; no se compran puertos.", "utilities.route_servers_joined":"Te has unido a {n} route servers.", "utilities.second_site":"Segunda ubicación", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index d4b87c0..8410879 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3064,19 +3064,25 @@ "tutorial.your_customers_want_the_whole":"Tes clients veulent tout Internet. Ouvre l’onglet Transit et achète un port chez un opérateur.", "tutorial.your_router_is_live_press_launch":"Ton routeur est en ligne. Appuie sur « Lancer le haut débit » pour vendre Internet aux habitants de ta ville.", "ui.n_d_left":"encore {n} j", -"utilities.hardware_note":"Matériel uniquement : répartis les services entre les deux sites et vérifie la diversité des liaisons et la capacité du routeur restant pour une protection complète contre les pannes.", -"utilities.install_missing":"Installer le matériel manquant", +"utilities.apply_kit":"Appliquer le kit de redondance", +"utilities.cache_moves":"Caches à déplacer : {n} (équilibrés par fournisseur)", +"utilities.cache_note":"Demande un cache par fournisseur éligible sur chaque site existant. Les caches existants sont conservés ; les fournisseurs exigent toujours un trafic suffisant.", +"utilities.cache_ports":"Il faut {need} ports de routeur libres ; {free} disponibles. Aucune demande tant que tous les caches ne peuvent pas être installés.", +"utilities.cache_quote":"{n} nouveaux caches · Matériel gratuit · Coût mensuel supplémentaire : {mo}", +"utilities.caches_requested":"{n} caches installés à {city}.", "utilities.ix_peering":"Peering IX sur tout le réseau", "utilities.join_route_servers":"Rejoindre tous les route servers ({n})", -"utilities.kit_complete":"Tous les composants du kit sont installés.", +"utilities.kit_applied":"Redondance mise à jour à {city}.", +"utilities.kit_balanced":"Matériel installé et caches équilibrés.", "utilities.kit_cost":"Coût initial : {cost} · Coût mensuel supplémentaire : {mo}", -"utilities.kit_installed":"Kit de redondance installé à {city}.", "utilities.peer_counts":"{ready} éligibles · {existing} existants · {blocked} indisponibles", "utilities.peering_note":"Demande les peers éligibles sur chaque IX rejoint. Les sessions existantes, y compris via le route server, sont ignorées. Les refus et seuils de trafic restent applicables. Aucun port ni PNI payant ne sera acheté.", "utilities.peers_requested":"{n} nouvelles sessions de peering IX établies.", "utilities.quote_changed":"Le devis a changé. Vérifie le nouveau prix et réessaie.", "utilities.redundancy_kit":"Kit de redondance du POP", +"utilities.redundancy_note":"Les caches existants sont équilibrés par fournisseur. Répartis séparément les connexions IX, PNI et transit entre les sites et vérifie la diversité des liaisons et la capacité de réserve des routeurs.", "utilities.request_all":"Demander tous les peers éligibles ({n})", +"utilities.request_caches":"Demander les caches manquants ({n})", "utilities.route_server_note":"Les peers des route servers nécessitent une politique de peering ouverte. Les sessions existantes restent activées ; aucun port ne sera acheté.", "utilities.route_servers_joined":"{n} route servers rejoints.", "utilities.second_site":"Deuxième site", diff --git a/site/i18n/it.js b/site/i18n/it.js index c6beb8c..6121288 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3064,19 +3064,25 @@ "tutorial.your_customers_want_the_whole":"I tuoi clienti vogliono tutta internet. Apri la scheda Transit e compra una porta da un carrier.", "tutorial.your_router_is_live_press_launch":"Il tuo router è acceso. Premi “Lancia la banda larga” per vendere internet alla gente della tua città.", "ui.n_d_left":"ancora {n}g", -"utilities.hardware_note":"Solo hardware: distribuisci i servizi tra le due sedi e verifica percorsi diversi e capacità del router superstite per una protezione completa dai guasti.", -"utilities.install_missing":"Installa l’hardware mancante", +"utilities.apply_kit":"Applica il kit di ridondanza", +"utilities.cache_moves":"Cache da spostare: {n} (bilanciate per fornitore)", +"utilities.cache_note":"Richiedi una cache per ogni fornitore idoneo in ciascuna sede esistente. Le cache esistenti restano; i fornitori richiedono comunque traffico sufficiente.", +"utilities.cache_ports":"Servono {need} porte router libere; disponibili: {free}. Nessuna richiesta finché non ci sarà spazio per tutte le cache.", +"utilities.cache_quote":"{n} nuove cache · Hardware gratuito · Costo mensile aggiuntivo: {mo}", +"utilities.caches_requested":"Installate {n} cache a {city}.", "utilities.ix_peering":"Peering IX su tutta la rete", "utilities.join_route_servers":"Unisciti a tutti i route server ({n})", -"utilities.kit_complete":"Tutti i componenti del kit sono installati.", +"utilities.kit_applied":"Ridondanza aggiornata a {city}.", +"utilities.kit_balanced":"Hardware installato e cache bilanciate.", "utilities.kit_cost":"Una tantum: {cost} · Costo mensile aggiuntivo: {mo}", -"utilities.kit_installed":"Kit di ridondanza installato a {city}.", "utilities.peer_counts":"{ready} idonei · {existing} esistenti · {blocked} non disponibili", "utilities.peering_note":"Richiedi i peer idonei in ogni IX a cui partecipi. Le sessioni esistenti, inclusi i peer del route server, vengono saltate. Rifiuti e soglie di traffico restano validi. Non vengono acquistate porte o PNI a pagamento.", "utilities.peers_requested":"Stabilite {n} nuove sessioni di peering IX.", "utilities.quote_changed":"Il preventivo è cambiato. Controlla il nuovo prezzo e riprova.", "utilities.redundancy_kit":"Kit di ridondanza del POP", +"utilities.redundancy_note":"Le cache esistenti vengono bilanciate per fornitore. Distribuisci separatamente le connessioni IX, PNI e transit tra le sedi e verifica percorsi diversi e capacità di riserva dei router.", "utilities.request_all":"Richiedi tutti i peer idonei ({n})", +"utilities.request_caches":"Richiedi le cache mancanti ({n})", "utilities.route_server_note":"I peer dei route server richiedono una politica di peering aperta. Le sessioni esistenti restano attive; non vengono acquistate porte.", "utilities.route_servers_joined":"Collegati {n} route server.", "utilities.second_site":"Seconda sede", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index cb05f6d..f9407d4 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3064,19 +3064,25 @@ "tutorial.your_customers_want_the_whole":"Seus clientes querem a internet inteira. Abra a aba Transit e compre uma porta de uma operadora.", "tutorial.your_router_is_live_press_launch":"Seu router está no ar. Aperte “Lançar banda larga” para vender internet ao pessoal da sua cidade.", "ui.n_d_left":"faltam {n}d", -"utilities.hardware_note":"Apenas hardware: distribui os serviços pelos dois locais e verifica ligações diversas e capacidade do router restante para proteção completa contra falhas.", -"utilities.install_missing":"Instalar hardware em falta", +"utilities.apply_kit":"Aplicar kit de redundância", +"utilities.cache_moves":"Caches a mover: {n} (equilibradas por fornecedor)", +"utilities.cache_note":"Solicita uma cache por fornecedor elegível em cada local existente. As caches existentes são mantidas; os fornecedores continuam a exigir tráfego suficiente.", +"utilities.cache_ports":"São necessárias {need} portas livres no router; disponíveis: {free}. Nada é solicitado até haver espaço para todas.", +"utilities.cache_quote":"{n} novas caches · Hardware gratuito · Custo mensal adicional: {mo}", +"utilities.caches_requested":"Instaladas {n} caches em {city}.", "utilities.ix_peering":"Peering IX em toda a rede", "utilities.join_route_servers":"Aderir a todos os route servers ({n})", -"utilities.kit_complete":"Todos os componentes do kit estão instalados.", +"utilities.kit_applied":"Redundância atualizada em {city}.", +"utilities.kit_balanced":"Hardware instalado e caches equilibradas.", "utilities.kit_cost":"Custo único: {cost} · Custo mensal adicional: {mo}", -"utilities.kit_installed":"Kit de redundância instalado em {city}.", "utilities.peer_counts":"{ready} elegíveis · {existing} existentes · {blocked} indisponíveis", "utilities.peering_note":"Solicita peers elegíveis em todos os IX a que aderiste. As sessões existentes, incluindo peers do route server, são ignoradas. Recusas e limites de tráfego continuam a aplicar-se. Não são compradas portas nem PNI pagos.", "utilities.peers_requested":"Estabelecidas {n} novas sessões de peering IX.", "utilities.quote_changed":"O orçamento mudou. Verifica o novo preço e tenta novamente.", "utilities.redundancy_kit":"Kit de redundância do POP", +"utilities.redundancy_note":"As caches existentes são equilibradas por fornecedor. Distribui separadamente as ligações IX, PNI e transit pelos locais e verifica ligações diversas e capacidade de reserva dos routers.", "utilities.request_all":"Solicitar todos os peers elegíveis ({n})", +"utilities.request_caches":"Solicitar caches em falta ({n})", "utilities.route_server_note":"Os peers dos route servers exigem uma política de peering aberta. As sessões existentes continuam ativas; não são compradas portas.", "utilities.route_servers_joined":"Adesão a {n} route servers concluída.", "utilities.second_site":"Segundo local", diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index 3d99f22..646f760 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -1,8 +1,17 @@ /* Utilities: plan from live state, then apply a whole batch with one recompute. */ function utilityRouteServers(){return S?Object.keys(S.ixp).filter(ix=>isIx(ix)&&!S.myIx[ix]&&!S.rs[ix]):[];} +function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new Map(),moves=[]; + for(const c of S.caches)if(c.city===city){let g=groups.get(c.net);if(!g){g={a:[],b:[]};groups.set(c.net,g);}g[c.site==='b'?'b':'a'].push(c);} + for(const g of groups.values()){const from=g.a.length>g.b.length?'a':'b',to=from==='a'?'b':'a'; + for(const c of g[from].slice(0,Math.floor(Math.abs(g.a.length-g.b.length)/2)))moves.push({id:c.id,site:to});} + return moves;} +function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have=new Set(); + for(const c of S.caches)if(c.city===city)have.add(c.net+'@'+(c.site==='b'?'b':'a')); + for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min)for(const site of sites)if(!have.has(n.id+'@'+site))add.push({net:n.id,site}); + return {add,key:add.map(c=>c.net+'@'+c.site).join(','),mo:add.length*CACHE_MO,free:Math.max(0,portsMax(city)-portsUsed(city))};} function utilityKit(city){const p=S&&S.pops[city];if(!p)return null; const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0; - return {gen,site,router,cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), + return {gen,site,router,moves:utilityCacheMoves(city),cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), mo:(gen?GEN_MO:0)+(site?SITE2_MO:0)+(router?routerMo(g):0)};} function utilityPeers(){if(!S)return [];return Object.keys(S.ixp).filter(isIx).map(ix=>{ const sessions=ixSessions(ix),requests=[],blocked=[];let existing=0; diff --git a/src/game/90-actions/88-utilities.js b/src/game/90-actions/88-utilities.js index 05b6615..57f818d 100644 --- a/src/game/90-actions/88-utilities.js +++ b/src/game/90-actions/88-utilities.js @@ -3,12 +3,18 @@ Object.assign(ACT,{ utilityPick:()=>{if(S&&$('utilityCity'))utilitiesModal($('utilityCity').value);}, utilityRouteServers:({city}={})=>{if(!S)return;const ids=utilityRouteServers();for(const ix of ids)S.rs[ix]=true; if(ids.length){sfx('build');after();}utilitiesModal(city,tr('utilities.route_servers_joined',{n:ids.length}));}, - utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||!q.cost)return; + utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||(!q.cost&&!q.moves.length))return; // Prices can change while a modal is open. Refresh the quote before spending more. if(q.cost!==+cost){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} - if(!spend(q.cost))return;const p=S.pops[city]; + if(q.cost&&!spend(q.cost))return;const p=S.pops[city]; if(q.gen)p.gen=true;if(q.site){p.site2=true;p.site2Day=S.day;}if(q.router)p.routers=2; - after();const msg=tr('utilities.kit_installed',{city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + const moves=new Map(q.moves.map(m=>[m.id,m.site]));for(const c of S.caches)if(moves.has(c.id))c.site=moves.get(c.id); + after();const msg=tr('utilities.kit_applied',{city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + utilityCaches:({city,quote,modal})=>{const q=utilityCaches(city);if(!q||!q.add.length)return; + if(q.key!==quote){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} + if(!portGate(city,q.add.length))return; + for(const c of q.add)S.caches.push({id:uid(),city,net:c.net,site:c.site}); + sfx('build');after();const msg=tr('utilities.caches_requested',{n:q.add.length,city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, utilityPeers:({city}={})=>{if(!S)return;const rows=utilityPeers();let n=0; for(const row of rows)for(const id of row.requests){S.peers[id+'@'+row.ix]=true;n++;} if(n){sfx('build');after();}utilitiesModal(city,tr('utilities.peers_requested',{n}));}, diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js index 3ed1e15..2d50105 100644 --- a/src/game/93-ui/55-utilities.js +++ b/src/game/93-ui/55-utilities.js @@ -2,8 +2,14 @@ function utilityKitHtml(city,modal=false){const q=utilityKit(city);if(!q)return const row=(label,have)=>`
${label}${have?tr('common.installed'):tr('common.none_304f')}
`; return `

${tr('utilities.redundancy_kit')}

${row(tr('common.backup_generator'),p.gen)}${row(tr('utilities.second_site'),p.site2)}${row(tr('utilities.two_routers'),(p.routers||1)>=2)} - ${q.cost?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.install_missing'),'utilityKit',{city,cost:q.cost,modal},'pink',S.cash`:`

${tr('utilities.kit_complete')}

`} -

${tr('utilities.hardware_note')}

`;} +

${tr('utilities.cache_moves',{n:q.moves.length})}

+ ${q.cost||q.moves.length?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.apply_kit'),'utilityKit',{city,cost:q.cost,modal},'pink',q.cost>0&&S.cash`:`

${tr('utilities.kit_balanced')}

`} +

${tr('utilities.redundancy_note')}

${utilityCachesHtml(city,modal)}`;} +function utilityCachesHtml(city,modal=false){const q=utilityCaches(city);if(!q)return ''; + return `

${tr('common.embedded_caches')}

${tr('utilities.cache_note')}

+

${tr('utilities.cache_quote',{n:q.add.length,mo:fmt$(q.mo)})}

+ ${q.free${tr('utilities.cache_ports',{need:q.add.length,free:fmtPorts(q.free)})}

`:''} +
${btn(tr('utilities.request_caches',{n:q.add.length}),'utilityCaches',{city,quote:q.key,modal},'pink',!q.add.length||q.free+1e-9
`;} function utilitiesModal(city,message){if(!S)return;const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); city=S.pops[city]?city:UI.sel&&UI.sel.type==='city'&&S.pops[UI.sel.id]?UI.sel.id:S.pops[S.home]?S.home:cities[0]; const rows=utilityPeers(),n=rows.reduce((v,r)=>v+r.requests.length,0),rs=utilityRouteServers().length; diff --git a/src/i18n/en.js b/src/i18n/en.js index c25a5c2..34d1a40 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3065,19 +3065,25 @@ "tutorial.your_customers_want_the_whole":"Your customers want the whole internet. Open the Transit tab and buy a port from a carrier.", "tutorial.your_router_is_live_press_launch":"Your router is live. Press “Launch broadband” to sell internet to the people of your city.", "ui.n_d_left":"{n}d left", -"utilities.hardware_note":"Hardware only: assign services across both sites and check diverse links and surviving router capacity for full failover protection.", -"utilities.install_missing":"Install missing hardware", +"utilities.apply_kit":"Apply redundancy kit", +"utilities.cache_moves":"Cache boxes to move: {n} (balanced per provider)", +"utilities.cache_note":"Request one cache per eligible provider at each existing site. Existing boxes are kept; providers still require sufficient traffic.", +"utilities.cache_ports":"Requires {need} free router ports; {free} available. Nothing is requested until the whole batch fits.", +"utilities.cache_quote":"{n} new cache boxes · Free hardware · Additional monthly cost: {mo}", +"utilities.caches_requested":"Installed {n} cache boxes in {city}.", "utilities.ix_peering":"Network-wide IX peering", "utilities.join_route_servers":"Join all route servers ({n})", -"utilities.kit_complete":"All kit components are installed.", +"utilities.kit_applied":"Redundancy updated in {city}.", +"utilities.kit_balanced":"Hardware installed and caches balanced.", "utilities.kit_cost":"One-off: {cost} · Additional monthly cost: {mo}", -"utilities.kit_installed":"Redundancy kit installed in {city}.", "utilities.peer_counts":"{ready} eligible · {existing} existing · {blocked} unavailable", "utilities.peering_note":"Request eligible peers at every IX you have joined. Existing sessions, including route-server peers, are skipped. Refusals and traffic thresholds still apply. No ports or paid PNIs are purchased.", "utilities.peers_requested":"Established {n} new IX peering sessions.", "utilities.quote_changed":"The quote changed. Review the new price and try again.", "utilities.redundancy_kit":"PoP redundancy kit", +"utilities.redundancy_note":"Existing caches are balanced per provider. Split IX, PNI and transit connections across sites separately, and check diverse links and spare router capacity.", "utilities.request_all":"Request all eligible peers ({n})", +"utilities.request_caches":"Request missing caches ({n})", "utilities.route_server_note":"Route-server peers require an Open peering policy. Existing sessions stay enabled; no ports are bought.", "utilities.route_servers_joined":"Joined {n} route servers.", "utilities.second_site":"Second site", diff --git a/tests/utilities-caches.test.js b/tests/utilities-caches.test.js new file mode 100644 index 0000000..70b212b --- /dev/null +++ b/tests/utilities-caches.test.js @@ -0,0 +1,109 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(t) { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev("ACT.start({});S.cash=1e8;UI.speed=0;for(const g of GOALS)S.done[g.id]=0;compute()"); + return h; +} + +test('kit balances each provider with minimal moves while buying the missing hardware', t => { + const { ev, errors } = setup(t); + ev("for(const [net,n] of [['cfl',4],['ggl',3]])for(let i=0;ic.id).join()'); + const quote = JSON.parse(ev("JSON.stringify(utilityKit('fra'))")); + assert.equal(quote.moves.length, 3); + ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})"); + assert.equal(ev('S.cash'), before - quote.cost); + assert.equal(ev("S.caches.filter(c=>c.city==='fra'&&c.net==='cfl'&&c.site==='b').length"), 2); + assert.equal(ev("S.caches.filter(c=>c.city==='fra'&&c.net==='ggl'&&c.site==='b').length"), 1); + assert.equal(ev("S.caches.find(c=>c.id==='elsewhere').site"), 'b'); + assert.equal(ev('S.caches.map(c=>c.id).join()'), ids); + assert.equal(ev("utilityKit('fra').moves.length"), 0); + const stable = ev('JSON.stringify(S.caches)'); + ev("ACT.utilityKit({city:'fra',cost:0})"); + assert.equal(ev('JSON.stringify(S.caches)'), stable); + assert.deepEqual(errors, []); +}); + +test('an already equipped PoP can balance caches for free, even with negative cash', t => { + const { ev, errors } = setup(t); + ev("Object.assign(S.pops.fra,{gen:true,site2:true,routers:3});for(const [net,site] of [['cfl','a'],['ggl','b']])for(let i=0;i<4;i++)S.caches.push({id:net+i,city:'fra',net,site});S.cash=-1;compute();selectCity('fra');ACT.tab({t:'links'})"); + assert.equal(ev("utilityKit('fra').moves.length"), 4, 'overall counts match but provider counts do not'); + assert.equal(ev("document.querySelector('#panelBody [data-act=utilityKit]').disabled"), false); + ev("document.querySelector('#panelBody [data-act=utilityKit]').click()"); + assert.equal(ev('S.cash'), -1); + assert.equal(ev('S.pops.fra.routers'), 3); + for (const net of ['cfl', 'ggl']) + assert.equal(ev(`S.caches.filter(c=>c.net==='${net}'&&c.site==='b').length`), 2); + assert.deepEqual(errors, []); +}); + +test('a rejected kit purchase never moves caches or partially installs hardware', t => { + const { ev, errors } = setup(t); + ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];S.cash=1;compute()"); + const before = ev('JSON.stringify({p:S.pops.fra,c:S.caches,cash:S.cash})'); + ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});ACT.utilityKit({city:'fra',cost:-1})"); + assert.equal(ev('JSON.stringify({p:S.pops.fra,c:S.caches,cash:S.cash})'), before); + assert.deepEqual(errors, []); +}); + +test('cache batch fills missing provider/site pairs, keeps extra boxes and respects eligibility', t => { + const { ev, errors } = setup(t); + ev("Object.assign(S.pops.fra,{site2:true,routers:2});S.caches=[{id:'keep1',city:'fra',net:'cfl'},{id:'keep2',city:'fra',net:'cfl',site:'a'}];compute();R.demTo={cfl:NET.cfl.cache.min,ggl:NET.ggl.cache.min-1}"); + const cash = ev('S.cash'), mo = ev('R.cost.caches'); + assert.equal(ev("utilityCaches('fra').add.length"), 1); + ev("ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})"); + assert.equal(ev('S.cash'), cash, 'cache hardware is free'); + assert.equal(ev('R.cost.caches'), mo + ev('CACHE_MO')); + assert.equal(ev("S.caches.filter(c=>c.net==='cfl'&&c.site==='b').length"), 1); + assert.equal(ev("S.caches.filter(c=>c.net==='cfl').length"), 3, 'extra existing A box kept'); + assert.equal(ev("S.caches.some(c=>c.net==='ggl')"), false); + const stable = ev('JSON.stringify(S.caches)'); + ev("R.demTo={cfl:NET.cfl.cache.min};ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})"); + assert.equal(ev('JSON.stringify(S.caches)'), stable); + assert.deepEqual(errors, []); +}); + +test('one-site requests add only A, then a new second site gets exactly its missing boxes', t => { + const { ev, errors } = setup(t); + ev("R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})"); + assert.equal(ev('S.caches.length'), 5); + assert.equal(ev("S.caches.every(c=>c.site==='a')"), true); + ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})"); + assert.equal(ev('S.caches.length'), 10); + assert.equal(ev("NETS.filter(n=>n.cache).every(n=>['a','b'].every(s=>S.caches.filter(c=>c.net===n.id&&c.site===s).length===1))"), true); + ev("save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));compute()"); + assert.equal(ev('S.caches.length'), 10); + assert.equal(ev("S.caches.filter(c=>c.site==='b').length"), 5); + assert.deepEqual(errors, []); +}); + +test('cache requests reject stale eligibility and insufficient port capacity atomically', t => { + const { ev, errors } = setup(t); + ev("S.pops.fra.site2=true;for(let i=0;i<7;i++)S.caches.push({id:'full'+i,city:'fra',net:'nfx'});compute();R.demTo={cfl:NET.cfl.cache.min};window.q=utilityCaches('fra');ACT.utilities()"); + assert.equal(ev('q.free'), 1); + assert.equal(ev('q.add.length'), 2); + assert.equal(ev("document.querySelector('[data-act=utilityCaches]').disabled"), true); + const before = ev('JSON.stringify(S.caches)'); + ev("ACT.utilityCaches({city:'fra',quote:q.key})"); + assert.equal(ev('JSON.stringify(S.caches)'), before); + ev("S.pops.fra.routers=2;R.demTo.ggl=NET.ggl.cache.min;ACT.utilityCaches({city:'fra',quote:q.key,modal:true})"); + assert.equal(ev('JSON.stringify(S.caches)'), before); + assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/); + ev("ACT.utilityCaches({city:'not-a-city',quote:''})"); + assert.deepEqual(errors, []); +}); + +test('balanced caches keep serving when either site fails', t => { + const { ev, errors } = setup(t); + ev("Object.assign(S.pops.fra,{site2:true,routers:2,rgen:RG.length-1,bb:{d:5000}});S.caches=[{id:'one',city:'fra',net:'ggl'},{id:'two',city:'fra',net:'ggl'}];compute();ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})"); + for (const site of ['a', 'b']) { + ev(`S.inc=[{id:'site-failure',type:'site',ref:'fra',site:'${site}',until:S.day+2}];compute()`); + assert.ok(ev('Object.values(R.useCache).reduce((a,b)=>a+b,0)') > 0); + assert.equal(ev(`S.caches.filter(c=>(c.site||'a')==='${site}').every(c=>!R.useCache[c.id])`), true); + } + assert.deepEqual(errors, []); +}); From ce83c01f83c7e219cce7b0cc0dad9adec3288744 Mon Sep 17 00:00:00 2001 From: Charles Miller Date: Wed, 28 Oct 2026 10:54:16 +0000 Subject: [PATCH 13/64] Distribute odd cache totals evenly between sites --- src/game/70-rules/95-utilities.js | 7 ++++++- tests/utilities-caches.test.js | 11 +++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index 646f760..5d759b7 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -2,8 +2,13 @@ function utilityRouteServers(){return S?Object.keys(S.ixp).filter(ix=>isIx(ix)&&!S.myIx[ix]&&!S.rs[ix]):[];} function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new Map(),moves=[]; for(const c of S.caches)if(c.city===city){let g=groups.get(c.net);if(!g){g={a:[],b:[]};groups.set(c.net,g);}g[c.site==='b'?'b':'a'].push(c);} + const move=(g,from,n)=>{const to=from==='a'?'b':'a';for(const c of g[from].splice(0,n)){g[to].push(c);moves.push({id:c.id,site:to});}}; for(const g of groups.values()){const from=g.a.length>g.b.length?'a':'b',to=from==='a'?'b':'a'; - for(const c of g[from].slice(0,Math.floor(Math.abs(g.a.length-g.b.length)/2)))moves.push({id:c.id,site:to});} + move(g,from,Math.floor((g[from].length-g[to].length)/2));} + // Spread odd-provider extras too, so the overall site counts also differ by at most one. + let diff=0;for(const g of groups.values())diff+=g.a.length-g.b.length; + const from=diff>0?'a':'b',to=from==='a'?'b':'a';let left=Math.floor(Math.abs(diff)/2); + for(const g of groups.values())if(left&&g[from].length>g[to].length){move(g,from,1);left--;} return moves;} function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have=new Set(); for(const c of S.caches)if(c.city===city)have.add(c.net+'@'+(c.site==='b'?'b':'a')); diff --git a/tests/utilities-caches.test.js b/tests/utilities-caches.test.js index 70b212b..64840bf 100644 --- a/tests/utilities-caches.test.js +++ b/tests/utilities-caches.test.js @@ -50,6 +50,17 @@ test('a rejected kit purchase never moves caches or partially installs hardware' assert.deepEqual(errors, []); }); +test('odd provider totals are balanced across the whole PoP with the fewest moves', t => { + const { ev, errors } = setup(t); + ev("Object.assign(S.pops.fra,{gen:true,site2:true,routers:2});for(const [net,n] of [['nfx',3],['cfl',1],['ggl',1]])for(let i=0;ic.site==='b').length"), 2); + assert.equal(ev("['nfx','cfl','ggl'].every(net=>Math.abs(S.caches.filter(c=>c.net===net&&c.site==='b').length-S.caches.filter(c=>c.net===net&&c.site!=='b').length)<=1)"), true); + assert.equal(ev("utilityCacheMoves('fra').length"), 0); + assert.deepEqual(errors, []); +}); + test('cache batch fills missing provider/site pairs, keeps extra boxes and respects eligibility', t => { const { ev, errors } = setup(t); ev("Object.assign(S.pops.fra,{site2:true,routers:2});S.caches=[{id:'keep1',city:'fra',net:'cfl'},{id:'keep2',city:'fra',net:'cfl',site:'a'}];compute();R.demTo={cfl:NET.cfl.cache.min,ggl:NET.ggl.cache.min-1}"); From 48e6200c532d486f79bc8376de0aecbf6169123b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 17:24:18 +0100 Subject: [PATCH 14/64] German, Glowball Sakura Lager, CN-Too premium in Moscow (1.37.0) --- CHANGELOG.md | 4 +++- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa39a98..eb2f3d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,11 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- China Telecomet now sells its CN-Too premium crossing in Moscow too, at the same price as in Hong Kong (#195). Haul your European traffic to Moscow and it reaches China with about 3% loss; nothing else of theirs is on offer there. +## [1.37.0] — 2026-10-28 + - Series of Tubes now speaks German. The game follows your browser's language the first time, and you can switch to German under Settings or on the title screen. Networking terms like Peering and Transit stay in English, the way network engineers say them. - Glowball Sakura Lager joins the map: a Tier 2 carrier in the big hubs of the US, Europe and Asia-Pacific that sells transit, takes PNIs and peers openly wherever it is. It is not a Tier 1, so it buys its own transit from three of them, while 13 smaller networks in its regions buy theirs from it, and one PNI with it reaches about 3% of all traffic. Far from home, in Asia and New Zealand, it charges more than the locals, and it sells no transit in Australia. +- China Telecomet now sells its CN-Too premium crossing in Moscow too, at the same price as in Hong Kong (#195). Haul your European traffic to Moscow and it reaches China with about 3% loss; nothing else of theirs is on offer there. ## [1.36.0] — 2026-10-28 diff --git a/package-lock.json b/package-lock.json index b0b4c4d..a378772 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "1.36.0", + "version": "1.37.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "1.36.0", + "version": "1.37.0", "license": "MIT", "devDependencies": { "jsdom": "24.1.3", diff --git a/package.json b/package.json index e9dff8b..55062b1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "1.36.0", + "version": "1.37.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", From 7c8fa68659ad53cb52701684c0de9733e45bee53 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 17:40:22 +0100 Subject: [PATCH 15/64] Standing orders: a NOC intern runs the player's orders once a day (#98) --- src/game/60-features/80-new-game.js | 2 +- src/game/60-features/90-automation.js | 23 +-- src/game/60-features/95-standing-orders.js | 157 ++++++++++++++++++++ src/game/80-simulation/30-compute.js | 2 +- src/game/80-simulation/50-sanitize.js | 2 +- src/game/88-days/10-day-tick.js | 1 + src/game/90-actions/50-customers.js | 3 +- src/game/90-actions/88-ops.js | 25 ++++ src/game/90-actions/89-game-and-settings.js | 2 +- src/game/90-actions/90-action-helpers.js | 2 +- src/game/93-ui/40-hud-and-panels.js | 5 +- src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/57-ops-panel.js | 40 +++++ src/game/93-ui/70-link-panels.js | 4 +- src/game/94-dashboard/60-dashboard.js | 2 +- src/game/99-loop.js | 1 - src/i18n/en.js | 106 ++++++++++++- src/styles/36-ops.css | 13 ++ 18 files changed, 351 insertions(+), 41 deletions(-) create mode 100644 src/game/60-features/95-standing-orders.js create mode 100644 src/game/90-actions/88-ops.js create mode 100644 src/game/93-ui/57-ops-panel.js create mode 100644 src/styles/36-ops.css diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 3dd1e86..e4c178c 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,autoSales:false,autoRepair:false,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:{}, + ltv:2,t1v:3,auV:1,ops:opsNew(),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,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{},rules:makeRules('oncall')}; } diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js index 8a2b0e8..aa4a274 100644 --- a/src/game/60-features/90-automation.js +++ b/src/game/60-features/90-automation.js @@ -1,17 +1,5 @@ -/* Optional operators use the same sales and repair actions as the player. */ -const AUTO_SALES_MS=5000; -function autoSalesSeconds(now=performance.now()){if(!S||!S.autoSales)return null; - const left=UI.autoGame===S&&autoActive()?AUTO_SALES_MS-(now-UI.autoSalesAt):AUTO_SALES_MS; - return Math.max(1,Math.min(AUTO_SALES_MS/1000,Math.ceil(left/1000)));} -function autoCountdownReady(o){if(!S||!S.autoSales||!o||!(o.exp>S.day)||!bCities(o).every(popUp)||!reqOk(o))return false; - const inc=S.inc.map(i=>i.id).join('|');let c=UI.autoReady; - // Share capacity trials between views and keep them until the next check, action or incident. - if(!c||c.s!==S||c.at!==UI.autoSalesAt||c.inc!==inc||c.event!==S.nextEvent)c=UI.autoReady={s:S,at:UI.autoSalesAt,inc,event:S.nextEvent,offers:new Map()}; - if(!c.offers.has(o))c.offers.set(o,!!autoOffer(o));return c.offers.get(o);} -function autoAcceptLabel(o){return tr('common.accept')+(S.autoSales?` ${autoCountdownReady(o)?`(${autoSalesSeconds()})`:''}`:'');} -function renderAutoCountdown(now=performance.now()){const n=autoSalesSeconds(now);if(UI.autoCount===n&&UI.autoCountResult===R)return;UI.autoCount=n;UI.autoCountResult=R; - const offers=new Map((S?S.offers:[]).map(o=>[o.id,o])); - for(const el of document.querySelectorAll('[data-auto-sales]'))el.textContent=n!==null&&autoCountdownReady(offers.get(el.dataset.autoSales))?`(${n})`:'';} +/* The sales engine of #185: would this offer work if signed now? The intern's sales order runs it once a day. + It trials the new demand on a copy of the game, so a failed trial leaves the live game untouched. */ function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};} function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null; const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; @@ -27,10 +15,3 @@ function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.ra const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null; }finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}} -function autoActive(){return !!(S&&UI.started&&!S.lost&&UI.speed&&$('modal').hidden&&document.visibilityState==='visible');} -function automationTick(now){if(UI.autoGame!==S){UI.autoGame=S;UI.autoSalesAt=now;} - if(!autoActive()){UI.autoSalesAt=now;return;} - if(S.autoRepair&&S.inc.length){purgeInc();for(const i of S.inc.slice()){if(!autoActive())break; - if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&i.cost<=S.cash&&!(i.slow&&i.rushed))ACT.fixInc({id:i.id});}} - if(!S.autoSales||!autoActive()){UI.autoSalesAt=now;return;}if(now-UI.autoSalesAtv+'×'},prov:{d:'cheap',ok:v=>v==='cheap'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}}, + {k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}}}, + {k:'caches',i:'📦',pop:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}}, + {k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}}, + {k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>tr(v?'common.on':'common.off')}}}, + {k:'sales',i:'💼',t:N_('ops.o_sales'),d:N_('ops.o_sales_d'),p:{acc:{d:true,v:[true,false],l:N_('ops.p_acc'),f:v=>tr(v?'common.on':'common.off')},min:{d:0,v:[0,2000,5000,10000,25000,50000],l:N_('ops.p_min'),f:v=>v?tr('common.price_mo',{price:fmt$(v)}):tr('ops.never')}}}, + {k:'repair',i:'🔧',cap:50000,t:N_('ops.o_repair'),d:N_('ops.o_repair_d'),p:{}}, + {k:'optics',i:'🌈',cap:250000,t:N_('ops.o_optics'),d:N_('ops.o_optics_d'),p:{at:{d:70,v:[50,60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'}}}, + {k:'decom',i:'🧹',t:N_('ops.o_decom'),d:N_('ops.o_decom_d'),p:{keep:{d:true,v:[true,false],l:N_('ops.p_keep'),f:v=>tr(v?'common.on':'common.off')}}}, +]; +const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k); +const OPS_TPL=['bb','transit','ix','kit']; +// What the shift log can say. One line per day: "{name} did this, that and the other." +const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke')}; +// Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. +const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; +const OPS_FF_RATE={oncall:1/150,bgp:1/60}; +function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:{},mon:0,skip:{},log:[],floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} +const opsO=()=>S.ops||(S.ops=opsNew()); +const opsHired=()=>!!(S&&S.ops&&S.ops.intern&&own(INTERNS,S.ops.intern)); +const opsCanHire=()=>lvl()>=2; +const opsName=(long)=>{const I=INTERNS[S.ops.intern];return I?tr(long?I.n:I.s):'';}; +function opsP(k,p){const P=OPSK[k].p[p],v=S.ops.p[k]&&S.ops.p[k][p];return v!==undefined&&(P.ok?P.ok(v):P.v.includes(v))?v:P.d;} +function opsCap(k){const c=S.ops.cap[k];return OPS_CAPS.includes(c)?c:OPSK[k].cap||0;} +const opsHere=(k,c)=>!(S.ops.skip[c]||[]).includes(k); +const opsPops=k=>Object.keys(S.pops).filter(c=>opsHere(k,c)); +// Saves are untrusted: rebuild ops from known orders, params, cities and log shapes. Old saves get no intern, +// and the two #185 toggles (auto-accept, auto-pay repairs) become the sales and repair orders. +function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s.ops)?s.ops:{},n=opsNew(),ob=x=>x&&typeof x==='object'&&!Array.isArray(x)?x:{}; + n.intern=typeof o.intern==='string'&&own(INTERNS,o.intern)?o.intern:null;n.hired=int(o.hired,0,1e7,0);n.mon=int(o.mon,0,1e6,0); + n.floor=OPS_FLOORS.includes(o.floor)?o.floor:n.floor; + const on=ob(o.on),p=ob(o.p),cap=ob(o.cap),sp=ob(o.spent); + for(const d of OPS){const k=d.k;n.on[k]=on[k]===true;const q=ob(p[k]),r={}; + for(const pk of Object.keys(d.p)){const P=d.p[pk];if(own(q,pk)&&(P.ok?P.ok(q[pk]):P.v.includes(q[pk])))r[pk]=q[pk];}n.p[k]=r; + if(d.cap&&OPS_CAPS.includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0));} + {const t=ob(o.tpl);for(const k of OPS_TPL)if(typeof t[k]==='boolean')n.tpl[k]=t[k];} + {const sk=ob(o.skip);for(const c of Object.keys(sk))if(isCity(c)&&Array.isArray(sk[c])){const ks=[...new Set(sk[c].filter(k=>OPS_POP.includes(k)))];if(ks.length)n.skip[c]=ks;}} + if(Array.isArray(o.log))n.log=o.log.map(opsLogOk).filter(Boolean).slice(0,OPS_LOG); + if(s.autoSales===true)n.on.sales=true;if(s.autoRepair===true)n.on.repair=true;delete s.autoSales;delete s.autoRepair; + s.ops=n;} +// A log entry: {d, i: intern, r: [[kind, n, [where…]]], f: fat-finger index, c: its city}. +const opsWhereOk=w=>typeof w==='string'&&w.length<=48&&/^[a-z0-9~|]+( [+\w.×→⇧]+)?$/i.test(w)&&w.split(' ')[0].split('|').every(x=>isIx(x)||own(OPSK,x)||isNet(x)); +function opsLogOk(e){if(!e||typeof e!=='object'||!own(INTERNS,e.i))return null;const r=Array.isArray(e.r)?e.r.filter(x=>Array.isArray(x)&&own(OPS_SAY,x[0])&&Array.isArray(x[2])).map(x=>[x[0],int(x[1],1,1e6,1),x[2].filter(opsWhereOk).slice(0,3)]).slice(0,16):[]; + const f=Number.isInteger(e.f)&&OPS_FF[e.f]?e.f:undefined;return {d:int(e.d,0,1e7,0),i:e.i,r,...(f!==undefined&&isCity(e.c)?{f,c:e.c}:{})};} +// "fra +1×100G", "fra|ams", "ams~3", "transit" (an order, for the budget line) or "ggl" (a network). +function opsWhere(w){const [a,x]=w.split(' '),nm=a.split('|').map(p=>own(OPSK,p)?tr(OPSK[p].t):isCity(p)?CITY[p].name:isNet(p)?NET[p].name:ixName(p)).join('–');return x?nm+' '+(isNet(x)?NET[x].name:x):nm;} +function opsLine(e){const I=INTERNS[e.i],name=I?tr(I.s):'',parts=e.r.map(([k,n,w])=>trn(OPS_SAY[k],n,{where:w.map(opsWhere).join(', ')})); + return parts.length?tr('ops.l_line',{name,list:parts.join(', ')}):tr('ops.l_quiet',{name});} +const opsFFLine=e=>tr('ops.ff_line',{name:tr(INTERNS[e.i].s),what:tr(OPS_FF[e.f],{city:CITY[e.c].name})}); +// Mute what a click would show (toasts, sounds, floaters, the full redraw) and keep the player's selection. +function opsQuiet(fn){const a=after,t=toast,s=sfx,f=floater,sel=UI.sel,cf=UI.confirm,tab=UI.tab;after=()=>{};toast=()=>{};sfx=()=>{};floater=()=>{}; + try{return fn();}finally{after=a;toast=t;sfx=s;floater=f;UI.confirm=cf;UI.tab=tab;UI.sel=sel&&(sel.type!=='link'||S.links.some(l=>l.id===sel.id))&&(sel.type!=='city'||isCity(sel.id))?sel:null;}} +// One shift's bookkeeping: what got done, and whether a job had to wait for next month's budget. +function opsShift(){const r=new Map(),broke=new Set(); + return {r,broke,did(k,w){const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, + can(k,cost){const O=S.ops,cap=opsCap(k);if(cost<=0)return true;if(S.cash-costcap)){broke.add(k);return false;}return true;}, + // Run a click and book what it really cost; false when the action refused (no ports, no cash, a quote changed). + pay(k,fn){const c0=S.cash,x=fn();const d=c0-S.cash;if(d>0&&OPSK[k].cap)S.ops.spent[k]+=d;return x===undefined?d>0:x;}};} +const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0]; +// The orders. Each takes the shift and does its jobs through the player's own actions. +const OPS_RUN={ + repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id})))X.did('repair');}, + sales(X){const min=opsP('sales','min'),acc=opsP('sales','acc'); + for(const o of S.offers.slice()){const T=BIZ_T[o.type];if(!T)continue;const v=T.event?(o.fee||0):bizMo(o); + if(min&&vx!==o);X.did('decline');continue;} + if(acc){ACT.accept({id:o.id,auto:true});if(!S.offers.includes(o)){X.did('sales');compute();}}}}, + routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'); + for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue; + const ld=Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));if(ld=0&&RG[nx].lvl<=lvl()&&!modelFits(c,nx)&&(rt>1||popIdle(c)),add=rt=4||!add);if(!doSwap&&(how==='swap'||!add))continue; + const cost=doSwap?swapCost(c,nx):routerCost(g,rt);if(!X.can('routers',cost))continue; + if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));}}, + transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x'),pv=opsP('transit','prov'); + for(const c of opsPops('transit')){let ts=S.transit.filter(t=>t.city===c);if(!ts.length)continue; + // Thirty days of 95th-percentile-ish history per port; their peaks summed is a safe (high) estimate of the POP's peak. + const peak=ts.reduce((a,t)=>a+(t.hist||[]).reduce((m,v)=>Math.max(m,v),0),0);if(!(peak>0))continue; + const n=pv!=='cheap'&&sellsAt(NET[pv],c)?NET[pv]:cheapestTransit(c);if(!n)continue; + for(let step=0;step<4;step++){const cap=ts.reduce((a,t)=>a+lagCap(PORT[t.tier].g,t.n),0);if(cap>=N*peak)break; + const t=ts.find(x=>x.net===n.id);let job=null; + if(t){const k=t.n||1,up=t.tier+1; + if(k<4&&portOk(c,t.tier))job={cost:PORT[t.tier].setup,go:()=>ACT.lagT({id:t.id,d:1}),w:'+1×'+PORT[t.tier].n}; + else if(PORT[up]&&portShown(up)&&portOk(c,up))job={cost:PORT[up].setup*k,go:()=>ACT.buyTransit({city:c,net:n.id,tier:up}),w:PORT[t.tier].n+'→'+PORT[up].n}; + else if(kACT.lagT({id:t.id,d:1}),w:'+1×'+PORT[t.tier].n};} + else{const need=N*peak-cap,ok=PORT.map((P,i)=>i).filter(i=>portShown(i)&&portOk(c,i)),i=ok.find(i=>PORT[i].g>=need)??ok.at(-1); + if(i!==undefined)job={cost:PORT[i].setup,go:()=>ACT.buyTransit({city:c,net:n.id,tier:i}),w:'+'+PORT[i].n};} + if(!job||!X.can('transit',job.cost)||!X.pay('transit',job.go))break; + X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);}}}, + optics(X){const at=opsP('optics','at')/100; + for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day)continue; + let cap=dfCap(l);const load=(R.load&&R.load[l.id])||0; + // New fiber gets its first channel; lit fiber gets more while it runs hot. + for(let step=0;step<8&&(cap<=0?!(l.ch||[]).length:load>=cap*at);step++){if(chMax(l)-(l.ch||[]).length-soldSlots(l)<=0)break; + const cnt={};for(const k of l.ch||[])cnt[k]=(cnt[k]||0)+1; + // More of what is already lit, or else the most Gbps per dollar that reaches. + const fit=Object.keys(OPT).filter(o=>!chWhy(l,o)),o=fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||fit.sort((a,b)=>optG(b,l)/optCost(b)-optG(a,l)/optCost(a))[0];if(!o)break; + const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break; + X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break; + cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);}}}, + caches(X){const g=opsP('caches','g'); + for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue; + const want=q.add.filter(x=>(R.cityDem[c]||0)*(NSH[x.net]||0)>=g),free=Math.floor(portsMax(c)-portsUsed(c)+1e-9); + for(const x of want.slice(0,Math.max(0,free))){S.caches.push({id:uid(),city:c,net:x.net,site:x.site});X.did('caches',c);}}}, + // Weekly, like a person going through PeeringDB on a Monday: route servers, then every willing member (#192). + ix(X){if(S.day%7)return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');} + for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}}, + // Weekly too: every willing network above the threshold, at its own minimum size and lead time (#181). + pni(X){if(S.day%7!==3)return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;const g=opsP('pni','g'),paid=opsP('pni','paid'); + const loc=q=>(R.cityDem[q.city]||0)*(NSH[q.net]||0); + for(const q of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){ + if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}}, + // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). + decom(X){const keep=opsP('decom','keep'),by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} + for(const ls of by.values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue; + let cap=live.reduce((a,l)=>a+capOf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0); + const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a)); + if(keep)small.shift(); + for(const l of small.reverse()){if(cap-capOf(l)(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; + const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true); + const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}} +const OPS_ORDER=['repair','sales','routers','transit','optics','caches','ix','pni','decom']; +// The shift: once per game day from dayTick, after outages and events have had their turn. +function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;} + const X=opsShift(),cash=S.cash; + opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])OPS_RUN[k](X);}); + const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke]]); + // Very rarely, and never under Change Freeze, the intern fat-fingers something harmless. + const ff=OPS_FF_RATE[rulePreset()];if(ff&&Object.keys(S.pops).length&&Math.random()t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;} + e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);} + if(e.r.length||e.f!==undefined){compute();O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);} + if(e.r.length)logNote(`${esc(tr('ops.shift',{name:opsName()}))} ${esc(opsLine(e))}`,cash>S.cash?'':'good',[],{a:'tab',v:'noc'});} +// New POP from the template: price the whole bundle first, then click through it in one go. +function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))return null;const T=S.ops.tpl,parts=[];let cost=popCost(c),net=null,ix=null,kit=null; + if(T.bb){cost+=bbCost(c);parts.push(tr('ops.tpl_bb'));} + if(T.transit&&!scnRule('noTransit')){const pv=opsP('transit','prov');net=pv!=='cheap'&&sellsAt(NET[pv],c)?NET[pv]:cheapestTransit(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}} + // DE-KICKS wants a sales call before any port, so the template leaves those to the player. + if(T.ix&&CITY[c].ix&&!isDk(c)){ix=c;cost+=ixPortMo(c,0);parts.push(tr('ops.tpl_ix'));} + if(T.kit){S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};try{kit=utilityKit(c);}finally{delete S.pops[c];}if(kit&&kit.cost){cost+=kit.cost;parts.push(tr('ops.tpl_kit'));}} + return {cost,net:net&&net.id,ix,kit:!!(kit&&kit.cost),parts};} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 866f634..0429a59 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -263,7 +263,7 @@ function compute(){ C.pni=S.pni.reduce((a,p)=>a+pniMo(p,R2.usePni[p.id]||0),0); C.caches=S.caches.length*CACHE_MO; C.loans=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity?0:l.model==='transit'?Math.round((C.transit||0)*(l.cut||0.3)):l.pay)+loanFees(l),0); - C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.inbox&&S.inbox.bot?AI_MO:0); + C.extras=(S.cnLic&&S.cnLic.state==='ok'?CN_JV_MO:0)+scrubMo()+Object.keys(S.pops).filter(ruCity).length*RU_BOX_MO+Object.values(S.pops).filter(p=>p.site2).length*SITE2_MO+(S.te?TE_MO:0)+(S.inbox&&S.inbox.bot?AI_MO:0)+(S.ops&&S.ops.intern?INTERN_MO:0); V.eyeballs=0;V.business=0;V.ix=0;V.grant=grantOn(R2)?GRANT_MO:0; C.wholesale=0;C.levy=0;const lev=scnRule('levy');for(const c in S.pops){const sf=sfOf(R2,c),v=R2.cityEye[c]*sf*EYE_RATE*(CITY[c].arpu||1);V.eyeballs+=v;if(CITY[c].au){if(lev)C.levy+=v*AU_LEVY;else C.wholesale+=v*AU_WHOLESALE;}} const ids=linkIds();for(const b of S.biz){if(capPend(b))continue;const sf=BIZ_T[b.type].fiber?(fiberOk(b,ids)?1:0):BIZ_T[b.type].l2?clamp((R2.l2[b.id]||0)/b.bw,0,1):sfOf(R2,b.city);V.business+=b.bw*b.rate*Math.min(1,sf/0.95);} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 0a48b3b..8976ceb 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -9,7 +9,7 @@ function sanitize(s){ ['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach','pairMet'].forEach(obj); s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000); s.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); - s.autoSales=s.autoSales===true;s.autoRepair=s.autoRepair===true; + opsSanitize(s); 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); 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;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 358220e..2630903 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -65,6 +65,7 @@ function dayTick(){ 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);} if(cm&&d>=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} if(dirty)compute(); + opsDay(d); // payday floaters if(d%30===0){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-(CITY[c].arpu||1));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');} checkGoals(); diff --git a/src/game/90-actions/50-customers.js b/src/game/90-actions/50-customers.js index 97e0261..1c22220 100644 --- a/src/game/90-actions/50-customers.js +++ b/src/game/90-actions/50-customers.js @@ -4,8 +4,7 @@ Object.assign(ACT,{ const T=BIZ_T[t],nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;}; // A capacity broker finds a buyer at once and keeps 10% of the monthly price. const o=fiberOffer(t,l,nm,0.9);o.broker=true;S.offers.push(o);toast(tr('customers.listed_with_a_capacity_broker_name',{name:esc(o.name),what:esc(o.what)}),'good');sfx('click');after();}, - autoToggle:({k})=>{if(k!=='autoSales'&&k!=='autoRepair')return;S[k]=!S[k];if(k==='autoSales'){UI.autoGame=S;UI.autoSalesAt=performance.now();}sfx('click');after();}, - accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;const customer=auto?(S.autoSales&&autoOffer(o)):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} + accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;const customer=auto?autoOffer(o):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)=o.start){toast(tr('customers.too_late_the_event_has_already'),'bad');return;} // A carrier renting more alien waves on a fiber it already rents grows its contract, like a real order for extra waves, diff --git a/src/game/90-actions/88-ops.js b/src/game/90-actions/88-ops.js new file mode 100644 index 0000000..121e7a8 --- /dev/null +++ b/src/game/90-actions/88-ops.js @@ -0,0 +1,25 @@ +// Standing orders: hiring the intern, the switches and dials, and a new POP from the template. +const opsCycle=(a,v)=>a[(a.indexOf(v)+1)%a.length]; +Object.assign(ACT,{ + opsOpen:()=>{if(S)opsModal();}, + opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO();O.intern=id;O.hired=S.day;O.mon=Math.floor(S.day/30); + O.log.unshift({d:S.day,i:id,r:[]});toast(esc(tr('ops.hired',{name:opsName(true)})),'good',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);after();opsModal();}, + opsFire:()=>{if(!opsHired())return;if(UI.confirm!=='opsFire'){UI.confirm='opsFire';opsModal();return;}UI.confirm=null;const nm=opsName();S.ops.intern=null; + toast(esc(tr('ops.fired',{name:nm})),'');after();opsModal();}, + opsToggle:({k})=>{if(!opsHired()||!own(OPSK,k))return;S.ops.on[k]=!S.ops.on[k];sfx('click');after();opsModal();}, + opsParam:({k,p})=>{if(!opsHired()||!own(OPSK,k)||!own(OPSK[k].p,p))return;const P=OPSK[k].p[p];let v; + if(p==='prov'){const ids=['cheap',...NETS.filter(n=>n.price&&Object.keys(S.pops).some(c=>sellsAt(n,c))).map(n=>n.id)];v=opsCycle(ids,opsP(k,p));}else v=opsCycle(P.v,opsP(k,p)); + (S.ops.p[k]||(S.ops.p[k]={}))[p]=v;sfx('click');after();opsModal();}, + opsCap:({k})=>{if(!opsHired()||!own(OPSK,k)||!OPSK[k].cap)return;S.ops.cap[k]=opsCycle(OPS_CAPS,opsCap(k));sfx('click');after();opsModal();}, + opsFloor:()=>{if(!opsHired())return;S.ops.floor=opsCycle(OPS_FLOORS,S.ops.floor);sfx('click');after();opsModal();}, + opsCity:({v})=>{if(!S||!S.pops[v])return;UI.opsCity=v;opsModal();}, + opsPop:({k,city})=>{if(!opsHired()||!OPS_POP.includes(k)||!S.pops[city])return;const sk=S.ops.skip,a=sk[city]||[];sk[city]=a.includes(k)?a.filter(x=>x!==k):[...a,k];if(!sk[city].length)delete sk[city]; + UI.opsCity=city;sfx('click');after();opsModal();}, + opsTpl:({k})=>{if(!opsHired()||!OPS_TPL.includes(k))return;S.ops.tpl[k]=!S.ops.tpl[k];sfx('click');after();opsModal();}, + // One tap, a whole POP: the same clicks in the same order, all or nothing on the price. + opsNewPop:({city})=>{if(!opsHired())return;const q=opsTplQuote(city);if(!q)return;if(S.cash{ACT.buildPop({city});if(!S.pops[city])return;if(S.ops.tpl.bb)ACT.launchBB({city});if(q.net)ACT.buyTransit({city,net:q.net,tier:0});if(q.ix)ACT.buyIx({city:q.ix,tier:0}); + if(q.kit){const k=utilityKit(city);if(k&&k.cost&&S.cash>=k.cost)ACT.utilityKit({city,cost:k.cost});}}); + if(!S.pops[city])return;UI.tab='links';floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');sfx('build'); + toast(esc(tr('ops.tpl_done',{name:opsName(),city:CITY[city].name,list:q.parts.join(', ')||tr('ops.tpl_just_pop')})),'good',[],{a:'city',v:city});after();}, +}); diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 70134bc..55ab145 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -29,7 +29,7 @@ Object.assign(ACT,{ ${btn(tr('game_and_settings.scenarios_amp_weekly_challenge'),'scenarios',{},'ghost')} ${btn(tr('common.how_to_play'),'help',{},'ghost')} ${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''} - ${btn(tr('utilities.title'),'utilities',{},'')} + ${btn('🧑‍💻 '+tr('ops.standing_orders'),'opsOpen',{},'')} ${btn(tr('common.settings'),'settings',{},'ghost')} ${btn(tr('common.start_a_new_network'),'resetAsk',{},'red')} ${chatHtml()}${issueHtml()}`);}, diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 002cdaa..0efe713 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -22,7 +22,7 @@ function chWhy(l,o){const O=OPT[o];if(O.lvl>lvl())return tr('action_helpers.unlo if((l.ch||[]).length+soldSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)}); for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&RG[p.rgen||0].clsinnerWidth>760&&innerWidth<=1200; function selectLink(id){UI.sel={type:'link',id};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;$('panel').classList.remove('full');renderPanel();renderLeft();} function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;const P=$('panel');if(P)P.classList.remove('full');if(!S.pops[c])UI.tab='cust';renderPanel();} diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 8ea4fcd..155f29a 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -39,18 +39,17 @@ function renderLeft(){checkLayer(); h+=GOALS.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `
${d?'✓':''}
${esc(g.t)}
${c||!d?`
${esc(g.d)}
`:''}${!d&&g.r?`
${tr('hud_and_panels.reward_cash',{cash:fmt$(g.r)})}
`:''}
`;}).join(''); h+=badgeGrid(); }else if(UI.left==='deals'){ - h+=`

${tr('automation.sales_every_five_seconds')}

`; {const st=custStats();if(st.n)h+=`
${tr('common.your_customers')} ${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}
${st.unhappy?`
${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}
`:''}
${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}
`;} h+=confSection(); {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}
${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}
`;} if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${bRisk(o)}${reqList(o)} -
${has?btn(autoAcceptLabel(o),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} +
${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}`;} }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+=`

${tr('automation.repairs_when_affordable')}

`; + h+=opsCard(); // 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/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index d20ab07..4c068b7 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -7,7 +7,7 @@ function cityPanel(c){ h+=`
${C.note?`

${esc(C.note)}

`:''} ${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`

${tr('city_panel.open_a_pop_here')}

${tr('city_panel.a_pop_point_of_presence_is')}

${C.ru?`

${tr('city_panel.includes_the_mandatory_government',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${btn(tr('city_panel.build_pop_cost_mo_mo',{cost:fmt$(popCost(c)),mo:fmt$(popMo(c))}),'buildPop',{city:c},'pink big',S.cash${tr('city_panel.or_drag_from_one_of_your')}

`}`; +

${tr('city_panel.or_drag_from_one_of_your')}

${opsTplHtml(c)}`}`; h+=offersHere(c); const trs=NETS.filter(n=>sellsAt(n,c)); const fh=FABS.filter(f=>f.cities.includes(c)); diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js new file mode 100644 index 0000000..b0bf525 --- /dev/null +++ b/src/game/93-ui/57-ops-panel.js @@ -0,0 +1,40 @@ +const OPS_TPL_L={bb:N_('ops.tpl_bb'),transit:N_('ops.tpl_transit'),ix:N_('ops.tpl_ix'),kit:N_('ops.tpl_kit')}; +// The Ops panel: the intern, their shift log, and the standing orders with their dials. A bottom sheet on phones. +function opsCard(){if(!S)return '';const last=opsHired()&&S.ops.log[0]; + return `
${opsHired()?`${INTERNS[S.ops.intern].i} ${esc(tr('ops.ops_name',{name:opsName(true)}))}`:`🧑‍💻 ${tr('ops.standing_orders')}`}
+
${opsHired()?esc(last?opsEntry(last):tr('ops.l_quiet',{name:opsName()})):opsCanHire()?tr('ops.hire_pitch_short'):tr('ops.locked',{lv:2})}
+
${btn(opsHired()?tr('ops.standing_orders'):tr('ops.hire_an_intern'),'opsOpen',{},opsHired()?'sm':'pink sm',!opsHired()&&!opsCanHire())}
`;} +const opsEntry=e=>(e.f!==undefined?opsFFLine(e)+' ':'')+(e.r.length||e.f===undefined?opsLine(e):''); +function opsVal(k,p){const P=OPSK[k].p[p],v=opsP(k,p);return p==='prov'?(v==='cheap'?tr('ops.cheapest'):NET[v].name):P.f(v);} +function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0; + return `
${tr(d.t)}
${tr(d.d)}
+
+ ${on?`
${Object.keys(d.p).map(p=>btn(`${tr(d.p[p].l)}: ${esc(opsVal(k,p))}`,'opsParam',{k,p},'ghost sm')).join('')} + ${d.cap?btn(`${tr('ops.budget')}: ${cap?tr('common.price_mo',{price:fmt$(cap)}):tr('ops.no_cap')}`,'opsCap',{k},'ghost sm'):''}
+ ${d.cap&&S.ops.spent[k]?`
${tr('ops.spent_this_month',{price:fmt$(S.ops.spent[k])})}
`:''} + ${k==='ix'&&ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

`:''}`:''}
`;} +function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr('ops.ops')}

${tr('ops.standing_orders')}

`; + if(!hired){h+=`

${tr('ops.hire_pitch')}

`; + if(!rule('clock'))h+=`

${tr('ops.no_clock')}

`;else if(!opsCanHire())h+=`

${tr('ops.locked',{lv:2})}

`; + else h+=Object.entries(INTERNS).map(([id,I])=>`
${tr(I.n)}
${tr(I.d)}
+ ${btn(tr('ops.hire_mo',{price:fmt$(INTERN_MO)}),'opsHire',{id},'pink sm',S.cash
`).join(''); + openModal(h+opsOnceHtml(),'ops');return;} + const O=S.ops,I=INTERNS[O.intern]; + h+=`
${tr(I.n)}
${tr('ops.salary',{price:fmt$(INTERN_MO),d:dateStr(O.hired)})}
+ ${btn(UI.confirm==='opsFire'?tr('ops.really_fire'):tr('ops.fire'),'opsFire',{},'ghost sm')}
+ ${O.log.length?`
${O.log.slice(0,6).map(e=>esc(tr('peering_inbox.day_d',{d:e.d})+': '+opsEntry(e))).join('\n')}
`:''} +

${ibx().bot?tr('ops.lpm_on',{name:opsName()}):tr('ops.lpm_off',{name:opsName()})}

+
${btn(`${tr('ops.floor')}: ${O.floor?fmt$(O.floor):tr('ops.no_cap')}`,'opsFloor',{},'ghost sm')}
`; + h+=`

${tr('ops.how_it_works',{name:opsName()})}

`+OPS.map(opsOrderHtml).join(''); + // Per POP: switch single orders off where the player wants to decide by hand. + const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)),c=S.pops[UI.opsCity]?UI.opsCity:cities[0]; + if(c)h+=`

${tr('ops.per_pop')}

+
${OPS_POP.map(k=>{const here=opsHere(k,c);return ``;}).join('')}
+

${tr('ops.per_pop_note')}

`; + h+=`

${tr('ops.template')}

${tr('ops.template_note',{name:opsName()})}

${OPS_TPL.map(k=>``).join('')}
`; + h+=opsOnceHtml();openModal(h,'ops');} +// The big one-off batches (#181, #192) live here now, next to the orders that run them every week. +const opsOnceHtml=()=>`

${tr('ops.by_hand')}

${tr('ops.by_hand_note')}

${btn(tr('utilities.title'),'utilities',{},'sm')}${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'sm')}
`; +// On a city without a POP: open it from the template in one tap. +function opsTplHtml(c){if(!opsHired())return '';const q=opsTplQuote(c);if(!q)return ''; + return `

${tr('ops.template')}

${esc(tr('ops.tpl_offer',{name:opsName(),list:[tr('ops.tpl_pop'),...q.parts].join(', ')}))}

${btn(tr('ops.tpl_open',{cost:fmt$(q.cost)}),'opsNewPop',{city:c},'pink',S.cash
`;} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 1ce06df..0b54d0f 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -104,7 +104,7 @@ function dfPanel(l){ if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l); h+=`

${tr('link_panels.selling_spare_capacity')}

${tr('link_panels.other_carriers_rent_what_you_do')}

${tr('common.free_channels')}${fc} / ${chMax(l)}
${sold.map(b=>`
${esc(b.name)}
${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}
`).join('')} - ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(autoAcceptLabel(off),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}
`;} + ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(tr('common.accept'),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}`;} h+=`

${tr('common.optics')}

${tr('link_panels.each_channel_is_a_pair_of')}

`; if(l.own&&l.sub)h+=subUpgradePanel(l); for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k); @@ -121,7 +121,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(autoAcceptLabel(o),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 85e9c64..f2c1bf7 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -18,7 +18,7 @@ function renderDash(){checkLayer(); {const k=UI.dashSort||'traffic',dir=UI.dashDir||-1,val=x=>k==='name'?x.n.name.toLowerCase():k==='asn'?x.n.asn:k==='type'?x.n.type:k==='cost'?x.cost:k==='lost'?x.lost:x.t;nets.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||b.t-a.t;});} if(DT==='cust')h+=custSection(); if(DT==='conn')h+=connSection(); - if(DT==='traffic')h+=`
${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'pink sm')}
`; + if(DT==='traffic')h+=`
${btn(tr('ops.standing_orders'),'opsOpen',{},'sm')}
`; if(DT==='traffic')h+=`

${tr('dashboard.traffic_by_network_asn')}

${tr('dashboard.where_your_users_traffic_comes_from')}

${['c','p','ix','t'].map(k=>`${EGC[k][0]}`).join('')}
${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>``).join('')} ${nets.map(({n,e,t,want})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?`
${btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm')}
`:''}
${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}
`; if(DT==='traffic'){const top=transitTop(S.transit.map(t=>t.id),8);if(top.length)h+=`

${tr('dashboard.who_your_transit_carries')}

${tr('dashboard.the_networks_you_pay_transit_to')}

${top.map(([id,v])=>`
${logo(NET[id])}
${esc(NET[id].name)} AS${NET[id].asn} · ${fmtG(v)} · ${tr('dashboard.about_price_mo',{price:fmt$((R.cost.transit||0)*v/tT)})}
${esc(offTransitHint(id))}
${btn(tr('common.where_6276'),'netFocus',{id},'ghost sm')}
`).join('')}
`;} diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 70a4e5d..7f1b386 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -10,7 +10,6 @@ function frame(now){ if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();} if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}} - try{automationTick(now);renderAutoCountdown();}catch(e){tickErr(e);} if(UI.speed&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ const t=animOn()?animT:0; if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;} diff --git a/src/i18n/en.js b/src/i18n/en.js index 959a73b..b2c756b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -13,11 +13,6 @@ "action_helpers.too_far_even_at_its_slowest":"Too far even at its slowest setting: an optical span here is {span} km and it reaches {max} km. Add a regen site (Line system).", "action_helpers.unlocks_at_customer_level_n":"Unlocks at customer level {n}.", "actions.your_router_can_t_take_a":"Your router can't take a {port} port.
Upgrade it in the Infra tab.", -"automation.auto_accept_sales":"Auto-accept sales: {state}", -"automation.auto_pay_repairs":"Auto-pay repairs: {state}", -"automation.next_auto_check":"Time until the next automatic requirements check.", -"automation.repairs_when_affordable":"While playing, automatically pay for available rush repairs when you can afford them.", -"automation.sales_every_five_seconds":"Every 5 seconds while playing, accept only offers whose requirements and service capacity are ready.", "badges.a_petabit_a_second":"A Petabit a Second", "badges.a_secret_badge":"A secret badge", "badges.attend_a_conference":"Attend a conference.", @@ -2522,6 +2517,107 @@ "notifications.n_min_ago":{"one":"{n} min ago","other":"{n} min ago"}, "notifications.nothing_in_the_last_10_minutes":"Nothing in the last 10 minutes.", "notifications.show_all_n":"Show all {n}", +"ops.annie":"Annie", +"ops.annie_d":"Answers from whichever desk is closest. Loves a cheap port and a full IX.", +"ops.anycast_annie":"Anycast Annie", +"ops.at_least_port":"at least {port}", +"ops.budget":"Budget", +"ops.by_hand":"One-off batches", +"ops.by_hand_note":"For when you want it all done right now: every peer at every exchange, a redundancy kit, PNIs with everyone.", +"ops.cheapest":"Cheapest", +"ops.ff_desc":"labelled a port in {city} “TODO: fix later (do not fix)”", +"ops.ff_hostname":"renamed the router in {city} to router-final-FINAL-v2", +"ops.ff_lag":"added one transit LAG member too many in {city}. It works, so it stays.", +"ops.ff_line":"Oops: {name} {what}.", +"ops.ff_ping":"pinged a public resolver from {city} for forty minutes, just to be sure", +"ops.ff_typo":"wrote “pering” in every interface description in {city}", +"ops.fire":"Let go", +"ops.fired":"{name} handed in the badge and took the good stapler. Your standing orders are paused.", +"ops.floor":"Keep at least", +"ops.hire_an_intern":"Hire a NOC intern", +"ops.hire_mo":"Hire · {price}/mo", +"ops.hire_pitch":"Tired of clicking the same fifteen buttons in every city? Hire a NOC intern. You write the standing orders once; they run them every day, pay exactly what your clicks would, and leave one line in the log.", +"ops.hire_pitch_short":"Set the rules once, and an intern clicks the buttons every day.", +"ops.hired":"{name} joined the NOC. Write some standing orders and they get to work tomorrow.", +"ops.how_add":"add a router", +"ops.how_auto":"add, then swap", +"ops.how_it_works":"Every day {name} works through the orders that are on, pays for each job exactly as if you had clicked it, and stops when an order's monthly budget, or your cash floor, is reached.", +"ops.how_swap":"swap generation", +"ops.kevin":"Kevin", +"ops.kevin_d":"Has seen every outage since the dot-com crash. Mostly from the break room.", +"ops.kevin_from_the_night_shift":"Kevin from the night shift", +"ops.l_broke":{"one":"stopped at the budget for {where}","other":"stopped at the budget for {n} orders ({where})"}, +"ops.l_caches":{"one":"racked a free cache in {where}","other":"racked {n} free caches ({where})"}, +"ops.l_decline":{"one":"declined a tiny offer","other":"declined {n} tiny offers"}, +"ops.l_decom":{"one":"handed back a small wave on {where}","other":"handed back {n} small waves ({where})"}, +"ops.l_line":"{name} {list}.", +"ops.l_optics":{"one":"lit a channel on {where}","other":"lit {n} channels ({where})"}, +"ops.l_peer":{"one":"peered with a network at {where}","other":"peered with {n} networks at {where}"}, +"ops.l_pni":{"one":"ordered a PNI in {where}","other":"ordered {n} PNIs ({where})"}, +"ops.l_quiet":"{name} watched the graphs. Nothing needed doing.", +"ops.l_repair":{"one":"rushed a repair","other":"rushed {n} repairs"}, +"ops.l_routers":{"one":"upgraded routers in {where}","other":"upgraded routers in {n} places ({where})"}, +"ops.l_rs":{"one":"joined a route server","other":"joined {n} route servers"}, +"ops.l_sales":{"one":"signed a customer","other":"signed {n} customers"}, +"ops.l_transit":{"one":"topped up transit in {where}","other":"topped up transit {n} times ({where})"}, +"ops.locked":"The NOC hires interns from customer level {lv}.", +"ops.lpm_off":"The peering inbox is still yours. Hire the Large Peering Model for that; {name} does not do email.", +"ops.lpm_on":"The Large Peering Model answers the peering inbox. {name} keeps out of its way.", +"ops.never":"never", +"ops.no_cap":"no limit", +"ops.no_clock":"No clock, no shifts: these rules have no days for an intern to work.", +"ops.o_caches":"Accept free caches", +"ops.o_caches_d":"Rack every free cache a network offers, once its traffic in that city passes a threshold.", +"ops.o_decom":"Retire small parallel links", +"ops.o_decom_d":"Once a bigger link between two cities is up, hand back the smaller waves it no longer needs. Never one a customer rents or relies on.", +"ops.o_ix":"Peer at every IX", +"ops.o_ix_d":"Every week: join the route servers and ask every willing member at each of your exchange ports.", +"ops.o_optics":"Light more fiber", +"ops.o_optics_d":"Add optics to dark fiber that runs hot, and light new fiber the day it is handed over.", +"ops.o_pni":"PNI with the big ones", +"ops.o_pni_d":"Every week: order a PNI with every willing network sending enough traffic at your POPs, at each network's own minimum size.", +"ops.o_repair":"Rush repairs", +"ops.o_repair_d":"Pay for the rush repair on every outage that has one, while the budget lasts.", +"ops.o_routers":"Keep routers ahead", +"ops.o_routers_d":"Add a router, or swap to the next generation where a second router carries the traffic, when load or ports pass a level.", +"ops.o_sales":"Handle sales", +"ops.o_sales_d":"Sign offers whose requirements are met with capacity to spare, and decline the ones that pay too little to bother.", +"ops.o_transit":"Keep transit headroom", +"ops.o_transit_d":"Keep transit at each POP above a multiple of its 30-day peak: add a LAG member, or move up a port size.", +"ops.ops":"Ops", +"ops.ops_name":"Ops · {name}", +"ops.p_acc":"Accept ready offers", +"ops.p_at":"Above", +"ops.p_g":"From", +"ops.p_how":"How", +"ops.p_keep":"Keep one spare", +"ops.p_min":"Decline below", +"ops.p_paid":"Paid peering", +"ops.p_prov":"Provider", +"ops.p_tier":"Size", +"ops.p_x":"Headroom", +"ops.paused":"Paused", +"ops.per_pop":"Per POP", +"ops.per_pop_note":"Green orders run in this POP. Switch one off to decide here by hand.", +"ops.really_fire":"Really let go?", +"ops.salary":"Salary {price}/mo · since {d}", +"ops.shift":"{name}'s shift", +"ops.spent_this_month":"Spent this month: {price}", +"ops.standing_orders":"Standing orders", +"ops.template":"New POP from template", +"ops.template_note":"Pick what {name} sets up when you open a city from the template. The standing orders take it from there.", +"ops.tpl_bb":"Broadband", +"ops.tpl_done":"{name} opened {city}: {list}.", +"ops.tpl_ix":"IX port", +"ops.tpl_just_pop":"just the POP", +"ops.tpl_kit":"Redundancy kit", +"ops.tpl_offer":"{name} can open this city in one go: {list}.", +"ops.tpl_open":"Open from template · {cost}", +"ops.tpl_pop":"POP", +"ops.tpl_transit":"10G transit", +"ops.tracy":"Tracy", +"ops.tracy_d":"Follows every packet hop by hop. Gets there in the end, with a star or two on the way.", +"ops.tracy_route":"Tracy Route", "optic_counts.apply_price":"Apply · {price}", "optic_counts.count_for_model":"Number of {model} channels", "optic_counts.only_n_channels_free":"Only {n} channels are free on this fiber.", diff --git a/src/styles/36-ops.css b/src/styles/36-ops.css new file mode 100644 index 0000000..5dc6720 --- /dev/null +++ b/src/styles/36-ops.css @@ -0,0 +1,13 @@ +/* Standing orders: the intern's card in the NOC and the Ops sheet */ +.ops-card{border:2px solid #8E5CF7;background:#F7F2FF;border-radius:12px;padding:8px 10px;margin:8px 0} +.ops-card .nm{font-weight:800} +.ops-o{border:2px solid var(--line);border-radius:12px;padding:8px 10px;margin:8px 0;background:var(--paper)} +.ops-o.on{border-color:var(--ok)} +.ops-h{display:flex;align-items:center;gap:8px} +.ops-h .grow{flex:1;min-width:0} +.ops-h .nm{font-weight:800;font-size:13.5px;line-height:1.2} +.ops-h .b{min-height:36px;flex:none} +.ops-i{font-size:22px;line-height:1;flex:none} +.ops-p{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} +.ops-p .b{white-space:normal;text-align:left;min-height:36px} +.ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto} From 4717bc0f751e47a1aada898f754eac0dc2dc7f8f Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 17:43:12 +0100 Subject: [PATCH 16/64] Standing orders in German, Spanish, French, Italian and Portuguese --- site/i18n/de.js | 106 +++++++++++++++++++++++++++++++++++++++++++++--- site/i18n/es.js | 106 +++++++++++++++++++++++++++++++++++++++++++++--- site/i18n/fr.js | 106 +++++++++++++++++++++++++++++++++++++++++++++--- site/i18n/it.js | 106 +++++++++++++++++++++++++++++++++++++++++++++--- site/i18n/pt.js | 106 +++++++++++++++++++++++++++++++++++++++++++++--- 5 files changed, 505 insertions(+), 25 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index e0b8d31..70c16fd 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -14,11 +14,6 @@ "action_helpers.too_far_even_at_its_slowest":"Zu weit, selbst in der langsamsten Einstellung: Ein optischer Abschnitt ist hier {span} km lang, die Reichweite beträgt {max} km. Füge einen Regenerator-Standort hinzu (Line System).", "action_helpers.unlocks_at_customer_level_n":"Wird ab Kundenlevel {n} freigeschaltet.", "actions.your_router_can_t_take_a":"Dein Router kann keinen {port}-Port aufnehmen.
Rüste ihn im Tab Infra auf.", -"automation.auto_accept_sales":"Deals automatisch annehmen: {state}", -"automation.auto_pay_repairs":"Reparaturen automatisch zahlen: {state}", -"automation.next_auto_check":"Zeit bis zur nächsten automatischen Prüfung der Anforderungen.", -"automation.repairs_when_affordable":"Zahlt während des Spiels automatisch Express-Reparaturen, wenn du sie dir leisten kannst.", -"automation.sales_every_five_seconds":"Alle 5 Sekunden während des Spiels: Nur Angebote, deren Anforderungen und Kapazität bereit sind, werden angenommen.", "badges.a_petabit_a_second":"Ein Petabit pro Sekunde", "badges.a_secret_badge":"Ein geheimes Abzeichen", "badges.attend_a_conference":"Besuche eine Konferenz.", @@ -2523,6 +2518,107 @@ "notifications.n_min_ago":{"one":"vor {n} Min.","other":"vor {n} Min."}, "notifications.nothing_in_the_last_10_minutes":"Nichts in den letzten 10 Minuten.", "notifications.show_all_n":"Alle {n} anzeigen", +"ops.annie":"Annie", +"ops.annie_d":"Antwortet vom nächstgelegenen Schreibtisch. Liebt billige Ports und volle IXe.", +"ops.anycast_annie":"Anycast-Annie", +"ops.at_least_port":"mindestens {port}", +"ops.budget":"Budget", +"ops.by_hand":"Einmal alles", +"ops.by_hand_note":"Für den Moment, in dem alles sofort erledigt sein soll: jeder Peer an jedem Exchange, ein Redundanz-Kit, PNIs mit allen.", +"ops.cheapest":"Günstigster", +"ops.ff_desc":"hat einen Port in {city} „TODO: später fixen (nicht fixen)“ beschriftet", +"ops.ff_hostname":"hat den Router in {city} in router-final-FINAL-v2 umbenannt", +"ops.ff_lag":"hat in {city} ein Transit-LAG-Member zu viel bestellt. Läuft, also bleibt es.", +"ops.ff_line":"Hoppla: {name} {what}.", +"ops.ff_ping":"hat aus {city} vierzig Minuten lang einen öffentlichen Resolver angepingt, nur zur Sicherheit", +"ops.ff_typo":"hat in {city} in jede Interface-Beschreibung „Pering“ geschrieben", +"ops.fire":"Entlassen", +"ops.fired":"{name} hat den Ausweis abgegeben und den guten Tacker mitgenommen. Deine Daueraufträge ruhen.", +"ops.floor":"Mindestens behalten", +"ops.hire_an_intern":"NOC-Praktikant einstellen", +"ops.hire_mo":"Einstellen · {price}/Monat", +"ops.hire_pitch":"Keine Lust mehr, in jeder Stadt dieselben fünfzehn Buttons zu klicken? Stell einen NOC-Praktikanten ein. Du schreibst die Daueraufträge einmal; er arbeitet sie jeden Tag ab, zahlt genau das, was deine Klicks kosten würden, und hinterlässt eine Zeile im Log.", +"ops.hire_pitch_short":"Regeln einmal festlegen, und ein Praktikant klickt jeden Tag die Buttons.", +"ops.hired":"{name} ist im NOC. Schreib ein paar Daueraufträge, morgen geht es los.", +"ops.how_add":"Router dazu", +"ops.how_auto":"erst dazu, dann tauschen", +"ops.how_it_works":"Jeden Tag arbeitet {name} die eingeschalteten Aufträge ab, bezahlt jeden Job genau so, als hättest du geklickt, und hört auf, sobald das Monatsbudget eines Auftrags oder deine Bargeld-Untergrenze erreicht ist.", +"ops.how_swap":"Generation tauschen", +"ops.kevin":"Kevin", +"ops.kevin_d":"Hat jeden Ausfall seit dem Dotcom-Crash miterlebt. Meistens aus der Kaffeeküche.", +"ops.kevin_from_the_night_shift":"Kevin von der Nachtschicht", +"ops.l_broke":{"one":"stand beim Budget für {where} an","other":"stand bei {n} Aufträgen am Budget an ({where})"}, +"ops.l_caches":{"one":"hat einen Gratis-Cache in {where} eingebaut","other":"hat {n} Gratis-Caches eingebaut ({where})"}, +"ops.l_decline":{"one":"hat ein Mini-Angebot abgelehnt","other":"hat {n} Mini-Angebote abgelehnt"}, +"ops.l_decom":{"one":"hat eine kleine Wave auf {where} zurückgegeben","other":"hat {n} kleine Waves zurückgegeben ({where})"}, +"ops.l_line":"{name} {list}.", +"ops.l_optics":{"one":"hat einen Kanal auf {where} aufgeschaltet","other":"hat {n} Kanäle aufgeschaltet ({where})"}, +"ops.l_peer":{"one":"hat mit einem Netz an {where} gepeert","other":"hat mit {n} Netzen an {where} gepeert"}, +"ops.l_pni":{"one":"hat einen PNI in {where} bestellt","other":"hat {n} PNIs bestellt ({where})"}, +"ops.l_quiet":"{name} hat auf die Graphen geschaut. Nichts zu tun.", +"ops.l_repair":{"one":"hat eine Reparatur beschleunigt","other":"hat {n} Reparaturen beschleunigt"}, +"ops.l_routers":{"one":"hat Router in {where} aufgerüstet","other":"hat Router an {n} Orten aufgerüstet ({where})"}, +"ops.l_rs":{"one":"hat sich einem Route Server angeschlossen","other":"hat sich {n} Route Servern angeschlossen"}, +"ops.l_sales":{"one":"hat einen Kunden unterschrieben","other":"hat {n} Kunden unterschrieben"}, +"ops.l_transit":{"one":"hat Transit in {where} aufgestockt","other":"hat {n}-mal Transit aufgestockt ({where})"}, +"ops.locked":"Das NOC stellt ab Kundenlevel {lv} Praktikanten ein.", +"ops.lpm_off":"Die Peering-Inbox bleibt deine Sache. Dafür gibt es das Large Peering Model; {name} macht keine E-Mails.", +"ops.lpm_on":"Das Large Peering Model beantwortet die Peering-Inbox. {name} geht ihm aus dem Weg.", +"ops.never":"nie", +"ops.no_cap":"kein Limit", +"ops.no_clock":"Keine Uhr, keine Schichten: Bei diesen Regeln gibt es keine Tage, an denen ein Praktikant arbeiten könnte.", +"ops.o_caches":"Gratis-Caches annehmen", +"ops.o_caches_d":"Jeden Gratis-Cache einbauen, den ein Netz anbietet, sobald sein Traffic in der Stadt eine Schwelle überschreitet.", +"ops.o_decom":"Kleine Parallel-Links abbauen", +"ops.o_decom_d":"Sobald ein größerer Link zwischen zwei Städten läuft, die kleineren Waves zurückgeben, die er nicht mehr braucht. Nie eine, die ein Kunde mietet oder braucht.", +"ops.o_ix":"An jedem IX peeren", +"ops.o_ix_d":"Jede Woche: den Route Servern beitreten und jedes willige Mitglied an jedem deiner Exchange-Ports fragen.", +"ops.o_optics":"Mehr Dark Fiber beleuchten", +"ops.o_optics_d":"Optiken auf heiß laufende Dark Fiber stecken und neue Glasfaser am Tag der Übergabe beleuchten.", +"ops.o_pni":"PNI mit den Großen", +"ops.o_pni_d":"Jede Woche: mit jedem willigen Netz, das an deinen POPs genug Traffic schickt, einen PNI bestellen, in der jeweils kleinsten Größe des Netzes.", +"ops.o_repair":"Reparaturen beschleunigen", +"ops.o_repair_d":"Für jeden Ausfall mit Eil-Reparatur zahlen, solange das Budget reicht.", +"ops.o_routers":"Router voraus halten", +"ops.o_routers_d":"Einen Router dazustellen oder auf die nächste Generation tauschen, wo ein zweiter Router den Traffic trägt, sobald Last oder Ports eine Grenze überschreiten.", +"ops.o_sales":"Vertrieb übernehmen", +"ops.o_sales_d":"Angebote unterschreiben, deren Anforderungen mit Kapazität übrig erfüllt sind, und die ablehnen, die sich nicht lohnen.", +"ops.o_transit":"Transit-Reserve halten", +"ops.o_transit_d":"Transit an jedem POP über einem Vielfachen seiner 30-Tage-Spitze halten: ein LAG-Member dazu oder eine Portgröße hoch.", +"ops.ops":"Ops", +"ops.ops_name":"Ops · {name}", +"ops.p_acc":"Fertige Angebote annehmen", +"ops.p_at":"Ab", +"ops.p_g":"Ab", +"ops.p_how":"Wie", +"ops.p_keep":"Einen in Reserve", +"ops.p_min":"Ablehnen unter", +"ops.p_paid":"Paid Peering", +"ops.p_prov":"Anbieter", +"ops.p_tier":"Größe", +"ops.p_x":"Reserve", +"ops.paused":"Pausiert", +"ops.per_pop":"Pro POP", +"ops.per_pop_note":"Grüne Aufträge laufen in diesem POP. Schalte einen aus, um hier selbst zu entscheiden.", +"ops.really_fire":"Wirklich entlassen?", +"ops.salary":"Gehalt {price}/Monat · seit {d}", +"ops.shift":"Schicht von {name}", +"ops.spent_this_month":"Diesen Monat ausgegeben: {price}", +"ops.standing_orders":"Daueraufträge", +"ops.template":"Neuer POP aus der Vorlage", +"ops.template_note":"Wähle, was {name} einrichtet, wenn du eine Stadt aus der Vorlage eröffnest. Den Rest übernehmen die Daueraufträge.", +"ops.tpl_bb":"Breitband", +"ops.tpl_done":"{name} hat {city} eröffnet: {list}.", +"ops.tpl_ix":"IX-Port", +"ops.tpl_just_pop":"nur den POP", +"ops.tpl_kit":"Redundanz-Kit", +"ops.tpl_offer":"{name} kann diese Stadt in einem Rutsch eröffnen: {list}.", +"ops.tpl_open":"Aus Vorlage eröffnen · {cost}", +"ops.tpl_pop":"POP", +"ops.tpl_transit":"10G Transit", +"ops.tracy":"Tracy", +"ops.tracy_d":"Verfolgt jedes Paket Hop für Hop. Kommt am Ende an, mit ein, zwei Sternchen unterwegs.", +"ops.tracy_route":"Tracy Route", "optic_counts.apply_price":"Übernehmen · {price}", "optic_counts.count_for_model":"Anzahl der {model}-Kanäle", "optic_counts.only_n_channels_free":"Auf dieser Glasfaser sind nur {n} Kanäle frei.", diff --git a/site/i18n/es.js b/site/i18n/es.js index f7d7cf0..9ded3e0 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -12,11 +12,6 @@ "action_helpers.too_far_even_at_its_slowest":"Demasiado lejos incluso en su ajuste más lento: aquí un tramo óptico mide {span} km y el alcance es de {max} km. Añade un sitio regenerador (Sistema de línea).", "action_helpers.unlocks_at_customer_level_n":"Se desbloquea en el nivel de cliente {n}.", "actions.your_router_can_t_take_a":"Tu router no admite un puerto de {port}.
Mejóralo en la pestaña Infra.", -"automation.auto_accept_sales":"Ventas automáticas: {state}", -"automation.auto_pay_repairs":"Reparaciones pagadas auto: {state}", -"automation.next_auto_check":"Tiempo hasta la próxima comprobación automática de requisitos.", -"automation.repairs_when_affordable":"Mientras juegas, paga automáticamente las reparaciones urgentes disponibles si hay fondos suficientes.", -"automation.sales_every_five_seconds":"Cada 5 segundos mientras juegas, acepta solo ofertas cuyos requisitos se cumplan y tengan capacidad de servicio disponible.", "badges.a_petabit_a_second":"Un petabit por segundo", "badges.a_secret_badge":"Una insignia secreta", "badges.attend_a_conference":"Asiste a una conferencia.", @@ -2521,6 +2516,107 @@ "notifications.n_min_ago":{"one":"hace {n} min","other":"hace {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Nada en los últimos 10 minutos.", "notifications.show_all_n":"Mostrar las {n}", +"ops.annie":"Annie", +"ops.annie_d":"Responde desde el escritorio más cercano. Le encantan los puertos baratos y los IX llenos.", +"ops.anycast_annie":"Annie Anycast", +"ops.at_least_port":"al menos {port}", +"ops.budget":"Presupuesto", +"ops.by_hand":"Lotes puntuales", +"ops.by_hand_note":"Para cuando lo quieres todo hecho ya: cada peer en cada exchange, un kit de redundancia, PNIs con todos.", +"ops.cheapest":"El más barato", +"ops.ff_desc":"etiquetó un puerto en {city} como «TODO: arreglar luego (no arreglar)»", +"ops.ff_hostname":"renombró el router de {city} a router-final-FINAL-v2", +"ops.ff_lag":"añadió un miembro LAG de tránsito de más en {city}. Funciona, así que se queda.", +"ops.ff_line":"Ups: {name} {what}.", +"ops.ff_ping":"hizo ping a un resolver público desde {city} durante cuarenta minutos, por si acaso", +"ops.ff_typo":"escribió «pering» en todas las descripciones de interfaz de {city}", +"ops.fire":"Despedir", +"ops.fired":"{name} devolvió la tarjeta y se llevó la grapadora buena. Tus órdenes permanentes quedan en pausa.", +"ops.floor":"Conservar al menos", +"ops.hire_an_intern":"Contratar a un becario del NOC", +"ops.hire_mo":"Contratar · {price}/mes", +"ops.hire_pitch":"¿Harto de pulsar los mismos quince botones en cada ciudad? Contrata a un becario del NOC. Escribes las órdenes permanentes una vez; las ejecuta cada día, paga exactamente lo que costarían tus clics y deja una línea en el registro.", +"ops.hire_pitch_short":"Fija las reglas una vez y un becario pulsa los botones cada día.", +"ops.hired":"{name} se ha unido al NOC. Escribe unas órdenes permanentes y mañana se pone a trabajar.", +"ops.how_add":"añadir router", +"ops.how_auto":"añadir y luego cambiar", +"ops.how_it_works":"Cada día {name} repasa las órdenes activas, paga cada trabajo exactamente como si hubieras hecho clic y se detiene al llegar al presupuesto mensual de una orden o a tu mínimo de caja.", +"ops.how_swap":"cambiar de generación", +"ops.kevin":"Kevin", +"ops.kevin_d":"Ha visto todas las caídas desde la burbuja puntocom. Casi todas desde la sala del café.", +"ops.kevin_from_the_night_shift":"Kevin, el del turno de noche", +"ops.l_broke":{"one":"se paró en el presupuesto de {where}","other":"se paró en el presupuesto de {n} órdenes ({where})"}, +"ops.l_caches":{"one":"montó una caché gratis en {where}","other":"montó {n} cachés gratis ({where})"}, +"ops.l_decline":{"one":"rechazó una oferta diminuta","other":"rechazó {n} ofertas diminutas"}, +"ops.l_decom":{"one":"devolvió una wave pequeña en {where}","other":"devolvió {n} waves pequeñas ({where})"}, +"ops.l_line":"{name} {list}.", +"ops.l_optics":{"one":"encendió un canal en {where}","other":"encendió {n} canales ({where})"}, +"ops.l_peer":{"one":"hizo peering con una red en {where}","other":"hizo peering con {n} redes en {where}"}, +"ops.l_pni":{"one":"pidió un PNI en {where}","other":"pidió {n} PNIs ({where})"}, +"ops.l_quiet":"{name} miró las gráficas. No había nada que hacer.", +"ops.l_repair":{"one":"aceleró una reparación","other":"aceleró {n} reparaciones"}, +"ops.l_routers":{"one":"mejoró los routers en {where}","other":"mejoró los routers en {n} sitios ({where})"}, +"ops.l_rs":{"one":"se unió a un route server","other":"se unió a {n} route servers"}, +"ops.l_sales":{"one":"firmó un cliente","other":"firmó {n} clientes"}, +"ops.l_transit":{"one":"amplió el tránsito en {where}","other":"amplió el tránsito {n} veces ({where})"}, +"ops.locked":"El NOC contrata becarios a partir del nivel de clientes {lv}.", +"ops.lpm_off":"La bandeja de peering sigue siendo cosa tuya. Para eso está el Large Peering Model; {name} no contesta correos.", +"ops.lpm_on":"El Large Peering Model contesta la bandeja de peering. {name} no se mete en su camino.", +"ops.never":"nunca", +"ops.no_cap":"sin límite", +"ops.no_clock":"Sin reloj no hay turnos: con estas reglas no hay días en los que un becario pueda trabajar.", +"ops.o_caches":"Aceptar cachés gratis", +"ops.o_caches_d":"Montar cada caché gratis que ofrezca una red, en cuanto su tráfico en esa ciudad pase un umbral.", +"ops.o_decom":"Retirar enlaces paralelos pequeños", +"ops.o_decom_d":"En cuanto funcione un enlace mayor entre dos ciudades, devolver las waves pequeñas que ya no hacen falta. Nunca una que un cliente alquile o necesite.", +"ops.o_ix":"Peering en cada IX", +"ops.o_ix_d":"Cada semana: unirse a los route servers y pedir peering a cada miembro dispuesto en cada uno de tus puertos de exchange.", +"ops.o_optics":"Encender más fibra", +"ops.o_optics_d":"Añadir ópticas a la fibra oscura que va caliente y encender la fibra nueva el día que te la entregan.", +"ops.o_pni":"PNI con los grandes", +"ops.o_pni_d":"Cada semana: pedir un PNI a cada red dispuesta que envíe suficiente tráfico en tus POPs, con el tamaño mínimo de cada red.", +"ops.o_repair":"Acelerar reparaciones", +"ops.o_repair_d":"Pagar la reparación urgente de cada caída que la tenga, mientras dure el presupuesto.", +"ops.o_routers":"Routers por delante", +"ops.o_routers_d":"Añadir un router, o pasar a la siguiente generación donde un segundo router lleve el tráfico, cuando la carga o los puertos pasen de un nivel.", +"ops.o_sales":"Llevar las ventas", +"ops.o_sales_d":"Firmar las ofertas cuyos requisitos se cumplen con capacidad de sobra y rechazar las que pagan demasiado poco.", +"ops.o_transit":"Margen de tránsito", +"ops.o_transit_d":"Mantener el tránsito de cada POP por encima de un múltiplo de su pico de 30 días: un miembro LAG más o un tamaño de puerto mayor.", +"ops.ops":"Ops", +"ops.ops_name":"Ops · {name}", +"ops.p_acc":"Aceptar ofertas listas", +"ops.p_at":"Por encima de", +"ops.p_g":"Desde", +"ops.p_how":"Cómo", +"ops.p_keep":"Dejar uno de reserva", +"ops.p_min":"Rechazar por debajo de", +"ops.p_paid":"Peering de pago", +"ops.p_prov":"Proveedor", +"ops.p_tier":"Tamaño", +"ops.p_x":"Margen", +"ops.paused":"En pausa", +"ops.per_pop":"Por POP", +"ops.per_pop_note":"Las órdenes en verde se ejecutan en este POP. Apaga una para decidir aquí a mano.", +"ops.really_fire":"¿Despedir de verdad?", +"ops.salary":"Sueldo {price}/mes · desde {d}", +"ops.shift":"Turno de {name}", +"ops.spent_this_month":"Gastado este mes: {price}", +"ops.standing_orders":"Órdenes permanentes", +"ops.template":"POP nuevo desde plantilla", +"ops.template_note":"Elige lo que monta {name} cuando abres una ciudad desde la plantilla. Las órdenes permanentes se encargan del resto.", +"ops.tpl_bb":"Banda ancha", +"ops.tpl_done":"{name} abrió {city}: {list}.", +"ops.tpl_ix":"Puerto IX", +"ops.tpl_just_pop":"solo el POP", +"ops.tpl_kit":"Kit de redundancia", +"ops.tpl_offer":"{name} puede abrir esta ciudad de una vez: {list}.", +"ops.tpl_open":"Abrir desde plantilla · {cost}", +"ops.tpl_pop":"POP", +"ops.tpl_transit":"Tránsito de 10G", +"ops.tracy":"Tracy", +"ops.tracy_d":"Sigue cada paquete salto a salto. Al final llega, con alguna estrellita por el camino.", +"ops.tracy_route":"Tracy Route", "optic_counts.apply_price":"Aplicar · {price}", "optic_counts.count_for_model":"Número de canales {model}", "optic_counts.only_n_channels_free":"Solo quedan {n} canales libres en esta fibra.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f58d605..7fc2ed1 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -12,11 +12,6 @@ "action_helpers.too_far_even_at_its_slowest":"Trop loin, même au débit le plus lent : ici une portée optique fait {span} km et l’optique va jusqu’à {max} km. Ajoute un site de régénération (Système de ligne).", "action_helpers.unlocks_at_customer_level_n":"Se débloque au niveau client {n}.", "actions.your_router_can_t_take_a":"Ton routeur ne supporte pas de port {port}.
Mets-le à niveau dans l’onglet Infra.", -"automation.auto_accept_sales":"Ventes automatiques : {state}", -"automation.auto_pay_repairs":"Réparations payées auto : {state}", -"automation.next_auto_check":"Temps avant la prochaine vérification automatique des conditions.", -"automation.repairs_when_affordable":"Pendant le jeu, paie automatiquement les réparations urgentes disponibles si les fonds suffisent.", -"automation.sales_every_five_seconds":"Toutes les 5 secondes pendant le jeu, accepte uniquement les offres dont les conditions sont remplies et la capacité de service disponible.", "badges.a_petabit_a_second":"Un pétabit par seconde", "badges.a_secret_badge":"Un badge secret", "badges.attend_a_conference":"Participe à une conférence.", @@ -2521,6 +2516,107 @@ "notifications.n_min_ago":{"one":"il y a {n} min","other":"il y a {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Rien ces 10 dernières minutes.", "notifications.show_all_n":"Tout afficher ({n})", +"ops.annie":"Annie", +"ops.annie_d":"Répond depuis le bureau le plus proche. Adore les ports pas chers et les IX bien remplis.", +"ops.anycast_annie":"Annie Anycast", +"ops.at_least_port":"au moins {port}", +"ops.budget":"Budget", +"ops.by_hand":"Lots ponctuels", +"ops.by_hand_note":"Pour quand tu veux tout, tout de suite : chaque peer sur chaque exchange, un kit de redondance, des PNI avec tout le monde.", +"ops.cheapest":"Le moins cher", +"ops.ff_desc":"a étiqueté un port à {city} « TODO : corriger plus tard (ne pas corriger) »", +"ops.ff_hostname":"a renommé le routeur de {city} en router-final-FINAL-v2", +"ops.ff_lag":"a ajouté un membre LAG de transit en trop à {city}. Ça marche, donc ça reste.", +"ops.ff_line":"Oups : {name} {what}.", +"ops.ff_ping":"a pingé un résolveur public depuis {city} pendant quarante minutes, au cas où", +"ops.ff_typo":"a écrit « pering » dans toutes les descriptions d'interface à {city}", +"ops.fire":"Remercier", +"ops.fired":"{name} a rendu son badge et emporté la bonne agrafeuse. Tes ordres permanents sont en pause.", +"ops.floor":"Garder au moins", +"ops.hire_an_intern":"Recruter un stagiaire NOC", +"ops.hire_mo":"Recruter · {price}/mois", +"ops.hire_pitch":"Marre de cliquer sur les mêmes quinze boutons dans chaque ville ? Recrute un stagiaire NOC. Tu écris les ordres permanents une fois ; il les exécute chaque jour, paie exactement ce que coûteraient tes clics et laisse une ligne dans le journal.", +"ops.hire_pitch_short":"Fixe les règles une fois, un stagiaire clique sur les boutons chaque jour.", +"ops.hired":"{name} a rejoint le NOC. Écris quelques ordres permanents, et au travail dès demain.", +"ops.how_add":"ajouter un routeur", +"ops.how_auto":"ajouter, puis changer", +"ops.how_it_works":"Chaque jour, {name} passe en revue les ordres actifs, paie chaque tâche exactement comme si tu avais cliqué et s'arrête dès que le budget mensuel d'un ordre, ou ton plancher de trésorerie, est atteint.", +"ops.how_swap":"changer de génération", +"ops.kevin":"Kevin", +"ops.kevin_d":"A vu toutes les pannes depuis la bulle internet. Surtout depuis la salle café.", +"ops.kevin_from_the_night_shift":"Kevin de l'équipe de nuit", +"ops.l_broke":{"one":"s'est arrêté au budget de {where}","other":"s'est arrêté au budget de {n} ordres ({where})"}, +"ops.l_caches":{"one":"a installé un cache gratuit à {where}","other":"a installé {n} caches gratuits ({where})"}, +"ops.l_decline":{"one":"a refusé une offre minuscule","other":"a refusé {n} offres minuscules"}, +"ops.l_decom":{"one":"a rendu une petite wave sur {where}","other":"a rendu {n} petites waves ({where})"}, +"ops.l_line":"{name} {list}.", +"ops.l_optics":{"one":"a allumé un canal sur {where}","other":"a allumé {n} canaux ({where})"}, +"ops.l_peer":{"one":"a peeré avec un réseau à {where}","other":"a peeré avec {n} réseaux à {where}"}, +"ops.l_pni":{"one":"a commandé un PNI à {where}","other":"a commandé {n} PNI ({where})"}, +"ops.l_quiet":"{name} a surveillé les graphes. Rien à faire.", +"ops.l_repair":{"one":"a accéléré une réparation","other":"a accéléré {n} réparations"}, +"ops.l_routers":{"one":"a mis à niveau les routeurs à {where}","other":"a mis à niveau les routeurs à {n} endroits ({where})"}, +"ops.l_rs":{"one":"a rejoint un route server","other":"a rejoint {n} route servers"}, +"ops.l_sales":{"one":"a signé un client","other":"a signé {n} clients"}, +"ops.l_transit":{"one":"a renforcé le transit à {where}","other":"a renforcé le transit {n} fois ({where})"}, +"ops.locked":"Le NOC recrute des stagiaires à partir du niveau clients {lv}.", +"ops.lpm_off":"La boîte de peering reste à toi. Pour ça, il y a le Large Peering Model ; {name} ne fait pas les mails.", +"ops.lpm_on":"Le Large Peering Model répond à la boîte de peering. {name} reste hors de son chemin.", +"ops.never":"jamais", +"ops.no_cap":"sans limite", +"ops.no_clock":"Pas d'horloge, pas de service : avec ces règles, il n'y a pas de jours où un stagiaire pourrait travailler.", +"ops.o_caches":"Accepter les caches gratuits", +"ops.o_caches_d":"Installer chaque cache gratuit qu'un réseau propose, dès que son trafic dans la ville dépasse un seuil.", +"ops.o_decom":"Retirer les petits liens parallèles", +"ops.o_decom_d":"Dès qu'un plus gros lien relie deux villes, rendre les petites waves devenues inutiles. Jamais une qu'un client loue ou dont il dépend.", +"ops.o_ix":"Peerer sur chaque IX", +"ops.o_ix_d":"Chaque semaine : rejoindre les route servers et solliciter chaque membre partant sur chacun de tes ports d'exchange.", +"ops.o_optics":"Allumer plus de fibre", +"ops.o_optics_d":"Ajouter des optiques sur la fibre noire qui chauffe, et allumer la nouvelle fibre le jour de sa livraison.", +"ops.o_pni":"PNI avec les gros", +"ops.o_pni_d":"Chaque semaine : commander un PNI avec chaque réseau partant qui envoie assez de trafic sur tes POP, à la taille minimale de chaque réseau.", +"ops.o_repair":"Accélérer les réparations", +"ops.o_repair_d":"Payer la réparation express de chaque panne qui en a une, tant que le budget suit.", +"ops.o_routers":"Garder les routeurs en avance", +"ops.o_routers_d":"Ajouter un routeur, ou passer à la génération suivante là où un second routeur porte le trafic, quand la charge ou les ports dépassent un seuil.", +"ops.o_sales":"Gérer les ventes", +"ops.o_sales_d":"Signer les offres dont les exigences sont remplies avec de la capacité en réserve, et refuser celles qui paient trop peu.", +"ops.o_transit":"Garder de la marge de transit", +"ops.o_transit_d":"Garder le transit de chaque POP au-dessus d'un multiple de son pic sur 30 jours : un membre LAG de plus, ou une taille de port au-dessus.", +"ops.ops":"Ops", +"ops.ops_name":"Ops · {name}", +"ops.p_acc":"Accepter les offres prêtes", +"ops.p_at":"Au-delà de", +"ops.p_g":"À partir de", +"ops.p_how":"Comment", +"ops.p_keep":"En garder un de secours", +"ops.p_min":"Refuser sous", +"ops.p_paid":"Peering payant", +"ops.p_prov":"Fournisseur", +"ops.p_tier":"Taille", +"ops.p_x":"Marge", +"ops.paused":"En pause", +"ops.per_pop":"Par POP", +"ops.per_pop_note":"Les ordres en vert s'appliquent à ce POP. Désactive-en un pour décider ici à la main.", +"ops.really_fire":"Vraiment remercier ?", +"ops.salary":"Salaire {price}/mois · depuis {d}", +"ops.shift":"Le service de {name}", +"ops.spent_this_month":"Dépensé ce mois-ci : {price}", +"ops.standing_orders":"Ordres permanents", +"ops.template":"Nouveau POP depuis le modèle", +"ops.template_note":"Choisis ce que {name} installe quand tu ouvres une ville depuis le modèle. Les ordres permanents s'occupent du reste.", +"ops.tpl_bb":"Haut débit", +"ops.tpl_done":"{name} a ouvert {city} : {list}.", +"ops.tpl_ix":"Port IX", +"ops.tpl_just_pop":"juste le POP", +"ops.tpl_kit":"Kit de redondance", +"ops.tpl_offer":"{name} peut ouvrir cette ville d'un coup : {list}.", +"ops.tpl_open":"Ouvrir depuis le modèle · {cost}", +"ops.tpl_pop":"POP", +"ops.tpl_transit":"Transit 10G", +"ops.tracy":"Tracy", +"ops.tracy_d":"Suit chaque paquet saut par saut. Arrive au bout, avec une ou deux étoiles en chemin.", +"ops.tracy_route":"Tracy Route", "optic_counts.apply_price":"Appliquer · {price}", "optic_counts.count_for_model":"Nombre de canaux {model}", "optic_counts.only_n_channels_free":"Il ne reste que {n} canaux libres sur cette fibre.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 8f35453..d6752e3 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -12,11 +12,6 @@ "action_helpers.too_far_even_at_its_slowest":"Troppo lontano anche alla velocità più bassa: qui una tratta ottica è di {span} km e l’ottica arriva a {max} km. Aggiungi un sito di rigenerazione (Sistema di linea).", "action_helpers.unlocks_at_customer_level_n":"Si sblocca al livello cliente {n}.", "actions.your_router_can_t_take_a":"Il tuo router non regge una porta {port}.
Aggiornalo nella scheda Infra.", -"automation.auto_accept_sales":"Vendite automatiche: {state}", -"automation.auto_pay_repairs":"Riparazioni a pagamento auto: {state}", -"automation.next_auto_check":"Tempo fino alla prossima verifica automatica dei requisiti.", -"automation.repairs_when_affordable":"Durante il gioco, paga automaticamente le riparazioni urgenti disponibili se hai abbastanza fondi.", -"automation.sales_every_five_seconds":"Ogni 5 secondi durante il gioco, accetta solo le offerte con requisiti soddisfatti e capacità di servizio disponibile.", "badges.a_petabit_a_second":"Un petabit al secondo", "badges.a_secret_badge":"Un badge segreto", "badges.attend_a_conference":"Partecipa a una conferenza.", @@ -2521,6 +2516,107 @@ "notifications.n_min_ago":{"one":"{n} min fa","other":"{n} min fa"}, "notifications.nothing_in_the_last_10_minutes":"Niente negli ultimi 10 minuti.", "notifications.show_all_n":"Mostra tutte e {n}", +"ops.annie":"Annie", +"ops.annie_d":"Risponde dalla scrivania più vicina. Adora le porte economiche e gli IX pieni.", +"ops.anycast_annie":"Annie Anycast", +"ops.at_least_port":"almeno {port}", +"ops.budget":"Budget", +"ops.by_hand":"Lotti una tantum", +"ops.by_hand_note":"Per quando vuoi tutto fatto subito: ogni peer su ogni exchange, un kit di ridondanza, PNI con tutti.", +"ops.cheapest":"Il più economico", +"ops.ff_desc":"ha etichettato una porta a {city} «TODO: sistemare dopo (non sistemare)»", +"ops.ff_hostname":"ha rinominato il router di {city} in router-final-FINAL-v2", +"ops.ff_lag":"ha aggiunto un membro LAG di transit di troppo a {city}. Funziona, quindi resta.", +"ops.ff_line":"Ops: {name} {what}.", +"ops.ff_ping":"ha pingato un resolver pubblico da {city} per quaranta minuti, giusto per sicurezza", +"ops.ff_typo":"ha scritto «pering» in tutte le descrizioni delle interfacce a {city}", +"ops.fire":"Licenzia", +"ops.fired":"{name} ha restituito il badge e si è preso la spillatrice buona. I tuoi ordini permanenti sono in pausa.", +"ops.floor":"Tieni almeno", +"ops.hire_an_intern":"Assumi uno stagista NOC", +"ops.hire_mo":"Assumi · {price}/mese", +"ops.hire_pitch":"Stufo di cliccare gli stessi quindici pulsanti in ogni città? Assumi uno stagista NOC. Scrivi gli ordini permanenti una volta sola; lui li esegue ogni giorno, paga esattamente quanto costerebbero i tuoi clic e lascia una riga nel registro.", +"ops.hire_pitch_short":"Fissa le regole una volta, e uno stagista clicca i pulsanti ogni giorno.", +"ops.hired":"{name} è entrato nel NOC. Scrivi qualche ordine permanente e domani si comincia.", +"ops.how_add":"aggiungi router", +"ops.how_auto":"aggiungi, poi cambia", +"ops.how_it_works":"Ogni giorno {name} esegue gli ordini attivi, paga ogni lavoro esattamente come se avessi cliccato tu e si ferma quando raggiunge il budget mensile di un ordine o la tua soglia di cassa.", +"ops.how_swap":"cambia generazione", +"ops.kevin":"Kevin", +"ops.kevin_d":"Ha visto ogni guasto dai tempi della bolla dot-com. Quasi sempre dalla macchinetta del caffè.", +"ops.kevin_from_the_night_shift":"Kevin del turno di notte", +"ops.l_broke":{"one":"si è fermato al budget di {where}","other":"si è fermato al budget di {n} ordini ({where})"}, +"ops.l_caches":{"one":"ha montato una cache gratuita a {where}","other":"ha montato {n} cache gratuite ({where})"}, +"ops.l_decline":{"one":"ha rifiutato un'offerta minuscola","other":"ha rifiutato {n} offerte minuscole"}, +"ops.l_decom":{"one":"ha restituito una wave piccola su {where}","other":"ha restituito {n} wave piccole ({where})"}, +"ops.l_line":"{name} {list}.", +"ops.l_optics":{"one":"ha acceso un canale su {where}","other":"ha acceso {n} canali ({where})"}, +"ops.l_peer":{"one":"ha fatto peering con una rete a {where}","other":"ha fatto peering con {n} reti a {where}"}, +"ops.l_pni":{"one":"ha ordinato un PNI a {where}","other":"ha ordinato {n} PNI ({where})"}, +"ops.l_quiet":"{name} ha guardato i grafici. Niente da fare.", +"ops.l_repair":{"one":"ha accelerato una riparazione","other":"ha accelerato {n} riparazioni"}, +"ops.l_routers":{"one":"ha potenziato i router a {where}","other":"ha potenziato i router in {n} posti ({where})"}, +"ops.l_rs":{"one":"si è unito a un route server","other":"si è unito a {n} route server"}, +"ops.l_sales":{"one":"ha firmato un cliente","other":"ha firmato {n} clienti"}, +"ops.l_transit":{"one":"ha aumentato il transit a {where}","other":"ha aumentato il transit {n} volte ({where})"}, +"ops.locked":"Il NOC assume stagisti dal livello clienti {lv}.", +"ops.lpm_off":"La casella del peering resta tua. Per quella c'è il Large Peering Model; {name} non risponde alle email.", +"ops.lpm_on":"Il Large Peering Model risponde alla casella del peering. {name} gli sta alla larga.", +"ops.never":"mai", +"ops.no_cap":"nessun limite", +"ops.no_clock":"Niente orologio, niente turni: con queste regole non ci sono giorni in cui uno stagista possa lavorare.", +"ops.o_caches":"Accetta cache gratuite", +"ops.o_caches_d":"Monta ogni cache gratuita che una rete offre, appena il suo traffico in quella città supera una soglia.", +"ops.o_decom":"Ritira i piccoli link paralleli", +"ops.o_decom_d":"Quando un link più grande tra due città è attivo, restituisci le wave piccole che non servono più. Mai una che un cliente noleggia o da cui dipende.", +"ops.o_ix":"Peering su ogni IX", +"ops.o_ix_d":"Ogni settimana: entra nei route server e chiedi il peering a ogni membro disponibile su ciascuna delle tue porte di exchange.", +"ops.o_optics":"Accendi più fibra", +"ops.o_optics_d":"Aggiungi ottiche alla dark fiber che scotta e accendi la fibra nuova il giorno della consegna.", +"ops.o_pni":"PNI con i grandi", +"ops.o_pni_d":"Ogni settimana: ordina un PNI con ogni rete disponibile che manda abbastanza traffico nei tuoi POP, alla taglia minima di ciascuna rete.", +"ops.o_repair":"Accelera le riparazioni", +"ops.o_repair_d":"Paga la riparazione urgente di ogni guasto che ce l'ha, finché il budget regge.", +"ops.o_routers":"Router sempre avanti", +"ops.o_routers_d":"Aggiungi un router, o passa alla generazione successiva dove un secondo router regge il traffico, quando carico o porte superano una soglia.", +"ops.o_sales":"Gestisci le vendite", +"ops.o_sales_d":"Firma le offerte i cui requisiti sono soddisfatti con capacità in avanzo, e rifiuta quelle che pagano troppo poco.", +"ops.o_transit":"Margine di transit", +"ops.o_transit_d":"Tieni il transit di ogni POP sopra un multiplo del suo picco a 30 giorni: un membro LAG in più, o una porta più grande.", +"ops.ops":"Ops", +"ops.ops_name":"Ops · {name}", +"ops.p_acc":"Accetta offerte pronte", +"ops.p_at":"Oltre", +"ops.p_g":"Da", +"ops.p_how":"Come", +"ops.p_keep":"Tienine uno di scorta", +"ops.p_min":"Rifiuta sotto", +"ops.p_paid":"Peering a pagamento", +"ops.p_prov":"Fornitore", +"ops.p_tier":"Taglia", +"ops.p_x":"Margine", +"ops.paused":"In pausa", +"ops.per_pop":"Per POP", +"ops.per_pop_note":"Gli ordini in verde valgono per questo POP. Spegnine uno per decidere qui a mano.", +"ops.really_fire":"Licenziare davvero?", +"ops.salary":"Stipendio {price}/mese · dal {d}", +"ops.shift":"Il turno di {name}", +"ops.spent_this_month":"Speso questo mese: {price}", +"ops.standing_orders":"Ordini permanenti", +"ops.template":"Nuovo POP da modello", +"ops.template_note":"Scegli cosa monta {name} quando apri una città dal modello. Al resto pensano gli ordini permanenti.", +"ops.tpl_bb":"Banda larga", +"ops.tpl_done":"{name} ha aperto {city}: {list}.", +"ops.tpl_ix":"Porta IX", +"ops.tpl_just_pop":"solo il POP", +"ops.tpl_kit":"Kit di ridondanza", +"ops.tpl_offer":"{name} può aprire questa città in un colpo solo: {list}.", +"ops.tpl_open":"Apri da modello · {cost}", +"ops.tpl_pop":"POP", +"ops.tpl_transit":"Transit 10G", +"ops.tracy":"Tracy", +"ops.tracy_d":"Segue ogni pacchetto hop per hop. Alla fine arriva, con qualche asterisco per strada.", +"ops.tracy_route":"Tracy Route", "optic_counts.apply_price":"Applica · {price}", "optic_counts.count_for_model":"Numero di canali {model}", "optic_counts.only_n_channels_free":"Su questa fibra sono liberi solo {n} canali.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a72d97f..b7acb7a 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -12,11 +12,6 @@ "action_helpers.too_far_even_at_its_slowest":"Longe demais até na configuração mais lenta: um span óptico aqui tem {span} km e ela alcança {max} km. Adicione um site de regeneração (Line system).", "action_helpers.unlocks_at_customer_level_n":"Desbloqueia no nível de cliente {n}.", "actions.your_router_can_t_take_a":"Seu router não aguenta uma porta {port}.
Faça upgrade na aba Infra.", -"automation.auto_accept_sales":"Vendas automáticas: {state}", -"automation.auto_pay_repairs":"Reparações pagas auto: {state}", -"automation.next_auto_check":"Tempo até à próxima verificação automática dos requisitos.", -"automation.repairs_when_affordable":"Durante o jogo, paga automaticamente as reparações urgentes disponíveis quando há fundos suficientes.", -"automation.sales_every_five_seconds":"A cada 5 segundos durante o jogo, aceita apenas ofertas com os requisitos cumpridos e capacidade de serviço disponível.", "badges.a_petabit_a_second":"Um petabit por segundo", "badges.a_secret_badge":"Um badge secreto", "badges.attend_a_conference":"Participe de uma conferência.", @@ -2521,6 +2516,107 @@ "notifications.n_min_ago":{"one":"há {n} min","other":"há {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Nada nos últimos 10 minutos.", "notifications.show_all_n":"Mostrar todas as {n}", +"ops.annie":"Annie", +"ops.annie_d":"Responde da mesa mais próxima. Adora uma porta barata e um IX cheio.", +"ops.anycast_annie":"Annie Anycast", +"ops.at_least_port":"pelo menos {port}", +"ops.budget":"Orçamento", +"ops.by_hand":"Lotes avulsos", +"ops.by_hand_note":"Para quando você quer tudo feito agora: cada peer em cada exchange, um kit de redundância, PNIs com todo mundo.", +"ops.cheapest":"O mais barato", +"ops.ff_desc":"etiquetou uma porta em {city} como “TODO: corrigir depois (não corrigir)”", +"ops.ff_hostname":"renomeou o roteador de {city} para router-final-FINAL-v2", +"ops.ff_lag":"adicionou um membro LAG de trânsito a mais em {city}. Funciona, então fica.", +"ops.ff_line":"Ops: {name} {what}.", +"ops.ff_ping":"pingou um resolver público de {city} por quarenta minutos, só para garantir", +"ops.ff_typo":"escreveu “pering” em todas as descrições de interface em {city}", +"ops.fire":"Dispensar", +"ops.fired":"{name} devolveu o crachá e levou o grampeador bom. Suas ordens permanentes estão em pausa.", +"ops.floor":"Manter pelo menos", +"ops.hire_an_intern":"Contratar um estagiário de NOC", +"ops.hire_mo":"Contratar · {price}/mês", +"ops.hire_pitch":"Cansado de clicar nos mesmos quinze botões em cada cidade? Contrate um estagiário de NOC. Você escreve as ordens permanentes uma vez; ele as executa todo dia, paga exatamente o que seus cliques custariam e deixa uma linha no registro.", +"ops.hire_pitch_short":"Defina as regras uma vez, e um estagiário clica nos botões todo dia.", +"ops.hired":"{name} entrou no NOC. Escreva algumas ordens permanentes e amanhã começa o trabalho.", +"ops.how_add":"adicionar roteador", +"ops.how_auto":"adicionar, depois trocar", +"ops.how_it_works":"Todo dia {name} passa pelas ordens ativas, paga cada tarefa exatamente como se você tivesse clicado e para quando chega ao orçamento mensal de uma ordem ou ao seu piso de caixa.", +"ops.how_swap":"trocar de geração", +"ops.kevin":"Kevin", +"ops.kevin_d":"Viu todas as quedas desde a bolha pontocom. A maioria da copa.", +"ops.kevin_from_the_night_shift":"Kevin do turno da noite", +"ops.l_broke":{"one":"parou no orçamento de {where}","other":"parou no orçamento de {n} ordens ({where})"}, +"ops.l_caches":{"one":"instalou um cache grátis em {where}","other":"instalou {n} caches grátis ({where})"}, +"ops.l_decline":{"one":"recusou uma oferta minúscula","other":"recusou {n} ofertas minúsculas"}, +"ops.l_decom":{"one":"devolveu uma wave pequena em {where}","other":"devolveu {n} waves pequenas ({where})"}, +"ops.l_line":"{name} {list}.", +"ops.l_optics":{"one":"acendeu um canal em {where}","other":"acendeu {n} canais ({where})"}, +"ops.l_peer":{"one":"fez peering com uma rede em {where}","other":"fez peering com {n} redes em {where}"}, +"ops.l_pni":{"one":"pediu um PNI em {where}","other":"pediu {n} PNIs ({where})"}, +"ops.l_quiet":"{name} ficou olhando os gráficos. Nada a fazer.", +"ops.l_repair":{"one":"acelerou um reparo","other":"acelerou {n} reparos"}, +"ops.l_routers":{"one":"melhorou os roteadores em {where}","other":"melhorou os roteadores em {n} lugares ({where})"}, +"ops.l_rs":{"one":"entrou em um route server","other":"entrou em {n} route servers"}, +"ops.l_sales":{"one":"fechou com um cliente","other":"fechou com {n} clientes"}, +"ops.l_transit":{"one":"reforçou o trânsito em {where}","other":"reforçou o trânsito {n} vezes ({where})"}, +"ops.locked":"O NOC contrata estagiários a partir do nível de clientes {lv}.", +"ops.lpm_off":"A caixa de peering continua com você. Para isso existe o Large Peering Model; {name} não responde e-mail.", +"ops.lpm_on":"O Large Peering Model responde a caixa de peering. {name} fica fora do caminho dele.", +"ops.never":"nunca", +"ops.no_cap":"sem limite", +"ops.no_clock":"Sem relógio, sem turnos: com estas regras não há dias para um estagiário trabalhar.", +"ops.o_caches":"Aceitar caches grátis", +"ops.o_caches_d":"Instalar cada cache grátis que uma rede oferece, assim que o tráfego dela na cidade passar de um limite.", +"ops.o_decom":"Desativar links paralelos pequenos", +"ops.o_decom_d":"Quando um link maior entre duas cidades estiver no ar, devolver as waves menores que não fazem mais falta. Nunca uma que um cliente aluga ou de que depende.", +"ops.o_ix":"Peering em cada IX", +"ops.o_ix_d":"Toda semana: entrar nos route servers e pedir peering a cada membro disposto em cada uma das suas portas de exchange.", +"ops.o_optics":"Acender mais fibra", +"ops.o_optics_d":"Adicionar ópticas à fibra escura que está esquentando e acender a fibra nova no dia da entrega.", +"ops.o_pni":"PNI com os grandes", +"ops.o_pni_d":"Toda semana: pedir um PNI com cada rede disposta que mande tráfego suficiente nos seus POPs, no tamanho mínimo de cada rede.", +"ops.o_repair":"Acelerar reparos", +"ops.o_repair_d":"Pagar o reparo urgente de cada queda que tenha um, enquanto o orçamento durar.", +"ops.o_routers":"Roteadores à frente", +"ops.o_routers_d":"Adicionar um roteador, ou trocar para a próxima geração onde um segundo roteador segura o tráfego, quando a carga ou as portas passarem de um nível.", +"ops.o_sales":"Cuidar das vendas", +"ops.o_sales_d":"Fechar as ofertas cujos requisitos estão atendidos com capacidade de sobra e recusar as que pagam pouco demais.", +"ops.o_transit":"Folga de trânsito", +"ops.o_transit_d":"Manter o trânsito de cada POP acima de um múltiplo do seu pico de 30 dias: mais um membro LAG, ou um tamanho de porta acima.", +"ops.ops":"Ops", +"ops.ops_name":"Ops · {name}", +"ops.p_acc":"Aceitar ofertas prontas", +"ops.p_at":"Acima de", +"ops.p_g":"A partir de", +"ops.p_how":"Como", +"ops.p_keep":"Manter um de reserva", +"ops.p_min":"Recusar abaixo de", +"ops.p_paid":"Peering pago", +"ops.p_prov":"Provedor", +"ops.p_tier":"Tamanho", +"ops.p_x":"Folga", +"ops.paused":"Em pausa", +"ops.per_pop":"Por POP", +"ops.per_pop_note":"As ordens em verde valem neste POP. Desligue uma para decidir aqui na mão.", +"ops.really_fire":"Dispensar mesmo?", +"ops.salary":"Salário {price}/mês · desde {d}", +"ops.shift":"Turno de {name}", +"ops.spent_this_month":"Gasto este mês: {price}", +"ops.standing_orders":"Ordens permanentes", +"ops.template":"Novo POP por modelo", +"ops.template_note":"Escolha o que {name} monta quando você abre uma cidade pelo modelo. As ordens permanentes cuidam do resto.", +"ops.tpl_bb":"Banda larga", +"ops.tpl_done":"{name} abriu {city}: {list}.", +"ops.tpl_ix":"Porta de IX", +"ops.tpl_just_pop":"só o POP", +"ops.tpl_kit":"Kit de redundância", +"ops.tpl_offer":"{name} pode abrir esta cidade de uma vez: {list}.", +"ops.tpl_open":"Abrir pelo modelo · {cost}", +"ops.tpl_pop":"POP", +"ops.tpl_transit":"Trânsito de 10G", +"ops.tracy":"Tracy", +"ops.tracy_d":"Segue cada pacote salto a salto. Chega no fim, com uma ou duas estrelinhas no caminho.", +"ops.tracy_route":"Tracy Route", "optic_counts.apply_price":"Aplicar · {price}", "optic_counts.count_for_model":"Número de canais {model}", "optic_counts.only_n_channels_free":"Só há {n} canais livres nesta fibra.", From 08413b53a3f1092b6eae16e611f1c25e1fdaafcd Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 17:46:16 +0100 Subject: [PATCH 17/64] Tests: #185 sales and repair run as standing orders; batches open from the Ops sheet --- tests/automation.test.js | 241 ++++++++------------------------------- tests/pni-global.test.js | 6 +- tests/utilities.test.js | 5 +- 3 files changed, 56 insertions(+), 196 deletions(-) diff --git a/tests/automation.test.js b/tests/automation.test.js index 5ae9473..6b772f8 100644 --- a/tests/automation.test.js +++ b/tests/automation.test.js @@ -2,136 +2,30 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); +// #185's sales and repair engines now run as the NOC intern's standing orders, once per game day. function setup(ev) { - ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});compute()"); + ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});S.lvl=2;S.ops.intern='kevin';S.ops.floor=0;S.rules=makeRules('freeze');compute()"); } +const orders = (ev, on) => ev(`for(const k of ${JSON.stringify(on)})S.ops.on[k]=true`); +const shift = ev => ev('opsDay(S.day)'); function offer(ev, id, extra = {}) { ev(`S.offers.push(${JSON.stringify({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`); } -test('auto-accept waits five real seconds at every game speed and the toggle stops it', () => { - for (const speed of [0.5, 1, 2, 4, 8]) { - const { ev, dom, errors } = load(); - setup(ev); - offer(ev, 'first'); - ev("ACT.autoToggle({k:'autoSales'});UI.autoSalesAt=1000"); - const start = ev('UI.autoSalesAt'); - ev(`UI.speed=${speed};automationTick(${start + 4999})`); - assert.equal(ev('S.biz.length'), 0, speed); - ev(`automationTick(${start + 5000})`); - assert.equal(ev('S.biz[0].id'), 'first', speed); - offer(ev, 'second'); - ev(`automationTick(${start + 9999})`); - assert.equal(ev('S.biz.length'), 1, speed); - ev(`automationTick(${start + 10000})`); - assert.equal(ev('S.biz.length'), 2, speed); - ev("ACT.autoToggle({k:'autoSales'})"); - offer(ev, 'off'); - ev(`automationTick(${start + 20000});ACT.accept({id:'off',auto:true})`); - assert.equal(ev('S.biz.length'), 2, speed); - assert.equal(ev('S.offers[0].id'), 'off', speed); - assert.deepEqual(errors, []); - dom.window.close(); - } -}); - -test('Accept buttons share a real-time countdown in Deals, city offers and fiber broker offers', () => { +test('the sales order signs ready offers once per shift, and pausing it stops it', () => { const { ev, dom, errors } = load(); setup(ev); - offer(ev, 'ready'); - offer(ev, 'waiting', { reqs: ['gen'] }); - ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';UI.leftOpen=true;renderAll()"); - assert.equal(dom.window.document.querySelectorAll('[data-auto-sales]').length, 0); - ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); - const counts = () => [...dom.window.document.querySelectorAll('[data-auto-sales]')]; - const readyCounts = () => counts().filter(el => el.dataset.autoSales === 'ready'); - assert.ok(readyCounts().length >= 2, 'Deals and the city panel both show it'); - assert.ok(readyCounts().every(el => el.textContent === '(5)')); - assert.ok(counts().filter(el => el.dataset.autoSales === 'waiting').every(el => el.textContent === ''), 'unmet requirements have no countdown'); - ev('testNow=2001;renderAutoCountdown()'); - assert.ok(readyCounts().every(el => el.textContent === '(4)')); - ev('testNow=3000;UI.speed=8;renderAutoCountdown()'); - assert.ok(readyCounts().every(el => el.textContent === '(3)')); - ev('UI.speed=0.5;renderAll();renderAutoCountdown()'); - assert.ok(readyCounts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone'); - assert.match(dom.window.document.querySelector('#leftBody [data-act="accept"]').textContent, /Accept \(3\)/); - ev("ACT.buildPop({city:'ams'});S.links.push({id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:[],own:true,km:450,ready:0,cut:0,mo:1})"); - offer(ev, 'broker', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 1, what: 'One wave' }); - ev("compute();UI.sel={type:'link',id:'fiber'};renderPanel()"); - const broker = dom.window.document.querySelector('#panelBody [data-act="accept"] [data-auto-sales]'); - assert.ok(broker); - assert.equal(broker.textContent, '(3)'); - ev('testNow=6000;automationTick(testNow);renderAutoCountdown()'); - assert.equal(ev("S.biz.some(b=>b.id==='ready')"), true); - assert.equal(ev("S.offers.some(o=>o.id==='waiting')"), true, 'the countdown does not bypass requirements'); - offer(ev, 'next-ready'); - ev('renderAll();renderAutoCountdown()'); - assert.ok(counts().filter(el => el.dataset.autoSales === 'next-ready').every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown'); - ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); - assert.equal(counts().length, 0); - assert.deepEqual(errors, []); - dom.window.close(); -}); - -test('only ready offers get a countdown, including after requirements or capacity change', () => { - const { ev, dom, errors } = load(); - setup(ev); - offer(ev, 'ready'); - offer(ev, 'needs-generator', { reqs: ['gen'] }); - offer(ev, 'too-big', { bw: 1000 }); - offer(ev, 'expired', { exp: 0 }); - ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); - const count = id => dom.window.document.querySelector(`#leftBody [data-auto-sales="${id}"]`).textContent; - assert.equal(count('ready'), '(5)'); - assert.equal(count('needs-generator'), ''); - assert.equal(count('too-big'), ''); - assert.equal(count('expired'), ''); - ev('S.pops.fra.gen=true;after()'); - assert.equal(count('needs-generator'), '(5)', 'becoming eligible shows the timer'); - ev('S.pops.fra.gen=false;compute();renderAutoCountdown()'); - assert.equal(count('needs-generator'), '', 'a requirement becoming false hides it immediately'); - ev("S.offers.find(o=>o.id==='too-big').bw=2;after()"); - assert.equal(count('too-big'), '(5)', 'actions invalidate the capacity preview'); - ev('testNow=6000;automationTick(testNow);renderAutoCountdown()'); - assert.equal(ev("S.offers.some(o=>o.id==='needs-generator')"), true, 'acceptance checks requirements again'); - assert.deepEqual(errors, []); - dom.window.close(); -}); - -test('readiness trials are shared between views and are not repeated for every redraw', () => { - const { ev, dom, errors } = load(); - setup(ev); - offer(ev, 'ready'); - ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';window.originalAutoOffer=autoOffer;window.trials=0;window.autoOffer=o=>{trials++;return originalAutoOffer(o)};ACT.autoToggle({k:'autoSales'})"); - assert.equal(ev('trials'), 1); - ev('renderAll();compute();renderAll();renderAutoCountdown()'); - assert.equal(ev('trials'), 1, 'ordinary routing refreshes reuse the preview'); - ev('after()'); - assert.equal(ev('trials'), 2, 'a real action refreshes readiness'); - ev('window.autoOffer=originalAutoOffer'); - assert.deepEqual(errors, []); - dom.window.close(); -}); - -test('auto-accept leaves unready and expired offers alone without failure notifications', () => { - const { ev, dom, errors } = load(); - setup(ev); - offer(ev, 'generator', { reqs: ['gen'] }); - offer(ev, 'missing-pop', { city: 'ams' }); - offer(ev, 'scrub', { type: 'scrub' }); - offer(ev, 'expired', { exp: 0 }); - offer(ev, 'ipv6', { reqs: ['ipv6'] }); - const log = ev('S.log.length'); - ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); - assert.equal(ev('S.biz.length'), 0); - assert.equal(ev('S.offers.length'), 5); - assert.equal(ev('S.log.length'), log, 'no repeated failed manual-action toasts'); - ev('S.pops.fra.gen=true;compute();automationTick(10000)'); - assert.equal(ev('S.biz.length'), 1); - assert.equal(ev('S.biz[0].id'), 'generator'); - // Manual acceptance keeps its existing sign-now, provision-later behavior. - ev("ACT.accept({id:'scrub'})"); - assert.equal(ev("S.biz.some(b=>b.id==='scrub')"), true); + offer(ev, 'first'); + shift(ev); + assert.equal(ev('S.biz.length'), 0, 'off by default'); + orders(ev, ['sales']); + shift(ev); + assert.equal(ev('S.biz[0].id'), 'first'); + ev("ACT.opsToggle({k:'sales'})"); + offer(ev, 'off'); + ev('dayTick()'); + assert.equal(ev('S.biz.length'), 1, 'a paused order signs nothing'); + assert.ok(ev("S.offers.some(o=>o.id==='off')")); assert.deepEqual(errors, []); dom.window.close(); }); @@ -146,7 +40,7 @@ test('the trial includes new bandwidth and later offers cannot overbook earlier assert.equal(ev('!!autoOffer(S.offers[0])'), true); assert.equal(ev('JSON.stringify(S)'), state); assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true); - ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + ev('S.ops.on.sales=true;opsDay(S.day)'); assert.equal(ev('S.biz.length'), 1); assert.equal(ev('S.offers[0].id'), 'two'); assert.ok(ev('bizSf(S.biz[0])') >= 0.95); @@ -154,7 +48,7 @@ test('the trial includes new bandwidth and later offers cannot overbook earlier dom.window.close(); }); -test('auto-accept checks actual circuits, latency and NNI capacity', () => { +test('the sales order checks actual circuits, latency and NNI capacity', () => { const { ev, dom, errors } = load(); setup(ev); ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;compute()"); @@ -170,7 +64,7 @@ test('auto-accept checks actual circuits, latency and NNI capacity', () => { offer(ev, 'fabric-one', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] }); offer(ev, 'fabric-two', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] }); // Transit has enough headroom, so the second rejection is the shared NNI port. - ev("S.transit[0].tier=4;compute();S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)"); + ev("S.transit[0].tier=4;compute();S.ops.on.sales=true;opsDay(S.day)"); assert.equal(ev('S.biz.length'), 1); assert.equal(ev('S.offers[0].id'), 'fabric-two'); assert.ok(ev("nniUsed('fra',fabric)<=NNI[0].g")); @@ -200,7 +94,7 @@ test('fiber sales check live equipment and free spectrum, and repeated carrier o assert.equal(ev('!!autoOffer(S.offers[0])'), false); ev("S.offers[0].slots=1;S.offers[0].name='Same Carrier';S.links[0].eqDown=10;compute()"); assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'a broken amplifier prevents a wave sale'); - ev('S.links[0].eqDown=0;compute();S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + ev('S.links[0].eqDown=0;compute();S.ops.on.sales=true;opsDay(S.day)'); assert.equal(ev('S.biz.length'), 1); assert.equal(ev('S.biz[0].slots'), 2); assert.equal(ev('S.biz[0].rate'), 1600); @@ -216,7 +110,7 @@ test('capacity pair sales need completed infrastructure and reserve it for the a assert.equal(ev('!!autoOffer(S.offers[0])'), false); ev("ACT.buildPop({city:'ams'});S.links=[{id:'own',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1}];compute()"); assert.equal(ev('!!autoOffer(S.offers[0])'), true); - ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + ev('S.ops.on.sales=true;opsDay(S.day)'); assert.equal(ev('S.biz[0].link'), 'own'); assert.equal(ev('capPend(S.biz[0])'), true, 'normal delivery handover still happens on a game day'); offer(ev, 'second-pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 }); @@ -230,7 +124,7 @@ test('future event demand is tested before signing, with booked events reserving setup(ev); offer(ev, 'event', { type: 'event', bw: 80, rate: 0, start: 10, dur: 3, fee: 5000, exp: 9 }); assert.equal(ev('!!autoOffer(S.offers[0])'), true); - ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + ev('S.ops.on.sales=true;opsDay(S.day)'); assert.equal(ev('S.biz[0].start'), 10, 'the trial does not move the actual event date'); assert.equal(ev('R.cityDem.fra'), 0); offer(ev, 'too-large', { bw: 30 }); @@ -257,7 +151,7 @@ test('failed capacity trials restore game, routing and map state even when compu dom.window.close(); }); -test('auto-pay rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its toggle', () => { +test('the repair order rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its pause', () => { const { ev, dom, errors } = load(); setup(ev); ev(`S.cash=10000;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,chFail:{i:0,until:10},mo:1}]; @@ -268,7 +162,7 @@ test('auto-pay rushes affordable repairs once, skips unaffordable and expired in {id:'orphan',type:'amp',ref:'gone',until:10,cost:299,msg:'Removed equipment'}, {id:'expired',type:'amp',ref:'fiber',until:0,cost:1000,msg:'Expired'}, {id:'ddos',type:'ddos',ref:'fra',until:10,cost:1000,msg:'Attack'}]; - S.autoRepair=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(1)`); + S.ops.on.repair=true;opsDay(S.day)`); assert.equal(ev('S.cash'), 3000); assert.equal(ev("S.inc.some(i=>i.id==='optic')"), false); assert.equal(ev('S.links[0].chFail'), null); @@ -276,88 +170,51 @@ test('auto-pay rushes affordable repairs once, skips unaffordable and expired in assert.equal(ev("S.inc.find(i=>i.id==='slow').until"), 1); assert.equal(ev("S.inc.find(i=>i.id==='slow').cost"), 0); assert.equal(ev('S.pops.fra.down'), 1); - ev('automationTick(2)'); + ev('opsDay(S.day)'); assert.equal(ev('S.cash'), 3000, 'no duplicate rush payment'); - ev('S.cash=40000;automationTick(3)'); + ev('S.cash=40000;opsDay(S.day)'); assert.equal(ev('S.cash'), 10000); assert.equal(ev('S.links[0].eqDown'), 0); assert.equal(ev("S.inc.some(i=>i.id==='amp')"), false); - ev("ACT.autoToggle({k:'autoRepair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});automationTick(4)"); + ev("ACT.opsToggle({k:'repair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});opsDay(S.day)"); assert.equal(ev('S.cash'), 10000); assert.equal(ev("S.inc.some(i=>i.id==='new')"), true); assert.deepEqual(errors, []); dom.window.close(); }); -test('automation pauses with the game, dialogs, hidden pages and game over', () => { +test('the sales order leaves unready and expired offers alone without failure notifications', () => { const { ev, dom, errors } = load(); setup(ev); - offer(ev, 'paused'); - ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;UI.speed=0;automationTick(5000)'); + offer(ev, 'generator', { reqs: ['gen'] }); + offer(ev, 'missing-pop', { city: 'ams' }); + offer(ev, 'scrub', { type: 'scrub' }); + offer(ev, 'expired', { exp: 0 }); + offer(ev, 'ipv6', { reqs: ['ipv6'] }); + const log = ev('S.log.length'); + ev('S.ops.on.sales=true;opsDay(S.day)'); assert.equal(ev('S.biz.length'), 0); - ev('UI.speed=1;automationTick(9999)'); - assert.equal(ev('S.biz.length'), 0, 'resume starts a fresh five-second wait'); - ev("openModal('

Menu

');automationTick(10000);closeModal()"); - ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'hidden'});automationTick(15000)"); - ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'visible'});S.lost=true;automationTick(20000);S.lost=false;automationTick(24999)"); - assert.equal(ev('S.biz.length'), 0); - ev('automationTick(25000)'); + assert.equal(ev('S.offers.length'), 5); + assert.equal(ev('S.log.length'), log, 'no failed manual-action toasts and no shift line when nothing got done'); + ev('S.pops.fra.gen=true;compute();opsDay(S.day)'); assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.biz[0].id'), 'generator'); + // Manual acceptance keeps its existing sign-now, provision-later behavior. + ev("ACT.accept({id:'scrub'})"); + assert.equal(ev("S.biz.some(b=>b.id==='scrub')"), true); assert.deepEqual(errors, []); dom.window.close(); }); -test('the frame loop repairs new incidents without waiting for the sales timer', () => { +test('the #185 toggles in old saves become the sales and repair orders, malformed ones stay off', () => { const { ev, dom, errors } = load(); setup(ev); - ev(`S.autoRepair=true;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,mo:1}]; - window.originalDay=dayTick;window.dayTick=()=>{S.links[0].eqDown=10;S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'Broken amp'})}; - window.cashBefore=S.cash;last=0;acc=DAY_MS;frame(16);window.dayTick=originalDay`); - assert.equal(ev('S.cash'), ev('cashBefore-1000')); - assert.equal(ev('S.inc.length'), 0); - assert.equal(ev('S.links[0].eqDown'), 0); + ev("delete S.ops;S.autoSales=true;S.autoRepair=true;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.ops.on.sales&&S.ops.on.repair'), true); + assert.equal(ev("'autoSales' in S||'autoRepair' in S"), false); + assert.equal(ev('S.ops.intern'), null, 'no intern until you hire one, so nothing runs yet'); + ev("delete S.ops;S.autoSales='true';S.autoRepair=1;S=migrate(S)"); + assert.equal(ev('S.ops.on.sales||S.ops.on.repair'), false); assert.deepEqual(errors, []); dom.window.close(); }); - -test('toggles persist, old and malformed saves default off, and the timer resets for another game', () => { - const { ev, dom, errors } = load(); - setup(ev); - assert.equal(ev('S.autoSales||S.autoRepair'), false); - ev("ACT.autoToggle({k:'autoSales'});ACT.autoToggle({k:'autoRepair'});save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')))"); - assert.equal(ev('S.autoSales&&S.autoRepair'), true); - ev("delete S.autoSales;delete S.autoRepair;S=migrate(S)"); - assert.equal(ev('S.autoSales||S.autoRepair'), false); - ev("S.autoSales='true';S.autoRepair=1;S=migrate(S);ACT.autoToggle({k:'cash'})"); - assert.equal(ev('S.autoSales||S.autoRepair'), false); - ev('UI.autoGame=S;UI.autoSalesAt=0;S=migrate(JSON.parse(JSON.stringify(S)));S.autoSales=true;compute()'); - offer(ev, 'imported'); - ev('automationTick(100000)'); - assert.equal(ev('S.biz.length'), 0, 'an imported game does not inherit another game timer'); - ev('automationTick(105000)'); - assert.equal(ev('S.biz.length'), 1); - assert.deepEqual(errors, []); - dom.window.close(); -}); - -test('both toggle buttons work by keyboard-compatible DOM events on phones in every language', () => { - for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { - const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); - setup(ev); - dom.window.innerWidth = 360; - for (const [tab, key] of [['deals', 'autoSales'], ['noc', 'autoRepair']]) { - ev(`ACT.leftTab({t:'${tab}'});renderAll()`); - const button = [...dom.window.document.querySelectorAll('#leftBody [data-act="autoToggle"]')].find(b => JSON.parse(b.dataset.args).k === key); - assert.ok(button, lang); - assert.equal(button.getAttribute('aria-pressed'), 'false', lang); - button.focus(); - button.click(); - const updated = dom.window.document.querySelector('#leftBody [data-act="autoToggle"]'); - assert.equal(updated.getAttribute('aria-pressed'), 'true', lang); - assert.equal(ev(`S.${key}`), true, lang); - assert.doesNotMatch(dom.window.document.getElementById('leftBody').textContent, /automation\./, lang); - } - assert.deepEqual(errors, [], lang); - dom.window.close(); - } -}); diff --git a/tests/pni-global.test.js b/tests/pni-global.test.js index de03c9a..9661a0d 100644 --- a/tests/pni-global.test.js +++ b/tests/pni-global.test.js @@ -100,14 +100,16 @@ test('global PNIs require the full budget and reject unsupported sizes and an em dom.window.close(); }); -test('the global Traffic button preserves scope, keyboard focus and translations on phones', () => { +test('the global batch, now in the Ops sheet, preserves scope, keyboard focus and translations on phones', () => { for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { const { dom, ev, errors } = load(lang === 'en' ? {} : { lang }); setup(ev); dom.window.innerWidth = 360; + // The Traffic tab now points at the Ops sheet, where the one-off batches live. ev("ACT.dash();ACT.dashTab({k:'traffic'})"); const doc = dom.window.document; - const button = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')].find(b => JSON.parse(b.dataset.args).net === null); + doc.querySelector('#dashCard [data-act="opsOpen"]').click(); + const button = [...doc.querySelectorAll('#modalCard [data-act="pniAllOpen"]')].find(b => JSON.parse(b.dataset.args).net === null); assert.ok(button, lang); button.click(); assert.equal(doc.querySelector('#modalCard h2').textContent, ev("tr('pni_all.peer_all_networks')"), lang); diff --git a/tests/utilities.test.js b/tests/utilities.test.js index 1e86ee5..d096951 100644 --- a/tests/utilities.test.js +++ b/tests/utilities.test.js @@ -89,11 +89,12 @@ test('bulk peering skips disconnected IXs, route server coverage and existing do assert.deepEqual(errors, []); }); -test('utilities are available from the menu and PoP Infra in every language', t => { +test('utilities are available from the Ops sheet in the menu and from PoP Infra in every language', t => { for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { const { ev, dom, errors } = setup(t, lang === 'en' ? {} : { lang }); ev('ACT.menu()'); - assert.ok(dom.window.document.querySelector('[data-act="utilities"]'), lang); + dom.window.document.querySelector('#modalCard [data-act="opsOpen"]').click(); + assert.ok(dom.window.document.querySelector('#modalCard [data-act="utilities"]'), lang); ev("selectCity('fra');ACT.tab({t:'links'})"); assert.ok(dom.window.document.querySelector('#panelBody [data-act="utilityKit"]'), lang); ev('ACT.utilities()'); From c3c25fe5656aa617469320a816b5107205457ac7 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 17:52:37 +0100 Subject: [PATCH 18/64] Tests for standing orders: each order costs what the clicks cost; budget, pause, saves, fat fingers, phones --- src/game/60-features/95-standing-orders.js | 13 +- tests/standing-orders.test.js | 325 +++++++++++++++++++++ 2 files changed, 332 insertions(+), 6 deletions(-) create mode 100644 tests/standing-orders.test.js diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 248fe53..582e273 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -27,7 +27,7 @@ const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_ // Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; const OPS_FF_RATE={oncall:1/150,bgp:1/60}; -function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:{},mon:0,skip:{},log:[],floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} +function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),mon:0,skip:{},log:[],floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} const opsO=()=>S.ops||(S.ops=opsNew()); const opsHired=()=>!!(S&&S.ops&&S.ops.intern&&own(INTERNS,S.ops.intern)); const opsCanHire=()=>lvl()>=2; @@ -65,9 +65,9 @@ function opsQuiet(fn){const a=after,t=toast,s=sfx,f=floater,sel=UI.sel,cf=UI.con // One shift's bookkeeping: what got done, and whether a job had to wait for next month's budget. function opsShift(){const r=new Map(),broke=new Set(); return {r,broke,did(k,w){const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, - can(k,cost){const O=S.ops,cap=opsCap(k);if(cost<=0)return true;if(S.cash-costcap)){broke.add(k);return false;}return true;}, + can(k,cost){const O=S.ops,cap=opsCap(k);if(cost<=0)return true;if(S.cash-costcap)){broke.add(k);return false;}return true;}, // Run a click and book what it really cost; false when the action refused (no ports, no cash, a quote changed). - pay(k,fn){const c0=S.cash,x=fn();const d=c0-S.cash;if(d>0&&OPSK[k].cap)S.ops.spent[k]+=d;return x===undefined?d>0:x;}};} + pay(k,fn){const c0=S.cash,x=fn();const d=c0-S.cash;if(d>0&&OPSK[k].cap)S.ops.spent[k]=(S.ops.spent[k]||0)+d;return x===undefined?d>0:x;}};} const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0]; // The orders. Each takes the shift and does its jobs through the player's own actions. const OPS_RUN={ @@ -151,7 +151,8 @@ function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!= function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))return null;const T=S.ops.tpl,parts=[];let cost=popCost(c),net=null,ix=null,kit=null; if(T.bb){cost+=bbCost(c);parts.push(tr('ops.tpl_bb'));} if(T.transit&&!scnRule('noTransit')){const pv=opsP('transit','prov');net=pv!=='cheap'&&sellsAt(NET[pv],c)?NET[pv]:cheapestTransit(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}} - // DE-KICKS wants a sales call before any port, so the template leaves those to the player. - if(T.ix&&CITY[c].ix&&!isDk(c)){ix=c;cost+=ixPortMo(c,0);parts.push(tr('ops.tpl_ix'));} - if(T.kit){S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false};try{kit=utilityKit(c);}finally{delete S.pops[c];}if(kit&&kit.cost){cost+=kit.cost;parts.push(tr('ops.tpl_kit'));}} + // Priced as if the POP were already there (an IX port is dearer from afar). DE-KICKS wants a sales call first, so not those. + S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false}; + try{if(T.ix&&CITY[c].ix&&!isDk(c)&&S.ixp[c]===undefined){ix=c;cost+=ixPortMo(c,0);parts.push(tr('ops.tpl_ix'));} + if(T.kit){kit=utilityKit(c);if(kit&&kit.cost){cost+=kit.cost;parts.push(tr('ops.tpl_kit'));}}}finally{delete S.pops[c];} return {cost,net:net&&net.id,ix,kit:!!(kit&&kit.cost),parts};} diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js new file mode 100644 index 0000000..af96b48 --- /dev/null +++ b/tests/standing-orders.test.js @@ -0,0 +1,325 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// A small network with a hired intern, every order off, no cash floor and no fat fingers (Change Freeze). +const BASE = "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.launchBB({city:'fra'});S.pops.fra.bb.d=300;S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()"; +function game(t, extra = '') { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev(BASE); + if (extra) h.ev(extra); + return h; +} +const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()"); +const on = (ev, k, p = {}, cap) => ev(`S.ops.on.${k}=true;S.ops.p.${k}=${JSON.stringify(p)};${cap === undefined ? '' : `S.ops.cap.${k}=${cap};`}`); +const shift = ev => ev('opsDay(S.day)'); +const cash = ev => ev('S.cash'); +// The same game twice: the intern's shift in one, the player's own clicks in the other. Both must cost the same and end the same. +function twins(t, extra, order, manual, pick) { + const A = game(t), B = game(t); + // Hire first: hiring recomputes, which would wipe any routing state the case stages. + hire(A.ev); hire(B.ev); + if (extra) { A.ev(extra); B.ev(extra); } + order(A.ev); + const a0 = cash(A.ev); shift(A.ev); const a1 = cash(A.ev); + const b0 = cash(B.ev); B.ev(manual); const b1 = cash(B.ev); + assert.ok(a0 - a1 > 0, 'the order did some paid work'); + assert.equal(a0 - a1, b0 - b1, 'the shift cost exactly what the clicks cost'); + if (pick) assert.equal(A.ev(pick), B.ev(pick), 'and left the network the same'); + assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []); + return A; +} + +test('a new game has no intern and every order off; nothing runs and no random numbers are drawn', t => { + const { ev, errors } = game(t); + assert.equal(ev('S.ops.intern'), null); + assert.equal(ev('Object.values(S.ops.on).some(Boolean)'), false); + ev("for(const k in S.ops.on)S.ops.on[k]=true"); + const r = ev('window.__n=0;window.__r=Math.random;Math.random=()=>{__n++;return __r()};const s=JSON.stringify(S);opsDay(S.day);Math.random=__r;s===JSON.stringify(S)&&__n===0'); + assert.equal(r, true, 'no intern: orders never run, even switched on'); + assert.deepEqual(errors, []); +}); + +test('the intern is hired from customer level 2 (or with gates open), costs a monthly salary, and can be let go', t => { + const { ev, errors } = game(t); + ev("S.lvl=1;ACT.opsHire({id:'kevin'})"); + assert.equal(ev('S.ops.intern'), null, 'level 1: not yet'); + ev("S.rules=makeRules('sandbox');S.rules.preset='freeze';ACT.opsHire({id:'annie'})"); + assert.equal(ev('S.ops.intern'), 'annie', 'gates open'); + ev("S.ops.intern=null;S.rules=makeRules('freeze');S.lvl=2;compute()"); + const mo = ev('R.costMo'), c0 = cash(ev); + ev("ACT.opsHire({id:'tracy'})"); + assert.equal(ev('S.ops.intern'), 'tracy'); + assert.equal(c0 - cash(ev), ev('INTERN_MO'), 'first month up front'); + assert.equal(ev('R.costMo') - mo, ev('INTERN_MO'), 'then a monthly salary'); + ev("ACT.opsFire();ACT.opsFire()"); + assert.equal(ev('S.ops.intern'), null); + assert.deepEqual(errors, []); +}); + +test('transit headroom adds a LAG member, exactly as the + member button would', t => { + const A = twins(t, "S.transit[0].hist=[60,80,70]", + ev => on(ev, 'transit', { x: 1.5 }), + "ACT.lagT({id:S.transit[0].id,d:1})", "JSON.stringify(S.transit.map(t=>[t.net,t.tier,t.n||1]))"); + assert.match(A.ev('opsEntry(S.ops.log[0])'), /Kevin topped up transit in Frankfurt \+1×100G/); +}); + +test('transit headroom buys a new port from a chosen provider and stops at the multiple', t => { + const A = twins(t, "S.transit[0].hist=[100]", + ev => on(ev, 'transit', { x: 2, prov: 'ntt' }), + "ACT.buyTransit({city:'fra',net:'ntt',tier:1})", "JSON.stringify(S.transit.map(t=>[t.net,t.tier,t.n||1]))"); + assert.ok(A.ev("S.transit.reduce((a,t)=>a+lagCap(PORT[t.tier].g,t.n),0)") >= 200); +}); + +test('routers: add one above the load level, as Add router would', t => { + twins(t, "R.nodeLoad.fra=R.nodeCap.fra*0.85", + ev => on(ev, 'routers', { at: 80, how: 'add' }), + "ACT.addRouter({city:'fra'})", 'S.pops.fra.routers'); +}); + +test('routers: swap generation only where a second router carries the traffic', t => { + const { ev, errors } = game(t, 'R.nodeLoad.fra=R.nodeCap.fra*0.95'); + hire(ev); on(ev, 'routers', { at: 80, how: 'swap' }); + shift(ev); + assert.equal(ev('S.pops.fra.rgen'), 1, 'one router: a swap would be an outage, so no'); + ev('S.pops.fra.routers=2;compute();R.nodeLoad.fra=R.nodeCap.fra*0.95'); + const want = ev('swapCost("fra",mainRG(RG[1].cls+1))'), c0 = cash(ev); + shift(ev); + assert.equal(ev('S.pops.fra.rgen'), ev('mainRG(RG[1].cls+1)')); + assert.equal(c0 - cash(ev), want, 'paid the swap price after trade-in'); + assert.equal(ev("S.inc.some(i=>i.type==='maint')"), false); + assert.deepEqual(errors, []); +}); + +test('caches: free boxes only once the network sends enough traffic locally', t => { + const { ev, errors } = game(t); + hire(ev); + const best = ev("NETS.filter(n=>n.cache&&(R.demTo[n.id]||0)>=n.cache.min).map(n=>(R.cityDem.fra||0)*NSH[n.id]).sort((a,b)=>b-a)[0]||0"); + assert.ok(best > 0, 'some network qualifies for a cache in this game'); + on(ev, 'caches', { g: 50 }); + if (best < 50) { shift(ev); assert.equal(ev('S.caches.length'), 0, 'below the threshold: nothing'); } + on(ev, 'caches', { g: 1 }); + const c0 = cash(ev); + shift(ev); + const want = JSON.parse(ev("JSON.stringify(utilityCaches('fra'))")); + assert.ok(ev('S.caches.length') > 0); + assert.equal(want.add.filter(x => ev(`(R.cityDem.fra||0)*NSH['${x.net}']`) >= 1).length, 0, 'every eligible box is in'); + assert.equal(cash(ev), c0, 'caches are free to rack'); + assert.deepEqual(errors, []); +}); + +test('IX: weekly route servers and every willing peer, the same as the #192 batch', t => { + const A = game(t, "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0})"), B = game(t, "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0})"); + hire(A.ev); on(A.ev, 'ix'); + A.ev('S.day=13');shift(A.ev); + assert.equal(A.ev('Object.keys(S.rs).length'), 0, 'not on a weekday the intern skips'); + A.ev('S.day=14');shift(A.ev); + B.ev('ACT.utilityRouteServers();ACT.utilityPeers()'); + assert.equal(A.ev('JSON.stringify(S.rs)'), B.ev('JSON.stringify(S.rs)')); + assert.equal(A.ev('JSON.stringify(Object.keys(S.peers).sort())'), B.ev('JSON.stringify(Object.keys(S.peers).sort())')); + assert.equal(A.ev('utilityPeers().reduce((n,r)=>n+r.requests.length,0)'), 0); + assert.deepEqual(A.errors, []); +}); + +test('PNI: weekly, big enough networks only, paid peering left out by default, at each network\'s own size and lead time', t => { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;compute()"); + hire(ev); on(ev, 'pni', { g: 5, tier: 1 }, 0); + ev('S.day=17;S.pops.fra.bb.d=3000;S.pops.ams.bb={d:3000};compute()'); + const plan = JSON.parse(ev("JSON.stringify(pniBatch(null,1).orders.filter(q=>(R.cityDem[q.city]||0)*NSH[q.net]>=5&&(NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).map(q=>({k:q.city+q.net,cost:q.cost,tier:q.tier,big:pniBig(q.net)})))")); + assert.ok(plan.length > 0); + const c0 = cash(ev); + shift(ev); + const got = JSON.parse(ev('JSON.stringify(S.pni.map(p=>({k:p.city+p.net,tier:p.tier,ready:p.ready})))')); + assert.deepEqual(got.map(p => p.k).sort(), plan.map(p => p.k).sort()); + // Lead times are each network's own (pniLead), quick here under Change Freeze. + for (const p of plan) { const g = got.find(x => x.k === p.k); assert.equal(g.tier, p.tier); assert.ok(g.ready > 17 && g.ready <= 17 + ev(p.big ? 'leadDays(365)' : 'leadDays(42)'), p.k); } + assert.equal(c0 - cash(ev), plan.reduce((a, p) => a + p.cost, 0), 'the same setup fees as the bulk order'); + assert.equal(ev("S.pni.some(p=>NET[p.net].pol==='paid'&&!paidFree(NET[p.net]))"), false); + assert.deepEqual(errors, []); +}); + +test('sales: decline offers below the minimum, sign the ready ones with #185\'s trial', t => { + const { ev, errors } = game(t); + hire(ev); on(ev, 'sales', { acc: true, min: 5000 }); + ev('S.transit[0].tier=3;S.pops.fra.rgen=3;compute()'); + ev("S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:30},{id:'big',city:'fra',name:'Big',type:'dia',bw:10,rate:600,reqs:[],exp:30},{id:'gen',city:'fra',name:'Gen',type:'dia',bw:10,rate:600,reqs:['gen'],exp:30}]"); + shift(ev); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz.map(b=>b.id))')), ['big']); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))')), ['gen'], 'unmet requirements wait, the tiny one is gone'); + assert.match(ev('opsEntry(S.ops.log[0])'), /declined a tiny offer, signed a customer/); + assert.deepEqual(errors, []); +}); + +test('repairs: rush what has a price, as the Rush repair button would', t => { + twins(t, "S.links=[{id:'f',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,mo:1}];S.inc=[{id:'amp',type:'amp',ref:'f',until:10,cost:3000,msg:'amp'}];S.pops.ams={day:0,bb:null,boost:0,down:0,routers:1,gen:false}", + ev => on(ev, 'repair'), "ACT.fixInc({id:'amp'})", 'S.inc.length'); +}); + +test('optics: light hot fiber with the optic already in it, at the #177 batch price', t => { + const extra = "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;S.links.push({id:'f',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,mo:1,trench:'f'});compute();R.load.f=dfCap(S.links.at(-1))*0.95"; + const A = twins(t, extra, ev => on(ev, 'optics', { at: 70 }), + "ACT.setChCount({id:'f',o:'zr4',n:2})", "JSON.stringify(S.links.find(l=>l.id==='f').ch)"); + assert.equal(A.ev("S.links.find(l=>l.id==='f').ch.length"), 2, 'one more channel brings the fiber under the level'); +}); + +test('decommission: smaller parallel waves go once the bigger link has room, never one a customer needs', t => { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier] of [['w1',0],['w2',0],['big',2]])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:450,sub:false,cut:0,mo:100,trench:id});compute()"); + hire(ev); on(ev, 'decom', { keep: true }); + ev("R.load={w1:1,w2:1,big:10}"); + shift(ev); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['big', 'w1'], 'one small wave kept as a spare'); + on(ev, 'decom', { keep: false }); + ev("S.biz.push({id:'c',name:'C',type:'l2vpn',city:'fra',city2:'ams',bw:1,rate:1,reqs:['diverse'],mood:100,since:0});R.load={w1:1,big:10}"); + shift(ev); + assert.ok(ev("S.links.some(l=>l.id==='w1')"), 'a diverse-path customer still needs it'); + ev("S.biz=[];R.load={w1:1,big:10}"); + shift(ev); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id))")), ['big']); + assert.deepEqual(errors, []); +}); + +test('the monthly budget cap and the cash floor stop the intern; a new month resets the budget', t => { + const { ev, errors } = game(t); + hire(ev); ev('S.transit[0].hist=[600]'); on(ev, 'transit', { x: 3 }, 10000); + const c0 = cash(ev); + shift(ev); + const spent = c0 - cash(ev); + assert.ok(spent > 0 && spent <= 10000, 'some work, never over the cap'); + assert.equal(ev('S.ops.spent.transit'), spent); + assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Keep transit headroom/); + const c1 = cash(ev); + shift(ev); + assert.equal(cash(ev), c1, 'the same month: nothing more'); + // The next step (four 100G members to 400G, $16k) never fits a $10k month; the budget still starts again. + ev('S.day+=30;S.ops.cap.transit=50000'); + shift(ev); + assert.ok(cash(ev) < c1, 'a new month, a new budget'); + assert.equal(ev('S.ops.spent.transit'), c1 - cash(ev), 'counted from zero'); + ev("S.ops.cap.transit=0;S.ops.floor=1e6;S.cash=1e6+500;S.transit[0].hist=[1e5]"); + const c2 = cash(ev); + shift(ev); + assert.equal(cash(ev), c2, 'the cash floor holds even without a cap'); + assert.deepEqual(errors, []); +}); + +test('pause: an order switched off does nothing, and per-POP switches leave a city alone', t => { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});ACT.buyTransit({city:'ams',net:'cog',tier:1});for(const t of S.transit)t.hist=[90]"); + hire(ev); on(ev, 'transit', { x: 2 }); + ev("ACT.opsToggle({k:'transit'})"); + const s0 = ev('JSON.stringify(S.transit)'); + shift(ev); + assert.equal(ev('JSON.stringify(S.transit)'), s0); + ev("ACT.opsToggle({k:'transit'});ACT.opsPop({k:'transit',city:'ams'});closeModal()"); + shift(ev); + assert.ok(ev("(S.transit.find(t=>t.city==='fra').n||1)") > 1, 'Frankfurt topped up'); + assert.equal(ev("(S.transit.find(t=>t.city==='ams').n||1)"), 1, 'Amsterdam left alone'); + assert.deepEqual(errors, []); +}); + +test('the shift runs inside dayTick, respects a stopped clock, batches its work and recomputes once', t => { + const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]"); + hire(ev); on(ev, 'transit', { x: 1.5 }); on(ev, 'caches', { g: 1 }); + const n = ev("window.__c=compute;window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"); + assert.equal(n, 1, 'one recompute for the whole shift'); + const d = ev('S.day'); + ev('dayTick()'); + assert.equal(ev('S.ops.log[0].d'), d + 1); + ev("S.rules.clock=false;const before=JSON.stringify(S.ops);dayTick();window.__same=before===JSON.stringify(S.ops)"); + assert.equal(ev('__same'), true, 'no clock, no shift'); + assert.deepEqual(errors, []); +}); + +test('the daily log line is folded into one NOC notification', t => { + const { ev, errors } = game(t, "S.transit[0].hist=[600]"); + hire(ev); on(ev, 'transit', { x: 1.5 }); + const n0 = ev('S.log.length'); + shift(ev); + assert.equal(ev('S.log.length'), n0 + 1); + assert.match(ev('S.log[0].t'), /Kevin's shift Kevin topped up transit/); + assert.deepEqual(errors, []); +}); + +test('fat fingers: never under Change Freeze, rare and harmless in On-call and BGP at 3 a.m.', t => { + const { ev, errors } = game(t); + hire(ev); + ev('window.__r=Math.random;Math.random=()=>0'); + for (let i = 0; i < 50; i++) shift(ev); + assert.equal(ev('S.ops.log.some(e=>e.f!==undefined)'), false, 'Change Freeze: never, even on the unluckiest roll'); + for (const p of ['oncall', 'bgp']) { + ev(`S.rules=makeRules('${p}');S.ops.log=[]`); + const c0 = cash(ev), links = ev('S.links.length'), pops = ev('Object.keys(S.pops).length'); + shift(ev); + assert.equal(ev('S.ops.log[0].f!==undefined'), true, p); + assert.ok(c0 - cash(ev) <= 20000, 'costs a little at most'); + assert.equal(ev('S.links.length'), links); assert.equal(ev('Object.keys(S.pops).length'), pops); + } + ev('Math.random=__r'); + assert.ok(ev("OPS_FF_RATE.oncall<0.01&&OPS_FF_RATE.bgp<0.02"), 'rare'); + assert.deepEqual(errors, []); +}); + +test('a new POP from the template costs exactly the clicks it replaces', t => { + const A = game(t), B = game(t); + hire(A.ev); hire(B.ev); + const q = JSON.parse(A.ev("JSON.stringify(opsTplQuote('ams'))")); + assert.ok(q.net && q.ix && q.kit); + const a0 = cash(A.ev); A.ev("ACT.opsNewPop({city:'ams'})"); const a1 = cash(A.ev); + const b0 = cash(B.ev); + B.ev(`ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});ACT.buyTransit({city:'ams',net:'${q.net}',tier:0});ACT.buyIx({city:'ams',tier:0});ACT.utilityKit({city:'ams',cost:utilityKit('ams').cost})`); + assert.equal(a0 - a1, q.cost, 'the quoted price'); + assert.equal(a0 - a1, b0 - cash(B.ev), 'the same as clicking it'); + assert.equal(A.ev('JSON.stringify([S.pops.ams.gen,S.pops.ams.site2,S.pops.ams.routers,!!S.pops.ams.bb,S.ixp.ams])'), B.ev('JSON.stringify([S.pops.ams.gen,S.pops.ams.site2,S.pops.ams.routers,!!S.pops.ams.bb,S.ixp.ams])')); + A.ev('S.cash=10');A.ev("ACT.opsNewPop({city:'lon'})"); + assert.equal(A.ev('!!S.pops.lon'), false, 'all or nothing on the price'); + assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []); +}); + +test('saves: old saves load with no intern and everything off, settings survive a reload, junk is repaired', t => { + const { ev, errors } = game(t); + ev("delete S.ops;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.ops.intern'), null); + assert.equal(ev('Object.values(S.ops.on).some(Boolean)'), false); + hire(ev); + ev("on=1;S.ops.on.pni=true;S.ops.p.pni={g:50,tier:2,paid:true};S.ops.cap.pni=1e6;S.ops.skip.fra=['caches'];save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')))"); + assert.equal(ev("S.ops.intern==='kevin'&&S.ops.on.pni&&S.ops.p.pni.tier===2&&S.ops.cap.pni===1e6&&S.ops.skip.fra[0]==='caches'"), true); + ev(`S.ops={intern:'mallory',on:{transit:'yes',hack:true},p:{transit:{x:99,prov:'nobody'}},cap:{transit:-5},spent:{transit:'lots'},skip:{atlantis:['transit'],fra:['ix','transit']}, + log:[{d:1,i:'kevin',r:[['transit',2,['fra +1×100G','']],['evil',1,[]]],f:99,c:'fra'},'junk'],floor:3,tpl:{bb:'no'}};S=migrate(S)`); + assert.equal(ev('S.ops.intern'), null); + assert.equal(ev("S.ops.on.transit===false&&!('hack' in S.ops.on)"), true); + assert.equal(ev("opsP('transit','x')===1.5&&opsP('transit','prov')==='cheap'&&opsCap('transit')===50000&&S.ops.spent.transit===0"), true); + assert.equal(ev("JSON.stringify(S.ops.skip)"), '{"fra":["transit"]}'); + assert.equal(ev("JSON.stringify(S.ops.log)"), '[{"d":1,"i":"kevin","r":[["transit",2,["fra +1×100G"]]]}]'); + assert.equal(ev('S.ops.floor===50000&&S.ops.tpl.bb===true'), true); + assert.deepEqual(errors, []); +}); + +test('the Ops sheet works at 360 px in every language, from the NOC tab and the phone tab bar', t => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const h = load(lang === 'en' ? {} : { lang }); + const { ev, dom, errors } = h; + ev(BASE); + dom.window.innerWidth = 360; + const doc = dom.window.document; + ev("ACT.phoneTab({t:'noc'})"); + const open = doc.querySelector('#leftBody [data-act="opsOpen"]'); + assert.ok(open, lang); + open.click(); + const hireBtn = doc.querySelector('#modalCard [data-act="opsHire"]'); + assert.ok(hireBtn, lang); + hireBtn.click(); + assert.ok(ev('opsHired()'), lang); + doc.querySelector('#modalCard [data-act="opsToggle"]').click(); + assert.equal(doc.querySelector('#modalCard [data-act="opsToggle"]').getAttribute('aria-pressed'), 'true', lang); + doc.querySelector('#modalCard [data-act="opsParam"]').click(); + const txt = doc.getElementById('modalCard').textContent; + assert.doesNotMatch(txt, /\bops\.[a-z_]+/, lang); + assert.ok(doc.querySelector('#modalCard select[data-chg="opsCity"]'), lang); + ev("closeModal();selectCity('ams')"); + assert.ok(doc.querySelector('#panelBody [data-act="opsNewPop"]'), lang); + assert.doesNotMatch(doc.getElementById('panelBody').textContent, /\bops\.[a-z_]+/, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); From 829d3a4ba63c6404e3932819b70af99a47cfe75b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 17:52:42 +0100 Subject: [PATCH 19/64] CHANGELOG and architecture notes for standing orders --- CHANGELOG.md | 5 +++-- docs/ARCHITECTURE.md | 4 +++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ff161e..fb39718 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,9 +27,10 @@ All notable changes to this project are documented here. The project follows - Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation. - Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf. - Order PNIs with one network or every network at all shared POPs from the NOC Traffic tab: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time. -- Toggle auto-accept in Deals to check ready sales every five real seconds, including their requirements and available service capacity, with a countdown beside eligible Accept buttons. -- Toggle auto-pay repairs in the NOC to pay for affordable rush repairs automatically while the game runs. - Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. +- Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, and the intern writes one line a day in the NOC (#98, #100, #102, #181, #185, #192, #177). +- Open a new city from a template in one tap: POP, broadband, transit, an IX port and the redundancy kit, priced up front, with your standing orders taking it from there (#98, #192). +- Auto-accept and auto-pay repairs are now the intern's sales and repair orders and run once a game day; saved games keep both switched on, and they start working once you hire an intern. The bulk peering and PNI batches moved into the Ops sheet, next to the orders that repeat them (#185, #181, #192). ## [1.36.0] — 2026-10-28 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d856f63..1e23b3b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -29,7 +29,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) | | `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) | | `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` | -| `60-features/` | Banks and loans, scenarios and the weekly challenge, conferences, the tutorial, traceroute, the share card, `newGame()` | +| `60-features/` | Banks and loans, scenarios and the weekly challenge, 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 inbox, peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | | `80-simulation/` | Dijkstra, RouteScript, `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, geography pricing and latency, second sites and service | | `85-incidents/` | `addInc()`, DDoS and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()` | @@ -99,6 +99,8 @@ never freezes the game. 3. Records history for 95th-percentile billing, stats and streaks. 4. Rolls failures (`fireFailure()`) and events (`fireEvent()`) when their timers run out, and expires incidents. + Then the NOC intern's standing orders (`opsDay()`), if one is hired: each order clicks the same `ACT` + actions a player would, muted, within its monthly budget, and the shift recomputes once at the end. 5. Updates customer mood, churn and new offers; IX members join; loans tick. 6. Every 30 days: bills the month (revenue minus costs) and checks for bankruptcy. 7. Checks goals, level, badges and scenario end conditions. From 47fbd1c12485f928e778e1095b7bc4e82a67c06b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 18:13:48 +0100 Subject: [PATCH 20/64] Standing orders: one sales trial per shift, so a big network's day stays fast --- src/game/60-features/95-standing-orders.js | 8 +++++--- tests/standing-orders.test.js | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 582e273..9aa65be 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -26,7 +26,7 @@ const OPS_TPL=['bb','transit','ix','kit']; const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke')}; // Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; -const OPS_FF_RATE={oncall:1/150,bgp:1/60}; +const OPS_TRIALS=1,OPS_FF_RATE={oncall:1/150,bgp:1/60}; function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),mon:0,skip:{},log:[],floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} const opsO=()=>S.ops||(S.ops=opsNew()); const opsHired=()=>!!(S&&S.ops&&S.ops.intern&&own(INTERNS,S.ops.intern)); @@ -72,10 +72,12 @@ const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>transitPerG(a, // The orders. Each takes the shift and does its jobs through the player's own actions. const OPS_RUN={ repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id})))X.did('repair');}, - sales(X){const min=opsP('sales','min'),acc=opsP('sales','acc'); + sales(X){const min=opsP('sales','min'),acc=opsP('sales','acc');let tries=0; for(const o of S.offers.slice()){const T=BIZ_T[o.type];if(!T)continue;const v=T.event?(o.fee||0):bizMo(o); if(min&&vx!==o);X.did('decline');continue;} - if(acc){ACT.accept({id:o.id,auto:true});if(!S.offers.includes(o)){X.did('sales');compute();}}}}, + // Each trial is a full routing pass: at most one a shift, and an offer that did not fit waits a week. + if(acc&&o.exp>S.day&&bCities(o).every(popUp)&&reqOk(o)&&triesS.day-7)){tries++;ACT.accept({id:o.id,auto:true}); + if(!S.offers.includes(o))X.did('sales');else{if(!UI.opsTried||UI.opsTried.s!==S)UI.opsTried={s:S,m:new Map()};UI.opsTried.m.set(o.id,S.day);}}}}, routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'); for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue; const ld=Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));if(ld { + const { ev, errors } = game(t); + hire(ev); on(ev, 'sales', { acc: true, min: 0 }); + ev("S.offers=['a','b','c'].map(id=>({id,city:'fra',name:id,type:'dia',bw:1e5,rate:600,reqs:[],exp:60}));window.__t=0;window.__a=autoOffer;autoOffer=o=>{__t++;return __a(o)}"); + shift(ev); + assert.equal(ev('__t'), 1, 'one routing trial per shift'); + for (let i = 0; i < 2; i++) { ev('S.day++'); shift(ev); } + assert.equal(ev('__t'), 3, 'each offer once'); + ev('S.day++'); shift(ev); + assert.equal(ev('__t'), 3, 'too big for the network: not tried again within the week'); + ev('S.day+=7'); shift(ev); + assert.equal(ev('__t'), 4); + ev('autoOffer=__a'); + assert.deepEqual(errors, []); +}); From 1f182b0df99523ef08253dfc5cc374f7809779b7 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 18:16:31 +0100 Subject: [PATCH 21/64] Pinned attack flows are routed even when RouteScript moves every other exit off their rank The rank loop skips ranks no list uses (RSET), but flows pinned to an entry port route at the port's plain rank. With 'prepend transit' or 'prefer transit' moving every transit to 2.9/4.4, rank 3 was skipped and the flood vanished. Fixes tests/routing-reference.test.js, which failed on v2. --- src/game/80-simulation/30-compute.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 9b35c84..055784d 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -167,6 +167,8 @@ function compute(){ // Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order. const byRank={},RSET=new Set();for(const id of NET_IDS){const m=byRank[id]={};for(const e of okBy[id]){const r=TR?eff(e,id):base(e,id);RSET.add(r);(m[r]||(m[r]=[])).push(e);} for(const r in m){const L=m[r];L.hi=L.some(e=>e.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}} + // Attack flows pinned to their entry port route at its plain rank, which RouteScript may have left with no list. + for(const f of flows)if(f.pin)for(const e of ingressE[f.pin]||[])RSET.add(base(e)); // The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index. let f=null,Dv=null,Pv=null,PP=null,vis=0;const walked=[],G=[],REST=[],NEG=[]; // An exit the flow can still try: not visited yet, not full when the flow started, and reachable from the POP. From 2d12a20e3405f315e242e8feefa31ff70bd88c50 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 18:36:44 +0100 Subject: [PATCH 22/64] Routing: a flow scans only the exits on its own island The big fixture is a dozen islands (POPs no backbone joins). Each flow scanned every exit in its rank's list and threw away the unreachable ones, two thirds of the scan. Lists are now split per island once per compute; with one island nothing changes. Same exits, same order, same result (routing-reference gains a network-of-islands case). --- src/game/80-simulation/30-compute.js | 8 ++++++-- tests/routing-reference.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 055784d..4ef8bdc 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -14,6 +14,8 @@ function compute(){ // ALONE[i]: no other city lies within 1e-6 of POP i (so only its own exits can be at distance 0 from it). const SPD={},SPP={},SDi=[],SPi=[],ALONE=new Uint8Array(NC),wW=e=>e.w,wLat=e=>e.lat+0.05; for(const s of pops){const i=CIDX[s],r=dijkstra(adj,i,wW);SDi[i]=SPD[s]=r.D;SPi[i]=SPP[s]=r.P;ALONE[i]=1;for(let x=0;x=0)continue;const D=SDi[i],k=NCOMP++;for(let x=0;xday||scnRule('spat'), leak=ev.leak&&ev.leak.until>day?ev.leak.net:null; for(const t of S.transit){if(!popUp(t.city)||t.down>day||!liveN(t.city,t.site,t.n))continue; @@ -165,8 +167,10 @@ function compute(){ const PASSES=TR&&TR.protect?[x=>x.bz,x=>!x.bz]:null; // Each network's exits by the rank they route at (RouteScript can move an exit per network), in E's order. // Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order. + // With several islands (POPs no backbone joins), each list is split by island: a flow only scans exits it can reach. + const idx=L=>{L.hi=L.some(e=>e.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}; const byRank={},RSET=new Set();for(const id of NET_IDS){const m=byRank[id]={};for(const e of okBy[id]){const r=TR?eff(e,id):base(e,id);RSET.add(r);(m[r]||(m[r]=[])).push(e);} - for(const r in m){const L=m[r];L.hi=L.some(e=>e.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}} + for(const r in m){const L=m[r];if(NCOMP>1){const cs=[];for(const e of L){const k=COMP[e.ci];if(k>=0)(cs[k]||(cs[k]=[])).push(e);}for(const s of cs)if(s)idx(s);m[r]={cs};}else idx(L);}} // Attack flows pinned to their entry port route at its plain rank, which RouteScript may have left with no list. for(const f of flows)if(f.pin)for(const e of ingressE[f.pin]||[])RSET.add(base(e)); // The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index. @@ -218,7 +222,7 @@ function compute(){ if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue; Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++; if(f.pin){for(const e of ingressE[f.pin]||[])if(base(e)===rank&&e.used { + const { ev, dom, errors } = load(); + try { + network(ev); + ev("S.links=S.links.filter(l=>!['df4','df9','w3','w4','w8','w9'].includes(l.id));compute()"); + assert.ok(ev("Object.keys(S.pops).some(c=>!pathExists('fra',c))"), 'the network is in pieces'); + const changes = [ + '', + "S.pni.forEach((p,i)=>p.pref=i%3===0?'high':i%3===1?'low':'normal')", + "S.te={on:true,script:'prefer pni for goggle\\nspill at 80%'}", + "S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}", + "S.links[0].cut=S.day+2", + "S.te=null;S.links[0].cut=0;S.links.push({id:'join',a:'par',b:'pek',kind:'wave',tier:2,km:8000,cut:0,mo:100})", + ]; + for (const change of changes) { + ev(change); + ev('window.priorR=JSON.stringify(R);referenceCompute();window.expectedR=JSON.stringify(R);R=JSON.parse(priorR);compute()'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(R)')), JSON.parse(ev('expectedR')), change || 'baseline'); + } + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); From 7def8113f4307075a4714bf9afd6c008e4722457 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 18:51:09 +0100 Subject: [PATCH 23/64] Routing: remember each list's first exit group per source city while its exits have room Most flows from one city ask the same rank list for the same nearest group of exits. Exits only fill up while routing, so while every exit in that group still has room the scan would find it again; it is reused instead. Networks with identical exit lists share one list, so the memory serves them all. Same groups, same order, same result (routing-reference and speed tests). --- src/game/80-simulation/30-compute.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 4ef8bdc..568b6f6 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -169,8 +169,11 @@ function compute(){ // Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order. // With several islands (POPs no backbone joins), each list is split by island: a flow only scans exits it can reach. const idx=L=>{L.hi=L.some(e=>e.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}; + // Networks with the same exits at a rank share one list (LIST, by content), so what one flow learns serves them all. + const LIST=new Map();for(let i=0;i1){const cs=[];for(const e of L){const k=COMP[e.ci];if(k>=0)(cs[k]||(cs[k]=[])).push(e);}for(const s of cs)if(s)idx(s);m[r]={cs};}else idx(L);}} + for(const r in m){const L=m[r],key=L.map(e=>e.xi).join(','),o=LIST.get(key);if(o){m[r]=o;continue;} + let V=L;if(NCOMP>1){const cs=[];for(const e of L){const k=COMP[e.ci];if(k>=0)(cs[k]||(cs[k]=[])).push(e);}for(const s of cs)if(s)idx(s);V={cs};}else idx(L);LIST.set(key,V);m[r]=V;}} // Attack flows pinned to their entry port route at its plain rank, which RouteScript may have left with no list. for(const f of flows)if(f.pin)for(const e of ingressE[f.pin]||[])RSET.add(base(e)); // The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index. @@ -234,13 +237,18 @@ function compute(){ // One scan: the best (preference, distance) so far and, in list order, the exits within 1e-6 of it. The best // distance only goes down, so dropping the ones it leaves behind gives exactly the exits a second scan would. // Exits that are full stay full for this pass: when a quarter of a list is, it is rewritten without them. + /* gc[ci]: the first group this list gave a flow from city ci. Exits only fill up during routing, so while all of + them still have room no other exit can have become better, and the scan would find the same group (an + empty one, no usable exit, stays empty). */ + const gc=lst.gc||(lst.gc=[]),c=gc[f.ci]; + if(c!==undefined&&c.every(e=>e.used=e.cap){full++;continue;}const d=Dv[e.ci];if(d===Infinity)continue;const h=e.hp; if(h=lst.length&&full){let k=0;for(let li=0;li1)continue; - if(G.length>1)sortD(G);} + if(bh>1){gc[f.ci]=[];continue;} + if(G.length>1)sortD(G);gc[f.ci]=G.slice();}} sendGroup(G,0,G.length); if(f.rem<=1e-6)continue; REST.length=0;for(let li=0;li Date: Wed, 28 Oct 2026 19:14:51 +0100 Subject: [PATCH 24/64] Sales trial: run the pass with the offer first, and skip the other when it cannot change the answer With events booked ahead the trial routed the network twice: without the offer (who is happy now) and with it. compute() only reads the previous result for scenic circuits, so without those the order of the two passes does not matter. With the offer first, a failing offer or one nobody is unhappy with needs no second pass. The same offers are signed (tests/sales-trial.test.js checks over 100 seeded offers against the original trial, scenic or not). --- src/game/60-features/90-automation.js | 9 +++- tests/sales-trial.test.js | 73 +++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 tests/sales-trial.test.js diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js index aa4a274..528c15a 100644 --- a/src/game/60-features/90-automation.js +++ b/src/game/60-features/90-automation.js @@ -11,7 +11,14 @@ function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.ra // Trial the added demand before signing; failed trials leave the live game untouched. try{S={...S,biz:S.biz}; // shortcut: future events reserve capacity together; use per-date trials if separate bookings must share capacity. - if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();} + if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x); + /* Signed if the offer works and nobody who works without it breaks. compute() reads the last result only for + scenic circuits, so without them the pass with the offer can go first: when the offer fails, or nobody is + unhappy with it, the pass without it cannot change the answer and is skipped. */ + const fut=S.biz,all=fut.concat(b); + if(!all.some(x=>x.route==='scenic')){if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=all;compute();if(bizWhy(b).length)return null; + const bad=fut.filter(x=>bizWhy(x).length);if(!bad.length)return b;S.biz=fut;compute();return bad.every(x=>bizWhy(x).length)?b:null;} + compute();} const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null; }finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}} diff --git a/tests/sales-trial.test.js b/tests/sales-trial.test.js new file mode 100644 index 0000000..814b62b --- /dev/null +++ b/tests/sales-trial.test.js @@ -0,0 +1,73 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); + +// The sales trial (#185, the intern's sales order) runs the pass with the offer first and skips the pass without +// it when it cannot change the answer. It must sign exactly the offers the original two-pass trial signs. +const ORIGINAL = `(function(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null; + const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; + if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null; + if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id; + if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;} + const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day); + try{S={...S,biz:S.biz}; + if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();} + const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); + return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null; + }finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}})`; + +test('the faster sales trial signs exactly the offers the two-pass trial signs', () => { + const { ev, dom, errors } = load(); + try { + const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();window.slowOffer=${ORIGINAL};`); + assert.ok(ev('S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day)'), 'the fixture has events booked ahead, so the shortcut runs'); + const seen = { yes: 0, no: 0, skipped: 0, third: 0 }; + ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}'); + for (let day = 0; day < 6; day++) { + ev(`__reseed(${1000 + day});S.offers=[];for(let i=0;i<10;i++)spawnOffer();`); + // Small offers that fit, and on alternate days a squeeze, so offers fail on capacity and on others' service too. + ev(`for(const o of S.offers)o.bw=Math.max(1,Math.round(o.bw*${day % 2 ? 1 : 0.05}))`); + if (day % 2) ev('for(const c in S.pops)S.pops[c].bb&&(S.pops[c].bb.d*=1.3)'); + // And circuits over the busiest links, which take bandwidth from customers who had it. + ev(`for(const l of S.links.filter(l=>!linkDown(l)&&S.pops[l.a]&&S.pops[l.b]&&R.load[l.id]>1).sort((x,y)=>R.load[y.id]/capOf(y)-R.load[x.id]/capOf(x)).slice(${day},${day}+2)) + S.offers.push({id:'sq'+l.id,city:l.a,city2:l.b,name:'Squeeze',type:'l2vpn',bw:${day % 2 ? 300 : 2},rate:100,reqs:[],exp:S.day+30})`); + for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) { + const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`; + const before = ev('JSON.stringify(R.load)+R.served'); + ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n'); + assert.equal(ev('JSON.stringify(R.load)+R.served'), before, 'a trial leaves the live result alone'); + const slow = ev(`JSON.stringify(slowOffer(${o}))`); + assert.equal(fast, slow, `offer ${id} (${ev(`${o}.type`)}) on day ${day}`); + if (fast !== 'null') seen.yes++; else seen.no++; + if (n === 1) seen.skipped++; + if (n === 2) seen.third++; + } + ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()'); + } + assert.ok(seen.yes >= 3 && seen.no >= 3, `both answers come up (${JSON.stringify(seen)})`); + assert.ok(seen.skipped >= 5, `the second pass is often skipped (${JSON.stringify(seen)})`); + assert.ok(seen.third >= 3, `and run when the offer hurts someone (${JSON.stringify(seen)})`); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); + +test('with a scenic circuit the sales trial keeps both passes in their original order', () => { + const { ev, dom, errors } = load(); + try { + const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.biz.find(b=>BIZ_T[b.type].l2).route='scenic';compute();window.slowOffer=${ORIGINAL};`); + ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}'); + ev('__reseed(77);S.offers=[];for(let i=0;i<6;i++)spawnOffer();'); + for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) { + const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`; + ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n'); + assert.equal(fast, ev(`JSON.stringify(slowOffer(${o}))`), id); + assert.ok(n === 0 || n === 2, 'both passes, as before'); + } + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); From 92d276bdc50ca6e3df2b03e39616cc9acb2ec802 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:32:53 +0100 Subject: [PATCH 25/64] Network panel names the peer that really carries a cone-reached network --- src/game/80-simulation/30-compute.js | 5 +++-- src/game/93-ui/40-hud-and-panels.js | 2 +- tests/tier1-cone.test.js | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 9b35c84..0697cce 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -41,8 +41,9 @@ function compute(){ // dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last. for(const e of E){e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}} for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];if(okBy[n.id].some(e=>e.rank>0&&e.k!=='t')){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id]; - // Reached without transit only through the customers of networks you peer with (#85). - if(!okBy[n.id].some(e=>(e.k==='p'||e.k==='ix')&&!coneOf(e,n.id)))R2.cone[n.id]=1;}} + // Reached without transit only through the customers of networks you peer with (#85). R.cone[id]: the peer that + // carries it, the first PNI's network or else the nearest upstream that is a member of an exchange you are on. + if(!okBy[n.id].some(e=>(e.k==='p'||e.k==='ix')&&!coneOf(e,n.id))){let by=null;for(const e of okBy[n.id]){if(e.k==='p'){by=e.net;break;}if(!by&&e.k==='ix'&&e.dir)by=ANC[n.id].find(u=>e.dir.has(u))||null;}R2.cone[n.id]=by||1;}}} const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net)); const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1); // Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index). diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index b1e0470..90ccb82 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -80,7 +80,7 @@ function renderLeft(){checkLayer(); h+=`
${btn(tr('common.all_networks'),'netFilter',{f:'all'},!foc&&!out?'sm':'ghost sm')}${btn(tr('hud_and_panels.out_of_reach_without_transit_n',{n:lostN}),'netFilter',{f:'out'},out?'sm':'ghost sm')}
`; if(out&&!lostN)h+=`

${tr('hud_and_panels.nothing_every_network_is_reachable')}

`; for(const n of foc?[foc]:out?ntLost():NETS){if(n.tail&&!UI.tailOpen&&!foc&&!out)continue; - h+=`
${logo(n)}
${esc(n.name)} AS${n.asn}
${TYPE_L[n.type]} ${n.pol} · ${tr('hud_and_panels.p_of_traffic',{p:(NSH[n.id]*100).toFixed(1)})}${n.price?` · ${tr('hud_and_panels.transit_price_gbps',{price:(n.price*S.priceMul).toFixed(2)})}`:''}
${esc(n.blurb)}
${netWhere(n,where)}${(foc||out)&&!R.nt[n.id]?`

${esc(offTransitHint(n.id))}

`:''}${(foc||out)&&coneVia(n.id)&&(R.cone[n.id]||!R.nt[n.id])?`

${R.cone[n.id]?tr('hud_and_panels.reached_through_the_customer_cone_of',{net:esc(coneVia(n.id).name)}):tr('hud_and_panels.buys_transit_from_net_peer_with',{net:esc(coneVia(n.id).name)})}

`:''}${foc||out&&!R.nt[n.id]?meetLine(n,foc?24:4):''}
`;} + h+=`
${logo(n)}
${esc(n.name)} AS${n.asn}
${TYPE_L[n.type]} ${n.pol} · ${tr('hud_and_panels.p_of_traffic',{p:(NSH[n.id]*100).toFixed(1)})}${n.price?` · ${tr('hud_and_panels.transit_price_gbps',{price:(n.price*S.priceMul).toFixed(2)})}`:''}
${esc(n.blurb)}
${netWhere(n,where)}${(foc||out)&&!R.nt[n.id]?`

${esc(offTransitHint(n.id))}

`:''}${(foc||out)&&coneVia(n.id)&&(R.cone[n.id]||!R.nt[n.id])?`

${R.cone[n.id]?tr('hud_and_panels.reached_through_the_customer_cone_of',{net:esc((NET[R.cone[n.id]]||coneVia(n.id)).name)}):tr('hud_and_panels.buys_transit_from_net_peer_with',{net:esc(coneVia(n.id).name)})}

`:''}${foc||out&&!R.nt[n.id]?meetLine(n,foc?24:4):''}
`;} if(!foc&&!out)h+=`
${tr('hud_and_panels.the_long_tail')} ${tr('hud_and_panels.n_small_networks',{n:tl.length})}
${tr('hud_and_panels.p_of_traffic_between_them_scattered',{p:(tl.reduce((a,n)=>a+NSH[n.id],0)*100).toFixed(1),n:tlOn})}
${btn(UI.tailOpen?tr('common.hide'):tr('common.show'),'tailTog',{},'ghost sm')}
`; } if(h!==UI._lh){UI._lh=h;morph($('leftBody'),h);} diff --git a/tests/tier1-cone.test.js b/tests/tier1-cone.test.js index bc79518..0b14823 100644 --- a/tests/tier1-cone.test.js +++ b/tests/tier1-cone.test.js @@ -146,3 +146,21 @@ test('routing with cones costs about what it did: exits are asked once, cones ar assert.ok(t < plain * 2 + 20, `compute() with cones ${t.toFixed(1)} ms vs without ${plain.toFixed(1)} ms`); assert.deepEqual(errors, []); }); + +test('the panel names the peer that really carries a network, not the first Tier 1 it buys from', () => { + const { ev, dom, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50"); + // a long-tail network that buys from Cogentle first and Level Tree second; peer only with Level Tree + const t = ev("NETS.find(n=>n.tail&&n.up.length===2&&n.up[0]==='cog'&&n.up[1]==='lvl').id"); + ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pl',net:'lvl',city:'fra',tier:2}];compute()"); + assert.equal(ev(`R.cone.${t}`), 'lvl'); + ev(`UI.left='goals';UI.leftOpen=true;ACT.netFocus({id:'${t}'})`); + const txt = dom.window.document.getElementById('leftBody').textContent; + assert.match(txt, /Reached through the customer cone of Level Tree/); + assert.doesNotMatch(txt, /customer cone of Cogentle/); + // over an exchange: the member you have a session with + ev("S.pni=[];compute()"); + assert.equal(ev(`!!R.cone.${t}`), false); + assert.match(ev(`(ACT.netFocus({id:'${t}'}),document.getElementById('leftBody').textContent)`), /Buys transit from Cogentle/); + assert.deepEqual(errors, []); +}); From 6693d734e60bfd45e4e86a2439512aa2d1f1b245 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:32:53 +0100 Subject: [PATCH 26/64] Traceroute shows every network down a customer cone, one hand-off per step --- src/game/60-features/50-traceroute.js | 8 ++++++-- tests/tier1-cone.test.js | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/game/60-features/50-traceroute.js b/src/game/60-features/50-traceroute.js index 250e9b5..8f4618a 100644 --- a/src/game/60-features/50-traceroute.js +++ b/src/game/60-features/50-traceroute.js @@ -10,9 +10,12 @@ function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev for(const x of S.caches)if(x.net===net&&popUp(x.city)&&!siteDown(x.city,'a'))out.push({k:'c',rank:0,city:x.city,pref:'normal',lab:tr('common.name_cache',{name:NET[net].cache.name}),used:R.useCache[x.id]||0,cap:CACHE_CAP}); // A peer's customer cone (#85): one AS hop more, so tried after direct peering and before transit, as in compute(). for(const p of S.pni)if(CONE_S[p.net].has(net)&&pniOn(p)&&popUp(p.city)&&liveN(p.city,p.site,p.n))out.push({k:'p',rank:p.net===net?1:CONE_RANK,via:p.net===net?null:p.net,city:p.city,pref:p.pref||'normal',lab:tr('common.pni_with_net',{net:NET[p.net].name}),used:R.usePni[p.id]||0,cap:liveCap(pniG(p),p.city,p.site,p.n)}); - for(const c in S.ixp){const ses=ixSessions(c),via=ses.has(net)?null:[...ses].find(id=>CONE_S[id].has(net));if((ses.has(net)||via)&&(popUp(ixCity(c))||remoteCities().includes(ixCity(c)))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:via?CONE_RANK:2,via,city:ixCity(c),id:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:tr('common.ix_peering',{ix:ixName(c)}),used:R.useIx[c]||0,cap:ixCap(c)});} + for(const c in S.ixp){const ses=ixSessions(c),via=ses.has(net)?null:ANC[net].find(u=>ses.has(u))||null;if((ses.has(net)||via)&&(popUp(ixCity(c))||remoteCities().includes(ixCity(c)))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:via?CONE_RANK:2,via,city:ixCity(c),id:c,pref:(S.ixPref&&S.ixPref[c])||'normal',lab:tr('common.ix_peering',{ix:ixName(c)}),used:R.useIx[c]||0,cap:ixCap(c)});} for(const t of S.transit)if(popUp(t.city)&&!(t.down>day)&&liveN(t.city,t.site,t.n)&&net!==leak&&!((ev.depeer>day||scnRule('spat'))&&t.net==='cog'&&net==='ggl'))out.push({k:'t',rank:3,city:t.city,pref:t.pref||'normal',lab:tr('traceroute.name_transit',{name:NET[t.net].name}),tnet:t.net,used:R.useT[t.id]||0,cap:liveCap(PORT[t.tier].g,t.city,t.site,t.n)}); return out;} +// coneChain(peer,net): [peer, …, net], the shortest walk down customer links (the network's up lists, read backwards). +function coneChain(top,id){const prev={[id]:null},q=[id];while(q.length){const x=q.shift();if(x===top)break;for(const u of NET[x].up||[])if(NET[u]&&!(u in prev)){prev[u]=x;q.push(u);}} + if(!(top in prev))return [top,id];const out=[];for(let x=top;x!==null;x=prev[x])out.push(x);return out;} function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1; const hop=(host,addr,extra,note)=>{rtt+=extra;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);}; hop(`lo0.cr1.${src}.${me}`,ip(hstr(src),1),0,tr('traceroute.city_your_router',{city:CITY[src].name})); @@ -30,7 +33,8 @@ function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[] hop(`${slug(N.name)}-peer.${far}.${slug(T.name)}.net`,`198.51.100.${hstr(N.id)%250}`,0.4,tr('traceroute.net_hands_it_to_to',{net:T.name,to:N.name}));}} else if(e.k==='ix'){hop(`${slug(ixName(e.city))}.peering.${e.city}`,`185.0.${hstr(e.city)%250}.${hstr(N.id)%250}`,0.3,tr('traceroute.across_the_ix_switch',{ix:ixName(e.city)}));} else if(e.k==='p'){hop(`pni-${slug(NET[e.via||N.id].name)}.${e.city}.${me}`,ip(hstr(N.id),3),0.2,tr('traceroute.private_cross_connect'));} - if(e.via){const V=NET[e.via];asPath.push(V.asn);hop(`${slug(N.name)}-cust.${e.city}.${slug(V.name)}.net`,`198.51.100.${(hstr(V.id)+3)%250}`,1.2,tr('traceroute.net_hands_it_to_its_customer',{net:V.name,to:N.name}));} + // Down the cone one customer at a time: the shortest chain of upstreams from the peer to the network, each AS on the path. + if(e.via){const ch=coneChain(e.via,N.id);for(let i=0;i { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50"); + // Doodoo buys from Hocus Pocus, which buys from Not That Telecom; a PNI with Not That Telecom only + ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pn',net:'ntt',city:'fra',tier:2}];compute()"); + const tr = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'ddo'}))")); + assert.deepEqual(tr.asPath, [ev('S.asn'), ev('NET.ntt.asn'), ev('NET.voc.asn'), ev('NET.ddo.asn')]); + assert.match(tr.text, /Not That Telecom hands it to its customer Hocus Pocus/); + assert.match(tr.text, /Hocus Pocus hands it to its customer Doodoo/); + assert.equal(ev("coneChain('ntt','ddo').join()"), 'ntt,voc,ddo'); + assert.equal(ev("R.cone.ddo"), 'ntt'); + assert.deepEqual(errors, []); +}); From cc898ea282278383e6669d98644cae4da88d9367 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:34:00 +0100 Subject: [PATCH 27/64] Badge variants are looked up as own keys, never through the prototype --- src/game/60-features/60-share-card.js | 2 +- src/game/80-simulation/50-sanitize.js | 2 +- src/game/88-days/20-badges.js | 4 ++-- tests/badges-variants.test.js | 14 ++++++++++++++ 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/game/60-features/60-share-card.js b/src/game/60-features/60-share-card.js index d545a29..9f01726 100644 --- a/src/game/60-features/60-share-card.js +++ b/src/game/60-features/60-share-card.js @@ -20,7 +20,7 @@ function shareCanvas(){const Wc=1200,Hc=630,cv=document.createElement('canvas'); if(S.scn)rows.unshift([scnName(),S.scn.done?(S.scn.id==='weekly'?tr('share_card.score_v',{v:fmtG(S.scn.score||S.stats.peak||0)}):tr('features.done_in_d_days',{d:S.scn.done})):S.scn.failed?tr('share_card.not_this_time'):tr('common.in_progress')]); let y=150;for(const [k,v] of rows.slice(0,9)){g.fillStyle='#fff';g.strokeStyle='#1E2640';g.lineWidth=3;g.beginPath();g.roundRect?g.roundRect(770,y,390,42,12):g.rect(770,y,390,42);g.fill();g.stroke();g.fillStyle='#5A6280';g.font='800 18px Nunito, sans-serif';g.fillText(k,786,y+11);g.fillStyle='#1E2640';g.font='900 22px Nunito, sans-serif';const tw=g.measureText(v).width;g.fillText(v,1146-tw,y+9);y+=48;} // Badge variants show as a ring: frosted for Change Freeze, fiery for BGP at 3 a.m. - top.forEach((b,i)=>{const v=S.achP&&S.achP[b.id];if(v&&v!=='oncall'&&BVAR[v]){g.strokeStyle=BVAR[v].col;g.lineWidth=4;g.beginPath();g.arc(60+i*48,537,22,0,7);g.stroke();}}); + top.forEach((b,i)=>{const v=S.achP&&S.achP[b.id];if(v&&v!=='oncall'&&own(BVAR,v)){g.strokeStyle=BVAR[v].col;g.lineWidth=4;g.beginPath();g.arc(60+i*48,537,22,0,7);g.stroke();}}); g.font='34px sans-serif';top.forEach((b,i)=>g.fillText(b.i,40+i*48,520)); {const n=v=>got.filter(b=>(S.achP&&S.achP[b.id]||'oncall')===v).length,f=n('freeze'),h=n('bgp');if(f||h){g.fillStyle='#1E2640';g.font='800 18px Nunito, sans-serif';g.fillText([h?`🔥 ${h}`:'',f?`🧊 ${f}`:''].filter(Boolean).join(' '),40+Math.max(1,top.length)*48+8,526);}} g.fillStyle='#1E2640';g.font='900 30px "Baloo 2", sans-serif';g.fillText('seriesoftub.es',40,572);g.font='700 20px Nunito, sans-serif';g.fillText(tr('share_card.build_the_internet_one_tube_at'),300,580); diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 5673200..b6f3bf3 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -75,7 +75,7 @@ function sanitize(s){ s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews; // Badges: S.ach[id] is the day it was earned (any save); S.achP[id] the variant (2.0). A missing variant is the standard one. for(const k of Object.keys(s.ach))s.ach[k]=num(s.ach[k],0); - {const p=s.achP&&typeof s.achP==='object'&&!Array.isArray(s.achP)?s.achP:{};s.achP={};for(const k of Object.keys(s.ach))s.achP[k]=BVAR[p[k]]?p[k]:'oncall';} + {const p=s.achP&&typeof s.achP==='object'&&!Array.isArray(s.achP)?s.achP:{};s.achP={};for(const k of Object.keys(s.ach))s.achP[k]=typeof p[k]==='string'&&own(BVAR,p[k])?p[k]:'oncall';} if(s.merged){const o={};if(typeof s.merged==='object')for(const m of MERGERS)if(isFinite(s.merged[m.id]))o[m.id]=+s.merged[m.id];s.merged=Object.keys(o).length?o:undefined;} // The rules (2.0): a save without them is the classic game, On-call (or a sandbox or puzzle, if it was one). Locked after the start. {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{},p=s.mode==='sandbox'?'sandbox':s.mode==='puzzle'?'puzzle':own(PRESETS,r.preset)?r.preset:'oncall';s.rules=makeRules(p,own(PRESETS,r.preset)?r:{});} diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 39cd21a..10ca87b 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -74,10 +74,10 @@ const BADGES=[ fiery one; Sandbox and the puzzles earn none (puzzles have stars). Earning a badge again under a harder preset upgrades its look, here and in the hall of fame. S.ach[id] stays the day it was earned; S.achP[id] is its variant. */ const BVAR={freeze:{k:'freeze',lv:1,i:'🧊',n:N_('badges.variant_freeze_dried'),col:'#5BC0EB'},oncall:{k:'oncall',lv:2,i:'⭐',n:N_('badges.variant_on_call'),col:'#FFD23F'},bgp:{k:'bgp',lv:3,i:'🔥',n:N_('badges.variant_forged_at_3_a_m'),col:'#FF5A1F'}}; -const BVAR_IDS=['freeze','oncall','bgp'],bvar=k=>BVAR[k]||BVAR.oncall; +const BVAR_IDS=['freeze','oncall','bgp'],bvar=k=>own(BVAR,k)?BVAR[k]:BVAR.oncall; // The preset this save plays under ('oncall' for every save from before rulesets), and the variant it earns (null: none). const rulePre=()=>(typeof rulePreset==='function'?rulePreset():(S&&S.rules&&S.rules.preset))||'oncall'; -function badgeVar(){if(!S||S.mode==='sandbox')return null;const p=rulePre();return p==='sandbox'||p==='puzzle'?null:BVAR[p]?p:'oncall';} +function badgeVar(){if(!S||S.mode==='sandbox')return null;const p=rulePre();return p==='sandbox'||p==='puzzle'?null:own(BVAR,p)?p:'oncall';} // The hall of fame is this device's localStorage, so it is checked like a save: unknown variants count as standard. function hof(){let h;try{h=JSON.parse(localStorage.getItem('sot-badges')||'{}');}catch(e){h=null;}if(!h||typeof h!=='object'||Array.isArray(h))return {}; for(const k of Object.keys(h)){const x=h[k];if(!x||typeof x!=='object'){delete h[k];continue;}const vs=x.vs&&typeof x.vs==='object'&&!Array.isArray(x.vs)?x.vs:{}; diff --git a/tests/badges-variants.test.js b/tests/badges-variants.test.js index 648aaed..5784f09 100644 --- a/tests/badges-variants.test.js +++ b/tests/badges-variants.test.js @@ -135,3 +135,17 @@ test('the share card rings the variant badges', () => { assert.ok(fiery > plain, `the ring and the tally are drawn (${fiery} > ${plain} calls)`); assert.deepEqual(errors, []); }); + +test('a variant named after an Object prototype key is not a variant', () => { + const { ev, errors } = load(); + start(ev); + for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) { + ev(`const o=JSON.parse(JSON.stringify(S));o.ach={hello:3};o.achP={hello:${JSON.stringify(k)}};S=migrate(o)`); + assert.equal(ev('S.achP.hello'), 'oncall', k); + assert.equal(ev(`bvar(${JSON.stringify(k)}).k`), 'oncall', `bvar(${k})`); + ev(`S.rules={preset:${JSON.stringify(k)}}`); + assert.equal(ev('badgeVar()'), 'oncall', `badgeVar() under preset ${k}`); + } + ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()"); + assert.deepEqual(errors, []); +}); From db429b1d74929ffaadc35f4be35f4baee523fed7 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:34:41 +0100 Subject: [PATCH 28/64] Badge upgraded toast follows the collection on this device --- CHANGELOG.md | 2 +- src/game/88-days/20-badges.js | 5 +++-- tests/badges-variants.test.js | 20 ++++++++++++++++++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f13ceb4..933f0bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ All notable changes to this project are documented here. The project follows - Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. - Puzzles: small, calm network builds you can finish in a coffee break (#190). Connect a few cities on the real map with POPs and leased waves, with no clock, no bills and nothing breaking, and earn up to three stars: one for the goal, one for staying under budget, and one if the network survives any single cut. Eighteen puzzles in four packs (more stars open the next pack), some with a twist like a latency target, no subsea cables or a ring, plus a weekly puzzle that is the same for everyone, with a streak and a result to share. Puzzles never touch your saved network; only your stars are kept. - Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won. -- Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge again under harder rules upgrades its look, and the badge list counts your collection of each kind on this device. On-call games earn the standard badges; Sandbox and puzzles earn none. +- Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge under harder rules than before upgrades it in your collection on this device, and the badge list counts how many of each kind you have. On-call games earn the standard badges; Sandbox and puzzles earn none. - China Telecomet now sells its CN-Too premium crossing in Moscow too, at the same price as in Hong Kong (#195). Haul your European traffic to Moscow and it reaches China with about 3% loss; nothing else of theirs is on offer there. - Series of Tubes now speaks German. The game follows your browser's language the first time, and you can switch to German under Settings or on the title screen. Networking terms like Peering and Transit stay in English, the way network engineers say them. - Glowball Sakura Lager joins the map: a Tier 2 carrier in the big hubs of the US, Europe and Asia-Pacific that sells transit, takes PNIs and peers openly wherever it is. It is not a Tier 1, so it buys its own transit from three of them, while 13 smaller networks in its regions buy theirs from it, and one PNI with it reaches about 3% of all traffic. Far from home, in Asia and New Zealand, it charges more than the locals, and it sells no transit in Australia. diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 10ca87b..0de9fa4 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -87,8 +87,9 @@ function hof(){let h;try{h=JSON.parse(localStorage.getItem('sot-badges')||'{}'); function checkBadges(){S.ach=S.ach||{};S.achP=S.achP||{};const v=badgeVar();if(!v)return;let h=null;const V=BVAR[v]; for(const b of BADGES){const had=S.ach[b.id]!==undefined;if(had&&bvar(S.achP[b.id]).lv>=V.lv)continue;let ok=false;try{ok=b.ok();}catch(e){} if(!ok)continue;if(!had)S.ach[b.id]=S.day;S.achP[b.id]=v;const R0=RARITY[b.r]; - if(!h)h=hof();const today=new Date().toISOString().slice(0,10),x=h[b.id]||(h[b.id]={d:today,n:S.name,vs:{}});if(x.vs[v]===undefined)x.vs[v]=today;if(bvar(x.v).lv${b.i} ${had?tr('badges.badge_upgraded_name',{name:esc(b.t)}):tr('badges.badge_unlocked_name',{name:esc(b.t)})}
${R0.n}${v==='oncall'?'':` · ${V.i} ${tr(V.n)}`} · ${esc(b.d)}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');track('badge_'+b.id+(v==='oncall'?'':'_'+v));} + // "Upgraded" is about this device's collection: the hall of fame already held the badge, only in a lower variant. + if(!h)h=hof();const today=new Date().toISOString().slice(0,10),up=!!h[b.id]&&bvar(h[b.id].v).lv${b.i} ${up?tr('badges.badge_upgraded_name',{name:esc(b.t)}):tr('badges.badge_unlocked_name',{name:esc(b.t)})}
${R0.n}${v==='oncall'?'':` · ${V.i} ${tr(V.n)}`} · ${esc(b.d)}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');track('badge_'+b.id+(v==='oncall'?'':'_'+v));} if(h)try{localStorage.setItem('sot-badges',JSON.stringify(h));}catch(e){}} // How many badges this device has ever earned in each variant: the collection. function badgeShelf(h){const o={freeze:0,oncall:0,bgp:0};for(const b of BADGES){const x=h[b.id];if(x)for(const v of BVAR_IDS)if(x.vs[v]!==undefined)o[v]++;}return o;} diff --git a/tests/badges-variants.test.js b/tests/badges-variants.test.js index 5784f09..9f1b6a2 100644 --- a/tests/badges-variants.test.js +++ b/tests/badges-variants.test.js @@ -149,3 +149,23 @@ test('a variant named after an Object prototype key is not a variant', () => { ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()"); assert.deepEqual(errors, []); }); + +test('"Badge upgraded" means the collection on this device got a better variant', () => { + const { ev, errors } = load(); + const spy = () => ev("window.__t=[];if(!window.__sp){window.__sp=1;const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);};}"); + // a new game, but this device already holds the frosted badge: the standard one upgrades it + start(ev, 'oncall'); + ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{freeze:'2026-01-01'}}}))"); + spy(); earnHello(ev); + assert.match(ev("window.__t.join(' ')"), /Badge upgraded/); + assert.equal(hof(ev).hello.v, 'oncall'); + // another new game, the device already holds the fiery one: earning the frosted one is a plain unlock + start(ev, 'freeze'); + ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{bgp:'2026-01-01'}}}))"); + spy(); earnHello(ev); + const t = ev("window.__t.join(' ')"); + assert.match(t, /Badge unlocked/); + assert.doesNotMatch(t, /Badge upgraded/); + assert.equal(hof(ev).hello.v, 'bgp', 'the best variant stays on the shelf'); + assert.deepEqual(errors, []); +}); From 9279908f7d82d9363b0191c830dfc14862baa4ce Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:35:27 +0100 Subject: [PATCH 29/64] Say which Australians sit in a Tier 1 cone, and test exactly those --- src/game/30-networks/40-traffic-shares.js | 4 +++- tests/tier1-cone.test.js | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/game/30-networks/40-traffic-shares.js b/src/game/30-networks/40-traffic-shares.js index 67a0c3b..8883887 100644 --- a/src/game/30-networks/40-traffic-shares.js +++ b/src/game/30-networks/40-traffic-shares.js @@ -8,7 +8,9 @@ const NET=Object.fromEntries(NETS.map(n=>[n.id,n])),NET_IDS=NETS.map(n=>n.id); PLDTea Time (Not That, Ta-Ta), TIM-Tam (its sibling Sparkly Seabone), Floptus (its parent SingTell), Sky-High and Tele-Nor-Way (Tell-Ya, Level Tree), Virgin Mediocre (Level Tree, Not That), and the long tail (tailUp()). The rest stay islands because they are too: the content giants, the transit-free incumbents (Doitsche, Comecast, Jio-graphy, Bee-Tee), - China and Korea, and Australians, who buy only from Australian carriers. */ + China and Korea, and Australia's big ISPs, which buy only from Australian carriers. Smaller Australians do sit in Tier 1 + cones: Kangaroo Courier buys from Cogentle, Doodoo and Spin2wintel from Hocus Pocus (Not That, Tell-Ya), Lintel from + Speedyloop (Tell-Ya). */ const CONE={},CONE_S={},DOWN={}; {const dn={};for(const n of NETS)for(const u of n.up||[])(dn[u]||(dn[u]=[])).push(n.id); for(const n of NETS){const s=new Set([n.id]),q=[n.id];while(q.length){for(const y of dn[q.pop()]||[])if(!s.has(y)){s.add(y);q.push(y);}} diff --git a/tests/tier1-cone.test.js b/tests/tier1-cone.test.js index 5d00376..00f5de8 100644 --- a/tests/tier1-cone.test.js +++ b/tests/tier1-cone.test.js @@ -23,8 +23,12 @@ test('cones are built once at load and hold customers of customers', () => { assert.equal(ev("NETS.filter(n=>n.tail).every(n=>ANC[n.id].some(u=>NET[u].type==='t1'))"), true, 'from a Tier 1, directly or through a carrier'); assert.equal(ev("NET.tail45.up.join()"), 'mag', 'Auckland has no Tier 1: Hobbit Hole buys from a carrier that is there'); assert.equal(ev("NETS.filter(n=>n.tail).map(n=>n.up.join('+')).join()"), ev("NETS.filter(n=>n.tail).map(n=>tailUp(n.name,n.pops).join('+')).join()"), 'stable: picked by name'); - // Australians buy only from Australian carriers, so a Tier 1 PNI is still no back door into Australia. - assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false); + // Australia's big ISPs buy only from Australian carriers, so a Tier 1 PNI is no back door to them. + assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg','inp'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false); + // The smaller ones that buy from a Tier 1 or a carrier of one do come along, and these are exactly the ones. + const au = "NETS.filter(n=>n.type==='eye'&&n.pops.length&&n.pops.every(c=>CITY[c].au)&&t1Need().some(t=>CONE_S[t.id].has(n.id))).map(n=>n.id).sort().join()"; + assert.equal(ev(au), 'ddo,ext,spn,tail44', 'Doodoo, Lintel, Spin2wintel, Kangaroo Courier'); + assert.equal(ev("[NET.tail44.name,NET.tail44.up.join(),NET.ddo.up.join(),NET.spn.up.join(),NET.ext.up.join(),NET.voc.up.join(),NET.spl.up.join()].join('|')"), 'Kangaroo Courier|cog|voc|voc|spl|ntt,tly|tly'); assert.deepEqual(errors, []); }); From 19a9c60fd5365671d470fe0459df7a83806ee111 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:35:29 +0100 Subject: [PATCH 30/64] Puzzles: a cable fails as a whole in the N-1 check Two waves on the same cable now share one failure, as in the main game's diversity checks. Kiwi Fruit Salad gets Los Angeles as a stepping stone (Seattle's only cable south is Hawaiki), Samba Sprint's budget rises to $1.06M, and the weekly reference ring never puts two hops on one cable. --- src/game/60-features/90-puzzles-data.js | 4 ++-- src/game/60-features/92-puzzles.js | 18 +++++++++------- src/game/95-modals/95-puzzles.js | 3 ++- tests/puzzles.test.js | 28 +++++++++++++++++-------- 4 files changed, 34 insertions(+), 19 deletions(-) diff --git a/src/game/60-features/90-puzzles-data.js b/src/game/60-features/90-puzzles-data.js index 1d7ede6..681d391 100644 --- a/src/game/60-features/90-puzzles-data.js +++ b/src/game/60-features/90-puzzles-data.js @@ -18,12 +18,12 @@ const PZ=[ {id:'aloha',pack:'fire',n:tr('puzzles.aloha_latency'),j:tr('puzzles.honolulu_the_world_s_most_scenic'),cities:['sjc','hnl','syd'],budget:1750000}, {id:'rimshot',pack:'fire',n:tr('puzzles.pacific_rim_shot'),j:tr('puzzles.seattle_to_singapore_with_a_stop'),cities:['sea','tok','hkg','sin'],budget:1200000}, {id:'fire',pack:'fire',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),cities:['tok','hkg','sin','syd'],ring:true,budget:1600000}, - {id:'kiwi',pack:'fire',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),cities:['akl','syd','sea'],via:['hnl','suv'],budget:1400000}, + {id:'kiwi',pack:'fire',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),cities:['akl','syd','sea'],via:['hnl','suv','lax'],budget:1400000}, {id:'guam',pack:'fire',n:tr('puzzles.guam_slam'),j:tr('puzzles.a_tiny_island_where_half_the'),cities:['tok','mnl','syd'],via:['gum'],budget:1600000}, {id:'flash',pack:'speed',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),cities:['nyc','lon'],lat:['nyc','lon',27],budget:450000}, {id:'pingpong',pack:'speed',n:tr('puzzles.ping_pong_to_tokyo'),j:tr('puzzles.the_pacific_is_big_light_is'),cities:['lax','tok'],via:['sea','sjc'],lat:['lax','tok',47],budget:850000}, {id:'suez',pack:'speed',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),cities:['fra','sin'],via:['mrs','bom'],lat:['fra','sin',68],budget:1000000}, - {id:'samba',pack:'speed',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),cities:['sao','mia'],via:['for','rio'],lat:['sao','mia',45],budget:950000}, + {id:'samba',pack:'speed',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),cities:['sao','mia'],via:['for','rio'],lat:['sao','mia',45],budget:1060000}, {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),cities:['lis','mad','par','mil'],via:['bcn','mrs'],noSub:true,budget:210000}, {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),cities:['nyc','lon','dub'],budget:380000}, {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),cities:['ams','ber','muc','zrh'],via:['ham','dus'],avoid:['fra'],budget:200000}, diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index b0ca38e..7ae3d2b 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -31,8 +31,9 @@ const pzLinkCost=(r,tier,div)=>pzMo(r,tier,div)*PZ_YEAR;// leased waves have no const pzPopCost=c=>popCost(c)+PZ_YEAR*POP_MO; const PZ_TIERS=[0,1,2]; function pzSpend(){let s=0;for(const c in S.pops)s+=pzPopCost(c);for(const l of S.links)s+=l.mo*PZ_YEAR;return s;} -// What one backhoe or one anchor takes out: waves in the same trench, or on the same cable between the same cities. -const pzUnit=l=>l.cable?'cab:'+l.cable+':'+edgeKey(l):String(l.trench||l.id); +// What one backhoe or one anchor takes out: waves in the same trench, or every wave on the same cable (a cable fails +// as a whole, as in the main game's diversity checks). +const pzUnit=l=>l.cable?'cab:'+l.cable:String(l.trench||l.id); // ---------- checks ---------- function pzComp(ls,skip,from){const adj={};for(const l of ls){if(skip&&pzUnit(l)===skip)continue;(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);} const seen=new Set([from]),q=[from];while(q.length){const u=q.pop();for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return seen;} @@ -51,7 +52,7 @@ function pzEval(){const P=S.pz,ls=S.links,cs=P.cities,spend=pzSpend(); if(P.minG)tw.push({k:'g',ok:ls.every(l=>LT[l.tier].g>=P.minG)}); if(P.avoid.length)tw.push({k:'avoid',ok:P.avoid.every(c=>!S.pops[c])}); const goal=conn&&tw.every(t=>t.ok),units=[...new Set(ls.map(pzUnit))]; - // N-1: the goal cities stay joined whichever single trench or cable segment is cut. + // N-1: the goal cities stay joined whichever single trench or cable is cut. const weak=conn?units.filter(u=>{const g=pzComp(ls,u,cs[0]);return !cs.every(c=>g.has(c));}):[]; const n1=conn&&units.length>0&&!weak.length,cheap=!P.budget||spend<=P.budget; return {marks,conn,tw,goal,spend,cheap,n1,weak,stars:goal?1+(cheap?1:0)+(n1?1:0):0};} @@ -61,11 +62,14 @@ function pzPrevKey(key){const m=/^(\d{4})-W(\d{2})$/.exec(key);if(!m)return null function pzWeekly(dt){const key=pzWeekKey(dt||new Date());let r=hstr('puzzle|'+key)||1;const nx=()=>{r=(Math.imul(r,1103515245)+12345)>>>0;return r/4294967296;}; const pool=PZ_WEEK_POOLS[Math.floor(nx()*PZ_WEEK_POOLS.length)].slice(),n=4+Math.floor(nx()*2),cities=[]; while(cities.lengthkmBetween(u,a)-kmBetween(u,b));ring.push(left.shift());} - let cost=cities.reduce((a,c)=>a+pzPopCost(c),0);for(let i=0;ipzLinkCost(x,0,false))); - return {id:'weekly',key,cities,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring};} + let cost=cities.reduce((a,c)=>a+pzPopCost(c),0);const used=new Set(),via=[]; + for(let i=0;i!x.cab||!used.has(x.cab)).sort((x,y)=>pzLinkCost(x,0,false)-pzLinkCost(y,0,false))[0]; + if(r.cab)used.add(r.cab);via.push(r.via);cost+=pzLinkCost(r,0,false);} + return {id:'weekly',key,cities,via:[],budget:Math.ceil(cost*1.1/10000)*10000,ref:ring,refVia:via};} function pzStreak(p,key){const st=p.streak;if(st.last===key)return;st.n=st.last&&st.last===pzPrevKey(key)?st.n+1:1;st.last=key;st.best=Math.max(st.best,st.n);} function pzShareText(e){const P=S.pz;return tr('puzzles.share_line',{what:P.id==='weekly'?P.key:pzName(pzDef(P.id)),stars:pzStarStr(e.stars),spend:fmt$(e.spend)});} // ---------- entering and leaving ---------- diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index 1ae57a6..d510721 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -8,7 +8,8 @@ function pzTwistTxt(t){const P=S.pz; const [a,b,ms]=P.lat;return isFinite(t.ms)?tr('puzzles.a_to_b_under_ms_now',{a:CITY[a].name,b:CITY[b].name,ms,now:t.ms.toFixed(1)}):tr('puzzles.a_to_b_under_ms',{a:CITY[a].name,b:CITY[b].name,ms});} // The short version, for the puzzle list. function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} -const pzUnitName=u=>{const l=S.links.find(x=>pzUnit(x)===u);return l?`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`:'';}; +// A cable carrying several of your waves is named on its own: cutting it takes them all. +const pzUnitName=u=>{const ls=S.links.filter(x=>pzUnit(x)===u),l=ls[0];return !l?'':l.cable&&ls.length>1?esc(CAB[l.cable].name):`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`;}; function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false; const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack); const star=(on,l)=>`⭐${l}`; diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index b7c4d6e..6b5c0d7 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -14,12 +14,13 @@ const REF = { aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['sjc', 'hnl', 'scx'], ['sjc', 'hnl', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] }, rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['tok', 'hkg', 'adc'], ['tok', 'hkg', 'apg'], ['hkg', 'sin', 'sjc2'], ['hkg', 'sin', 'land']] }, fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] }, - kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'sea', 'hwk'], ['sea', 'hnl', 'hwk'], ['hnl', 'akl', 'hwk'], ['akl', 'syd', 'tasman'], ['akl', 'syd', 'scx']] }, - guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']] }, + // Hawaiki is Seattle's only cable south, so the second way out runs overland to LA and on via Suva. + kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'syd', 'tasman'], ['akl', 'sea', 'hwk'], ['syd', 'suv', 'scxn'], ['sea', 'lax', 'land'], ['lax', 'suv', 'scxn']] }, + guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['tok', 'mnl', 'jup'], ['tok', 'syd', 'sushi'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam']] }, flash: { one: [['nyc', 'lon', 'hibx']], three: [['nyc', 'lon', 'hibx'], ['nyc', 'lon', 'grace']] }, pingpong: { one: [['lax', 'tok', 'jup']], three: [['lax', 'tok', 'jup'], ['lax', 'sea', 'land'], ['sea', 'tok', 'fast']] }, suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['mrs', 'bom', 'twoaf'], ['bom', 'sin', 'land']] }, - samba: { one: [['sao', 'mia', 'monet']], three: [['sao', 'mia', 'monet'], ['sao', 'for', 'land'], ['for', 'mia', 'monet']] }, + samba: { one: [['sao', 'mia', 'monet']], three: [['sao', 'for', 'land'], ['sao', 'for', 'land'], ['for', 'mia', 'monet'], ['for', 'mia', 'sam1']] }, sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land'], ['mil', 'lis', 'land']] }, braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix'], ['dub', 'nyc', 'havf']] }, nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land'], ['zrh', 'ams', 'land']] }, @@ -77,6 +78,15 @@ test('stars: goal, budget, N-1 and twists each count', () => { build(ev, REF.shining.one); ev("ACT.pzLinkTo({a:'nyc',b:'chi'});ACT.pzVia({v:'land'});ACT.pzDiv({v:0});ACT.pzLink({tier:0})"); assert.equal(ev("new Set(S.links.filter(l=>edgeKey(l)==='chi|nyc').map(pzUnit)).size"), 1, 'same trench shares the cut'); + // A cable fails as a whole: two waves on one cable, even between different cities, are one cut. + ev("pzBegin(pzDef('guam'))"); + build(ev, [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']]); + e = evalP(ev); + assert.ok(e.goal && !e.n1, 'both of Sydney\'s links ride the Guam cable: one anchor splits Sydney off'); + assert.equal(ev("new Set(S.links.filter(l=>l.cable==='guam').map(pzUnit)).size"), 1, 'one cable, one failure unit'); + assert.ok(ev("document.getElementById('pzBox').textContent").includes('One cut splits it: ' + ev('CAB.guam.name')), 'the weak spot names the cable'); + ev("ACT.pzRmLink({id:S.links[3].id})");build(ev, [['tok', 'syd', 'sushi']]); + assert.equal(evalP(ev).stars, 3, 'a second cable into Sydney fixes it'); // Twists: no subsea, ring, latency, minimum size, cities to avoid. ev("pzBegin(pzDef('sharks'))");build(ev, REF.sharks.one); assert.ok(evalP(ev).goal); @@ -180,16 +190,16 @@ test('weekly puzzle: stable seed per ISO week, solvable, share string and streak assert.equal(w.key, '2026-W44'); assert.ok(w.cities.length >= 4 && w.cities.length <= 5 && w.budget > 0); // Every week of a few years can be solved with three stars by its own reference ring. - for (let i = 0; i < 160; i += 7) { + for (let i = 0; i < 400; i += 7) { ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`); - const ring = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')).ref)')); - const links = ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; }); - build(ev, links); + const w = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')))')); + const cabs = w.refVia.filter((v) => v !== 'land'); + assert.equal(new Set(cabs).size, cabs.length, `week +${i}: no two hops of the reference ring share a cable`); + build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]])); assert.equal(evalP(ev).stars, 3, `week +${i}`); } ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))"); - const ring = w.ref; - build(ev, ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; })); + build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]])); assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle 2026-W44 ⭐⭐⭐ \$\d+k · seriesoftub\.es$/); assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).streak.n"), 1); // A streak counts weeks in a row; a gap starts again. From 843811956b94917d01031da8e09d81256b623f0b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:36:12 +0100 Subject: [PATCH 31/64] Puzzles: a POP in a thin market counts its higher monthly rent The puzzle price and the city panel now use the city's own monthly POP rent (Suva is 1.5x), not the plain one, matching the higher setup already charged. --- src/game/60-features/92-puzzles.js | 2 +- src/game/95-modals/95-puzzles.js | 2 +- tests/puzzles.test.js | 11 +++++++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index 7ae3d2b..3fa9fa5 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -28,7 +28,7 @@ function pzRoutes(a,b){const out=[],sub=isSub(a,b); return out;} const pzMo=(r,tier,div)=>Math.round(waveMo(r.km,r.sub,tier)*r.f*(div?DIVERSE:1)); const pzLinkCost=(r,tier,div)=>pzMo(r,tier,div)*PZ_YEAR;// leased waves have no setup fee: a year of rent -const pzPopCost=c=>popCost(c)+PZ_YEAR*POP_MO; +const pzPopCost=c=>popCost(c)+PZ_YEAR*popMo(c);// thin markets cost more every month too (#94) const PZ_TIERS=[0,1,2]; function pzSpend(){let s=0;for(const c in S.pops)s+=pzPopCost(c);for(const l of S.links)s+=l.mo*PZ_YEAR;return s;} // What one backhoe or one anchor takes out: waves in the same trench, or every wave on the same cable (a cable fails diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index d510721..3f67961 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -29,7 +29,7 @@ function pzPanel(sel){const head=(eb,name,facts)=>`
${tr('common.your_pop')}`:'')+'
'; if(k==='avoid')return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

`; - if(!p)h+=`

${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(POP_MO)})}

${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}
`; + if(!p)h+=`

${tr('puzzles.a_pop_costs_setup_plus_a_year',{setup:fmt$(popCost(c)),mo:fmt$(popMo(c))})}

${btn(tr('puzzles.open_a_pop_cost',{cost:fmt$(pzPopCost(c))}),'pzPop',{city:c},'pink big')}
`; else{const others=[...S.pz.cities,...S.pz.via].filter(x=>x!==c); h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

${tr('puzzles.lease_a_wave_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}
`; const ls=S.links.filter(l=>l.a===c||l.b===c);if(ls.length)h+=`

${tr('common.links')}

`+ls.map(l=>`
${esc(CITY[l.a===c?l.b:l.a].name)}
${capName(l)} · ${linkLat(l).toFixed(1)} ms
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`).join(''); diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 6b5c0d7..402815f 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -263,3 +263,14 @@ test('puzzles in every language', () => { assert.deepEqual(errors, [], lang); } }); + +test('a POP in a thin market costs its higher monthly rent too, and the panel says so', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('kiwi'))"); + assert.ok(ev('colo("suv")') > 1, 'Suva is a thin market'); + assert.equal(ev("pzPopCost('suv')"), ev("popCost('suv')+12*popMo('suv')")); + assert.ok(ev("pzPopCost('suv')") > ev("popCost('suv')+12*POP_MO")); + ev("selectCity('suv')"); + assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo')); + assert.deepEqual(errors, []); +}); From e0a02276a278a8b3deb06a293ae8418fc736b9de Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:37:40 +0100 Subject: [PATCH 32/64] =?UTF-8?q?Only=20Sp=C3=A4tzle-IX=20asks=20for=2050%?= =?UTF-8?q?=20reach,=20now=20that=20Tier=201=20cones=20count?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 1 + site/i18n/de.js | 2 +- site/i18n/es.js | 2 +- site/i18n/fr.js | 2 +- site/i18n/it.js | 2 +- site/i18n/pt.js | 2 +- src/game/60-features/20-scenarios.js | 2 +- src/game/94-dashboard/10-progress.js | 2 +- src/i18n/en.js | 2 +- tests/modes.test.js | 4 ++-- tests/tier1-cone.test.js | 13 +++++++++++++ 11 files changed, 24 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 933f0bd..7c2bd70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this project are documented here. The project follows - Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. - Puzzles: small, calm network builds you can finish in a coffee break (#190). Connect a few cities on the real map with POPs and leased waves, with no clock, no bills and nothing breaking, and earn up to three stars: one for the goal, one for staying under budget, and one if the network survives any single cut. Eighteen puzzles in four packs (more stars open the next pack), some with a twist like a latency target, no subsea cables or a ring, plus a weekly puzzle that is the same for everyone, with a streak and a result to share. Puzzles never touch your saved network; only your stars are kept. - Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won. +- Only Spätzle-IX now asks for 50% reach instead of 45%, since peering with the Tier 1 club brings their customers along. Two Tier 1 PNIs and the exchange are no longer quite enough (#114). - Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge under harder rules than before upgrades it in your collection on this device, and the badge list counts how many of each kind you have. On-call games earn the standard badges; Sandbox and puzzles earn none. - China Telecomet now sells its CN-Too premium crossing in Moscow too, at the same price as in Hong Kong (#195). Haul your European traffic to Moscow and it reaches China with about 3% loss; nothing else of theirs is on offer there. - Series of Tubes now speaks German. The game follows your browser's language the first time, and you can switch to German under Settings or on the title screen. Networking terms like Peering and Transit stay in English, the way network engineers say them. diff --git a/site/i18n/de.js b/site/i18n/de.js index c6b6e91..9ed9cc0 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3205,7 +3205,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada auf den Azoren, mitten im Atlantik. Florida–Spanien und Lissabon–Lagos sind einfach zu lang für eine 1.6T-Wave: direkt hinüber trägt jede nur 1.2T. Lande auf den Inseln dazwischen, starte das Licht neu, und jeder Hop läuft mit 1.6T oder besser. Du startest mit freigeschalteter 1.6T-Hardware.", "scenarios.pops_in_bogota_lima_santiago_and":"POPs in Bogotá, Lima, Santiago und São Paulo, und 150 Gbps bedient", "scenarios.ports_on_15_ix_brrr_exchanges":"Ports an 15 IX.brrr-Exchanges, einer davon in Manaus, und 200 Gbps bedient", -"scenarios.reach_45_of_the_internet_and":"Erreiche 45 % des Internets und bediene 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Erreiche 50 % des Internets und bediene 300 Gbps", "scenarios.red_sea_crisis":"Krise im Roten Meer", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio, ganz von vorn. Der Karneval beginnt in 90 Tagen und will fünf Tage am Stück 400 Gbps. Die ganze Welt schaut zu.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Sandbox-Modus
Eine Milliarde Dollar und alles freigeschaltet. Chaos: {chaos}. Bau das Internet, das du immer wolltest, und halt einen Ersatzbagger bereit.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 4ab93d8..b8bd3b7 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3203,7 +3203,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, en las Azores, a medio camino por el Atlántico. De Florida a España y de Lisboa a Lagos es demasiado largo para una onda de 1.6T: en línea recta, cada una lleva 1.2T. Aterriza en las islas intermedias, empieza la luz de nuevo, y cada salto va a 1.6T o más. Empiezas con equipo de 1.6T desbloqueado.", "scenarios.pops_in_bogota_lima_santiago_and":"POPs en Bogotá, Lima, Santiago y São Paulo, y 150 Gbps servidos", "scenarios.ports_on_15_ix_brrr_exchanges":"Puertos en 15 intercambios IX.brrr, uno de ellos en Manaos, y 200 Gbps servidos", -"scenarios.reach_45_of_the_internet_and":"Llega al 45 % de internet y sirve 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Llega al 50 % de internet y sirve 300 Gbps", "scenarios.red_sea_crisis":"Crisis del Mar Rojo", "scenarios.rio_from_scratch_carnaval_starts_in":"Río desde cero. El Carnaval empieza en 90 días y quiere 400 Gbps durante cinco días seguidos. Todo el mundo está mirando.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Modo sandbox
Mil millones de dólares y todo desbloqueado. Caos: {chaos}. Construye el internet que siempre quisiste, y ten a mano una excavadora de repuesto.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 26a6ad8..6e84730 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3203,7 +3203,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, aux Açores, à mi-chemin de l’Atlantique. De la Floride à l’Espagne et de Lisbonne à Lagos, c’est juste trop long pour une onde de 1.6T : en ligne droite, chacune transporte 1.2T. Atterrissez sur les îles entre les deux, relancez la lumière, et chaque saut passe à 1.6T ou mieux. Vous commencez avec l’équipement 1.6T débloqué.", "scenarios.pops_in_bogota_lima_santiago_and":"Des POP à Bogotá, Lima, Santiago et São Paulo, et 150 Gbps servis", "scenarios.ports_on_15_ix_brrr_exchanges":"Des ports sur 15 IX.brrr, dont un à Manaus, et 200 Gbps servis", -"scenarios.reach_45_of_the_internet_and":"Couvre 45 % d’internet et sers 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Couvre 50 % d’internet et sers 300 Gbps", "scenarios.red_sea_crisis":"Crise en mer Rouge", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio en partant de zéro. Le Carnaval commence dans 90 jours et veut 400 Gbps pendant cinq jours d’affilée. Le monde entier regarde.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Mode bac à sable
Un milliard de dollars et tout débloqué. Chaos : {chaos}. Construis l’internet dont tu as toujours rêvé, et garde une pelleteuse de rechange sous la main.", diff --git a/site/i18n/it.js b/site/i18n/it.js index b2547d1..8e099b6 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3203,7 +3203,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, nelle Azzorre, a metà dell’Atlantico. Dalla Florida alla Spagna e da Lisbona a Lagos è appena troppo lungo per un’onda da 1.6T: in linea diretta ognuna porta 1.2T. Approda sulle isole in mezzo, fai ripartire la luce e ogni tratto va a 1.6T o più. Parti con l’attrezzatura da 1.6T sbloccata.", "scenarios.pops_in_bogota_lima_santiago_and":"POP a Bogotá, Lima, Santiago e São Paulo, e 150 Gbps serviti", "scenarios.ports_on_15_ix_brrr_exchanges":"Porte su 15 exchange IX.brrr, una delle quali a Manaus, e 200 Gbps serviti", -"scenarios.reach_45_of_the_internet_and":"Raggiungi il 45% di internet e servi 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Raggiungi il 50% di internet e servi 300 Gbps", "scenarios.red_sea_crisis":"Crisi nel Mar Rosso", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio da zero. Il Carnaval comincia tra 90 giorni e vuole 400 Gbps per cinque giorni di fila. Il mondo intero sta guardando.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Modalità sandbox
Un miliardo di dollari e tutto sbloccato. Caos: {chaos}. Costruisci l’internet che hai sempre sognato, e tieni una ruspa di scorta a portata di mano.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a05f651..b1786c5 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3203,7 +3203,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, nos Açores, no meio do Atlântico. Da Flórida à Espanha e de Lisboa a Lagos é um pouco longo demais para uma onda de 1.6T: em linha direta, cada uma leva 1.2T. Pouse nas ilhas no meio, recomece a luz, e cada trecho roda a 1.6T ou mais. Você começa com equipamento de 1.6T desbloqueado.", "scenarios.pops_in_bogota_lima_santiago_and":"POPs em Bogotá, Lima, Santiago e São Paulo, e 150 Gbps servidos", "scenarios.ports_on_15_ix_brrr_exchanges":"Portas em 15 exchanges IX.brrr, uma delas em Manaus, e 200 Gbps servidos", -"scenarios.reach_45_of_the_internet_and":"Alcance 45% da internet e atenda 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Alcance 50% da internet e atenda 300 Gbps", "scenarios.red_sea_crisis":"Crise no Mar Vermelho", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio do zero. O Carnaval começa em 90 dias e quer 400 Gbps por cinco dias seguidos. O mundo inteiro está assistindo.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Modo sandbox
Um bilhão de dólares e tudo desbloqueado. Caos: {chaos}. Construa a internet que você sempre quis, e deixe uma retroescavadeira reserva à mão.", diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index abd4507..d8854ce 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -11,7 +11,7 @@ const scnName=()=>S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}) const AU_BB=['syd','mel','bne','adl','per'],auExits=()=>new Set(S.links.filter(l=>l.sub&&!!CITY[l.a].au!==!!CITY[l.b].au&&!(l.ready>S.day)).map(l=>l.cable||l.id)).size; const brIxN=()=>CITIES.filter(c=>c.br&&S.ixp[c.id]!==undefined).length; const SCN=[ - {id:'stg',n:tr('scenarios.only_spatzle_ix'),city:'stg',cash:400000,days:730,rules:{noTransit:true,local:true},d:tr('scenarios.start_in_stuttgart_where_nobody'),goal:tr('scenarios.reach_45_of_the_internet_and'),ok:()=>R.reach>=0.45&&R.served>=300}, + {id:'stg',n:tr('scenarios.only_spatzle_ix'),city:'stg',cash:400000,days:730,rules:{noTransit:true,local:true},d:tr('scenarios.start_in_stuttgart_where_nobody'),goal:tr('scenarios.reach_50_of_the_internet_and'),ok:()=>R.reach>=0.5&&R.served>=300}, {id:'redsea',n:tr('scenarios.red_sea_crisis'),city:'mrs',cash:2500000,days:540,rules:{banCities:['cai','jed'],banPairs:['eig:dxb-mrs','gbi:fuj-mrs','smw4:khi-mrs','smw6:mrs-bom','smw6:mrs-sin','peace:mrs-sin','aae:mrs-hkg','twoaf:mrs-bom','medn:cai-mrs','medn:ist-mrs','twoaf:jnb-mrs','eassy:nbo-mrs']},d:tr('scenarios.every_cable_through_the_red_sea'),goal:tr('scenarios.a_path_from_marseille_to_singapore'),ok:()=>pathExists('mrs','sin')&&(S.stats.asiaRun||0)>=RS_DAYS}, {id:'spat',n:tr('scenarios.the_cogentle_spat'),city:'nyc',cash:700000,days:540,rules:{spat:true},d:tr('scenarios.cogentle_and_goggle_are_not_speaking'),goal:tr('scenarios.99_reach_and_150_gbps_served'),ok:()=>R.reach>=0.99&&R.served>=150}, {id:'carnaval',n:tr('common.carnaval'),city:'rio',cash:600000,days:100,rules:{},setup:()=>{S.biz.push({id:uid(),scripted:true,city:'rio',city2:null,reqs:[],name:'Carnaval Parade in Rio de Janeiro',type:'event',bw:400,rate:0,mood:100,since:0,start:90,dur:5,fee:400*5*70});},d:tr('scenarios.rio_from_scratch_carnaval_starts_in'),goal:tr('scenarios.deliver_carnaval_in_full'),ok:()=>(S.stats.evFull||0)>=1}, diff --git a/src/game/94-dashboard/10-progress.js b/src/game/94-dashboard/10-progress.js index be14c3a..111df9b 100644 --- a/src/game/94-dashboard/10-progress.js +++ b/src/game/94-dashboard/10-progress.js @@ -4,7 +4,7 @@ const RS_G=80,RS_DAYS=30,asiaG=()=>S.links.reduce((a,l)=>a+((CITY[l.a].reg==='AS const pSrv=g=>({l:tr('common.traffic_served'),v:R.served,max:g,txt:`${fmtG(R.served)} / ${fmtG(g)}`}); const pReach=()=>({l:tr('common.reach'),v:R.reach,max:0.99,txt:`${pct(R.reach)} / 99%`}); const pChk=(l,ok)=>({l,v:ok?1:0,max:1,txt:ok?'✓':'—'}); -const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.45,txt:`${pct(R.reach)} / 45%`},pSrv(300)],redsea:()=>{const g=asiaG(),n=S.stats.asiaRun||0;return [pChk(tr('progress.a_path_from_marseille_to_singapore'),pathExists('mrs','sin')),{l:tr('progress.your_traffic_to_and_from_asia'),v:Math.min(g,RS_G),max:RS_G,txt:`${fmtG(g)} / ${fmtG(RS_G)}`},{l:tr('progress.days_in_a_row_at_g',{g:fmtG(RS_G)}),v:n,max:RS_DAYS,txt:`${n} / ${RS_DAYS}`}];},spat:()=>[pReach(),pSrv(150)], +const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.5,txt:`${pct(R.reach)} / 50%`},pSrv(300)],redsea:()=>{const g=asiaG(),n=S.stats.asiaRun||0;return [pChk(tr('progress.a_path_from_marseille_to_singapore'),pathExists('mrs','sin')),{l:tr('progress.your_traffic_to_and_from_asia'),v:Math.min(g,RS_G),max:RS_G,txt:`${fmtG(g)} / ${fmtG(RS_G)}`},{l:tr('progress.days_in_a_row_at_g',{g:fmtG(RS_G)}),v:n,max:RS_DAYS,txt:`${n} / ${RS_DAYS}`}];},spat:()=>[pReach(),pSrv(150)], carnaval:()=>[pChk(tr('progress.carnaval_delivered_in_full'),(S.stats.evFull||0)>=1)],ixbr:()=>{const n=brIxN();return [{l:tr('progress.ix_brrr_ports'),v:n,max:15,txt:`${n} / 15`},pChk(tr('progress.a_port_on_ix_brrr_manaus'),S.ixp.mao!==undefined),pSrv(200)];}, c2c:()=>[pChk(tr('progress.a_path_from_cape_town_to'),pathExists('cpt','cai')),...['lag','nbo'].map(c=>pChk(tr('progress.pop_in_city',{city:CITY[c].name}),!!S.pops[c])),pSrv(150)], pac:()=>[pChk(tr('progress.1_6t_on_every_hop_from'),fastPath('lax','syd',1600)),pChk(tr('progress.a_path_from_los_angeles_to'),pathExists('lax','tok')),pSrv(150)], diff --git a/src/i18n/en.js b/src/i18n/en.js index 9e5308b..d13d34c 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3204,7 +3204,7 @@ "scenarios.ponta_delgada_in_the_azores_halfway":"Ponta Delgada, in the Azores, halfway across the Atlantic. Florida to Spain and Lisbon to Lagos are just too long for a 1.6T wave: straight across, each carries 1.2T. Land on the islands in between, start the light fresh, and every hop runs at 1.6T or better. You start with 1.6T gear unlocked.", "scenarios.pops_in_bogota_lima_santiago_and":"POPs in Bogotá, Lima, Santiago and São Paulo, and 150 Gbps served", "scenarios.ports_on_15_ix_brrr_exchanges":"Ports on 15 IX.brrr exchanges, one of them in Manaus, and 200 Gbps served", -"scenarios.reach_45_of_the_internet_and":"Reach 45% of the internet and serve 300 Gbps", +"scenarios.reach_50_of_the_internet_and":"Reach 50% of the internet and serve 300 Gbps", "scenarios.red_sea_crisis":"Red Sea Crisis", "scenarios.rio_from_scratch_carnaval_starts_in":"Rio from scratch. Carnaval starts in 90 days and wants 400 Gbps for five days straight. The whole world is watching.", "scenarios.sandbox_mode_a_billion_dollars_chaos":"Sandbox mode
A billion dollars and every unlock. Chaos: {chaos}. Build the internet you always wanted, and keep a spare backhoe handy.", diff --git a/tests/modes.test.js b/tests/modes.test.js index 622de40..95ef1bd 100644 --- a/tests/modes.test.js +++ b/tests/modes.test.js @@ -409,8 +409,8 @@ test('#114 Only Spätzle-IX can be won by peering alone', () => { const { ev, errors } = load(); ev("ACT.startScn({id:'stg',sure:1})"); assert.equal(ev("scnRule('local')&&scnRule('noTransit')"), true); - assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /45%.*300 Gbps/); - assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.45, 300]); + assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /50%.*300 Gbps/); + assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.5, 300]); // a game saved before the fix picks the rule up on load ev("const o=JSON.parse(JSON.stringify(S));delete o.scn.rules.local;migrate(o);window.__mig=o.scn.rules.local"); assert.equal(ev('window.__mig'), true); diff --git a/tests/tier1-cone.test.js b/tests/tier1-cone.test.js index 00f5de8..55b5372 100644 --- a/tests/tier1-cone.test.js +++ b/tests/tier1-cone.test.js @@ -182,3 +182,16 @@ test('a traceroute down a two-level cone shows every network on the way', () => assert.equal(ev("R.cone.ddo"), 'ntt'); assert.deepEqual(errors, []); }); + +test('#114 Only Spätzle-IX still takes more than the exchange and two Tier 1 PNIs, now that cones count', () => { + const { ev, errors } = load(); + ev("UI.pitched=true;beginGame('T','stg',{scn:SCN.find(x=>x.id==='stg')});S.cash=1e9;S.lvl=10;S.pops.stg.bb={d:400};S.ixp.stg=0;for(const id of ixMembers('stg'))S.peers[id+'@stg']=1;compute()"); + const reach = (ts) => ev(`S.pni=[];for(const t of ${JSON.stringify(ts)})S.pni.push({id:'p'+t,net:t,city:'stg',tier:2});compute();R.reach`); + const T = ['lvl', 'ntt', 'tly', 'cog', 'tat']; + const goal = ev("SCN.find(x=>x.id==='stg').ok.toString()"); + assert.match(goal, /R\.reach>=0\.5/); + for (let i = 0; i < T.length; i++) for (let j = i + 1; j < T.length; j++) + assert.ok(reach([T[i], T[j]]) < 0.5, `${T[i]}+${T[j]} is not enough`); + assert.ok(reach(['lvl', 'ntt', 'tly']) >= 0.5, 'three Tier 1 PNIs and the exchange can be'); + assert.deepEqual(errors, []); +}); From e3534cad4b1a4d90ad6fcfc0cc1455569aa24202 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:38:55 +0100 Subject: [PATCH 33/64] Custom metric panel updates on Safari after switching multiplier and cost (#131) --- src/game/90-actions/60-links.js | 4 ++-- src/game/93-ui/70-link-panels.js | 2 ++ tests/metric-panel.test.js | 40 ++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 tests/metric-panel.test.js diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index d9b1000..7c046d0 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -30,10 +30,10 @@ Object.assign(ACT,{ setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();}, setMetric:({id,v})=>{if(v!=='custom'&&!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;const m=S.pairMet||(S.pairMet={}),k=edgeKey(l); // Switching to custom starts from the current preset's factor, so nothing moves until the player edits it. - if(v==='custom'){if(!pairCm(k))m[k]={k:'f',v:MET[pairMet(k)].f};}else if(v==='normal')delete m[k];else m[k]=v;sfx('click');after();}, + if(v==='custom'){if(!pairCm(k))m[k]={k:'f',v:MET[pairMet(k)].f};}else if(v==='normal')delete m[k];else m[k]=v;metBlur();sfx('click');after();}, metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l)return;const key=edgeKey(l),c=pairCm(key);if(!c||c.k===k)return; // The cost stays what it was on this link, written the other way. - const w=pairW(key,l.km);S.pairMet[key]={k,v:clampM(k,k==='w'?w:w/(l.km+60))};sfx('click');after();}, + const w=pairW(key,l.km);S.pairMet[key]={k,v:clampM(k,k==='w'?w:w/(l.km+60))};metBlur();sfx('click');after();}, metricSet:({id})=>{const l=S.links.find(x=>x.id===id),t=$('metIn');if(!l||!t)return;const key=edgeKey(l),c=pairCm(key);if(!c)return;const v=parseFloat(String(t.value).replace(',','.'));if(!Number.isFinite(v)){sfx('err');return;} t.blur();S.pairMet[key]={k:c.k,v:clampM(c.k,v)};sfx('click');after();}, setStandby:({id,on})=>{const l=S.links.find(x=>x.id===id);if(!l)return;if(on)l.standby=true;else delete l.standby;sfx('click');after();}, diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 4633d68..85a3af8 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -67,6 +67,8 @@ function trafficSection(l){ if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`

${tr('link_panels.biggest_feeder_egress_in_city_set',{egress:esc(d.lab),city:CITY[d.city].name})}

`;} return h+`
`; } +// Safari keeps the number field focused through a button tap, and renderPanel() skips a focused field: let go first (#131). +const metBlur=()=>{const t=$('metIn');if(t&&document.activeElement===t)t.blur();}; function metricSection(l){const key=edgeKey(l),cur=pairMet(key),pl=pairLinks(l.a,l.b),sb=!!l.standby,base=l.km+60,sel=k=>cur===k?'pink sm':'ghost sm'; let h=`

${tr('common.routing_metric')}

${tr('link_panels.your_routers_pick_the_lowest_cost_0160')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},sel(k))).join('')}${btn(tr('common.custom'),'setMetric',{id:l.id,v:'custom'},sel('custom'))}
`; const cm=pairCm(key); diff --git a/tests/metric-panel.test.js b/tests/metric-panel.test.js new file mode 100644 index 0000000..fdf2d5a --- /dev/null +++ b/tests/metric-panel.test.js @@ -0,0 +1,40 @@ +// #131 on Safari: the custom metric field keeps focus through a button tap, and the panel skips re-rendering a +// focused field, so switching between multiplier and cost (or to a preset) left the old panel on screen. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const setup = (ev) => { + ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal()"); + ev("window.L=S.links[0].id;ACT.selLink({id:L});renderAll();ACT.setMetric({id:L,v:'custom'});renderAll()"); +}; + +test('#131 switching the custom metric mode re-renders even while the field has focus', () => { + const { ev, dom, errors } = load(); + const d = dom.window.document; + setup(ev); + d.getElementById('metIn').focus(); + assert.equal(d.activeElement.id, 'metIn'); + ev("ACT.metricMode({id:L,k:'w'})"); + assert.equal(d.getElementById('metIn').getAttribute('step'), '1', 'the field is now the exact cost'); + assert.equal(+d.getElementById('metIn').value, ev("S.pairMet[edgeKey(S.links[0])].v")); + d.getElementById('metIn').focus(); + ev("ACT.metricMode({id:L,k:'f'})"); + assert.equal(d.getElementById('metIn').getAttribute('step'), '0.1', 'and back to a multiplier'); + d.getElementById('metIn').focus(); + ev("ACT.setMetric({id:L,v:'normal'})"); + assert.equal(d.getElementById('metIn'), null, 'a preset hides the field'); + assert.deepEqual(errors, []); +}); + +test('#131 the daily re-render still keeps a half-typed value', () => { + const { ev, dom, errors } = load(); + const d = dom.window.document; + setup(ev); + const t = d.getElementById('metIn'); + t.focus(); t.value = '3.5'; + ev("S.day++;renderPanel()"); + assert.equal(d.getElementById('metIn').value, '3.5'); + assert.equal(d.activeElement.id, 'metIn'); + assert.deepEqual(errors, []); +}); From d3f550cc3e6139efe025060b09c3b33f1276609e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:39:00 +0100 Subject: [PATCH 34/64] Puzzles: budgets follow a difficulty curve The first pack leaves 16-18% over the cheapest three-star build, the Pacific and speed packs about 10%, and the N-1 Club 6-7%. The first pack no longer promises no budget. A brute-force check in the tests keeps each reference build the cheapest. --- site/i18n/de.js | 2 +- site/i18n/es.js | 2 +- site/i18n/fr.js | 2 +- site/i18n/it.js | 2 +- site/i18n/pt.js | 2 +- src/game/60-features/90-puzzles-data.js | 28 +++++----- src/i18n/en.js | 2 +- tests/puzzles.test.js | 71 +++++++++++++++++++------ 8 files changed, 75 insertions(+), 36 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index c6b6e91..184b824 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2945,7 +2945,7 @@ "puzzles.weekly_puzzle":"Wochenpuzzle", "puzzles.weekly_puzzle_key":"Wochenpuzzle {key}", "puzzles.with_the_pop_price":"mit POP: {price}", -"puzzles.your_first_tubes_no_pressure":"Deine ersten Röhren. Kein Druck, kein Budget.", +"puzzles.your_first_tubes_roomy_budgets":"Deine ersten Röhren. Großzügige Budgets, und die ersten zwei gehen aufs Haus.", "puzzles.your_stars":"Deine Sterne", "reach_and_subsea.premium_submarine_terminals":"Premium-Seekabel-Terminals", "release_notes.and_n_more_change":{"one":"… und {n} weitere Änderung","other":"… und {n} weitere Änderungen"}, diff --git a/site/i18n/es.js b/site/i18n/es.js index 4ab93d8..b32aea6 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2943,7 +2943,7 @@ "puzzles.weekly_puzzle":"Puzle semanal", "puzzles.weekly_puzzle_key":"Puzle semanal {key}", "puzzles.with_the_pop_price":"con el POP: {price}", -"puzzles.your_first_tubes_no_pressure":"Tus primeros tubos. Sin presión, sin presupuesto.", +"puzzles.your_first_tubes_roomy_budgets":"Tus primeros tubos. Presupuestos holgados, y los dos primeros invita la casa.", "puzzles.your_stars":"Tus estrellas", "reach_and_subsea.premium_submarine_terminals":"Terminales submarinas premium", "release_notes.and_n_more_change":{"one":"…y {n} cambio más","other":"…y {n} cambios más"}, diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 26a6ad8..c13b174 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2943,7 +2943,7 @@ "puzzles.weekly_puzzle":"Puzzle de la semaine", "puzzles.weekly_puzzle_key":"Puzzle de la semaine {key}", "puzzles.with_the_pop_price":"avec le POP : {price}", -"puzzles.your_first_tubes_no_pressure":"Tes premiers tubes. Pas de pression, pas de budget.", +"puzzles.your_first_tubes_roomy_budgets":"Tes premiers tubes. Des budgets confortables, et les deux premiers sont offerts par la maison.", "puzzles.your_stars":"Tes étoiles", "reach_and_subsea.premium_submarine_terminals":"Terminaux sous-marins premium", "release_notes.and_n_more_change":{"one":"…et {n} autre changement","other":"…et {n} autres changements"}, diff --git a/site/i18n/it.js b/site/i18n/it.js index b2547d1..ce49ce3 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2943,7 +2943,7 @@ "puzzles.weekly_puzzle":"Puzzle della settimana", "puzzles.weekly_puzzle_key":"Puzzle della settimana {key}", "puzzles.with_the_pop_price":"con il POP: {price}", -"puzzles.your_first_tubes_no_pressure":"I tuoi primi tubi. Niente pressione, niente budget.", +"puzzles.your_first_tubes_roomy_budgets":"I tuoi primi tubi. Budget comodi, e i primi due li offre la casa.", "puzzles.your_stars":"Le tue stelle", "reach_and_subsea.premium_submarine_terminals":"Terminali sottomarini avanzati", "release_notes.and_n_more_change":{"one":"…e {n} altra modifica","other":"…e altre {n} modifiche"}, diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a05f651..dca69b7 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2943,7 +2943,7 @@ "puzzles.weekly_puzzle":"Puzzle da semana", "puzzles.weekly_puzzle_key":"Puzzle da semana {key}", "puzzles.with_the_pop_price":"com o POP: {price}", -"puzzles.your_first_tubes_no_pressure":"Seus primeiros tubos. Sem pressão, sem orçamento.", +"puzzles.your_first_tubes_roomy_budgets":"Seus primeiros tubos. Orçamentos folgados, e os dois primeiros são por conta da casa.", "puzzles.your_stars":"Suas estrelas", "reach_and_subsea.premium_submarine_terminals":"Terminais submarinos premium", "release_notes.and_n_more_change":{"one":"…e mais {n} mudança","other":"…e mais {n} mudanças"}, diff --git a/src/game/60-features/90-puzzles-data.js b/src/game/60-features/90-puzzles-data.js index 681d391..a6b7bba 100644 --- a/src/game/60-features/90-puzzles-data.js +++ b/src/game/60-features/90-puzzles-data.js @@ -4,7 +4,7 @@ noSub (no subsea cables), ring (one ring through every POP), lat:[a,b,ms] (best path under ms), minG (every link at least this many Gbps), avoid (cities shown on the map that you may not build in). */ const PZ_PACKS=[ - {id:'hello',n:tr('puzzles.hello_world'),d:tr('puzzles.your_first_tubes_no_pressure'),need:0}, + {id:'hello',n:tr('puzzles.hello_world'),d:tr('puzzles.your_first_tubes_roomy_budgets'),need:0}, {id:'fire',n:tr('puzzles.ring_of_fire'),d:tr('puzzles.the_pacific_rim_where_every_hop'),need:6}, {id:'speed',n:tr('puzzles.speed_runs'),d:tr('puzzles.beat_the_clock_light_in_glass'),need:14}, {id:'n1',n:tr('puzzles.n_1_club'),d:tr('puzzles.for_architects_who_sleep_through_backhoes'),need:22}, @@ -12,22 +12,22 @@ const PZ_PACKS=[ const PZ=[ {id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),cities:['lon','nyc'],budget:0}, {id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),cities:['lon','ams','fra'],budget:0}, - {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),cities:['nyc','chi','dal','sjc'],budget:300000}, - {id:'smorgas',pack:'hello',n:tr('puzzles.smorgasbord'),j:tr('puzzles.four_capitals_one_very_long_winter'),cities:['osl','sto','cph','hel'],budget:190000}, - {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),cities:['syd','mel','bne','adl'],budget:300000}, - {id:'aloha',pack:'fire',n:tr('puzzles.aloha_latency'),j:tr('puzzles.honolulu_the_world_s_most_scenic'),cities:['sjc','hnl','syd'],budget:1750000}, - {id:'rimshot',pack:'fire',n:tr('puzzles.pacific_rim_shot'),j:tr('puzzles.seattle_to_singapore_with_a_stop'),cities:['sea','tok','hkg','sin'],budget:1200000}, - {id:'fire',pack:'fire',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),cities:['tok','hkg','sin','syd'],ring:true,budget:1600000}, - {id:'kiwi',pack:'fire',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),cities:['akl','syd','sea'],via:['hnl','suv','lax'],budget:1400000}, - {id:'guam',pack:'fire',n:tr('puzzles.guam_slam'),j:tr('puzzles.a_tiny_island_where_half_the'),cities:['tok','mnl','syd'],via:['gum'],budget:1600000}, - {id:'flash',pack:'speed',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),cities:['nyc','lon'],lat:['nyc','lon',27],budget:450000}, - {id:'pingpong',pack:'speed',n:tr('puzzles.ping_pong_to_tokyo'),j:tr('puzzles.the_pacific_is_big_light_is'),cities:['lax','tok'],via:['sea','sjc'],lat:['lax','tok',47],budget:850000}, - {id:'suez',pack:'speed',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),cities:['fra','sin'],via:['mrs','bom'],lat:['fra','sin',68],budget:1000000}, + {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),cities:['nyc','chi','dal','sjc'],budget:340000}, + {id:'smorgas',pack:'hello',n:tr('puzzles.smorgasbord'),j:tr('puzzles.four_capitals_one_very_long_winter'),cities:['osl','sto','cph','hel'],budget:210000}, + {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),cities:['syd','mel','bne','adl'],budget:320000}, + {id:'aloha',pack:'fire',n:tr('puzzles.aloha_latency'),j:tr('puzzles.honolulu_the_world_s_most_scenic'),cities:['sjc','hnl','syd'],budget:1830000}, + {id:'rimshot',pack:'fire',n:tr('puzzles.pacific_rim_shot'),j:tr('puzzles.seattle_to_singapore_with_a_stop'),cities:['sea','tok','hkg','sin'],budget:1240000}, + {id:'fire',pack:'fire',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),cities:['tok','hkg','sin','syd'],ring:true,budget:1610000}, + {id:'kiwi',pack:'fire',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),cities:['akl','syd','sea'],via:['hnl','suv','lax'],budget:1450000}, + {id:'guam',pack:'fire',n:tr('puzzles.guam_slam'),j:tr('puzzles.a_tiny_island_where_half_the'),cities:['tok','mnl','syd'],via:['gum'],budget:1700000}, + {id:'flash',pack:'speed',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),cities:['nyc','lon'],lat:['nyc','lon',27],budget:465000}, + {id:'pingpong',pack:'speed',n:tr('puzzles.ping_pong_to_tokyo'),j:tr('puzzles.the_pacific_is_big_light_is'),cities:['lax','tok'],via:['sea','sjc'],lat:['lax','tok',47],budget:880000}, + {id:'suez',pack:'speed',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),cities:['fra','sin'],via:['mrs','bom'],lat:['fra','sin',68],budget:1010000}, {id:'samba',pack:'speed',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),cities:['sao','mia'],via:['for','rio'],lat:['sao','mia',45],budget:1060000}, {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),cities:['lis','mad','par','mil'],via:['bcn','mrs'],noSub:true,budget:210000}, {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),cities:['nyc','lon','dub'],budget:380000}, - {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),cities:['ams','ber','muc','zrh'],via:['ham','dus'],avoid:['fra'],budget:200000}, - {id:'fatpipes',pack:'n1',n:tr('puzzles.fat_pipes_only'),j:tr('puzzles.nobody_ever_got_fired_for_buying'),cities:['par','mrs','mil','zrh'],minG:100,budget:240000}, + {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),cities:['ams','ber','muc','zrh'],via:['ham','dus'],avoid:['fra'],budget:192000}, + {id:'fatpipes',pack:'n1',n:tr('puzzles.fat_pipes_only'),j:tr('puzzles.nobody_ever_got_fired_for_buying'),cities:['par','mrs','mil','zrh'],minG:100,budget:235000}, ]; // Weekly puzzle pools: each is one landmass and one region, so every pair has an overland route. const PZ_WEEK_POOLS=[ diff --git a/src/i18n/en.js b/src/i18n/en.js index 9e5308b..b4943a0 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2944,7 +2944,7 @@ "puzzles.weekly_puzzle":"Weekly puzzle", "puzzles.weekly_puzzle_key":"Weekly puzzle {key}", "puzzles.with_the_pop_price":"with the POP: {price}", -"puzzles.your_first_tubes_no_pressure":"Your first tubes. No pressure, no budget.", +"puzzles.your_first_tubes_roomy_budgets":"Your first tubes. Roomy budgets, and the first two are on the house.", "puzzles.your_stars":"Your stars", "reach_and_subsea.premium_submarine_terminals":"Premium submarine terminals", "release_notes.and_n_more_change":{"one":"…and {n} more change","other":"…and {n} more changes"}, diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 402815f..f560c62 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -7,24 +7,24 @@ const { load } = require('./harness'); // `one` earns the goal star, `three` earns all three. A second land link on the same pair is a diverse route. const REF = { hello: { one: [['lon', 'nyc', 'grace']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'amitie']] }, - eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['lon', 'ams', 'uly'], ['lon', 'ams', 'concerto'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] }, - shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['nyc', 'chi', 'land'], ['chi', 'sjc', 'land'], ['sjc', 'dal', 'land'], ['dal', 'nyc', 'land']] }, - smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['hel', 'cph', 'land'], ['cph', 'osl', 'land']] }, - downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['adl', 'bne', 'land'], ['bne', 'syd', 'land']] }, - aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['sjc', 'hnl', 'scx'], ['sjc', 'hnl', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] }, - rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['tok', 'hkg', 'adc'], ['tok', 'hkg', 'apg'], ['hkg', 'sin', 'sjc2'], ['hkg', 'sin', 'land']] }, - fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] }, + eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['ams', 'lon', 'concerto'], ['ams', 'lon', 'nshuttle'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] }, + shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['chi', 'nyc', 'land'], ['chi', 'sjc', 'land'], ['dal', 'nyc', 'land'], ['dal', 'sjc', 'land']] }, + smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['cph', 'osl', 'land'], ['cph', 'hel', 'land'], ['hel', 'sto', 'land']] }, + downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['mel', 'syd', 'land'], ['bne', 'syd', 'land'], ['adl', 'mel', 'land'], ['adl', 'bne', 'land']] }, + aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['hnl', 'sjc', 'scx'], ['hnl', 'sjc', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] }, + rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['hkg', 'tok', 'apg'], ['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['hkg', 'sin', 'land']] }, + fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] }, // Hawaiki is Seattle's only cable south, so the second way out runs overland to LA and on via Suva. - kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'syd', 'tasman'], ['akl', 'sea', 'hwk'], ['syd', 'suv', 'scxn'], ['sea', 'lax', 'land'], ['lax', 'suv', 'scxn']] }, - guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['tok', 'mnl', 'jup'], ['tok', 'syd', 'sushi'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam']] }, - flash: { one: [['nyc', 'lon', 'hibx']], three: [['nyc', 'lon', 'hibx'], ['nyc', 'lon', 'grace']] }, + kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'syd', 'tasman'], ['akl', 'sea', 'hwk'], ['suv', 'syd', 'scxn'], ['lax', 'sea', 'land'], ['lax', 'suv', 'scxn']] }, + guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['mnl', 'tok', 'jup'], ['syd', 'tok', 'sushi'], ['gum', 'mnl', 'bifrost'], ['gum', 'syd', 'guam']] }, + flash: { one: [['nyc', 'lon', 'hibx']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'hibx']] }, pingpong: { one: [['lax', 'tok', 'jup']], three: [['lax', 'tok', 'jup'], ['lax', 'sea', 'land'], ['sea', 'tok', 'fast']] }, - suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['mrs', 'bom', 'twoaf'], ['bom', 'sin', 'land']] }, - samba: { one: [['sao', 'mia', 'monet']], three: [['sao', 'for', 'land'], ['sao', 'for', 'land'], ['for', 'mia', 'monet'], ['for', 'mia', 'sam1']] }, - sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land'], ['mil', 'lis', 'land']] }, - braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix'], ['dub', 'nyc', 'havf']] }, - nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land'], ['zrh', 'ams', 'land']] }, - fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1], ['zrh', 'par', 'land', 1]] }, + suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['bom', 'sin', 'land'], ['bom', 'mrs', 'twoaf']] }, + samba: { one: [['sao', 'mia', 'monet']], three: [['for', 'sao', 'land'], ['for', 'sao', 'land'], ['for', 'mia', 'monet'], ['for', 'mia', 'sam1']] }, + sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['lis', 'mil', 'land'], ['mad', 'par', 'land'], ['mil', 'par', 'land']] }, + braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['lon', 'nyc', 'grace'], ['dub', 'nyc', 'havf'], ['dub', 'lon', 'celtix']] }, + nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ams', 'zrh', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']] }, + fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'zrh', 'land', 1], ['mrs', 'par', 'land', 1], ['mil', 'mrs', 'land', 1], ['mil', 'zrh', 'land', 1]] }, }; // Builds links the way a player does: POP at the first city, then the link picker for each hop. @@ -62,6 +62,45 @@ test('puzzle data: every puzzle is valid, solvable, and its 3-star reference ear assert.deepEqual(errors, []); }); +// Brute force over every route between the puzzle's cities (one size: 10G, or 100G under minG): is any 3-star build +// cheaper than `limit`? Each cable is one failure unit; each overland link its own trench (a second one is diverse). +function cheaper3(ev, id, limit) { + const D = JSON.parse(ev(`(()=>{pzBegin(pzDef('${id}'));const P=S.pz,cs=[...P.cities,...P.via],tier=P.minG?1:0,o=[]; + for(const a of cs)for(const b of cs)if(a o[i].cab ? 'c' + o[i].cab : 't' + i; + const reach = (ls, skip) => { const adj = {}; for (const i of ls) { if (unit(i) === skip) continue; const { a, b } = o[i]; (adj[a] = adj[a] || []).push(b); (adj[b] = adj[b] || []).push(a); } + const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) for (const v of adj[q.pop()] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } return P.cities.every((c) => seen.has(c)); }; + const lat = (ls) => { const d = { [P.lat[0]]: 0 }, done = new Set(); for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null) return Infinity; if (u === P.lat[1]) return d[u]; done.add(u); + for (const i of ls) { const l = o[i]; if (l.a !== u && l.b !== u) continue; const v = l.a === u ? l.b : l.a, nd = d[u] + l.ms + 0.05; if (!(nd >= d[v])) d[v] = nd; } } }; + const ring = (ls) => { const nb = {}; for (const i of ls) { const { a, b } = o[i]; (nb[a] = nb[a] || new Set()).add(b); (nb[b] = nb[b] || new Set()).add(a); } const ns = Object.keys(nb); + if (ns.length < 3 || !ns.every((c) => nb[c].size === 2)) return false; let prev = null, cur = ns[0], n = 0; do { const nx = [...nb[cur]].find((x) => x !== prev); prev = cur; cur = nx; n++; } while (cur !== ns[0] && n <= ns.length); return n === ns.length; }; + const ok = (ls) => { if (!reach(ls, null) || (P.ring && !ring(ls)) || (P.lat && lat(ls) > P.lat[2])) return false; return [...new Set(ls.map(unit))].every((u) => reach(ls, u)); }; + let found = null; + const rec = (start, ls, cost) => { if (found) return; if (ls.length && cost < limit - 1) { const pops = new Set(P.cities); for (const i of ls) { pops.add(o[i].a); pops.add(o[i].b); } const tot = cost + [...pops].reduce((x, c) => x + pop[c], 0); if (tot < limit - 1 && ok(ls)) { found = tot; return; } } + if (ls.length >= 7) return; for (let i = start; i < o.length; i++) { if (o[i].div && !ls.some((j) => !o[j].div && !o[j].cab && o[j].a === o[i].a && o[j].b === o[i].b)) continue; if (cost + o[i].cost < limit - 1) rec(i + 1, [...ls, i], cost + o[i].cost); } }; + rec(0, [], 0); + return found; +} + +test('budgets follow the difficulty curve: roomy first pack, ~10% in the middle, tight N-1 Club', () => { + const { ev, errors } = load(); + const SLACK = { hello: [0.15, 0.2], fire: [0.09, 0.11], speed: [0.09, 0.11], n1: [0.05, 0.08] }; + const rows = JSON.parse(ev('JSON.stringify(PZ.filter(p=>p.budget).map(p=>({id:p.id,pack:p.pack,budget:p.budget})))')); + for (const { id, pack, budget } of rows) { + ev(`pzBegin(pzDef('${id}'))`); + build(ev, REF[id].three); + const e = evalP(ev); + assert.equal(e.stars, 3, id); + assert.equal(cheaper3(ev, id, e.spend), null, `${id}: the reference is the cheapest 3-star build`); + const slack = budget / e.spend - 1, [lo, hi] = SLACK[pack]; + assert.ok(slack >= lo && slack <= hi, `${id}: ${(slack * 100).toFixed(1)}% slack, want ${lo * 100}-${hi * 100}%`); + } + assert.match(ev("PZ_PACKS[0].d"), /Roomy budgets/, 'the first pack does not promise "no budget"'); + assert.deepEqual(errors, []); +}); + test('stars: goal, budget, N-1 and twists each count', () => { const { ev, errors } = load(); ev("pzBegin(pzDef('braces'))"); From 66652576e5208845f5322ce04b41dc76ebda39ec Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:41:10 +0100 Subject: [PATCH 35/64] Puzzles: the best spend in the list is the cheapest build at your best stars Progress is recorded on every change, not only when the stars go up: more stars start the best spend again, and a cheaper build at the same stars replaces it. --- src/game/60-features/92-puzzles.js | 7 ++++-- tests/puzzles.test.js | 35 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index 3fa9fa5..91f156b 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -101,8 +101,11 @@ const pzNewPop=()=>({day:0,bb:null,boost:0,down:0,routers:1,gen:false}); 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: a better result than this attempt has had opens the results card. -function pzCheck(){const e=pzEval();if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;pzRecord(e);pzResults(e,prev);return e;} +// Every solved state is recorded, so a cheaper build at the same stars counts too. +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;pzResults(e,prev);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=bag[k]||{st:0,sp:null}; - r.st=Math.max(r.st,e.stars);r.sp=r.sp==null?e.spend:Math.min(r.sp,e.spend);bag[k]=r;if(P.id==='weekly')pzStreak(p,P.key);pzStore(p);} + if(e.starsx.id===S.pz.id);for(let j=i+1;j { + const { ev, errors } = load(); + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))"); + const rec = () => JSON.parse(ev("JSON.stringify(pzLoad().s.braces||null)")); + build(ev, REF.braces.one); + const two = evalP(ev).spend; + assert.deepEqual(rec(), { st: 2, sp: two }); + // A gold-plated third link: N-1 but over budget is still two stars, and dearer, so the best stays. + ev("ACT.pzLinkTo({a:'dub',b:'nyc'});ACT.pzVia({v:'havf'});ACT.pzLink({tier:2});closeModal()"); + assert.equal(evalP(ev).stars, 2); + assert.deepEqual(rec(), { st: 2, sp: two }); + // Shrinking it to 10G earns the third star: the best spend starts again at the 3-star build. + ev('ACT.pzTier({id:S.links[2].id,tier:0})'); + const three = evalP(ev); + assert.equal(three.stars, 3); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + // With a looser budget, a dearer 3-star build does not replace it; going back to the cheaper one keeps it. + ev('S.pz.budget=1e7;ACT.pzTier({id:S.links[0].id,tier:1})'); + assert.equal(evalP(ev).stars, 3); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + // A cheaper 3-star build after a dearer first one is recorded (the old code only recorded star rises). + ev("localStorage.removeItem('sot-puzzles')"); + ev('ACT.pzTier({id:S.links[1].id,tier:1})'); + const dear = evalP(ev).spend; + assert.deepEqual(rec(), { st: 3, sp: dear }); + ev('ACT.pzTier({id:S.links[1].id,tier:0});ACT.pzTier({id:S.links[0].id,tier:0})'); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + // Fewer stars never overwrite more. + ev('ACT.pzRmLink({id:S.links[2].id})'); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + ev('ACT.puzzleMenu({})'); + assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`))); + assert.deepEqual(errors, []); +}); From 837c56c13e404d859c594617a46d5e769fd96349 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:42:35 +0100 Subject: [PATCH 36/64] Connectivity prices for the 47 cities that had no data (#94) --- src/game/20-world/55-city-pdb.js | 50 +++++++++++++++++++++++++++++++- tests/regions.test.js | 7 ++++- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/src/game/20-world/55-city-pdb.js b/src/game/20-world/55-city-pdb.js index 2233152..1b6d62f 100644 --- a/src/game/20-world/55-city-pdb.js +++ b/src/game/20-world/55-city-pdb.js @@ -1,15 +1,18 @@ /* Real-world calibration, pulled 2026-10-25 (Pacific islands 2026-10-26). Per city: [carrier-neutral facilities, network presences across them, ASNs registered in its country]. Facilities and presences are PeeringDB facilities within 50 km or in the same city (peeringdb.com/api/fac, net_count summed); ASNs per country are from bgp.he.net/report/world. - A city missing here keeps the plain regional price. One entry per line, sorted by id. */ + Cities PeeringDB barely knows (added 2026-10-28) are marked: est. is an estimate from what is known to be there, with + the country's ASN count. A city missing here keeps the plain regional price. One entry per line, sorted by id. */ const CITY_PDB={ abj:[5,11,32], acc:[7,78,124], add:[2,3,10], + adl:[6,70,3196], // est. aju:[4,3,9693], akl:[27,398,755], alg:[0,0,16], ams:[69,2731,1827], + anc:[3,12,33300], // est. apw:[0,0,11], ash:[86,1010,33300], asu:[3,8,124], @@ -17,11 +20,13 @@ const CITY_PDB={ atn:[42,589,33300], auh:[4,1,231], bcn:[13,159,1341], + bda:[2,8,25], // est. bde:[0,0,4027], beg:[7,49,227], bel:[3,7,9693], ber:[22,351,3705], bet:[16,174,152], + bgi:[1,5,20], // est. bhz:[13,40,9693], bkk:[32,397,675], blr:[14,104,6412], @@ -30,6 +35,7 @@ const CITY_PDB={ bom:[59,1050,6412], bos:[31,209,33300], bru:[33,328,443], + brw:[0,0,33300], // est. bsb:[14,108,9693], bud:[6,146,369], bue:[28,372,1357], @@ -41,15 +47,18 @@ const CITY_PDB={ cas:[2,2,39], cau:[2,2,9693], cbo:[1,0,33], + cbr:[5,60,3196], // est. ccs:[6,32,296], cgb:[4,5,9693], cgr:[4,4,9693], + chc:[4,30,755], // est. chi:[64,809,33300], cor:[2,29,1357], cph:[30,290,529], cpq:[19,65,9693], cpt:[6,267,879], cpv:[4,12,9693], + cur:[3,20,25], // est. cwb:[11,79,9693], cxj:[2,3,9693], dac:[30,107,2105], @@ -58,26 +67,37 @@ const CITY_PDB={ del:[31,479,6412], den:[28,310,33300], dkr:[2,4,23], + dks:[0,0,6683], // est. dla:[3,14,34], doh:[6,29,31], drw:[3,15,3196], dub:[21,277,350], dur:[4,137,879], + dus:[13,350,3705], // 14 listed, one closed; Digital Realty DUS1-3 alone has 141 networks + dut:[0,0,33300], // est. dxb:[8,135,231], + dyr:[0,0,6683], // est. + ebj:[1,5,529], // est. edi:[4,46,4027], + fdf:[1,5,10], // est. fec:[5,4,9693], fih:[7,19,57], fln:[5,23,9693], for:[16,362,9693], fra:[56,2450,3705], fuj:[1,49,231], + fuk:[5,50,1330], // QTnet QD3 has 14 networks, BBIX Fukuoka is there; the rest est. gbe:[1,2,39], gdl:[4,22,814], + gdx:[1,2,6683], // est. gua:[5,16,103], gum:[6,28,11], gyn:[5,28,9693], ham:[26,228,3705], + hav:[0,0,8], // est.: no neutral data center + hba:[2,10,3196], // est. hel:[23,232,427], + hfx:[3,20,2595], // est. hir:[1,0,11], hkg:[57,1107,1514], hnl:[7,33,33300], @@ -87,15 +107,20 @@ const CITY_PDB={ icn:[37,201,1197], igu:[5,26,124], ist:[28,334,1290], + ivc:[1,2,755], // est. + jam:[0,0,2], // est. jed:[5,25,220], jib:[3,19,5], jkt:[98,3015,4108], jnb:[14,561,879], + jnu:[1,2,33300], // est. jpa:[4,18,9693], kcy:[22,313,33300], kgl:[5,14,34], khi:[7,15,488], + kin:[2,10,30], // est. kla:[2,18,71], + krs:[3,15,448], // est. kul:[20,210,434], kyv:[33,506,2342], lad:[8,27,79], @@ -115,6 +140,7 @@ const CITY_PDB={ mao:[7,15,9693], mba:[4,176,274], mcp:[2,0,9693], + mct:[3,25,45], // Equinix MC1 and WCS; presences est. mcz:[1,5,9693], mde:[2,18,598], mel:[20,395,3196], @@ -122,54 +148,71 @@ const CITY_PDB={ mgf:[4,9,9693], mia:[27,553,33300], mil:[29,728,1534], + mle:[1,3,15], // est. + mmk:[2,4,6683], // est. mnl:[17,352,750], mos:[49,632,6683], mpm:[7,20,36], mrs:[8,273,2249], + mru:[3,20,60], // est. mtl:[35,283,2595], mty:[5,27,814], muc:[22,230,3705], mvd:[1,2,53], + nas:[1,4,20], // est. nat:[1,3,9693], nbo:[9,283,274], nou:[2,2,19], nyc:[96,1322,33300], + ome:[0,0,33300], // est. oos:[5,22,443], osa:[19,229,1330], osl:[20,209,448], ott:[6,21,2595], pan:[8,26,158], par:[77,1528,2249], + pcn:[0,0,0], // est.: no network of its own + pdl:[1,3,187], // est. pek:[10,15,6717], per:[12,248,3196], phx:[26,279,33300], + pkc:[1,2,6683], // est. pmo:[3,46,1534], pmw:[3,8,9693], poa:[22,120,9693], pom:[2,0,46], + pos:[2,10,35], // est. ppg:[0,0,2], ppt:[0,0,6], prg:[24,336,775], + prr:[0,0,2595], // est. pvh:[3,4,9693], + pvs:[0,0,6683], // est. qro:[11,144,814], + rai:[1,3,8], // est. rao:[6,3,9693], rbr:[0,0,9693], rec:[6,31,9693], rek:[15,51,93], ria:[2,2,9693], rio:[33,577,9693], + rix:[8,60,330], // 8 listed, Perses 2 has 19 networks; presences est. rom:[12,213,1534], ror:[0,0,4], ruh:[8,29,220], + run:[3,15,15], // est. sao:[70,1875,9693], scl:[36,274,450], + sdq:[4,25,90], // est. sea:[37,539,33300], + sez:[1,4,20], // est. sgn:[6,36,1068], sha:[11,27,6717], sin:[58,1271,782], sjc:[57,1048,33300], sjo:[8,6,128], sjp:[2,4,9693], + sju:[5,40,60], // est. slc:[22,202,33300], slz:[1,6,9693], sof:[15,451,889], @@ -180,16 +223,21 @@ const CITY_PDB={ svg:[2,14,448], syd:[40,979,3196], tbu:[0,0,5], + tci:[3,30,1341], // est. the:[2,1,9693], + tik:[0,0,6683], // est. tll:[7,80,256], + tnr:[1,4,25], // est. tok:[58,917,1330], tor:[46,509,2595], tpe:[15,274,500], tun:[2,0,30], uio:[9,16,287], + uus:[1,3,6683], // est. van:[13,214,2595], vie:[30,377,860], vix:[6,30,9693], + vvo:[5,25,6683], // est. waw:[25,855,2743], wdh:[1,2,22], zrh:[38,535,1209], diff --git a/tests/regions.test.js b/tests/regions.test.js index 139c27f..875f3a1 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -1076,7 +1076,12 @@ test('prices follow real connectivity: thin markets cost more, hubs stay put', ( const { ev, errors } = load(); start(ev); assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(CITY_PDB).filter(c=>!CITY[c]))')), [], 'every entry is a city on the map'); - assert.ok(ev('Object.keys(CITY_PDB).length') >= 190, 'real-world data for most cities'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(CITIES.filter(c=>!CITY_PDB[c.id]).map(c=>c.id))')), [], 'every city has data, so none keeps the plain price by accident'); + assert.ok(ev('Object.values(CITY_PDB).every(q=>Array.isArray(q)&&q.length===3&&q.every(x=>Number.isInteger(x)&&x>=0)&&q[1]>=0)'), '[facilities, presences, ASNs], whole numbers'); + // The cities that used to have none: thin markets cost more than Frankfurt, and the Arctic has no neutral data center. + for (const c of ['dus', 'rix', 'mct', 'mle', 'fuk', 'sju', 'kin', 'anc', 'tik']) assert.ok(ev(`txComp('${c}')`) > 1, `${c} is no hub`); + for (const c of ['brw', 'tik', 'pvs', 'hav']) assert.equal(ev(`colo('${c}')`), 1.5, `${c}: no carrier-neutral data center`); + assert.ok(ev("txComp('dus')") < ev("txComp('rix')") && ev("txComp('rix')") < ev("txComp('mle')"), 'Düsseldorf, Riga, Malé: ever thinner'); // A city without data keeps the plain regional price. assert.equal(ev("(()=>{const q=CITY_PDB.fra;delete CITY_PDB.fra;const r=[txComp('fra'),colo('fra'),popMo('fra')];CITY_PDB.fra=q;return r.join()})()"), `1,1,${ev('POP_MO')}`); assert.equal(ev("regionMult('syd')"), ev('AU_TRANSIT'), 'Australia keeps its hand-set transit price'); From ed4d029ba1d69009c6da10ac0de9a33ea8f4d40e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:42:35 +0100 Subject: [PATCH 37/64] CHANGELOG: connectivity prices without naming data providers --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c2bd70..3c03ace 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,7 @@ All notable changes to this project are documented here. The project follows - Glowball Sakura Lager joins the map: a Tier 2 carrier in the big hubs of the US, Europe and Asia-Pacific that sells transit, takes PNIs and peers openly wherever it is. It is not a Tier 1, so it buys its own transit from three of them, while 13 smaller networks in its regions buy theirs from it, and one PNI with it reaches about 3% of all traffic. Far from home, in Asia and New Zealand, it charges more than the locals, and it sells no transit in Australia. - Check a selected link’s redundancy against current demand: see disconnected endpoints, additional service loss and full fallback links without changing the live network. - Links can now use a custom routing metric, set either as a multiplier or as an exact cost. Pick Custom under Routing metric to fine-tune where your traffic goes; it explains how a link's cost is worked out and what each preset comes to on that link. -- Prices now follow how connected each city really is, based on PeeringDB and Hurricane Electric data. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices. +- Prices now follow how connected each city really is, based on public peering and routing data. Every city on the map now has it, from Düsseldorf and Riga to Malé, the Caribbean and the Russian Arctic. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices. - Attacks are more varied: sizes, lengths and ingress ports change from one attack to the next, and several can hit at once. Hosting game servers or cloud gaming makes attacks more frequent, as it does in real life. - The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels. - Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. From 499862b140e1814f2f2c2e012c511ada413717f3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:47:19 +0100 Subject: [PATCH 38/64] Redundancy check routes once, against the live routing (#62) --- src/game/93-ui/70-link-panels.js | 7 ++++--- tests/link-trial.test.js | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 tests/link-trial.test.js diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 85a3af8..9167cb4 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -34,10 +34,11 @@ function vxcPanel(l){ return h; } function prefCtl(kind,id,cur){cur=cur||'normal';return `
${tr('common.egress')}${Object.keys(PREF).map(v=>btn(PREF[v],'setPref',{kind,id,v},cur===v?'pink sm':'ghost sm')).join('')}
`;} -// Trial routing is isolated from the live save, counters and scenic-route memory. +// Trial routing is isolated from the live save, counters and scenic-route memory. "Before" is the live routing, which +// after() keeps current, so a check costs one compute() on a big network, not two. function linkTrial(id){const save=S,live=R,hot=UI.hotMap,cache=TE_CACHE; - try{S=JSON.parse(JSON.stringify(save));const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return null; - compute();const before=R;l.cut=S.day+1;compute(); + try{const l0=save.links.find(x=>x.id===id);if(!l0||linkDown(l0))return null; + S=JSON.parse(JSON.stringify(save));const l=S.links.find(x=>x.id===id),before=live;l.cut=S.day+1;compute(); const allowed=new Set(Object.keys(S.pops).filter(popUp).concat(remoteCities())),adj={}; for(const x of S.links)if(!linkDown(x)&&allowed.has(x.a)&&allowed.has(x.b)){(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];for(let i=0;i { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}]"); + ev("S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0},{id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0}];compute()"); + ev("window.__n=0;window.__c=compute;compute=function(){window.__n++;return window.__c.apply(this,arguments);}"); + const t = JSON.parse(ev("JSON.stringify(linkTrial('main'))")); + assert.equal(ev('window.__n'), 1, 'one routing pass per check'); + assert.equal(t.split, false); + assert.equal(t.loss, 70); + assert.equal(ev("linkTrial('nope')"), null); + assert.equal(ev('window.__n'), 1, 'an unknown link costs nothing'); + ev('compute=window.__c'); + // the old way: route the copy twice, before and after the cut + const old = ev(`(()=>{const save=S,live=R;try{S=JSON.parse(JSON.stringify(save));compute();const b=R;S.links[0].cut=S.day+1;compute(); + const g=c=>Math.max(0,(b.citySrv[c]||0)-(R.citySrv[c]||0)),l2=Math.max(0,(b.l2.circuit||0)-(R.l2.circuit||0)); + return Object.keys(S.pops).reduce((a,c)=>a+(g(c)>.01?g(c):0),0)+(l2>.01?l2:0);}finally{S=save;R=live;}})()`); + assert.equal(t.loss, old); + assert.deepEqual(errors, []); +}); From 9902599a23f8ea4209bc8b4a590cfd95837c888a Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:48:11 +0100 Subject: [PATCH 39/64] Puzzles: main-game toasts and buttons no longer reach into a puzzle Toasts are cleared when a puzzle starts and when you leave it, and every main-game action (ops, inbox, bank, building, routers and the rest) does nothing while a puzzle is on; only the puzzle's own actions, menus and settings work there. --- src/game/60-features/92-puzzles.js | 6 ++++-- src/game/90-actions/95-puzzles.js | 5 +++++ tests/puzzles.test.js | 31 ++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index 91f156b..01f4b13 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -73,6 +73,8 @@ function pzWeekly(dt){const key=pzWeekKey(dt||new Date());let r=hstr('puzzle|'+k function pzStreak(p,key){const st=p.streak;if(st.last===key)return;st.n=st.last&&st.last===pzPrevKey(key)?st.n+1:1;st.last=key;st.best=Math.max(st.best,st.n);} function pzShareText(e){const P=S.pz;return tr('puzzles.share_line',{what:P.id==='weekly'?P.key:pzName(pzDef(P.id)),stars:pzStarStr(e.stars),spend:fmt$(e.spend)});} // ---------- entering and leaving ---------- +// Toasts from one world never carry over into the other (their buttons act on the S they came from). +const pzToastsClear=()=>{$('toasts').textContent='';}; // The running game gets its usual save first, so leaving the puzzle can load it back exactly as booting does. A huge // save is compressed in the background and may not have landed yet, so the game object is kept in memory too. function pzFlush(){save(true);UI.pzKeep=UI.gzBusy||saveFailing()?S:null;} @@ -80,13 +82,13 @@ function pzBegin(def){if(!def)return; const go=()=>{newGame(pzName(def),def.cities[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:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null}; UI.pzHist=[];UI.pzTop=0;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null; - $('dash').hidden=true;$('bankBox').hidden=true;closeModal();document.body.classList.add('pz'); + $('dash').hidden=true;$('bankBox').hidden=true;closeModal();pzToastsClear();document.body.classList.add('pz'); compute();pzCam();renderAll();track('puzzle_'+def.id); toast(`${esc(pzName(def))}
${tr('puzzles.connect_list',{list:def.cities.map(c=>CITY[c].name).join(', ')})}`,'goal');}; 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;document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; +function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=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){S=null;UI.started=false;}}} renderAll();showTitle();} diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 41667e0..24701cb 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -24,3 +24,8 @@ Object.assign(ACT,{ const copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'),copy=()=>{try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}}; if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}copy();track('puzzle_share');}, }); +// A puzzle is its own S: a leftover main-game button (an old toast, a stale panel, a shortcut) must not build, buy or +// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. This file is the +// last of the actions, so every one is here to wrap. +const PZ_ACTS=new Set(['animSet','closeModal','closePanel','help','helpClose','install','keepPlaying','langSet','menu','mute','prefSet','puzzleDoor','puzzleMenu','selLink','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); +for(const k of Object.keys(ACT))if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k)){const f=ACT[k];ACT[k]=a=>pzOn()?undefined:f(a);} diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index c99d41b..40f0df5 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -348,3 +348,34 @@ test('best spend: kept for the best star count, and a cheaper build at the same assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`))); assert.deepEqual(errors, []); }); + +test('main-game toasts and leftover buttons do nothing in a puzzle', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true)"); + ev("toast('main game news','bad',[{l:'Fix',act:'opsOpen',args:{}}]);save(true)"); + assert.ok(ev("document.querySelectorAll('#toasts .toast').length") > 0); + const before = ev("localStorage.getItem('sot-save-v1')"); + ev("ACT.pzStart({id:'hello'})"); + assert.equal(ev("[...document.querySelectorAll('#toasts .toast')].filter(t=>/main game news/.test(t.textContent)).length"), 0, 'main-game toasts are cleared'); + ev("ACT.pzPop({city:'lon'})"); + const st = () => ev("JSON.stringify({p:S.pops,l:S.links.length,c:S.cash,m:S.mode,te:!!S.te,ops:S.ops,sc:S.scrubs.length,dash:$('dash').hidden,bank:$('bankBox').hidden,left:$('left').hidden,modal:$('modal').hidden,cam:[cam.x,cam.y]})"); + const s0 = st(); + for (const a of ["opsOpen({})", "inbox({})", "leftTab({t:'noc'})", "focusCity({city:'par'})", "fixInc({id:'x'})", "custGo({id:'x'})", "bank({})", "dash({})", + "exportSave({})", "launchBB({city:'lon'})", "ad({city:'lon'})", "addRouter({city:'lon'})", "upRouter({city:'lon'})", "addSite({city:'lon'})", "buyTE({})", + "buildScrub({city:'lon',tier:0})", "buildPop({city:'par'})", "buyTransit({city:'lon',net:'cog',tier:1})", "scenarios({})", "share({})", "importGo({})", "cont({})", "start({})", "newgame({})"]) { + ev('ACT.' + a); + assert.equal(st(), s0, `${a} does nothing in a puzzle`); + } + assert.equal(ev('S.mode'), 'puzzle'); + // A leftover toast button is a no-op too, through the real click path. + ev("toast('stray','',[{l:'Go',act:'opsOpen',args:{}}]);document.querySelector('#toasts [data-act=opsOpen]').click()"); + assert.equal(st(), s0); + ev("toast('puzzle news','good')"); + ev('ACT.pzLeave({})'); + assert.equal(ev("document.querySelectorAll('#toasts .toast').length"), 0, 'puzzle toasts do not follow you home'); + assert.equal(ev("localStorage.getItem('sot-save-v1')"), before); + // Back in the main game, the same actions work again. + ev("ACT.addRouter({city:'ams'})"); + assert.equal(ev('S.pops.ams.routers'), 2); + assert.deepEqual(errors, []); +}); From 28743698a37c48e33651b2d473bbb87cad0bb353 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:50:08 +0100 Subject: [PATCH 40/64] Puzzles: a city to avoid reads as a rule You cannot build in it anyway, so the card shows "Rule: not via Frankfurt" instead of a goal that could never be failed. --- site/i18n/de.js | 2 +- site/i18n/es.js | 2 +- site/i18n/fr.js | 2 +- site/i18n/it.js | 2 +- site/i18n/pt.js | 2 +- src/game/95-modals/95-puzzles.js | 4 ++-- src/i18n/en.js | 2 +- src/styles/70-puzzles.css | 2 +- tests/puzzles.test.js | 12 ++++++++++++ 9 files changed, 21 insertions(+), 9 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 184b824..150a6db 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2886,7 +2886,6 @@ "puzzles.no_budget_star_on_the_house":"kein Budget: ⭐ geht aufs Haus", "puzzles.no_cable_lands_in_both_try":"Kein Kabel landet in {a} und {b}. Versuch es mit einem Trittstein dazwischen.", "puzzles.no_clock_no_bills_nothing_breaks":"Keine Uhr, keine Rechnungen, nichts geht kaputt. Verbinde die Städte und hol dir drei Sterne: unter Budget, und noch verbunden, wenn irgendein Link durchtrennt wird.", -"puzzles.no_pop_in_list":"Kein POP in {list}", "puzzles.no_subsea":"kein Seekabel", "puzzles.no_subsea_cables":"Keine Seekabel", "puzzles.nobody_ever_got_fired_for_buying":"Für 100G ist noch nie jemand gefeuert worden.", @@ -2913,6 +2912,7 @@ "puzzles.ring":"Ring", "puzzles.ring_of_fire":"Ring of Fire", "puzzles.rock_solid_and_gold_plated_the":"Felsenfest und vergoldet. Der CFO hat Fragen.", +"puzzles.rule_not_via_list":"Regel: nicht über {list}", "puzzles.samba_sprint":"Samba-Sprint", "puzzles.same_puzzle_for_everyone_this_week":"Diese Woche für alle dasselbe Puzzle", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Gleicher Graben (billiger, ein Bagger kappt beide)", diff --git a/site/i18n/es.js b/site/i18n/es.js index b32aea6..ef5b2cf 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2884,7 +2884,6 @@ "puzzles.no_budget_star_on_the_house":"sin presupuesto: ⭐ invita la casa", "puzzles.no_cable_lands_in_both_try":"Ningún cable llega a {a} y a {b}. Prueba con una escala entre medias.", "puzzles.no_clock_no_bills_nothing_breaks":"Sin reloj, sin facturas, nada se rompe. Conecta las ciudades y ve a por tres estrellas: bajo presupuesto, y aún conectado si se corta cualquier enlace.", -"puzzles.no_pop_in_list":"Ningún POP en {list}", "puzzles.no_subsea":"sin submarinos", "puzzles.no_subsea_cables":"Sin cables submarinos", "puzzles.nobody_ever_got_fired_for_buying":"A nadie lo han despedido nunca por comprar 100G.", @@ -2911,6 +2910,7 @@ "puzzles.ring":"anillo", "puzzles.ring_of_fire":"Anillo de fuego", "puzzles.rock_solid_and_gold_plated_the":"A prueba de bombas, y bañado en oro. El director financiero tiene preguntas.", +"puzzles.rule_not_via_list":"Regla: sin pasar por {list}", "puzzles.samba_sprint":"Sprint de samba", "puzzles.same_puzzle_for_everyone_this_week":"El mismo puzle para todos esta semana", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Misma zanja (más barata, una retroexcavadora corta las dos)", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c13b174..8af1595 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2884,7 +2884,6 @@ "puzzles.no_budget_star_on_the_house":"sans budget : ⭐ offerte par la maison", "puzzles.no_cable_lands_in_both_try":"Aucun câble n’atterrit à la fois à {a} et à {b}. Essaie une escale entre les deux.", "puzzles.no_clock_no_bills_nothing_breaks":"Pas d’horloge, pas de factures, rien ne casse. Relie les villes, puis vise trois étoiles : sous le budget, et toujours relié si n’importe quel lien est coupé.", -"puzzles.no_pop_in_list":"Aucun POP à {list}", "puzzles.no_subsea":"pas de sous-marin", "puzzles.no_subsea_cables":"Pas de câbles sous-marins", "puzzles.nobody_ever_got_fired_for_buying":"Personne ne s’est jamais fait virer pour avoir acheté du 100G.", @@ -2911,6 +2910,7 @@ "puzzles.ring":"anneau", "puzzles.ring_of_fire":"Ceinture de feu", "puzzles.rock_solid_and_gold_plated_the":"Solide comme un roc, et plaqué or. Le DAF a des questions.", +"puzzles.rule_not_via_list":"Règle : pas par {list}", "puzzles.samba_sprint":"Sprint samba", "puzzles.same_puzzle_for_everyone_this_week":"Le même puzzle pour tout le monde cette semaine", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Même tranchée (moins cher, une pelleteuse coupe les deux)", diff --git a/site/i18n/it.js b/site/i18n/it.js index ce49ce3..d36d2bd 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2884,7 +2884,6 @@ "puzzles.no_budget_star_on_the_house":"senza budget: ⭐ offerta dalla casa", "puzzles.no_cable_lands_in_both_try":"Nessun cavo approda sia a {a} che a {b}. Prova con una tappa in mezzo.", "puzzles.no_clock_no_bills_nothing_breaks":"Niente orologio, niente bollette, non si rompe niente. Collega le città, poi punta alle tre stelle: sotto budget, e ancora collegato se si taglia un link qualsiasi.", -"puzzles.no_pop_in_list":"Nessun POP a {list}", "puzzles.no_subsea":"niente sottomarini", "puzzles.no_subsea_cables":"Niente cavi sottomarini", "puzzles.nobody_ever_got_fired_for_buying":"Nessuno è mai stato licenziato per aver comprato 100G.", @@ -2911,6 +2910,7 @@ "puzzles.ring":"anello", "puzzles.ring_of_fire":"Cintura di fuoco", "puzzles.rock_solid_and_gold_plated_the":"Solida come una roccia, e placcata d’oro. Il CFO ha delle domande.", +"puzzles.rule_not_via_list":"Regola: niente passaggi da {list}", "puzzles.samba_sprint":"Sprint di samba", "puzzles.same_puzzle_for_everyone_this_week":"Lo stesso puzzle per tutti questa settimana", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Stesso scavo (più economico, una ruspa li taglia tutti e due)", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index dca69b7..d96b22d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2884,7 +2884,6 @@ "puzzles.no_budget_star_on_the_house":"sem orçamento: ⭐ por conta da casa", "puzzles.no_cable_lands_in_both_try":"Nenhum cabo chega a {a} e a {b}. Tente uma escala no meio.", "puzzles.no_clock_no_bills_nothing_breaks":"Sem relógio, sem contas, nada quebra. Conecte as cidades e busque três estrelas: dentro do orçamento, e ainda conectado se qualquer link for cortado.", -"puzzles.no_pop_in_list":"Nenhum POP em {list}", "puzzles.no_subsea":"sem submarino", "puzzles.no_subsea_cables":"Sem cabos submarinos", "puzzles.nobody_ever_got_fired_for_buying":"Ninguém nunca foi demitido por comprar 100G.", @@ -2911,6 +2910,7 @@ "puzzles.ring":"anel", "puzzles.ring_of_fire":"Anel de Fogo", "puzzles.rock_solid_and_gold_plated_the":"Sólida como rocha, e banhada a ouro. O CFO tem perguntas.", +"puzzles.rule_not_via_list":"Regra: sem passar por {list}", "puzzles.samba_sprint":"Corrida de samba", "puzzles.same_puzzle_for_everyone_this_week":"O mesmo puzzle para todo mundo nesta semana", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Mesma vala (mais barata, uma retroescavadeira corta as duas)", diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index 3f67961..dd2f9c1 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -4,7 +4,6 @@ function pzTwistTxt(t){const P=S.pz; if(t.k==='sub')return tr('puzzles.no_subsea_cables'); if(t.k==='ring')return tr('puzzles.one_ring_through_every_pop'); if(t.k==='g')return tr('puzzles.every_link_n_g_or_more',{n:P.minG}); - if(t.k==='avoid')return tr('puzzles.no_pop_in_list',{list:P.avoid.map(c=>CITY[c].name).join(', ')}); const [a,b,ms]=P.lat;return isFinite(t.ms)?tr('puzzles.a_to_b_under_ms_now',{a:CITY[a].name,b:CITY[b].name,ms,now:t.ms.toFixed(1)}):tr('puzzles.a_to_b_under_ms',{a:CITY[a].name,b:CITY[b].name,ms});} // The short version, for the puzzle list. function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} @@ -17,7 +16,8 @@ function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hi if(d)h+=`

${esc(d.j)}

`; h+=`
${star(e.goal,tr('puzzles.goal'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`; h+=`
${e.marks.map(m=>`${esc(CITY[m.c].name)}${m.st===2?' ✓':m.st===1?' ·':' …'}`).join('')}
`; - for(const t of e.tw)h+=`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; + // Cities to avoid cannot be built in at all, so they read as a rule, not as a box to tick. + for(const t of e.tw)h+=t.k==='avoid'?`
🚫 ${tr('puzzles.rule_not_via_list',{list:P.avoid.map(c=>esc(CITY[c].name)).join(', ')})}
`:`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; const sp=fmt$(e.spend); h+=P.budget?`
${tr('puzzles.spent_x_of_y',{x:sp,y:fmt$(P.budget)})}${e.cheap?'✓':'✗'}
` :`
${tr('puzzles.spent_x',{x:sp})}${tr('puzzles.no_budget_star_on_the_house')}
`; diff --git a/src/i18n/en.js b/src/i18n/en.js index b4943a0..dd1cac2 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2885,7 +2885,6 @@ "puzzles.no_budget_star_on_the_house":"no budget: ⭐ on the house", "puzzles.no_cable_lands_in_both_try":"No cable lands in both {a} and {b}. Try a stepping stone in between.", "puzzles.no_clock_no_bills_nothing_breaks":"No clock, no bills, nothing breaks. Connect the cities, then go for three stars: under budget, and still connected when any one link is cut.", -"puzzles.no_pop_in_list":"No POP in {list}", "puzzles.no_subsea":"no subsea", "puzzles.no_subsea_cables":"No subsea cables", "puzzles.nobody_ever_got_fired_for_buying":"Nobody ever got fired for buying 100G.", @@ -2912,6 +2911,7 @@ "puzzles.ring":"ring", "puzzles.ring_of_fire":"Ring of Fire", "puzzles.rock_solid_and_gold_plated_the":"Rock solid, and gold plated. The CFO has questions.", +"puzzles.rule_not_via_list":"Rule: not via {list}", "puzzles.samba_sprint":"Samba Sprint", "puzzles.same_puzzle_for_everyone_this_week":"Same puzzle for everyone this week", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Same trench (cheaper, one backhoe cuts both)", diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index 20fa6b1..061c5d1 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -7,7 +7,7 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzs span small{font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em}.pzs span.on{filter:none;opacity:1;background:#FFF3C4;transform:scale(1.05)} .pzck{display:flex;flex-wrap:wrap;gap:5px;margin:6px 0}.pzc{font-weight:900;font-size:12px;border:2px solid var(--ink);border-radius:999px;padding:1px 8px;background:#fff} .pzc.s1{background:#FFE3F0}.pzc.s2{background:var(--ok);color:#fff} -.pztw{font-size:12.5px;font-weight:800;color:var(--bad);margin:3px 0}.pztw.ok{color:var(--eye)} +.pztw{font-size:12.5px;font-weight:800;color:var(--bad);margin:3px 0}.pztw.ok{color:var(--eye)}.pztw.rule{color:var(--ink2)} .pzbud{margin:6px 0}.pzbud .kv{font-size:12.5px} .pzn1{font-size:12.5px;font-weight:800;margin:6px 0;padding:4px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} .pzn1.on{border-color:var(--ok);background:#DFFBEA;color:var(--ink);animation:pzglow 1.6s ease-in-out infinite}.pzn1.bad{border-color:var(--warn);background:#FFF4D6;color:var(--ink)} diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 40f0df5..27597eb 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -379,3 +379,15 @@ test('main-game toasts and leftover buttons do nothing in a puzzle', () => { assert.equal(ev('S.pops.ams.routers'), 2); assert.deepEqual(errors, []); }); + +test('a city to avoid reads as a rule, not a goal that can fail', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('nofra'))"); + const tw = () => ev("[...document.querySelectorAll('#pzBox .pztw')].map(x=>x.className+'|'+x.textContent).join('\\n')"); + assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/); + assert.doesNotMatch(tw(), /[✓✗].*Frankfurt/); + build(ev, REF.nofra.three); + assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/, 'still a rule once solved'); + assert.equal(evalP(ev).stars, 3); + assert.deepEqual(errors, []); +}); From 0c4d9c08691bf08b7b331b8e9a368ffaeec76bd1 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:51:21 +0100 Subject: [PATCH 41/64] Infra tab shows the redundancy kit as one line instead of repeating its rows (#192) --- CHANGELOG.md | 2 +- src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/55-utilities.js | 5 +++++ tests/utilities.test.js | 21 +++++++++++++++++++++ 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c03ace..ab1a660 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,7 @@ All notable changes to this project are documented here. The project follows - Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation. - Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf. - Order PNIs with one network or every network at all shared POPs from the NOC Traffic tab: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time. -- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. +- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. A POP's Infra tab shows the redundancy kit as one line with its price, above the rows it fills in. - Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, and the intern writes one line a day in the NOC (#98, #100, #102, #181, #185, #192, #177). - Open a new city from a template in one tap: POP, broadband, transit, an IX port and the redundancy kit, priced up front, with your standing orders taking it from there (#98, #192). - Auto-accept and auto-pay repairs are now the intern's sales and repair orders and run once a game day; saved games keep both switched on, and they start working once you hire an intern. The bulk peering and PNI batches moved into the Ops sheet, next to the orders that repeat them (#185, #181, #192). diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 4c068b7..b816232 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -67,7 +67,7 @@ function cityPanel(c){ ${have.length?btn(tr('common.remove'),'rmCache',{id:(have.find(x=>x.site==='b')||have[0]).id},'ghost sm'):''}${btn(have.length?tr('common.box'):tr('common.request'),'cache',{city:c,net:n.id},'sm',!ok)}
${S.pops[c].site2&&have.length?(()=>{const nb=have.filter(x=>x.site==='b').length,na=have.length-nb;return `
${tr('city_panel.boxes_a_in_a_b_in',{a:na,b:nb})}${na?btn(tr('city_panel.move_one_to_b'),'cacheSite',{city:c,net:n.id,s:'b'},'ghost sm'):''}${nb?btn(tr('city_panel.move_one_to_a'),'cacheSite',{city:c,net:n.id,s:'a'},'ghost sm'):''}
`;})():''}`;} h+=``; }else{ - h+=utilityKitHtml(c); + h+=utilityKitLine(c); const ls=S.links.filter(l=>l.a===c||l.b===c); const rt=p.routers||1,g=p.rgen||0,G=RG[g],nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||nodeCap(c),Ni=g===mainRG(G.cls)?mainRG(G.cls+1):-1,N=Ni>=0?RG[Ni]:null,pu=portsUsed(c),pm=portsMax(c); h+=`

${tr('common.routers')}

${tr('city_panel.the_model_sets_your_fastest')}

diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js index 2d50105..3398392 100644 --- a/src/game/93-ui/55-utilities.js +++ b/src/game/93-ui/55-utilities.js @@ -5,6 +5,11 @@ function utilityKitHtml(city,modal=false){const q=utilityKit(city);if(!q)return

${tr('utilities.cache_moves',{n:q.moves.length})}

${q.cost||q.moves.length?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.apply_kit'),'utilityKit',{city,cost:q.cost,modal},'pink',q.cost>0&&S.cash`:`

${tr('utilities.kit_balanced')}

`}

${tr('utilities.redundancy_note')}

${utilityCachesHtml(city,modal)}`;} +// In the Infra tab (#192): one line and the button, since the generator, second site, routers and caches each have +// their own rows below; the full kit with its caches is in Utilities. +function utilityKitLine(city){const q=utilityKit(city);if(!q)return '';const todo=q.cost||q.moves.length; + return `

${tr('utilities.redundancy_kit')} · ${todo?tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})+(q.moves.length?' · '+tr('utilities.cache_moves',{n:q.moves.length}):''):tr('utilities.kit_balanced')}

+
${todo?btn(tr('utilities.apply_kit'),'utilityKit',{city,cost:q.cost},'pink sm',q.cost>0&&S.cash
`;} function utilityCachesHtml(city,modal=false){const q=utilityCaches(city);if(!q)return ''; return `

${tr('common.embedded_caches')}

${tr('utilities.cache_note')}

${tr('utilities.cache_quote',{n:q.add.length,mo:fmt$(q.mo)})}

diff --git a/tests/utilities.test.js b/tests/utilities.test.js index d096951..feba9a5 100644 --- a/tests/utilities.test.js +++ b/tests/utilities.test.js @@ -136,3 +136,24 @@ test('route-server batch leaves peering policy and player-owned exchanges alone' assert.equal(ev('S.rs.fra'), false, 'owned exchange has no join-route-server control'); assert.deepEqual(errors, []); }); + +test('#192 the Infra tab shows the kit as one line, without repeating its rows', t => { + for (const w of [1280, 360]) { + const { ev, dom, errors } = setup(t); + ev(`window.innerWidth=${w}`); + ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];compute();selectCity('fra');ACT.tab({t:'links'})"); + const body = dom.window.document.getElementById('panelBody'); + const txt = body.textContent; + assert.match(txt, /PoP redundancy kit · One-off: /); + assert.doesNotMatch(txt, /Second site(None|Installed)/, 'no second copy of the second-site row'); + assert.doesNotMatch(txt, /At least two routers/, 'no second copy of the routers row'); + assert.doesNotMatch(txt, /Request missing caches/, 'caches are in the Peering tab and Utilities'); + assert.equal(body.querySelectorAll('section h3').length, [...body.querySelectorAll('section h3')].filter(h => h.textContent !== 'PoP redundancy kit').length); + assert.equal(txt.split('Backup generator').length - 1, 1, 'the generator shows once, in Power'); + assert.ok(body.querySelector('[data-act="utilityKit"]'), 'the kit is one tap away'); + body.querySelector('[data-act="utilities"]').click(); + assert.match(dom.window.document.getElementById('modalCard').textContent, /At least two routers/, 'the full kit is in Utilities'); + assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra'); + assert.deepEqual(errors, [], `${w}px`); + } +}); From f4980dc098cc5f175c43e66b83d6752680918488 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:56:55 +0100 Subject: [PATCH 42/64] Puzzles: bigger buttons and clearer city chips on phones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On phones the puzzle card's Undo, Reset, Back and menu buttons are 40 px touch targets and stay pinned at the foot of the sheet when longer languages make it scroll. Goal cities show a leading mark (○ to reach, ◐ POP open, ✓ joined) instead of a trailing one that looked cut off. --- src/game/95-modals/95-puzzles.js | 3 ++- src/styles/70-puzzles.css | 7 ++++++- tests/puzzles.test.js | 20 ++++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index dd2f9c1..9a1599b 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -15,7 +15,8 @@ function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hi let h=`
${pk?esc(pk.n):tr('puzzles.weekly_puzzle')}

${esc(pzName(d||P))}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; if(d)h+=`

${esc(d.j)}

`; h+=`
${star(e.goal,tr('puzzles.goal'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`; - h+=`
${e.marks.map(m=>`${esc(CITY[m.c].name)}${m.st===2?' ✓':m.st===1?' ·':' …'}`).join('')}
`; + // ○ still to reach, ◐ has a POP, ✓ joined up. A leading mark, so nothing looks cut off. + h+=`
${e.marks.map(m=>` ${esc(CITY[m.c].name)}`).join('')}
`; // Cities to avoid cannot be built in at all, so they read as a rule, not as a box to tick. for(const t of e.tw)h+=t.k==='avoid'?`
🚫 ${tr('puzzles.rule_not_via_list',{list:P.avoid.map(c=>esc(CITY[c].name)).join(', ')})}
`:`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; const sp=fmt$(e.spend); diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index 061c5d1..8a12495 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -6,6 +6,7 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzs{display:flex;gap:6px;margin:6px 0}.pzs span{flex:1;display:flex;flex-direction:column;align-items:center;border:2.5px solid var(--ink);border-radius:11px;padding:3px 0;font-size:20px;filter:grayscale(1);opacity:.45;transition:transform .25s,opacity .25s} .pzs span small{font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em}.pzs span.on{filter:none;opacity:1;background:#FFF3C4;transform:scale(1.05)} .pzck{display:flex;flex-wrap:wrap;gap:5px;margin:6px 0}.pzc{font-weight:900;font-size:12px;border:2px solid var(--ink);border-radius:999px;padding:1px 8px;background:#fff} +.pzc i{font-style:normal} .pzc.s1{background:#FFE3F0}.pzc.s2{background:var(--ok);color:#fff} .pztw{font-size:12.5px;font-weight:800;color:var(--bad);margin:3px 0}.pztw.ok{color:var(--eye)}.pztw.rule{color:var(--ink2)} .pzbud{margin:6px 0}.pzbud .kv{font-size:12.5px} @@ -26,6 +27,9 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB @media (max-width:760px),(max-height:500px) and (pointer:coarse){ #pzBox{top:auto;left:0;right:0;width:auto;bottom:0;max-height:min(46%,330px);border-radius:20px 20px 0 0;border-bottom:0;box-shadow:0 -3px 0 var(--ink);padding:0 12px calc(10px + env(safe-area-inset-bottom,0px))} #pzBox .grab{display:block} + #pzBox .btns .b,#pzBox .pzh .b{min-height:40px;min-width:40px;padding:4px 12px} + /* Long languages make the sheet scroll: Undo, Reset and Back stay pinned at its foot. */ + #pzBox>.btns{position:sticky;bottom:0;background:var(--paper);margin:6px -12px 0;padding:6px 12px 0;box-shadow:0 -6px 6px -6px rgba(30,38,64,.25)} #pzBox.mini{max-height:none}#pzBox.mini>:not(.grab):not(.pzh):not(.pzs){display:none} #pzBox.mini .pzs{margin-top:0} body.pz.sheet-open #pzBox{display:none} @@ -34,7 +38,8 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .pzbig{font-size:40px} } @media (orientation:landscape) and (max-height:500px) and (pointer:coarse),(orientation:landscape) and (max-width:760px) and (max-height:500px){ - #pzBox{left:auto;right:0;width:min(360px,52%);top:calc(env(safe-area-inset-top,0px) + 50px);max-height:none;border-radius:20px 0 0 0;border-right:0} + #pzBox{left:auto;right:0;width:min(360px,52%);top:calc(env(safe-area-inset-top,0px) + 50px);max-height:calc(100% - 50px - env(safe-area-inset-top,0px));overscroll-behavior:contain;border-radius:20px 0 0 0;border-right:0} + #pzBox .pzj{display:none}#pzBox .pzs span{font-size:16px;padding:1px 0} body.pz #hint{bottom:12px !important;left:30% !important} body.pz #toasts{left:8px !important;transform:none !important;width:calc(48% - 16px) !important} } diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 27597eb..4337d52 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -391,3 +391,23 @@ test('a city to avoid reads as a rule, not a goal that can fail', () => { assert.equal(evalP(ev).stars, 3); assert.deepEqual(errors, []); }); + +test('phone sheet: 40 px touch targets, pinned actions, and goal chips with a clear mark', () => { + const { ev, errors } = load(); + // jsdom has no layout: read the phone media rules from the page's stylesheet (Chromium at 360 px measures 40 px). + const rules = JSON.parse(ev(`JSON.stringify([...document.styleSheets].flatMap(s=>[...s.cssRules]).filter(r=>r.media&&/max-width: ?760px/.test(r.media.mediaText)) + .flatMap(m=>[...m.cssRules]).filter(r=>/#pzBox/.test(r.selectorText||'')).map(r=>({sel:r.selectorText,mh:r.style.getPropertyValue('min-height'),mw:r.style.getPropertyValue('min-width'),pos:r.style.getPropertyValue('position'),bottom:r.style.getPropertyValue('bottom')})))`)); + const tap = rules.find((r) => /#pzBox \.btns \.b/.test(r.sel) && /#pzBox \.pzh \.b/.test(r.sel)); + assert.ok(tap && parseFloat(tap.mh) >= 40 && parseFloat(tap.mw) >= 40, `Undo/Reset/Back/☰ are at least 40 px (${JSON.stringify(tap)})`); + const pin = rules.find((r) => /^#pzBox ?> ?\.btns$/.test(r.sel)); + assert.ok(pin && pin.pos === 'sticky' && parseFloat(pin.bottom) === 0, `the action row stays at the foot of a scrolling sheet (${JSON.stringify(pin)})`); + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));pzBegin(pzDef('braces'))"); + const chips = () => ev("[...document.querySelectorAll('#pzBox .pzc')].map(x=>x.textContent).join('|')"); + assert.equal(chips(), '○ New York|○ London|○ Dublin', 'not reached yet: a hollow mark, nothing that looks cut off'); + assert.doesNotMatch(chips(), /…/); + build(ev, [['nyc', 'lon', 'grace']]); + ev("ACT.pzPop({city:'dub'})"); + assert.equal(chips(), '✓ New York|✓ London|◐ Dublin'); + assert.ok(ev("[...document.querySelectorAll('#pzBox button')].every(b=>b.classList.contains('b'))"), 'every sheet button is a .b the rule sizes'); + assert.deepEqual(errors, []); +}); From 3fa3b3e5790f35c0e8cce30fb814e61e96ddf428 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:01:58 +0100 Subject: [PATCH 43/64] Puzzles: results pull you on to the next one After three stars, Next puzzle is the one big button (and has the focus); the results card counts the stars still to win in the pack; and when one more link within budget would earn the third star, the card and the results say so. --- site/i18n/de.js | 3 +++ site/i18n/es.js | 3 +++ site/i18n/fr.js | 3 +++ site/i18n/it.js | 3 +++ site/i18n/pt.js | 3 +++ src/game/60-features/92-puzzles.js | 8 +++++++ src/game/95-modals/95-puzzles.js | 14 +++++++----- src/i18n/en.js | 3 +++ src/styles/70-puzzles.css | 4 ++++ tests/puzzles.test.js | 34 ++++++++++++++++++++++++++++++ 10 files changed, 73 insertions(+), 5 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 150a6db..4b0b5d7 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2856,6 +2856,7 @@ "puzzles.euro_trip":"Euro-Trip", "puzzles.every_internet_starts_with_one_tube":"Jedes Internet beginnt mit einer Röhre.", "puzzles.every_link_n_g_or_more":"Jeder Link {n}G oder mehr", +"puzzles.every_star_in_this_pack_is":"Alle Sterne in diesem Paket gehören dir.", "puzzles.fat_pipes_only":"Nur dicke Rohre", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Für Architekten, die die Baggersaison verschlafen.", @@ -2878,6 +2879,7 @@ "puzzles.n_1_club":"N-1-Club", "puzzles.n_1_connect_everything_first":"N-1: erst alles verbinden", "puzzles.n_g_links":"{n}G-Links", +"puzzles.n_stars_left_in_this_pack":{"one":"Noch {n} ⭐ in diesem Paket","other":"Noch {n} ⭐ in diesem Paket"}, "puzzles.n_week_streak":{"one":"{n} Woche in Folge","other":"{n} Wochen in Folge"}, "puzzles.new_zealand_is_far_from_everything":"Neuseeland ist weit weg von allem. Genau das ist der Witz, und das Problem.", "puzzles.next_pack_unlocks_at_n":"Nächstes Paket, {pack}, ab {n}⭐", @@ -2923,6 +2925,7 @@ "puzzles.size":"Größe", "puzzles.small_calm_network_builds":"Kleine, entspannte Netzbauten", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Fast: noch ein Link, und kein Bagger kann dir was.", "puzzles.speed_runs":"Speedruns", "puzzles.spent_x":"Ausgegeben {x}", "puzzles.spent_x_of_y":"Ausgegeben {x} / {y}", diff --git a/site/i18n/es.js b/site/i18n/es.js index ef5b2cf..0b717d2 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2854,6 +2854,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Todo internet empieza con un tubo.", "puzzles.every_link_n_g_or_more":"Cada enlace de {n}G o más", +"puzzles.every_star_in_this_pack_is":"Todas las estrellas de este paquete son tuyas.", "puzzles.fat_pipes_only":"Solo tuberías gordas", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Para arquitectos que duermen tranquilos en temporada de retroexcavadoras.", @@ -2876,6 +2877,7 @@ "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1: primero conéctalo todo", "puzzles.n_g_links":"enlaces de {n}G", +"puzzles.n_stars_left_in_this_pack":{"one":"Queda {n} ⭐ en este paquete","other":"Quedan {n} ⭐ en este paquete"}, "puzzles.n_week_streak":{"one":"{n} semana seguida","other":"{n} semanas seguidas"}, "puzzles.new_zealand_is_far_from_everything":"Nueva Zelanda está lejos de todo. Esa es la gracia, y el problema.", "puzzles.next_pack_unlocks_at_n":"El siguiente pack, {pack}, se desbloquea con {n}⭐", @@ -2921,6 +2923,7 @@ "puzzles.size":"Tamaño", "puzzles.small_calm_network_builds":"Redes pequeñas y tranquilas", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Casi: un enlace más y ninguna retroexcavadora podrá contigo.", "puzzles.speed_runs":"Contrarreloj", "puzzles.spent_x":"Gastado {x}", "puzzles.spent_x_of_y":"Gastado {x} / {y}", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 8af1595..28f4001 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2854,6 +2854,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Tout internet commence par un tube.", "puzzles.every_link_n_g_or_more":"Chaque lien à {n}G ou plus", +"puzzles.every_star_in_this_pack_is":"Toutes les étoiles de ce pack sont à toi.", "puzzles.fat_pipes_only":"Gros tuyaux uniquement", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Pour les architectes qui dorment pendant la saison des pelleteuses.", @@ -2876,6 +2877,7 @@ "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1 : relie d’abord tout", "puzzles.n_g_links":"liens {n}G", +"puzzles.n_stars_left_in_this_pack":{"one":"Encore {n} ⭐ dans ce pack","other":"Encore {n} ⭐ dans ce pack"}, "puzzles.n_week_streak":{"one":"{n} semaine d’affilée","other":"{n} semaines d’affilée"}, "puzzles.new_zealand_is_far_from_everything":"La Nouvelle-Zélande est loin de tout. C’est tout l’intérêt, et tout le problème.", "puzzles.next_pack_unlocks_at_n":"Prochain pack, {pack}, à {n}⭐", @@ -2921,6 +2923,7 @@ "puzzles.size":"Taille", "puzzles.small_calm_network_builds":"Petits réseaux, tranquillement", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Presque : encore un lien et aucune pelleteuse ne pourra rien contre toi.", "puzzles.speed_runs":"Contre la montre", "puzzles.spent_x":"Dépensé {x}", "puzzles.spent_x_of_y":"Dépensé {x} / {y}", diff --git a/site/i18n/it.js b/site/i18n/it.js index d36d2bd..009e74f 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2854,6 +2854,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Ogni internet comincia con un tubo.", "puzzles.every_link_n_g_or_more":"Ogni link da {n}G o più", +"puzzles.every_star_in_this_pack_is":"Tutte le stelle di questo pacchetto sono tue.", "puzzles.fat_pipes_only":"Solo tubi grossi", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Per architetti che dormono sonni tranquilli nella stagione delle ruspe.", @@ -2876,6 +2877,7 @@ "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1: prima collega tutto", "puzzles.n_g_links":"link da {n}G", +"puzzles.n_stars_left_in_this_pack":{"one":"Ancora {n} ⭐ in questo pacchetto","other":"Ancora {n} ⭐ in questo pacchetto"}, "puzzles.n_week_streak":{"one":"{n} settimana di fila","other":"{n} settimane di fila"}, "puzzles.new_zealand_is_far_from_everything":"La Nuova Zelanda è lontana da tutto. È proprio questo il bello, e il problema.", "puzzles.next_pack_unlocks_at_n":"Il prossimo pacchetto, {pack}, si sblocca a {n}⭐", @@ -2921,6 +2923,7 @@ "puzzles.size":"Taglia", "puzzles.small_calm_network_builds":"Piccole reti, con calma", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Ci sei quasi: ancora un link e nessuna ruspa può toccarti.", "puzzles.speed_runs":"Corse contro il tempo", "puzzles.spent_x":"Speso {x}", "puzzles.spent_x_of_y":"Speso {x} / {y}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index d96b22d..0c148b8 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2854,6 +2854,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Toda internet começa com um tubo.", "puzzles.every_link_n_g_or_more":"Todo link com {n}G ou mais", +"puzzles.every_star_in_this_pack_is":"Todas as estrelas deste pacote são suas.", "puzzles.fat_pipes_only":"Só tubos grossos", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"Para arquitetos que dormem tranquilos na temporada das retroescavadeiras.", @@ -2876,6 +2877,7 @@ "puzzles.n_1_club":"Clube N-1", "puzzles.n_1_connect_everything_first":"N-1: conecte tudo primeiro", "puzzles.n_g_links":"links de {n}G", +"puzzles.n_stars_left_in_this_pack":{"one":"Falta {n} ⭐ neste pacote","other":"Faltam {n} ⭐ neste pacote"}, "puzzles.n_week_streak":{"one":"{n} semana seguida","other":"{n} semanas seguidas"}, "puzzles.new_zealand_is_far_from_everything":"A Nova Zelândia fica longe de tudo. Essa é a graça, e o problema.", "puzzles.next_pack_unlocks_at_n":"O próximo pacote, {pack}, abre com {n}⭐", @@ -2921,6 +2923,7 @@ "puzzles.size":"Tamanho", "puzzles.small_calm_network_builds":"Redes pequenas, com calma", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"Quase lá: mais um link e nenhuma retroescavadeira te alcança.", "puzzles.speed_runs":"Contra o relógio", "puzzles.spent_x":"Gasto {x}", "puzzles.spent_x_of_y":"Gasto {x} / {y}", diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index 01f4b13..79cc1a9 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -56,6 +56,14 @@ function pzEval(){const P=S.pz,ls=S.links,cs=P.cities,spend=pzSpend(); const weak=conn?units.filter(u=>{const g=pzComp(ls,u,cs[0]);return !cs.every(c=>g.has(c));}):[]; const n1=conn&&units.length>0&&!weak.length,cheap=!P.budget||spend<=P.budget; return {marks,conn,tw,goal,spend,cheap,n1,weak,stars:goal?1+(cheap?1:0)+(n1?1:0):0};} +// Two stars, and one more link within budget would survive any cut? Then the third star is close. Tries every route +// between the puzzle's cities at the smallest allowed size, so the nudge is true, not a guess. +function pzOneMore(e){const P=S.pz;if(e.stars!==2||!e.cheap||e.n1)return false;const cs=[...P.cities,...P.via],tier=P.minG?1:0,cs0=P.cities[0]; + for(const a of cs)for(const b of cs){if(a>=b)continue;for(const r of pzRoutes(a,b)){if((P.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))continue; + const div=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),cost=pzLinkCost(r,tier,div)+(S.pops[a]?0:pzPopCost(a))+(S.pops[b]?0:pzPopCost(b)); + if(e.spend+cost>P.budget)continue;const ls=[...S.links,{id:'pz?',a,b,cable:r.cab,trench:r.cab?'cab:'+r.cab:'pz?'}];if(P.ring&&!pzRingOk(ls))continue; + if([...new Set(ls.map(pzUnit))].every(u=>{const g=pzComp(ls,u,cs0);return P.cities.every(c=>g.has(c));}))return true;}} + return false;} // ---------- the weekly puzzle: the same for everyone, seeded by the ISO week like the weekly challenge ---------- function pzWeekKey(dt){const {y,w}=isoWeek(dt);return `${y}-W${String(w).padStart(2,'0')}`;} function pzPrevKey(key){const m=/^(\d{4})-W(\d{2})$/.exec(key);if(!m)return null;return pzWeekKey(new Date(+m[1],0,4+(+m[2]-2)*7));} diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index 9a1599b..bd0092b 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -22,7 +22,7 @@ function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hi const sp=fmt$(e.spend); h+=P.budget?`
${tr('puzzles.spent_x_of_y',{x:sp,y:fmt$(P.budget)})}${e.cheap?'✓':'✗'}
` :`
${tr('puzzles.spent_x',{x:sp})}${tr('puzzles.no_budget_star_on_the_house')}
`; - h+=!e.conn?`
🛡 ${tr('puzzles.n_1_connect_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut')}
`:`
⚠️ ${tr('puzzles.one_cut_splits_it_where',{where:pzUnitName(e.weak[0])})}
`; + h+=!e.conn?`
🛡 ${tr('puzzles.n_1_connect_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut')}
`:`
⚠️ ${tr('puzzles.one_cut_splits_it_where',{where:pzUnitName(e.weak[0])})}${pzOneMore(e)?`
${tr('puzzles.so_close_one_more_link_and')}`:''}
`; h+=`
${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)}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'ghost sm')}
`; if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} function pzPanel(sel){const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; @@ -56,17 +56,21 @@ function pzLinkModal(a,b,keep){const kb=pzKind(b); h+=`
${PZ_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),c=pzLinkCost(r,i,div)+pop;return ``;}).join('')}
`; 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_backhoe_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_backhoe'):!e.n1?(pzOneMore(e)?tr('puzzles.so_close_one_more_link_and'):tr('puzzles.one_backhoe_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=''; for(let i=0;i<28;i++)h+=``; return ``;} -function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(); +function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left=pzPackLeft(P),done=e.stars>=3; const row=(ok,l,v)=>`
${ok?'⭐':'☆'} ${l}${v}
`; const stars=[0,1,2].map(i=>`⭐`).join(''); openModal(`
${e.stars>=3?pzConfetti():''}
${tr('puzzles.puzzle_solved')}

${esc(pzName(pzDef(P.id)||P))}

-
${stars}

${pzLine(e)}

+
${stars}

${pzLine(e)}

${left==null?'':`

${left?trn('puzzles.n_stars_left_in_this_pack',left):tr('puzzles.every_star_in_this_pack_is')}

`} ${row(true,tr('puzzles.goal'),tr('puzzles.connected'))}${row(e.cheap,tr('puzzles.budget'),P.budget?tr('puzzles.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(P.budget)}):tr('puzzles.on_the_house'))}${row(e.n1,'N-1',e.n1?tr('puzzles.survives_any_single_cut'):tr('puzzles.one_cut_splits_it'))} -
${nx?btn(tr('puzzles.next_puzzle'),'pzStart',{id:nx.id},'pink big'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big')}${e.stars<3?btn(tr('puzzles.retry_for_3_stars'),'pzRetry',{},''):''}${btn(tr('common.share_2cd9'),'pzShare',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`); +
${nx?btn(tr('puzzles.next_puzzle')+(done?' →':''),'pzStart',{id:nx.id},'pink big pznext'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big pznext')}${!done?btn(tr('puzzles.retry_for_3_stars'),'pzRetry',{},''):''}${btn(tr('common.share_2cd9'),'pzShare',{},done?'ghost':'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`); + // Three stars: Next is the one big obvious tap (and the keyboard's default). + if(done){const b=document.querySelector('#modalCard .pznext');if(b)try{b.focus({preventScroll:true});}catch(_){}} for(let i=prev;i{sfx('star');haptic(15);},Math.max(0,i-prev)*450+150); if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);} // ---------- the list ---------- diff --git a/src/i18n/en.js b/src/i18n/en.js index dd1cac2..17189f0 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2855,6 +2855,7 @@ "puzzles.euro_trip":"Euro Trip", "puzzles.every_internet_starts_with_one_tube":"Every internet starts with one tube.", "puzzles.every_link_n_g_or_more":"Every link {n}G or more", +"puzzles.every_star_in_this_pack_is":"Every star in this pack is yours.", "puzzles.fat_pipes_only":"Fat Pipes Only", "puzzles.flash_boys":"Flash Boys", "puzzles.for_architects_who_sleep_through_backhoes":"For architects who sleep through backhoe season.", @@ -2877,6 +2878,7 @@ "puzzles.n_1_club":"N-1 Club", "puzzles.n_1_connect_everything_first":"N-1: connect everything first", "puzzles.n_g_links":"{n}G links", +"puzzles.n_stars_left_in_this_pack":{"one":"{n} ⭐ left in this pack","other":"{n} ⭐ left in this pack"}, "puzzles.n_week_streak":{"one":"{n} week in a row","other":"{n} weeks in a row"}, "puzzles.new_zealand_is_far_from_everything":"New Zealand is far from everything. That is the point, and the problem.", "puzzles.next_pack_unlocks_at_n":"Next pack, {pack}, unlocks at {n}⭐", @@ -2922,6 +2924,7 @@ "puzzles.size":"Size", "puzzles.small_calm_network_builds":"Small, calm network builds", "puzzles.smorgasbord":"Smörgåsbord", +"puzzles.so_close_one_more_link_and":"So close: one more link and a backhoe can't touch you.", "puzzles.speed_runs":"Speed Runs", "puzzles.spent_x":"Spent {x}", "puzzles.spent_x_of_y":"Spent {x} / {y}", diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index 8a12495..eeedbe3 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -19,6 +19,10 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .scn.lock{opacity:.5} .pzres{position:relative}.pzstars{display:flex;justify-content:center;gap:10px;margin:10px 0 2px} .pzbig{font-size:46px;filter:grayscale(1);opacity:.3}.pzbig.on{filter:none;opacity:1} +.pzleft{text-align:center;font-weight:900;font-size:13px;margin:2px 0 0;color:var(--ink2)} +.btns.pzdone .pznext{flex:1 1 100%;font-size:22px;padding:10px 18px 8px;animation:pznudge 1.8s ease-in-out 1.6s infinite} +@keyframes pznudge{50%{transform:translateY(-2px);box-shadow:0 5px 0 var(--ink)}} +@media (prefers-reduced-motion:reduce){.btns.pzdone .pznext{animation:none}} .pzbig.pop{animation:pzpop .5s cubic-bezier(.3,1.6,.5,1) var(--d) both} @keyframes pzpop{0%{transform:scale(0) rotate(-40deg);opacity:0}100%{transform:scale(1) rotate(0);opacity:1}} .pzconf{position:absolute;inset:-16px;pointer-events:none;overflow:hidden;z-index:2} diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 4337d52..d96acea 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -411,3 +411,37 @@ test('phone sheet: 40 px touch targets, pinned actions, and goal chips with a cl assert.ok(ev("[...document.querySelectorAll('#pzBox button')].every(b=>b.classList.contains('b'))"), 'every sheet button is a .b the rule sizes'); assert.deepEqual(errors, []); }); + +test('results pull you on: Next is the big tap after three stars, stars left in the pack, and a nudge when 3 stars are one link away', () => { + const { ev, errors } = load(); + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))"); + build(ev, REF.braces.one); + let card = ev("document.getElementById('modalCard').textContent"); + assert.equal(evalP(ev).stars, 2); + assert.match(card, /So close: one more link and a backhoe can't touch you\./, 'Dublin to New York would do it, within budget'); + assert.match(ev("document.getElementById('pzBox').textContent"), /So close/); + assert.match(card, /10 ⭐ left in this pack/, '4 puzzles × 3 stars, 2 won'); + assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')")); + assert.ok(!ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')")); + build(ev, [['dub', 'nyc', 'havf']]); + card = ev("document.getElementById('modalCard').textContent"); + assert.match(card, /9 ⭐ left in this pack/); + assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')"), 'three stars: the big Next layout'); + assert.ok(ev("document.activeElement===document.querySelector('#modalCard .pznext')"), 'the big button has the focus'); + assert.equal(ev("document.querySelector('#modalCard [data-act=pzRetry]')"), null, 'no retry after three stars'); + assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /More puzzles/, 'the last pack points back to the list'); + ev("pzBegin(pzDef('eurotrip'))");build(ev, REF.eurotrip.three); + assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/); + assert.equal(ev("document.activeElement.dataset.act"), 'pzStart'); + // No nudge when no single link fits the budget: an over-budget gold plate is not "close". + ev("pzBegin(pzDef('braces'));S.pz.budget=245000"); + build(ev, REF.braces.one); + assert.equal(evalP(ev).stars, 2); + assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /So close/); + assert.match(ev("document.getElementById('modalCard').textContent"), /One backhoe away/); + // A finished pack says so. + ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{sharks:{st:3},braces:{st:3},nofra:{st:3},fatpipes:{st:2}}}));pzBegin(pzDef('fatpipes'))"); + build(ev, REF.fatpipes.three); + assert.match(ev("document.getElementById('modalCard').textContent"), /Every star in this pack is yours/); + assert.deepEqual(errors, []); +}); From ad07bfeada362183f68f6466815e3a75d40a76e6 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:02:02 +0100 Subject: [PATCH 44/64] CHANGELOG: puzzle budgets get tighter pack by pack, and a cable fails as a whole --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f13ceb4..bc78a63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ All notable changes to this project are documented here. The project follows - A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before. - Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips the peering inbox, hardware shortages and sold-out routes. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. - Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. -- Puzzles: small, calm network builds you can finish in a coffee break (#190). Connect a few cities on the real map with POPs and leased waves, with no clock, no bills and nothing breaking, and earn up to three stars: one for the goal, one for staying under budget, and one if the network survives any single cut. Eighteen puzzles in four packs (more stars open the next pack), some with a twist like a latency target, no subsea cables or a ring, plus a weekly puzzle that is the same for everyone, with a streak and a result to share. Puzzles never touch your saved network; only your stars are kept. +- Puzzles: small, calm network builds you can finish in a coffee break (#190). Connect a few cities on the real map with POPs and leased waves, with no clock, no bills and nothing breaking, and earn up to three stars: one for the goal, one for staying under budget, and one if the network survives any single cut (a trench, or a whole cable). Eighteen puzzles in four packs, with roomy budgets at first and tighter ones as you go (more stars open the next pack), some with a twist like a latency target, no subsea cables or a ring, plus a weekly puzzle that is the same for everyone, with a streak and a result to share. Puzzles never touch your saved network; only your stars are kept. - Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won. - Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge again under harder rules upgrades its look, and the badge list counts your collection of each kind on this device. On-call games earn the standard badges; Sandbox and puzzles earn none. - China Telecomet now sells its CN-Too premium crossing in Moscow too, at the same price as in Hong Kong (#195). Haul your European traffic to Moscow and it reaches China with about 3% loss; nothing else of theirs is on offer there. From a0a492f19efda2c5c24317f455b7e977d6085a8c Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:03:25 +0100 Subject: [PATCH 45/64] Standing orders: a re-hired intern starts on a fresh month's budget --- src/game/90-actions/88-ops.js | 4 +++- tests/standing-orders.test.js | 11 +++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/game/90-actions/88-ops.js b/src/game/90-actions/88-ops.js index 121e7a8..8068818 100644 --- a/src/game/90-actions/88-ops.js +++ b/src/game/90-actions/88-ops.js @@ -2,7 +2,9 @@ const opsCycle=(a,v)=>a[(a.indexOf(v)+1)%a.length]; Object.assign(ACT,{ opsOpen:()=>{if(S)opsModal();}, - opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO();O.intern=id;O.hired=S.day;O.mon=Math.floor(S.day/30); + opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO(),m=Math.floor(S.day/30);O.intern=id;O.hired=S.day; + // A new hire starts on a fresh month's budget, whatever the last one spent. + if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;} O.log.unshift({d:S.day,i:id,r:[]});toast(esc(tr('ops.hired',{name:opsName(true)})),'good',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);after();opsModal();}, opsFire:()=>{if(!opsHired())return;if(UI.confirm!=='opsFire'){UI.confirm='opsFire';opsModal();return;}UI.confirm=null;const nm=opsName();S.ops.intern=null; toast(esc(tr('ops.fired',{name:nm})),'');after();opsModal();}, diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index fc9bd6f..f7c853e 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -339,3 +339,14 @@ test('sales trial at most one offer a shift, and an offer that did not fit waits ev('autoOffer=__a'); assert.deepEqual(errors, []); }); + +test('re-hiring in a later month starts on a fresh budget, not last month\'s spending', t => { + const { ev, errors } = game(t); + hire(ev); + ev("S.ops.spent.transit=50000;ACT.opsFire();ACT.opsFire();S.day=400;ACT.opsHire({id:'kevin'});closeModal()"); + assert.equal(ev('S.ops.spent.transit'), 0); + assert.equal(ev('S.ops.mon'), ev('Math.floor(S.day/30)')); + ev("S.ops.spent.transit=1234;ACT.opsFire();ACT.opsFire();ACT.opsHire({id:'annie'});closeModal()"); + assert.equal(ev('S.ops.spent.transit'), 1234, 'the same month: what was spent stays spent'); + assert.deepEqual(errors, []); +}); From d69e340f9a808c0e9b66a5a153920ac19827d32a Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:07:08 +0100 Subject: [PATCH 46/64] Standing orders: transit never comes from a provider that breaks a customer's requirement, a covenant or the Spat --- src/game/60-features/95-standing-orders.js | 16 ++++++++--- tests/standing-orders.test.js | 31 ++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 9aa65be..4c251b6 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -68,7 +68,15 @@ function opsShift(){const r=new Map(),broke=new Set(); can(k,cost){const O=S.ops,cap=opsCap(k);if(cost<=0)return true;if(S.cash-costcap)){broke.add(k);return false;}return true;}, // Run a click and book what it really cost; false when the action refused (no ports, no cash, a quote changed). pay(k,fn){const c0=S.cash,x=fn();const d=c0-S.cash;if(d>0&&OPSK[k].cap)S.ops.spent[k]=(S.ops.spent[k]||0)+d;return x===undefined?d>0:x;}};} -const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0]; +// Never buy from a provider that breaks a promise: a customer's "no Cogentle" or "two upstreams", a bank's covenant, +// or Cogentle while it is not speaking to Goggle (the Spat scenario, a de-peering). Only met → failed counts. +const OPS_TREQ=['nocog','twoup']; +function opsTransitOk(n,c){if(n.id==='cog'&&(scnRule('spat')||S.ev.depeer>S.day))return false; + const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>OPS_TREQ.includes(k))),ls=(S.loans||[]).filter(l=>(l.covs||[]).includes('nocog'));if(!bz.length&&!ls.length)return true; + const chk=()=>bz.map(b=>b.reqs.every(k=>!OPS_TREQ.includes(k)||REQS[k].ok(b))).concat(ls.map(l=>COVS.nocog.ok(l))); + const was=chk(),all=S.transit;S.transit=all.concat({net:n.id,city:c});try{const now=chk();return was.every((v,i)=>!v||now[i]);}finally{S.transit=all;}} +const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)&&opsTransitOk(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0]; +const opsProv=c=>{const pv=opsP('transit','prov');return pv!=='cheap'&&sellsAt(NET[pv],c)&&opsTransitOk(NET[pv],c)?NET[pv]:cheapestTransit(c);}; // The orders. Each takes the shift and does its jobs through the player's own actions. const OPS_RUN={ repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id})))X.did('repair');}, @@ -87,11 +95,11 @@ const OPS_RUN={ const doSwap=how==='swap'?swap:how==='add'?false:swap&&(rt>=4||!add);if(!doSwap&&(how==='swap'||!add))continue; const cost=doSwap?swapCost(c,nx):routerCost(g,rt);if(!X.can('routers',cost))continue; if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));}}, - transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x'),pv=opsP('transit','prov'); + transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x'); for(const c of opsPops('transit')){let ts=S.transit.filter(t=>t.city===c);if(!ts.length)continue; // Thirty days of 95th-percentile-ish history per port; their peaks summed is a safe (high) estimate of the POP's peak. const peak=ts.reduce((a,t)=>a+(t.hist||[]).reduce((m,v)=>Math.max(m,v),0),0);if(!(peak>0))continue; - const n=pv!=='cheap'&&sellsAt(NET[pv],c)?NET[pv]:cheapestTransit(c);if(!n)continue; + const n=opsProv(c);if(!n)continue; for(let step=0;step<4;step++){const cap=ts.reduce((a,t)=>a+lagCap(PORT[t.tier].g,t.n),0);if(cap>=N*peak)break; const t=ts.find(x=>x.net===n.id);let job=null; if(t){const k=t.n||1,up=t.tier+1; @@ -152,7 +160,7 @@ function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!= // New POP from the template: price the whole bundle first, then click through it in one go. function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))return null;const T=S.ops.tpl,parts=[];let cost=popCost(c),net=null,ix=null,kit=null; if(T.bb){cost+=bbCost(c);parts.push(tr('ops.tpl_bb'));} - if(T.transit&&!scnRule('noTransit')){const pv=opsP('transit','prov');net=pv!=='cheap'&&sellsAt(NET[pv],c)?NET[pv]:cheapestTransit(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}} + if(T.transit&&!scnRule('noTransit')){net=opsProv(c);if(net){cost+=PORT[0].setup;parts.push(tr('ops.tpl_transit'));}} // Priced as if the POP were already there (an IX port is dearer from afar). DE-KICKS wants a sales call first, so not those. S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false}; try{if(T.ix&&CITY[c].ix&&!isDk(c)&&S.ixp[c]===undefined){ix=c;cost+=ixPortMo(c,0);parts.push(tr('ops.tpl_ix'));} diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index f7c853e..7f36fe0 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -350,3 +350,34 @@ test('re-hiring in a later month starts on a fresh budget, not last month\'s spe assert.equal(ev('S.ops.spent.transit'), 1234, 'the same month: what was spent stays spent'); assert.deepEqual(errors, []); }); + +test('transit never comes from a provider that breaks a promise: no-Cogentle customers, bank covenants, the Spat', t => { + const { ev, errors } = game(t, "S.transit=[];ACT.buyTransit({city:'fra',net:'lvl',tier:0});compute();S.transit[0].hist=Array(30).fill(200)"); + hire(ev); on(ev, 'transit', { x: 1.5 }); + assert.equal(ev("cheapestTransit('fra').id"), 'cog', 'Cogentle is the cheapest here, so it would be the pick'); + ev("S.biz.push({id:'b1',city:'fra',name:'X',type:'dia',bw:1,rate:100,mood:100,since:S.day,reqs:['nocog']})"); + assert.equal(ev("reqOk(S.biz[0])"), true); + shift(ev); + assert.ok(ev('S.transit.length') > 1 || ev('S.transit[0].n') > 1, 'the intern still topped up'); + assert.equal(ev("S.transit.some(t=>t.net==='cog')"), false); + assert.equal(ev("reqOk(S.biz[0])"), true, 'the customer still gets what they signed for'); + ev("S.ops.p.transit={x:1.5,prov:'cog'}"); + assert.notEqual(ev("opsProv('fra').id"), 'cog', 'even when the player picked Cogentle'); + assert.notEqual(ev("opsTplQuote('ams').net"), 'cog', 'and the new-POP template too'); + // A bank covenant says the same. + ev("S.biz=[];S.loans=[{bank:'db',covs:['nocog'],pay:1,bal:1}]"); + assert.notEqual(ev("cheapestTransit('fra').id"), 'cog'); + // Cogentle is not speaking to Goggle: the Spat scenario, or a de-peering. + ev("S.loans=[]"); + assert.equal(ev("cheapestTransit('fra').id"), 'cog'); + ev("S.ev.depeer=S.day+5"); + assert.notEqual(ev("cheapestTransit('fra').id"), 'cog'); + ev("S.ev.depeer=0;S.scn={id:'spat',rules:{spat:true}}"); + assert.notEqual(ev("cheapestTransit('fra').id"), 'cog'); + // Two upstreams: once met, never undone (adding is fine; the order never removes). + ev("S.scn=null;S.biz=[{id:'b2',city:'fra',name:'Y',type:'dia',bw:1,rate:1,mood:100,since:0,reqs:['twoup']}]"); + assert.ok(ev("cheapestTransit('fra')")); + ev("S.transit=[]"); + assert.equal(ev("cheapestTransit('fra')"), undefined, 'a lone first upstream would break "two upstreams"'); + assert.deepEqual(errors, []); +}); From 7b7d3ea1b3174cf8191f084b787a7e637f86c408 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:12:54 +0100 Subject: [PATCH 47/64] Standing orders: the spare wave kept by decommission sits in another trench than the big link --- src/game/60-features/95-standing-orders.js | 3 ++- tests/standing-orders.test.js | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 4c251b6..6495095 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -138,7 +138,8 @@ const OPS_RUN={ for(const ls of by.values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue; let cap=live.reduce((a,l)=>a+capOf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0); const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a)); - if(keep)small.shift(); + // The spare is there for when the big link's trench is cut, so it has to live in another trench. + if(keep&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);} for(const l of small.reverse()){if(cap-capOf(l) { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T1'],['s2',0,'T2']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:tr});compute()"); + hire(ev); on(ev, 'decom', { keep: true }); + ev("R.load={big:1,s1:0,s2:0}"); + shift(ev); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['big', 's2'], 'the 100G in the same trench goes, the 10G in its own trench stays'); + // Every small wave shares the big one's trench: keep the largest, as before. + ev("S.links=S.links.filter(l=>l.id==='big');for(const [id,tier] of [['a',1],['b',0]])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:'T1'});compute();R.load={big:1}"); + shift(ev); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['a', 'big']); + assert.deepEqual(errors, []); +}); From 9dbbfbe1b81a02f8d84fc1bd80e303a144c8fb72 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:16:35 +0100 Subject: [PATCH 48/64] Standing orders: decommission routes with this shift's new customers before handing back waves --- src/game/60-features/95-standing-orders.js | 5 ++++- tests/standing-orders.test.js | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 6495095..37a65d9 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -63,8 +63,9 @@ const opsFFLine=e=>tr('ops.ff_line',{name:tr(INTERNS[e.i].s),what:tr(OPS_FF[e.f] function opsQuiet(fn){const a=after,t=toast,s=sfx,f=floater,sel=UI.sel,cf=UI.confirm,tab=UI.tab;after=()=>{};toast=()=>{};sfx=()=>{};floater=()=>{}; try{return fn();}finally{after=a;toast=t;sfx=s;floater=f;UI.confirm=cf;UI.tab=tab;UI.sel=sel&&(sel.type!=='link'||S.links.some(l=>l.id===sel.id))&&(sel.type!=='city'||isCity(sel.id))?sel:null;}} // One shift's bookkeeping: what got done, and whether a job had to wait for next month's budget. +// dirty: a job changed the network, so R (loads, routing) is out of date until the next compute(). function opsShift(){const r=new Map(),broke=new Set(); - return {r,broke,did(k,w){const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, + return {r,broke,dirty:false,did(k,w){if(k!=='decline')this.dirty=true;const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, can(k,cost){const O=S.ops,cap=opsCap(k);if(cost<=0)return true;if(S.cash-costcap)){broke.add(k);return false;}return true;}, // Run a click and book what it really cost; false when the action refused (no ports, no cash, a quote changed). pay(k,fn){const c0=S.cash,x=fn();const d=c0-S.cash;if(d>0&&OPSK[k].cap)S.ops.spent[k]=(S.ops.spent[k]||0)+d;return x===undefined?d>0:x;}};} @@ -135,6 +136,8 @@ const OPS_RUN={ if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}}, // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). decom(X){const keep=opsP('decom','keep'),by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} + // Loads must include what this shift already did (a customer just signed, a repair): recompute first, if anything could go. + if(X.dirty&&[...by.values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'))){compute();X.dirty=false;} for(const ls of by.values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue; let cap=live.reduce((a,l)=>a+capOf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0); const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a)); diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index 9d80b77..cbd53c9 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -394,3 +394,15 @@ test('decommission keeps its spare in another trench than the big link', t => { assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['a', 'big']); assert.deepEqual(errors, []); }); + +test('decommission sees the traffic of a customer signed earlier in the same shift', t => { + const { ev, errors } = game(t, "S.pops.fra.bb.d=30;ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T2'],['s2',1,'T3']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:1000,trench:tr});compute()"); + hire(ev); on(ev, 'sales', { acc: true, min: 0 }); on(ev, 'decom', { keep: false }); + ev("S.offers=[{id:'o1',city:'fra',city2:'ams',name:'Bulk Co',type:'l2vpn',bw:450,rate:20,reqs:[],exp:S.day+20}]"); + shift(ev); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz.map(b=>b.id))')).length, 1, 'signed'); + assert.equal(ev('S.links.length'), 3, 'its 450G needs every wave, so none goes'); + ev('compute()'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bizWhy(S.biz[0]))')), []); + assert.deepEqual(errors, []); +}); From e7554f66ea708790713cc870b74d38a57e605d4b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:17:59 +0100 Subject: [PATCH 49/64] Standing orders: no recompute on a shift that changed nothing in the network --- src/game/60-features/95-standing-orders.js | 6 ++++-- tests/standing-orders.test.js | 12 ++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 37a65d9..a4644ea 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -157,9 +157,11 @@ function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!= const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke]]); // Very rarely, and never under Change Freeze, the intern fat-fingers something harmless. const ff=OPS_FF_RATE[rulePreset()];if(ff&&Object.keys(S.pops).length&&Math.random()t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;} + if(f===3){const t=S.transit.find(t=>t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;else X.dirty=true;} e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);} - if(e.r.length||e.f!==undefined){compute();O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);} + // Declining an offer or stopping at a budget changes nothing a route depends on: no recompute for those. + if(X.dirty)compute(); + if(e.r.length||e.f!==undefined){O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);} if(e.r.length)logNote(`${esc(tr('ops.shift',{name:opsName()}))} ${esc(opsLine(e))}`,cash>S.cash?'':'good',[],{a:'tab',v:'noc'});} // New POP from the template: price the whole bundle first, then click through it in one go. function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))return null;const T=S.ops.tpl,parts=[];let cost=popCost(c),net=null,ix=null,kit=null; diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index cbd53c9..848ea85 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -406,3 +406,15 @@ test('decommission sees the traffic of a customer signed earlier in the same shi assert.deepEqual(JSON.parse(ev('JSON.stringify(bizWhy(S.biz[0]))')), []); assert.deepEqual(errors, []); }); + +test('no recompute on a shift that only declined offers or stopped at a budget', t => { + const { ev, errors } = game(t); + hire(ev); on(ev, 'sales', { acc: false, min: 50000 }); on(ev, 'transit', { x: 3 }, 10000); + ev("S.ops.spent.transit=10000;S.transit[0].hist=[600];S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:30}]"); + const n = ev("window.__c=compute;window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"); + assert.equal(n, 0, 'nothing in the network changed'); + assert.match(ev('opsEntry(S.ops.log[0])'), /declined a tiny offer, stopped at the budget/); + ev("S.ops.spent.transit=0"); + assert.equal(ev("window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"), 1, 'a real job still recomputes once'); + assert.deepEqual(errors, []); +}); From 4c0d535369cc3f335b4aaa24010e61a7de580dd4 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:18:06 +0100 Subject: [PATCH 50/64] Keep the cone carrier lookup out of compute() --- src/game/80-simulation/30-compute.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 0697cce..b69566c 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -1,5 +1,7 @@ // tr() with one placeholder, remembered: compute() labels every port, PNI and cache on every run. const LABS=new Map();function labOf(s,k,v){const key=s+'|'+v;let o=LABS.get(key);if(o===undefined)LABS.set(key,o=tr(s,{[k]:v}));return o;} +// Who carries a network reached only through a cone (kept out of compute(), whose size the JIT is sensitive to). +function coneBy(L,id){let by=null;for(const e of L){if(e.k==='p')return e.net;if(!by&&e.k==='ix'&&e.dir)by=ANC[id].find(u=>e.dir.has(u))||null;}return by||1;} function compute(){ const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length; // The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order. @@ -43,7 +45,7 @@ function compute(){ for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];if(okBy[n.id].some(e=>e.rank>0&&e.k!=='t')){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id]; // Reached without transit only through the customers of networks you peer with (#85). R.cone[id]: the peer that // carries it, the first PNI's network or else the nearest upstream that is a member of an exchange you are on. - if(!okBy[n.id].some(e=>(e.k==='p'||e.k==='ix')&&!coneOf(e,n.id))){let by=null;for(const e of okBy[n.id]){if(e.k==='p'){by=e.net;break;}if(!by&&e.k==='ix'&&e.dir)by=ANC[n.id].find(u=>e.dir.has(u))||null;}R2.cone[n.id]=by||1;}}} + if(!okBy[n.id].some(e=>(e.k==='p'||e.k==='ix')&&!coneOf(e,n.id)))R2.cone[n.id]=coneBy(okBy[n.id],n.id);}} const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net)); const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1); // Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index). From 23634241c028605c75154d499437578b7467e1c3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:19:48 +0100 Subject: [PATCH 51/64] Standing orders: per-POP exceptions are dropped with their POP --- src/game/60-features/95-standing-orders.js | 5 +++-- src/game/80-simulation/50-sanitize.js | 2 +- src/game/93-ui/60-decommission.js | 2 +- tests/standing-orders.test.js | 13 +++++++++++++ 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index a4644ea..d5a87a1 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -36,7 +36,8 @@ function opsP(k,p){const P=OPSK[k].p[p],v=S.ops.p[k]&&S.ops.p[k][p];return v!==u function opsCap(k){const c=S.ops.cap[k];return OPS_CAPS.includes(c)?c:OPSK[k].cap||0;} const opsHere=(k,c)=>!(S.ops.skip[c]||[]).includes(k); const opsPops=k=>Object.keys(S.pops).filter(c=>opsHere(k,c)); -// Saves are untrusted: rebuild ops from known orders, params, cities and log shapes. Old saves get no intern, +// Saves are untrusted: rebuild ops from known orders, params, cities and log shapes. Runs after the POPs are repaired, +// so exceptions only survive for POPs that still exist. Old saves get no intern, // and the two #185 toggles (auto-accept, auto-pay repairs) become the sales and repair orders. function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s.ops)?s.ops:{},n=opsNew(),ob=x=>x&&typeof x==='object'&&!Array.isArray(x)?x:{}; n.intern=typeof o.intern==='string'&&own(INTERNS,o.intern)?o.intern:null;n.hired=int(o.hired,0,1e7,0);n.mon=int(o.mon,0,1e6,0); @@ -46,7 +47,7 @@ function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s for(const pk of Object.keys(d.p)){const P=d.p[pk];if(own(q,pk)&&(P.ok?P.ok(q[pk]):P.v.includes(q[pk])))r[pk]=q[pk];}n.p[k]=r; if(d.cap&&OPS_CAPS.includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0));} {const t=ob(o.tpl);for(const k of OPS_TPL)if(typeof t[k]==='boolean')n.tpl[k]=t[k];} - {const sk=ob(o.skip);for(const c of Object.keys(sk))if(isCity(c)&&Array.isArray(sk[c])){const ks=[...new Set(sk[c].filter(k=>OPS_POP.includes(k)))];if(ks.length)n.skip[c]=ks;}} + {const sk=ob(o.skip);for(const c of Object.keys(sk))if(isCity(c)&&own(s.pops,c)&&Array.isArray(sk[c])){const ks=[...new Set(sk[c].filter(k=>OPS_POP.includes(k)))];if(ks.length)n.skip[c]=ks;}} if(Array.isArray(o.log))n.log=o.log.map(opsLogOk).filter(Boolean).slice(0,OPS_LOG); if(s.autoSales===true)n.on.sales=true;if(s.autoRepair===true)n.on.repair=true;delete s.autoSales;delete s.autoRepair; s.ops=n;} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 5673200..f02d82f 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -11,11 +11,11 @@ function sanitize(s){ ['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach','pairMet'].forEach(obj); s.v=1;s.name=String(s.name==null?'Packet Pals':s.name).slice(0,24);s.day=int(s.day,0,1e7,0);s.cash=num(s.cash,0);s.asn=int(s.asn,1,4294967294,200000); s.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); - opsSanitize(s); 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); 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); const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);return l;}); for(const l of s.links)repairSubUpgradeDates(l,s.day); diff --git a/src/game/93-ui/60-decommission.js b/src/game/93-ui/60-decommission.js index 4386098..e2db4cf 100644 --- a/src/game/93-ui/60-decommission.js +++ b/src/game/93-ui/60-decommission.js @@ -15,7 +15,7 @@ function decomModal(){const sel=[...(UI.decom||[])],im=decomImpact(sel),all=Obje function decommission(cities){const set=new Set(cities),im=decomImpact(cities),lids=new Set(im.links.map(l=>l.id)),bids=new Set(im.biz.map(b=>b.id)); S.links=S.links.filter(l=>!lids.has(l.id));prunePairMet();S.biz=S.biz.filter(b=>!bids.has(b.id));S.offers=S.offers.filter(o=>!bCities(o).some(c=>set.has(c))); S.transit=S.transit.filter(t=>!set.has(t.city));S.pni=S.pni.filter(x=>!set.has(x.city));S.caches=S.caches.filter(x=>!set.has(x.city));S.nni=(S.nni||[]).filter(x=>!set.has(x.city)); - for(const c of cities){for(const x of ixIdsIn(c)){delete S.ixp[x];delete S.rs[x];if(S.ixn)delete S.ixn[x];if(S.ixSite)delete S.ixSite[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}delete S.myIx[c];S.scrubs=S.scrubs.filter(x=>x.city!==c);delete S.pops[c];} + for(const c of cities){for(const x of ixIdsIn(c)){delete S.ixp[x];delete S.rs[x];if(S.ixn)delete S.ixn[x];if(S.ixSite)delete S.ixSite[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}delete S.myIx[c];S.scrubs=S.scrubs.filter(x=>x.city!==c);if(S.ops)delete S.ops.skip[c];delete S.pops[c];} const rem=remoteCities();for(const x in S.ixp){const c=ixCity(x);if(!S.pops[c]&&!rem.includes(c)){delete S.ixp[x];delete S.rs[x];for(const k in S.peers)if(k.endsWith('@'+x))delete S.peers[k];}} if(set.has(S.home))S.home=Object.keys(S.pops)[0]; purgeInc();S.cash-=im.fee;S.stats.decom=(S.stats.decom||0)+cities.length; diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index 848ea85..126d126 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -418,3 +418,16 @@ test('no recompute on a shift that only declined offers or stopped at a budget', assert.equal(ev("window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"), 1, 'a real job still recomputes once'); assert.deepEqual(errors, []); }); + +test('per-POP exceptions go with the POP: on decommission, and in a save that lost it', t => { + const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});ACT.buildPop({city:'lon'});compute()"); + hire(ev); + ev("ACT.opsPop({k:'transit',city:'ams'});ACT.opsPop({k:'caches',city:'lon'});closeModal()"); + ev("decommission(['ams'])"); + assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}'); + ev("ACT.buildPop({city:'ams'});closeModal()"); + assert.equal(ev("opsHere('transit','ams')"), true, 'a rebuilt POP starts with every order on'); + ev("S.ops.skip.par=['transit'];S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}', 'no POP in Paris: its exception is dropped on load'); + assert.deepEqual(errors, []); +}); From ef700a3480fd0996ef4168a75dfda9bbd48617f3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:22:09 +0100 Subject: [PATCH 52/64] Standing orders: one failing order is paused instead of breaking the day; the LAG slip follows the transit order's switches --- site/i18n/de.js | 1 + site/i18n/es.js | 1 + site/i18n/fr.js | 1 + site/i18n/it.js | 1 + site/i18n/pt.js | 1 + src/game/60-features/95-standing-orders.js | 7 +++-- src/i18n/en.js | 1 + tests/standing-orders.test.js | 34 ++++++++++++++++++++++ 8 files changed, 44 insertions(+), 3 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index c6b6e91..8271f7b 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2570,6 +2570,7 @@ "ops.l_routers":{"one":"hat Router in {where} aufgerüstet","other":"hat Router an {n} Orten aufgerüstet ({where})"}, "ops.l_rs":{"one":"hat sich einem Route Server angeschlossen","other":"hat sich {n} Route Servern angeschlossen"}, "ops.l_sales":{"one":"hat einen Kunden unterschrieben","other":"hat {n} Kunden unterschrieben"}, +"ops.l_snag":{"one":"ist bei {where} hängen geblieben und hat den Auftrag pausiert, bis du draufschaust","other":"ist bei {n} Aufträgen hängen geblieben ({where}) und hat sie pausiert, bis du draufschaust"}, "ops.l_transit":{"one":"hat Transit in {where} aufgestockt","other":"hat {n}-mal Transit aufgestockt ({where})"}, "ops.locked":"Das NOC stellt ab Kundenlevel {lv} Praktikanten ein.", "ops.lpm_off":"Die Peering-Inbox bleibt deine Sache. Dafür gibt es das Large Peering Model; {name} macht keine E-Mails.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 4ab93d8..ed4c0a0 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2568,6 +2568,7 @@ "ops.l_routers":{"one":"mejoró los routers en {where}","other":"mejoró los routers en {n} sitios ({where})"}, "ops.l_rs":{"one":"se unió a un route server","other":"se unió a {n} route servers"}, "ops.l_sales":{"one":"firmó un cliente","other":"firmó {n} clientes"}, +"ops.l_snag":{"one":"se atascó con {where} y la pausó hasta que le eches un vistazo","other":"se atascó con {n} órdenes ({where}) y las pausó hasta que les eches un vistazo"}, "ops.l_transit":{"one":"amplió el tránsito en {where}","other":"amplió el tránsito {n} veces ({where})"}, "ops.locked":"El NOC contrata becarios a partir del nivel de clientes {lv}.", "ops.lpm_off":"La bandeja de peering sigue siendo cosa tuya. Para eso está el Large Peering Model; {name} no contesta correos.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 26a6ad8..0a23368 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2568,6 +2568,7 @@ "ops.l_routers":{"one":"a mis à niveau les routeurs à {where}","other":"a mis à niveau les routeurs à {n} endroits ({where})"}, "ops.l_rs":{"one":"a rejoint un route server","other":"a rejoint {n} route servers"}, "ops.l_sales":{"one":"a signé un client","other":"a signé {n} clients"}, +"ops.l_snag":{"one":"a calé sur {where} et l'a mis en pause en attendant que tu jettes un œil","other":"a calé sur {n} ordres ({where}) et les a mis en pause en attendant que tu jettes un œil"}, "ops.l_transit":{"one":"a renforcé le transit à {where}","other":"a renforcé le transit {n} fois ({where})"}, "ops.locked":"Le NOC recrute des stagiaires à partir du niveau clients {lv}.", "ops.lpm_off":"La boîte de peering reste à toi. Pour ça, il y a le Large Peering Model ; {name} ne fait pas les mails.", diff --git a/site/i18n/it.js b/site/i18n/it.js index b2547d1..045e456 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2568,6 +2568,7 @@ "ops.l_routers":{"one":"ha potenziato i router a {where}","other":"ha potenziato i router in {n} posti ({where})"}, "ops.l_rs":{"one":"si è unito a un route server","other":"si è unito a {n} route server"}, "ops.l_sales":{"one":"ha firmato un cliente","other":"ha firmato {n} clienti"}, +"ops.l_snag":{"one":"si è bloccato su {where} e l'ha messo in pausa finché non dai un'occhiata","other":"si è bloccato su {n} ordini ({where}) e li ha messi in pausa finché non dai un'occhiata"}, "ops.l_transit":{"one":"ha aumentato il transit a {where}","other":"ha aumentato il transit {n} volte ({where})"}, "ops.locked":"Il NOC assume stagisti dal livello clienti {lv}.", "ops.lpm_off":"La casella del peering resta tua. Per quella c'è il Large Peering Model; {name} non risponde alle email.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a05f651..7435693 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2568,6 +2568,7 @@ "ops.l_routers":{"one":"melhorou os roteadores em {where}","other":"melhorou os roteadores em {n} lugares ({where})"}, "ops.l_rs":{"one":"entrou em um route server","other":"entrou em {n} route servers"}, "ops.l_sales":{"one":"fechou com um cliente","other":"fechou com {n} clientes"}, +"ops.l_snag":{"one":"travou em {where} e pausou a ordem até você dar uma olhada","other":"travou em {n} ordens ({where}) e pausou-as até você dar uma olhada"}, "ops.l_transit":{"one":"reforçou o trânsito em {where}","other":"reforçou o trânsito {n} vezes ({where})"}, "ops.locked":"O NOC contrata estagiários a partir do nível de clientes {lv}.", "ops.lpm_off":"A caixa de peering continua com você. Para isso existe o Large Peering Model; {name} não responde e-mail.", diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index d5a87a1..10b4d89 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -23,7 +23,7 @@ const OPS=[ const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k); const OPS_TPL=['bb','transit','ix','kit']; // What the shift log can say. One line per day: "{name} did this, that and the other." -const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke')}; +const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')}; // Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; const OPS_TRIALS=1,OPS_FF_RATE={oncall:1/150,bgp:1/60}; @@ -154,11 +154,12 @@ const OPS_ORDER=['repair','sales','routers','transit','optics','caches','ix','pn // The shift: once per game day from dayTick, after outages and events have had their turn. function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;} const X=opsShift(),cash=S.cash; - opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])OPS_RUN[k](X);}); + // One order that trips over something (an odd save, a bug) is paused and noted; payday, goals and the save still happen. + opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])try{OPS_RUN[k](X);}catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);}}); const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke]]); // Very rarely, and never under Change Freeze, the intern fat-fingers something harmless. const ff=OPS_FF_RATE[rulePreset()];if(ff&&Object.keys(S.pops).length&&Math.random()t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;else X.dirty=true;} + if(f===3){const t=O.on.transit&&opsHere('transit',c)&&!scnRule('noTransit')&&S.transit.find(t=>t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;else X.dirty=true;} e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);} // Declining an offer or stopping at a budget changes nothing a route depends on: no recompute for those. if(X.dirty)compute(); diff --git a/src/i18n/en.js b/src/i18n/en.js index 9e5308b..cce79e4 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2569,6 +2569,7 @@ "ops.l_routers":{"one":"upgraded routers in {where}","other":"upgraded routers in {n} places ({where})"}, "ops.l_rs":{"one":"joined a route server","other":"joined {n} route servers"}, "ops.l_sales":{"one":"signed a customer","other":"signed {n} customers"}, +"ops.l_snag":{"one":"got stuck on {where} and paused it until you have a look","other":"got stuck on {n} orders ({where}) and paused them until you have a look"}, "ops.l_transit":{"one":"topped up transit in {where}","other":"topped up transit {n} times ({where})"}, "ops.locked":"The NOC hires interns from customer level {lv}.", "ops.lpm_off":"The peering inbox is still yours. Hire the Large Peering Model for that; {name} does not do email.", diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index 126d126..0ebad47 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -431,3 +431,37 @@ test('per-POP exceptions go with the POP: on decommission, and in a save that lo assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}', 'no POP in Paris: its exception is dropped on load'); assert.deepEqual(errors, []); }); + +test('one order that throws is paused and noted; the rest of the shift and the day still run', t => { + const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]"); + hire(ev); on(ev, 'repair'); on(ev, 'transit', { x: 1.5 }); + ev("window.__r=OPS_RUN.repair;OPS_RUN.repair=()=>{throw new Error('boom')};window.__e=console.error;console.error=()=>{}"); + const d = ev('S.day'), saves = ev("window.__s=0;window.__sv=save;save=()=>{__s++;return __sv()};S.day=29;dayTick();save=__sv;__s"); + ev("OPS_RUN.repair=__r;console.error=__e"); + assert.ok(d >= 0 && saves >= 1, 'dayTick reached the save on day 30'); + assert.equal(ev('S.ops.on.repair'), false, 'the broken order is paused'); + assert.ok(ev("(S.transit[0].n||1)") > 1, 'the next order still ran'); + assert.match(ev('opsEntry(S.ops.log[0])'), /got stuck on Rush repairs and paused it/); + assert.deepEqual(errors, []); +}); + +test('the fat-fingered LAG member respects a paused transit order and per-POP exceptions', t => { + const { ev, errors } = game(t); + hire(ev); + // Each shift rolls: fat finger yes, the only POP, the LAG slip (index 3). + ev("S.rules=makeRules('bgp');window.__r=Math.random;window.__k=0;Math.random=()=>[0,0,0.7][__k++%3]"); + const n0 = ev('S.transit[0].n||1'), c0 = cash(ev); + shift(ev); + assert.equal(ev('__k'), 3); + assert.equal(ev('S.ops.log[0].f'), 0, 'transit order paused: a harmless label instead'); + assert.equal(ev('S.transit[0].n||1'), n0); assert.equal(cash(ev), c0); + on(ev, 'transit', { x: 1 }); ev("ACT.opsPop({k:'transit',city:'fra'});closeModal();S.transit[0].hist=[0]"); + shift(ev); + assert.equal(ev('S.ops.log[0].f'), 0, 'Frankfurt excepted: the same'); + ev("ACT.opsPop({k:'transit',city:'fra'});closeModal()"); + shift(ev); + assert.equal(ev('S.ops.log[0].f'), 3, 'allowed: the extra member'); + assert.equal(ev('S.transit[0].n||1'), n0 + 1); + ev('Math.random=__r'); + assert.deepEqual(errors, []); +}); From e56659f9499337cea39a4eee2b337239564264ef Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:28:50 +0100 Subject: [PATCH 53/64] Standing orders: caches get a running-cost budget and respect the cash floor; budgets and the shift log show monthly costs --- site/i18n/de.js | 5 +- site/i18n/es.js | 5 +- site/i18n/fr.js | 5 +- site/i18n/it.js | 5 +- site/i18n/pt.js | 5 +- src/game/60-features/95-standing-orders.js | 53 +++++++++++++++------- src/game/90-actions/88-ops.js | 4 +- src/game/93-ui/57-ops-panel.js | 8 ++-- src/i18n/en.js | 5 +- tests/standing-orders.test.js | 41 +++++++++++++++++ 10 files changed, 107 insertions(+), 29 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 8271f7b..75bd6cc 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2533,8 +2533,10 @@ "ops.anycast_annie":"Anycast-Annie", "ops.at_least_port":"mindestens {port}", "ops.budget":"Budget", +"ops.budget_running":"Höchstens dazu", "ops.by_hand":"Einmal alles", "ops.by_hand_note":"Für den Moment, in dem alles sofort erledigt sein soll: jeder Peer an jedem Exchange, ein Redundanz-Kit, PNIs mit allen.", +"ops.caches_rent":"Kostenlos ins Rack, aber jede Box kostet {price}/Monat für Platz und Strom.", "ops.cheapest":"Günstigster", "ops.ff_desc":"hat einen Port in {city} „TODO: später fixen (nicht fixen)“ beschriftet", "ops.ff_hostname":"hat den Router in {city} in router-final-FINAL-v2 umbenannt", @@ -2563,6 +2565,7 @@ "ops.l_decom":{"one":"hat eine kleine Wave auf {where} zurückgegeben","other":"hat {n} kleine Waves zurückgegeben ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"hat einen Kanal auf {where} aufgeschaltet","other":"hat {n} Kanäle aufgeschaltet ({where})"}, +"ops.l_paid":"Kosten: {cost} einmalig, {mo}/Monat.", "ops.l_peer":{"one":"hat mit einem Netz an {where} gepeert","other":"hat mit {n} Netzen an {where} gepeert"}, "ops.l_pni":{"one":"hat einen PNI in {where} bestellt","other":"hat {n} PNIs bestellt ({where})"}, "ops.l_quiet":"{name} hat auf die Graphen geschaut. Nichts zu tun.", @@ -2614,7 +2617,7 @@ "ops.really_fire":"Wirklich entlassen?", "ops.salary":"Gehalt {price}/Monat · seit {d}", "ops.shift":"Schicht von {name}", -"ops.spent_this_month":"Diesen Monat ausgegeben: {price}", +"ops.spent_and_mo":"Diesen Monat: {price} einmalig, {mo}/Monat auf der Rechnung", "ops.standing_orders":"Daueraufträge", "ops.template":"Neuer POP aus der Vorlage", "ops.template_note":"Wähle, was {name} einrichtet, wenn du eine Stadt aus der Vorlage eröffnest. Den Rest übernehmen die Daueraufträge.", diff --git a/site/i18n/es.js b/site/i18n/es.js index ed4c0a0..c908c6b 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2531,8 +2531,10 @@ "ops.anycast_annie":"Annie Anycast", "ops.at_least_port":"al menos {port}", "ops.budget":"Presupuesto", +"ops.budget_running":"Añade como máximo", "ops.by_hand":"Lotes puntuales", "ops.by_hand_note":"Para cuando lo quieres todo hecho ya: cada peer en cada exchange, un kit de redundancia, PNIs con todos.", +"ops.caches_rent":"Instalarla es gratis, pero cada caja cuesta {price}/mes en espacio y energía.", "ops.cheapest":"El más barato", "ops.ff_desc":"etiquetó un puerto en {city} como «TODO: arreglar luego (no arreglar)»", "ops.ff_hostname":"renombró el router de {city} a router-final-FINAL-v2", @@ -2561,6 +2563,7 @@ "ops.l_decom":{"one":"devolvió una wave pequeña en {where}","other":"devolvió {n} waves pequeñas ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"encendió un canal en {where}","other":"encendió {n} canales ({where})"}, +"ops.l_paid":"Coste: {cost} de entrada, {mo}/mes.", "ops.l_peer":{"one":"hizo peering con una red en {where}","other":"hizo peering con {n} redes en {where}"}, "ops.l_pni":{"one":"pidió un PNI en {where}","other":"pidió {n} PNIs ({where})"}, "ops.l_quiet":"{name} miró las gráficas. No había nada que hacer.", @@ -2612,7 +2615,7 @@ "ops.really_fire":"¿Despedir de verdad?", "ops.salary":"Sueldo {price}/mes · desde {d}", "ops.shift":"Turno de {name}", -"ops.spent_this_month":"Gastado este mes: {price}", +"ops.spent_and_mo":"Este mes: {price} de entrada, {mo}/mes en la factura", "ops.standing_orders":"Órdenes permanentes", "ops.template":"POP nuevo desde plantilla", "ops.template_note":"Elige lo que monta {name} cuando abres una ciudad desde la plantilla. Las órdenes permanentes se encargan del resto.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 0a23368..26232c8 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2531,8 +2531,10 @@ "ops.anycast_annie":"Annie Anycast", "ops.at_least_port":"au moins {port}", "ops.budget":"Budget", +"ops.budget_running":"Ajoute au plus", "ops.by_hand":"Lots ponctuels", "ops.by_hand_note":"Pour quand tu veux tout, tout de suite : chaque peer sur chaque exchange, un kit de redondance, des PNI avec tout le monde.", +"ops.caches_rent":"Gratuit à installer, mais chaque boîtier coûte {price}/mois en espace et en électricité.", "ops.cheapest":"Le moins cher", "ops.ff_desc":"a étiqueté un port à {city} « TODO : corriger plus tard (ne pas corriger) »", "ops.ff_hostname":"a renommé le routeur de {city} en router-final-FINAL-v2", @@ -2561,6 +2563,7 @@ "ops.l_decom":{"one":"a rendu une petite wave sur {where}","other":"a rendu {n} petites waves ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"a allumé un canal sur {where}","other":"a allumé {n} canaux ({where})"}, +"ops.l_paid":"Coût : {cost} d'entrée, {mo}/mois.", "ops.l_peer":{"one":"a peeré avec un réseau à {where}","other":"a peeré avec {n} réseaux à {where}"}, "ops.l_pni":{"one":"a commandé un PNI à {where}","other":"a commandé {n} PNI ({where})"}, "ops.l_quiet":"{name} a surveillé les graphes. Rien à faire.", @@ -2612,7 +2615,7 @@ "ops.really_fire":"Vraiment remercier ?", "ops.salary":"Salaire {price}/mois · depuis {d}", "ops.shift":"Le service de {name}", -"ops.spent_this_month":"Dépensé ce mois-ci : {price}", +"ops.spent_and_mo":"Ce mois-ci : {price} d'entrée, {mo}/mois sur la facture", "ops.standing_orders":"Ordres permanents", "ops.template":"Nouveau POP depuis le modèle", "ops.template_note":"Choisis ce que {name} installe quand tu ouvres une ville depuis le modèle. Les ordres permanents s'occupent du reste.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 045e456..8142ba8 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2531,8 +2531,10 @@ "ops.anycast_annie":"Annie Anycast", "ops.at_least_port":"almeno {port}", "ops.budget":"Budget", +"ops.budget_running":"Aggiunge al massimo", "ops.by_hand":"Lotti una tantum", "ops.by_hand_note":"Per quando vuoi tutto fatto subito: ogni peer su ogni exchange, un kit di ridondanza, PNI con tutti.", +"ops.caches_rent":"Gratis da montare, ma ogni box costa {price}/mese di spazio e corrente.", "ops.cheapest":"Il più economico", "ops.ff_desc":"ha etichettato una porta a {city} «TODO: sistemare dopo (non sistemare)»", "ops.ff_hostname":"ha rinominato il router di {city} in router-final-FINAL-v2", @@ -2561,6 +2563,7 @@ "ops.l_decom":{"one":"ha restituito una wave piccola su {where}","other":"ha restituito {n} wave piccole ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"ha acceso un canale su {where}","other":"ha acceso {n} canali ({where})"}, +"ops.l_paid":"Costo: {cost} subito, {mo}/mese.", "ops.l_peer":{"one":"ha fatto peering con una rete a {where}","other":"ha fatto peering con {n} reti a {where}"}, "ops.l_pni":{"one":"ha ordinato un PNI a {where}","other":"ha ordinato {n} PNI ({where})"}, "ops.l_quiet":"{name} ha guardato i grafici. Niente da fare.", @@ -2612,7 +2615,7 @@ "ops.really_fire":"Licenziare davvero?", "ops.salary":"Stipendio {price}/mese · dal {d}", "ops.shift":"Il turno di {name}", -"ops.spent_this_month":"Speso questo mese: {price}", +"ops.spent_and_mo":"Questo mese: {price} subito, {mo}/mese in bolletta", "ops.standing_orders":"Ordini permanenti", "ops.template":"Nuovo POP da modello", "ops.template_note":"Scegli cosa monta {name} quando apri una città dal modello. Al resto pensano gli ordini permanenti.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 7435693..ae1ec38 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2531,8 +2531,10 @@ "ops.anycast_annie":"Annie Anycast", "ops.at_least_port":"pelo menos {port}", "ops.budget":"Orçamento", +"ops.budget_running":"Adiciona no máximo", "ops.by_hand":"Lotes avulsos", "ops.by_hand_note":"Para quando você quer tudo feito agora: cada peer em cada exchange, um kit de redundância, PNIs com todo mundo.", +"ops.caches_rent":"Instalar é grátis, mas cada caixa custa {price}/mês em espaço e energia.", "ops.cheapest":"O mais barato", "ops.ff_desc":"etiquetou uma porta em {city} como “TODO: corrigir depois (não corrigir)”", "ops.ff_hostname":"renomeou o roteador de {city} para router-final-FINAL-v2", @@ -2561,6 +2563,7 @@ "ops.l_decom":{"one":"devolveu uma wave pequena em {where}","other":"devolveu {n} waves pequenas ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"acendeu um canal em {where}","other":"acendeu {n} canais ({where})"}, +"ops.l_paid":"Custo: {cost} de entrada, {mo}/mês.", "ops.l_peer":{"one":"fez peering com uma rede em {where}","other":"fez peering com {n} redes em {where}"}, "ops.l_pni":{"one":"pediu um PNI em {where}","other":"pediu {n} PNIs ({where})"}, "ops.l_quiet":"{name} ficou olhando os gráficos. Nada a fazer.", @@ -2612,7 +2615,7 @@ "ops.really_fire":"Dispensar mesmo?", "ops.salary":"Salário {price}/mês · desde {d}", "ops.shift":"Turno de {name}", -"ops.spent_this_month":"Gasto este mês: {price}", +"ops.spent_and_mo":"Este mês: {price} de entrada, {mo}/mês na fatura", "ops.standing_orders":"Ordens permanentes", "ops.template":"Novo POP por modelo", "ops.template_note":"Escolha o que {name} monta quando você abre uma cidade pelo modelo. As ordens permanentes cuidam do resto.", diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 10b4d89..5e77a1d 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -2,17 +2,18 @@ A NOC intern runs the player's standing orders once per game day. Every job goes through the same action a click would (ACT.*, pniPlace, the #185/#192 planners), so it costs exactly what the click costs, with toasts and redraws muted and one recompute at the end. Without an intern nothing here runs and no random numbers are drawn. */ -const INTERN_MO=6000,OPS_LOG=12,OPS_CAPS=[10000,50000,250000,1e6,5e6,0],OPS_FLOORS=[0,50000,250000,1e6,5e6]; +const INTERN_MO=6000,OPS_LOG=12,OPS_CAPS=[10000,50000,250000,1e6,5e6,0],OPS_CAPS_MO=[1000,2500,5000,10000,25000,0],OPS_FLOORS=[0,50000,250000,1e6,5e6]; const INTERNS={ annie:{i:'📡',n:N_('ops.anycast_annie'),s:N_('ops.annie'),d:N_('ops.annie_d')}, kevin:{i:'🌙',n:N_('ops.kevin_from_the_night_shift'),s:N_('ops.kevin'),d:N_('ops.kevin_d')}, tracy:{i:'🧭',n:N_('ops.tracy_route'),s:N_('ops.tracy'),d:N_('ops.tracy_d')}, }; -// The orders, in the order the panel shows them. pop: can be switched off per POP. cap: default monthly budget. +// The orders, in the order the panel shows them. pop: can be switched off per POP. cap: default monthly budget, of setup +// fees, or (mo) of the running costs the order adds, for caches, which are free to rack but cost rent every month. const OPS=[ {k:'transit',i:'📈',pop:1,cap:50000,t:N_('ops.o_transit'),d:N_('ops.o_transit_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'},prov:{d:'cheap',ok:v=>v==='cheap'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}}, {k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}}}, - {k:'caches',i:'📦',pop:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}}, + {k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}}, {k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}}, {k:'pni',i:'🤝',pop:1,cap:50000,t:N_('ops.o_pni'),d:N_('ops.o_pni_d'),p:{g:{d:25,v:[5,10,25,50,100],l:N_('ops.p_g'),f:v=>fmtG(v)},tier:{d:0,v:[0,1,2],l:N_('ops.p_tier'),f:v=>tr('ops.at_least_port',{port:PORT[v].n})},paid:{d:false,v:[false,true],l:N_('ops.p_paid'),f:v=>tr(v?'common.on':'common.off')}}}, {k:'sales',i:'💼',t:N_('ops.o_sales'),d:N_('ops.o_sales_d'),p:{acc:{d:true,v:[true,false],l:N_('ops.p_acc'),f:v=>tr(v?'common.on':'common.off')},min:{d:0,v:[0,2000,5000,10000,25000,50000],l:N_('ops.p_min'),f:v=>v?tr('common.price_mo',{price:fmt$(v)}):tr('ops.never')}}}, @@ -27,13 +28,14 @@ const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_ // Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; const OPS_TRIALS=1,OPS_FF_RATE={oncall:1/150,bgp:1/60}; -function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),mon:0,skip:{},log:[],floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} +function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),addMo:{},mon:0,skip:{},log:[],floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} const opsO=()=>S.ops||(S.ops=opsNew()); const opsHired=()=>!!(S&&S.ops&&S.ops.intern&&own(INTERNS,S.ops.intern)); const opsCanHire=()=>lvl()>=2; const opsName=(long)=>{const I=INTERNS[S.ops.intern];return I?tr(long?I.n:I.s):'';}; function opsP(k,p){const P=OPSK[k].p[p],v=S.ops.p[k]&&S.ops.p[k][p];return v!==undefined&&(P.ok?P.ok(v):P.v.includes(v))?v:P.d;} -function opsCap(k){const c=S.ops.cap[k];return OPS_CAPS.includes(c)?c:OPSK[k].cap||0;} +const opsCaps=k=>OPSK[k].mo?OPS_CAPS_MO:OPS_CAPS; +function opsCap(k){const c=S.ops.cap[k];return opsCaps(k).includes(c)?c:OPSK[k].cap||0;} const opsHere=(k,c)=>!(S.ops.skip[c]||[]).includes(k); const opsPops=k=>Object.keys(S.pops).filter(c=>opsHere(k,c)); // Saves are untrusted: rebuild ops from known orders, params, cities and log shapes. Runs after the POPs are repaired, @@ -45,31 +47,47 @@ function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s const on=ob(o.on),p=ob(o.p),cap=ob(o.cap),sp=ob(o.spent); for(const d of OPS){const k=d.k;n.on[k]=on[k]===true;const q=ob(p[k]),r={}; for(const pk of Object.keys(d.p)){const P=d.p[pk];if(own(q,pk)&&(P.ok?P.ok(q[pk]):P.v.includes(q[pk])))r[pk]=q[pk];}n.p[k]=r; - if(d.cap&&OPS_CAPS.includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0));} + if(d.cap&&opsCaps(k).includes(cap[k]))n.cap[k]=cap[k];if(d.cap)n.spent[k]=Math.max(0,num(sp[k],0)); + {const v=num(ob(o.addMo)[k],0);if(v)n.addMo[k]=Math.max(-1e9,Math.min(1e9,v));}} {const t=ob(o.tpl);for(const k of OPS_TPL)if(typeof t[k]==='boolean')n.tpl[k]=t[k];} {const sk=ob(o.skip);for(const c of Object.keys(sk))if(isCity(c)&&own(s.pops,c)&&Array.isArray(sk[c])){const ks=[...new Set(sk[c].filter(k=>OPS_POP.includes(k)))];if(ks.length)n.skip[c]=ks;}} if(Array.isArray(o.log))n.log=o.log.map(opsLogOk).filter(Boolean).slice(0,OPS_LOG); if(s.autoSales===true)n.on.sales=true;if(s.autoRepair===true)n.on.repair=true;delete s.autoSales;delete s.autoRepair; s.ops=n;} -// A log entry: {d, i: intern, r: [[kind, n, [where…]]], f: fat-finger index, c: its city}. +// A log entry: {d, i: intern, r: [[kind, n, [where…]]], f: fat-finger index, c: its city, up: paid up front, mo: running costs added}. const opsWhereOk=w=>typeof w==='string'&&w.length<=48&&/^[a-z0-9~|]+( [+\w.×→⇧]+)?$/i.test(w)&&w.split(' ')[0].split('|').every(x=>isIx(x)||own(OPSK,x)||isNet(x)); function opsLogOk(e){if(!e||typeof e!=='object'||!own(INTERNS,e.i))return null;const r=Array.isArray(e.r)?e.r.filter(x=>Array.isArray(x)&&own(OPS_SAY,x[0])&&Array.isArray(x[2])).map(x=>[x[0],int(x[1],1,1e6,1),x[2].filter(opsWhereOk).slice(0,3)]).slice(0,16):[]; - const f=Number.isInteger(e.f)&&OPS_FF[e.f]?e.f:undefined;return {d:int(e.d,0,1e7,0),i:e.i,r,...(f!==undefined&&isCity(e.c)?{f,c:e.c}:{})};} + const f=Number.isInteger(e.f)&&OPS_FF[e.f]?e.f:undefined,up=int(e.up,0,1e12,0),mo=int(e.mo,-1e9,1e9,0); + return {d:int(e.d,0,1e7,0),i:e.i,r,...(f!==undefined&&isCity(e.c)?{f,c:e.c}:{}),...(up?{up}:{}),...(mo?{mo}:{})};} // "fra +1×100G", "fra|ams", "ams~3", "transit" (an order, for the budget line) or "ggl" (a network). function opsWhere(w){const [a,x]=w.split(' '),nm=a.split('|').map(p=>own(OPSK,p)?tr(OPSK[p].t):isCity(p)?CITY[p].name:isNet(p)?NET[p].name:ixName(p)).join('–');return x?nm+' '+(isNet(x)?NET[x].name:x):nm;} function opsLine(e){const I=INTERNS[e.i],name=I?tr(I.s):'',parts=e.r.map(([k,n,w])=>trn(OPS_SAY[k],n,{where:w.map(opsWhere).join(', ')})); - return parts.length?tr('ops.l_line',{name,list:parts.join(', ')}):tr('ops.l_quiet',{name});} + return (parts.length?tr('ops.l_line',{name,list:parts.join(', ')}):tr('ops.l_quiet',{name}))+opsPaid(e);} +const opsMo$=v=>(v>0?'+':'')+fmt$(v); +const opsPaid=e=>e.up||e.mo?' '+tr('ops.l_paid',{cost:fmt$(e.up||0),mo:opsMo$(e.mo||0)}):''; +// What the network costs every month before traffic: what a job adds to the bill (ports, routers, rent, links, cache boxes). +// PNIs count from the day they are ordered, at the size they are going to be. +function opsMoNow(){let m=S.caches.length*CACHE_MO; + for(const c in S.pops){const p=S.pops[c],rt=p.routers||1;m+=(rt-1)*ROUTER_MO+cageMo(rt)+rt*RG[p.rgen||0].mo;} + for(const l of S.links)m+=(l.mo||0)+(l.kind==='df'?(l.spares?Math.round(150+(l.ch||[]).length*80):0)+(l.regen|0)*REGEN_MO:0); + for(const t of S.transit)m+=transitMo(t,0); + for(const p of S.pni){const q=p.up||p,N=NET[p.net];m+=(q.g1?Math.round(PORT[0].pni/2):PORT[q.tier].pni)*(q.n||1)+(N.pol==='paid'&&!paidFree(N)?N.paidFee:0);} + return m;} const opsFFLine=e=>tr('ops.ff_line',{name:tr(INTERNS[e.i].s),what:tr(OPS_FF[e.f],{city:CITY[e.c].name})}); // Mute what a click would show (toasts, sounds, floaters, the full redraw) and keep the player's selection. function opsQuiet(fn){const a=after,t=toast,s=sfx,f=floater,sel=UI.sel,cf=UI.confirm,tab=UI.tab;after=()=>{};toast=()=>{};sfx=()=>{};floater=()=>{}; try{return fn();}finally{after=a;toast=t;sfx=s;floater=f;UI.confirm=cf;UI.tab=tab;UI.sel=sel&&(sel.type!=='link'||S.links.some(l=>l.id===sel.id))&&(sel.type!=='city'||isCity(sel.id))?sel:null;}} // One shift's bookkeeping: what got done, and whether a job had to wait for next month's budget. // dirty: a job changed the network, so R (loads, routing) is out of date until the next compute(). +// up/mo/rev: what this shift paid up front, added to the monthly bill, and signed in monthly revenue. function opsShift(){const r=new Map(),broke=new Set(); - return {r,broke,dirty:false,did(k,w){if(k!=='decline')this.dirty=true;const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, - can(k,cost){const O=S.ops,cap=opsCap(k);if(cost<=0)return true;if(S.cash-costcap)){broke.add(k);return false;}return true;}, + return {r,broke,dirty:false,up:0,mo:0,rev:0,did(k,w){if(k!=='decline')this.dirty=true;const x=r.get(k)||{n:0,w:[]};x.n++;if(w&&x.w.length<3&&!x.w.includes(w))x.w.push(w);r.set(k,x);}, + // A job that costs nothing up front still has to pass the cash floor if it adds to the monthly bill. + can(k,cost,mo=0){const O=S.ops,cap=opsCap(k);if(cost<=0&&!(mo>0))return true; + if(S.cash-Math.max(0,cost)cap)){broke.add(k);return false;}return true;}, + book(k,d,dm){const O=S.ops;if(d>0){this.up+=d;if(OPSK[k].cap)O.spent[k]=(O.spent[k]||0)+d;}if(dm){this.mo+=dm;O.addMo[k]=(O.addMo[k]||0)+dm;}}, // Run a click and book what it really cost; false when the action refused (no ports, no cash, a quote changed). - pay(k,fn){const c0=S.cash,x=fn();const d=c0-S.cash;if(d>0&&OPSK[k].cap)S.ops.spent[k]=(S.ops.spent[k]||0)+d;return x===undefined?d>0:x;}};} + pay(k,fn){const c0=S.cash,m0=opsMoNow(),x=fn();this.book(k,c0-S.cash,opsMoNow()-m0);return x===undefined?c0-S.cash>0:x;}};} // Never buy from a provider that breaks a promise: a customer's "no Cogentle" or "two upstreams", a bank's covenant, // or Cogentle while it is not speaking to Goggle (the Spat scenario, a de-peering). Only met → failed counts. const OPS_TREQ=['nocog','twoup']; @@ -87,7 +105,7 @@ const OPS_RUN={ if(min&&vx!==o);X.did('decline');continue;} // Each trial is a full routing pass: at most one a shift, and an offer that did not fit waits a week. if(acc&&o.exp>S.day&&bCities(o).every(popUp)&&reqOk(o)&&triesS.day-7)){tries++;ACT.accept({id:o.id,auto:true}); - if(!S.offers.includes(o))X.did('sales');else{if(!UI.opsTried||UI.opsTried.s!==S)UI.opsTried={s:S,m:new Map()};UI.opsTried.m.set(o.id,S.day);}}}}, + if(!S.offers.includes(o)){X.did('sales');X.rev+=bizMo(o);}else{if(!UI.opsTried||UI.opsTried.s!==S)UI.opsTried={s:S,m:new Map()};UI.opsTried.m.set(o.id,S.day);}}}}, routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'); for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue; const ld=Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));if(ld(R.cityDem[c]||0)*(NSH[x.net]||0)>=g),free=Math.floor(portsMax(c)-portsUsed(c)+1e-9); - for(const x of want.slice(0,Math.max(0,free))){S.caches.push({id:uid(),city:c,net:x.net,site:x.site});X.did('caches',c);}}}, + for(const x of want.slice(0,Math.max(0,free))){if(!X.can('caches',0,CACHE_MO))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site});X.book('caches',0,CACHE_MO);X.did('caches',c);}}}, // Weekly, like a person going through PeeringDB on a Monday: route servers, then every willing member (#192). ix(X){if(S.day%7)return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');} for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}}, @@ -144,7 +162,7 @@ const OPS_RUN={ const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a)); // The spare is there for when the big link's trench is cut, so it has to live in another trench. if(keep&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);} - for(const l of small.reverse()){if(cap-capOf(l)ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}}, }; // A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first. function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; @@ -152,7 +170,7 @@ function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='dive const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}} const OPS_ORDER=['repair','sales','routers','transit','optics','caches','ix','pni','decom']; // The shift: once per game day from dayTick, after outages and events have had their turn. -function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;} +function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} const X=opsShift(),cash=S.cash; // One order that trips over something (an odd save, a bug) is paused and noted; payday, goals and the save still happen. opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])try{OPS_RUN[k](X);}catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);}}); @@ -161,10 +179,11 @@ function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!= const ff=OPS_FF_RATE[rulePreset()];if(ff&&Object.keys(S.pops).length&&Math.random()t.city===c&&(t.n||1)X.pay('transit',()=>ACT.lagT({id:t.id,d:1}))))f=0;else X.dirty=true;} e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);} + if(X.up)e.up=Math.round(X.up);if(Math.round(X.mo))e.mo=Math.round(X.mo); // Declining an offer or stopping at a budget changes nothing a route depends on: no recompute for those. if(X.dirty)compute(); if(e.r.length||e.f!==undefined){O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);} - if(e.r.length)logNote(`${esc(tr('ops.shift',{name:opsName()}))} ${esc(opsLine(e))}`,cash>S.cash?'':'good',[],{a:'tab',v:'noc'});} + if(e.r.length||e.up||e.mo)logNote(`${esc(tr('ops.shift',{name:opsName()}))} ${esc(opsLine(e))}`,cash>S.cash?'':'good',[],{a:'tab',v:'noc'});} // New POP from the template: price the whole bundle first, then click through it in one go. function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))return null;const T=S.ops.tpl,parts=[];let cost=popCost(c),net=null,ix=null,kit=null; if(T.bb){cost+=bbCost(c);parts.push(tr('ops.tpl_bb'));} diff --git a/src/game/90-actions/88-ops.js b/src/game/90-actions/88-ops.js index 8068818..e76b13f 100644 --- a/src/game/90-actions/88-ops.js +++ b/src/game/90-actions/88-ops.js @@ -4,7 +4,7 @@ Object.assign(ACT,{ opsOpen:()=>{if(S)opsModal();}, opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO(),m=Math.floor(S.day/30);O.intern=id;O.hired=S.day; // A new hire starts on a fresh month's budget, whatever the last one spent. - if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;} + if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} O.log.unshift({d:S.day,i:id,r:[]});toast(esc(tr('ops.hired',{name:opsName(true)})),'good',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);after();opsModal();}, opsFire:()=>{if(!opsHired())return;if(UI.confirm!=='opsFire'){UI.confirm='opsFire';opsModal();return;}UI.confirm=null;const nm=opsName();S.ops.intern=null; toast(esc(tr('ops.fired',{name:nm})),'');after();opsModal();}, @@ -12,7 +12,7 @@ Object.assign(ACT,{ opsParam:({k,p})=>{if(!opsHired()||!own(OPSK,k)||!own(OPSK[k].p,p))return;const P=OPSK[k].p[p];let v; if(p==='prov'){const ids=['cheap',...NETS.filter(n=>n.price&&Object.keys(S.pops).some(c=>sellsAt(n,c))).map(n=>n.id)];v=opsCycle(ids,opsP(k,p));}else v=opsCycle(P.v,opsP(k,p)); (S.ops.p[k]||(S.ops.p[k]={}))[p]=v;sfx('click');after();opsModal();}, - opsCap:({k})=>{if(!opsHired()||!own(OPSK,k)||!OPSK[k].cap)return;S.ops.cap[k]=opsCycle(OPS_CAPS,opsCap(k));sfx('click');after();opsModal();}, + opsCap:({k})=>{if(!opsHired()||!own(OPSK,k)||!OPSK[k].cap)return;S.ops.cap[k]=opsCycle(opsCaps(k),opsCap(k));sfx('click');after();opsModal();}, opsFloor:()=>{if(!opsHired())return;S.ops.floor=opsCycle(OPS_FLOORS,S.ops.floor);sfx('click');after();opsModal();}, opsCity:({v})=>{if(!S||!S.pops[v])return;UI.opsCity=v;opsModal();}, opsPop:({k,city})=>{if(!opsHired()||!OPS_POP.includes(k)||!S.pops[city])return;const sk=S.ops.skip,a=sk[city]||[];sk[city]=a.includes(k)?a.filter(x=>x!==k):[...a,k];if(!sk[city].length)delete sk[city]; diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js index b0bf525..58dc5d4 100644 --- a/src/game/93-ui/57-ops-panel.js +++ b/src/game/93-ui/57-ops-panel.js @@ -6,12 +6,12 @@ function opsCard(){if(!S)return '';const last=opsHired()&&S.ops.log[0];
${btn(opsHired()?tr('ops.standing_orders'):tr('ops.hire_an_intern'),'opsOpen',{},opsHired()?'sm':'pink sm',!opsHired()&&!opsCanHire())}
`;} const opsEntry=e=>(e.f!==undefined?opsFFLine(e)+' ':'')+(e.r.length||e.f===undefined?opsLine(e):''); function opsVal(k,p){const P=OPSK[k].p[p],v=opsP(k,p);return p==='prov'?(v==='cheap'?tr('ops.cheapest'):NET[v].name):P.f(v);} -function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0; - return `
${tr(d.t)}
${tr(d.d)}
+function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.ops.spent[k]||0,am=Math.round(S.ops.addMo[k]||0); + return `
${tr(d.t)}
${tr(d.d)}${k==='caches'?' '+tr('ops.caches_rent',{price:fmt$(CACHE_MO)}):''}
${on?`
${Object.keys(d.p).map(p=>btn(`${tr(d.p[p].l)}: ${esc(opsVal(k,p))}`,'opsParam',{k,p},'ghost sm')).join('')} - ${d.cap?btn(`${tr('ops.budget')}: ${cap?tr('common.price_mo',{price:fmt$(cap)}):tr('ops.no_cap')}`,'opsCap',{k},'ghost sm'):''}
- ${d.cap&&S.ops.spent[k]?`
${tr('ops.spent_this_month',{price:fmt$(S.ops.spent[k])})}
`:''} + ${d.cap?btn(`${d.mo?tr('ops.budget_running'):tr('ops.budget')}: ${cap?tr('common.price_mo',{price:(d.mo?'+':'')+fmt$(cap)}):tr('ops.no_cap')}`,'opsCap',{k},'ghost sm'):''}
+ ${sp||am?`
${tr('ops.spent_and_mo',{price:fmt$(sp),mo:opsMo$(am)})}
`:''} ${k==='ix'&&ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

`:''}`:''}
`;} function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr('ops.ops')}

${tr('ops.standing_orders')}

`; if(!hired){h+=`

${tr('ops.hire_pitch')}

`; diff --git a/src/i18n/en.js b/src/i18n/en.js index cce79e4..356b390 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2532,8 +2532,10 @@ "ops.anycast_annie":"Anycast Annie", "ops.at_least_port":"at least {port}", "ops.budget":"Budget", +"ops.budget_running":"Adds at most", "ops.by_hand":"One-off batches", "ops.by_hand_note":"For when you want it all done right now: every peer at every exchange, a redundancy kit, PNIs with everyone.", +"ops.caches_rent":"Free to rack, but each box costs {price}/mo in space and power.", "ops.cheapest":"Cheapest", "ops.ff_desc":"labelled a port in {city} “TODO: fix later (do not fix)”", "ops.ff_hostname":"renamed the router in {city} to router-final-FINAL-v2", @@ -2562,6 +2564,7 @@ "ops.l_decom":{"one":"handed back a small wave on {where}","other":"handed back {n} small waves ({where})"}, "ops.l_line":"{name} {list}.", "ops.l_optics":{"one":"lit a channel on {where}","other":"lit {n} channels ({where})"}, +"ops.l_paid":"Cost: {cost} up front, {mo}/mo.", "ops.l_peer":{"one":"peered with a network at {where}","other":"peered with {n} networks at {where}"}, "ops.l_pni":{"one":"ordered a PNI in {where}","other":"ordered {n} PNIs ({where})"}, "ops.l_quiet":"{name} watched the graphs. Nothing needed doing.", @@ -2613,7 +2616,7 @@ "ops.really_fire":"Really let go?", "ops.salary":"Salary {price}/mo · since {d}", "ops.shift":"{name}'s shift", -"ops.spent_this_month":"Spent this month: {price}", +"ops.spent_and_mo":"This month: {price} up front, {mo}/mo on the bill", "ops.standing_orders":"Standing orders", "ops.template":"New POP from template", "ops.template_note":"Pick what {name} sets up when you open a city from the template. The standing orders take it from there.", diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index 0ebad47..1f5e0d7 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -465,3 +465,44 @@ test('the fat-fingered LAG member respects a paused transit order and per-POP ex ev('Math.random=__r'); assert.deepEqual(errors, []); }); + +test('caches: the cash floor and a running-cost budget hold; the panel and the log show what a month costs', t => { + const { ev, errors } = game(t); + hire(ev); on(ev, 'caches', { g: 1 }); + const add = () => ev("utilityCaches('fra').add.filter(x=>(R.cityDem.fra||0)*NSH[x.net]>=1).length"); + assert.ok(add() >= 2, 'several boxes on offer'); + ev('S.ops.floor=50000;S.cash=1000'); + shift(ev); + assert.equal(ev('S.caches.length'), 0, 'below the floor: no new rent either'); + assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Accept free caches/); + ev('S.cash=1e8;S.ops.cap.caches=1000'); + const m0 = ev('opsMoNow()'); + shift(ev); + assert.equal(ev('S.caches.length'), 2, 'a $1k/mo budget fits two $400/mo boxes'); + assert.equal(ev('S.ops.addMo.caches'), 800); + assert.equal(ev('opsMoNow()') - m0, 800); + assert.equal(ev('S.ops.log[0].mo'), 800); + assert.match(ev('opsEntry(S.ops.log[0])'), /racked 2 free caches \(Frankfurt\).*Cost: \$0 up front, \+\$800\/mo\./); + ev('opsModal()'); + const txt = ev("document.getElementById('modalCard').textContent"); + assert.match(txt, /each box costs \$400\/mo/); + assert.match(txt, /Adds at most: \+\$1\.0k\/mo/); + assert.match(txt, /This month: \$0 up front, \+\$800\/mo on the bill/); + ev('S.day+=30;S.ops.cap.caches=0'); shift(ev); + assert.equal(ev('S.ops.addMo.caches'), (ev('S.caches.length') - 2) * 400, 'a new month counts from zero'); + assert.deepEqual(errors, []); +}); + +test('transit: the log line and budget line show the monthly cost a top-up adds', t => { + const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]"); + hire(ev); on(ev, 'transit', { x: 1.5 }); + const m0 = ev('opsMoNow()'), c0 = cash(ev); + shift(ev); + const mo = ev('opsMoNow()') - m0; + assert.ok(mo > 0); + assert.equal(ev('S.ops.log[0].up'), c0 - cash(ev)); + assert.equal(ev('S.ops.log[0].mo'), Math.round(mo)); + assert.equal(ev('Math.round(S.ops.addMo.transit)'), Math.round(mo)); + assert.match(ev('S.log[0].t'), /Cost: \$[\d.]+k up front, \+\$[\d.]+k?\/mo\./); + assert.deepEqual(errors, []); +}); From 0788b98729eafdab4b21d52d8f4d42e9d29112f2 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:38:27 +0100 Subject: [PATCH 54/64] Standing orders: the intern's NOC notice is one shift report a week; the daily lines stay in the Ops sheet --- site/i18n/de.js | 6 +++- site/i18n/es.js | 6 +++- site/i18n/fr.js | 6 +++- site/i18n/it.js | 6 +++- site/i18n/pt.js | 6 +++- src/game/60-features/95-standing-orders.js | 22 ++++++++++++-- src/game/90-actions/88-ops.js | 2 +- src/i18n/en.js | 6 +++- tests/standing-orders.test.js | 34 ++++++++++++++++++---- 9 files changed, 78 insertions(+), 16 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 75bd6cc..ba24ef2 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2616,7 +2616,7 @@ "ops.per_pop_note":"Grüne Aufträge laufen in diesem POP. Schalte einen aus, um hier selbst zu entscheiden.", "ops.really_fire":"Wirklich entlassen?", "ops.salary":"Gehalt {price}/Monat · seit {d}", -"ops.shift":"Schicht von {name}", +"ops.shift_report":"{name}s Woche", "ops.spent_and_mo":"Diesen Monat: {price} einmalig, {mo}/Monat auf der Rechnung", "ops.standing_orders":"Daueraufträge", "ops.template":"Neuer POP aus der Vorlage", @@ -2633,6 +2633,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Verfolgt jedes Paket Hop für Hop. Kommt am Ende an, mit ein, zwei Sternchen unterwegs.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Woche gesamt: {cost} einmalig, {mo}/Monat.", +"ops.w_oops":{"one":"hat sich einmal kurz vertippt","other":"hat sich {n}-mal kurz vertippt"}, +"ops.w_sales":{"one":"hat einen Kunden gewonnen ({rev}/Monat)","other":"hat {n} Kunden gewonnen ({rev}/Monat)"}, "optic_counts.apply_price":"Übernehmen · {price}", "optic_counts.count_for_model":"Anzahl der {model}-Kanäle", "optic_counts.only_n_channels_free":"Auf dieser Glasfaser sind nur {n} Kanäle frei.", diff --git a/site/i18n/es.js b/site/i18n/es.js index c908c6b..926231d 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2614,7 +2614,7 @@ "ops.per_pop_note":"Las órdenes en verde se ejecutan en este POP. Apaga una para decidir aquí a mano.", "ops.really_fire":"¿Despedir de verdad?", "ops.salary":"Sueldo {price}/mes · desde {d}", -"ops.shift":"Turno de {name}", +"ops.shift_report":"La semana de {name}", "ops.spent_and_mo":"Este mes: {price} de entrada, {mo}/mes en la factura", "ops.standing_orders":"Órdenes permanentes", "ops.template":"POP nuevo desde plantilla", @@ -2631,6 +2631,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Sigue cada paquete salto a salto. Al final llega, con alguna estrellita por el camino.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Total de la semana: {cost} de entrada, {mo}/mes.", +"ops.w_oops":{"one":"tuvo un pequeño despiste","other":"tuvo {n} pequeños despistes"}, +"ops.w_sales":{"one":"firmó un cliente ({rev}/mes)","other":"firmó {n} clientes ({rev}/mes)"}, "optic_counts.apply_price":"Aplicar · {price}", "optic_counts.count_for_model":"Número de canales {model}", "optic_counts.only_n_channels_free":"Solo quedan {n} canales libres en esta fibra.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 26232c8..4f802ad 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2614,7 +2614,7 @@ "ops.per_pop_note":"Les ordres en vert s'appliquent à ce POP. Désactive-en un pour décider ici à la main.", "ops.really_fire":"Vraiment remercier ?", "ops.salary":"Salaire {price}/mois · depuis {d}", -"ops.shift":"Le service de {name}", +"ops.shift_report":"La semaine de {name}", "ops.spent_and_mo":"Ce mois-ci : {price} d'entrée, {mo}/mois sur la facture", "ops.standing_orders":"Ordres permanents", "ops.template":"Nouveau POP depuis le modèle", @@ -2631,6 +2631,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Suit chaque paquet saut par saut. Arrive au bout, avec une ou deux étoiles en chemin.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Total de la semaine : {cost} d'entrée, {mo}/mois.", +"ops.w_oops":{"one":"a fait une petite bourde","other":"a fait {n} petites bourdes"}, +"ops.w_sales":{"one":"a signé un client ({rev}/mois)","other":"a signé {n} clients ({rev}/mois)"}, "optic_counts.apply_price":"Appliquer · {price}", "optic_counts.count_for_model":"Nombre de canaux {model}", "optic_counts.only_n_channels_free":"Il ne reste que {n} canaux libres sur cette fibre.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 8142ba8..3dd131c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2614,7 +2614,7 @@ "ops.per_pop_note":"Gli ordini in verde valgono per questo POP. Spegnine uno per decidere qui a mano.", "ops.really_fire":"Licenziare davvero?", "ops.salary":"Stipendio {price}/mese · dal {d}", -"ops.shift":"Il turno di {name}", +"ops.shift_report":"La settimana di {name}", "ops.spent_and_mo":"Questo mese: {price} subito, {mo}/mese in bolletta", "ops.standing_orders":"Ordini permanenti", "ops.template":"Nuovo POP da modello", @@ -2631,6 +2631,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Segue ogni pacchetto hop per hop. Alla fine arriva, con qualche asterisco per strada.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Totale della settimana: {cost} subito, {mo}/mese.", +"ops.w_oops":{"one":"ha fatto un piccolo pasticcio","other":"ha fatto {n} piccoli pasticci"}, +"ops.w_sales":{"one":"ha firmato un cliente ({rev}/mese)","other":"ha firmato {n} clienti ({rev}/mese)"}, "optic_counts.apply_price":"Applica · {price}", "optic_counts.count_for_model":"Numero di canali {model}", "optic_counts.only_n_channels_free":"Su questa fibra sono liberi solo {n} canali.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index ae1ec38..98dd58f 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2614,7 +2614,7 @@ "ops.per_pop_note":"As ordens em verde valem neste POP. Desligue uma para decidir aqui na mão.", "ops.really_fire":"Dispensar mesmo?", "ops.salary":"Salário {price}/mês · desde {d}", -"ops.shift":"Turno de {name}", +"ops.shift_report":"A semana de {name}", "ops.spent_and_mo":"Este mês: {price} de entrada, {mo}/mês na fatura", "ops.standing_orders":"Ordens permanentes", "ops.template":"Novo POP por modelo", @@ -2631,6 +2631,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Segue cada pacote salto a salto. Chega no fim, com uma ou duas estrelinhas no caminho.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Total da semana: {cost} de entrada, {mo}/mês.", +"ops.w_oops":{"one":"cometeu um pequeno deslize","other":"cometeu {n} pequenos deslizes"}, +"ops.w_sales":{"one":"assinou um cliente ({rev}/mês)","other":"assinou {n} clientes ({rev}/mês)"}, "optic_counts.apply_price":"Aplicar · {price}", "optic_counts.count_for_model":"Número de canais {model}", "optic_counts.only_n_channels_free":"Só há {n} canais livres nesta fibra.", diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 5e77a1d..38e84d6 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -28,7 +28,7 @@ const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_ // Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little. const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')]; const OPS_TRIALS=1,OPS_FF_RATE={oncall:1/150,bgp:1/60}; -function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),addMo:{},mon:0,skip:{},log:[],floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} +function opsNew(){return {intern:null,hired:0,on:Object.fromEntries(OPS.map(o=>[o.k,false])),p:{},cap:{},spent:Object.fromEntries(OPS.filter(o=>o.cap).map(o=>[o.k,0])),addMo:{},mon:0,skip:{},log:[],wk:null,rep:null,floor:50000,tpl:{bb:true,transit:true,ix:true,kit:true}};} const opsO=()=>S.ops||(S.ops=opsNew()); const opsHired=()=>!!(S&&S.ops&&S.ops.intern&&own(INTERNS,S.ops.intern)); const opsCanHire=()=>lvl()>=2; @@ -52,6 +52,7 @@ function opsSanitize(s){const o=s.ops&&typeof s.ops==='object'&&!Array.isArray(s {const t=ob(o.tpl);for(const k of OPS_TPL)if(typeof t[k]==='boolean')n.tpl[k]=t[k];} {const sk=ob(o.skip);for(const c of Object.keys(sk))if(isCity(c)&&own(s.pops,c)&&Array.isArray(sk[c])){const ks=[...new Set(sk[c].filter(k=>OPS_POP.includes(k)))];if(ks.length)n.skip[c]=ks;}} if(Array.isArray(o.log))n.log=o.log.map(opsLogOk).filter(Boolean).slice(0,OPS_LOG); + n.wk=opsWkOk(o.wk);n.rep=opsWkOk(o.rep); if(s.autoSales===true)n.on.sales=true;if(s.autoRepair===true)n.on.repair=true;delete s.autoSales;delete s.autoRepair; s.ops=n;} // A log entry: {d, i: intern, r: [[kind, n, [where…]]], f: fat-finger index, c: its city, up: paid up front, mo: running costs added}. @@ -59,6 +60,17 @@ const opsWhereOk=w=>typeof w==='string'&&w.length<=48&&/^[a-z0-9~|]+( [+\w.×→ function opsLogOk(e){if(!e||typeof e!=='object'||!own(INTERNS,e.i))return null;const r=Array.isArray(e.r)?e.r.filter(x=>Array.isArray(x)&&own(OPS_SAY,x[0])&&Array.isArray(x[2])).map(x=>[x[0],int(x[1],1,1e6,1),x[2].filter(opsWhereOk).slice(0,3)]).slice(0,16):[]; const f=Number.isInteger(e.f)&&OPS_FF[e.f]?e.f:undefined,up=int(e.up,0,1e12,0),mo=int(e.mo,-1e9,1e9,0); return {d:int(e.d,0,1e7,0),i:e.i,r,...(f!==undefined&&isCity(e.c)?{f,c:e.c}:{}),...(up?{up}:{}),...(mo?{mo}:{})};} +// A week's tally, for the shift report and the one NOC notice a week: {w: week, i: intern, n: {kind: count}, wh: {kind: [where…]}, up, mo, rev, ff}. +function opsWkOk(x){if(!x||typeof x!=='object'||Array.isArray(x)||!own(INTERNS,x.i))return null;const n={},wh={},xn=x.n&&typeof x.n==='object'?x.n:{},xw=x.wh&&typeof x.wh==='object'?x.wh:{}; + for(const k of Object.keys(OPS_SAY)){if(own(xn,k)){const v=int(xn[k],0,1e6,0);if(v)n[k]=v;}if(own(xw,k)&&Array.isArray(xw[k])){const w=xw[k].filter(opsWhereOk).slice(0,3);if(w.length)wh[k]=w;}} + return {w:int(x.w,0,1e6,0),i:x.i,n,wh,up:int(x.up,0,1e12,0),mo:int(x.mo,-1e9,1e9,0),rev:int(x.rev,0,1e9,0),ff:int(x.ff,0,7,0)};} +const opsWkNew=w=>({w,i:S.ops.intern,n:{},wh:{},up:0,mo:0,rev:0,ff:0}); +const opsWkAny=x=>!!x&&(Object.keys(x.n).length>0||x.ff>0); +// "Kevin's week: signed 3 customers (+$41k/mo), topped up transit 2 times (Frankfurt +1×100G), declined 17 tiny offers. Week total: …" +function opsWeekLine(x){const I=INTERNS[x.i],name=I?tr(I.s):'',ks=Object.keys(x.n).sort((a,b)=>(a==='sales'?-1:b==='sales'?1:0)||(a==='broke')-(b==='broke')); + const parts=ks.map(k=>k==='sales'?trn('ops.w_sales',x.n[k],{rev:opsMo$(x.rev)}):trn(OPS_SAY[k],x.n[k],{where:(x.wh[k]||[]).map(opsWhere).join(', ')})); + if(x.ff)parts.push(trn('ops.w_oops',x.ff)); + return tr('ops.w_line',{name,list:parts.join(', ')})+(x.up||x.mo?' '+tr('ops.w_money',{cost:fmt$(x.up),mo:opsMo$(x.mo)}):'');} // "fra +1×100G", "fra|ams", "ams~3", "transit" (an order, for the budget line) or "ggl" (a network). function opsWhere(w){const [a,x]=w.split(' '),nm=a.split('|').map(p=>own(OPSK,p)?tr(OPSK[p].t):isCity(p)?CITY[p].name:isNet(p)?NET[p].name:ixName(p)).join('–');return x?nm+' '+(isNet(x)?NET[x].name:x):nm;} function opsLine(e){const I=INTERNS[e.i],name=I?tr(I.s):'',parts=e.r.map(([k,n,w])=>trn(OPS_SAY[k],n,{where:w.map(opsWhere).join(', ')})); @@ -171,7 +183,9 @@ function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='dive const OPS_ORDER=['repair','sales','routers','transit','optics','caches','ix','pni','decom']; // The shift: once per game day from dayTick, after outages and events have had their turn. function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} - const X=opsShift(),cash=S.cash; + // A new week: last week's tally becomes the shift report, and the one NOC notice of the week. + const w=Math.floor(d/7);if(!O.wk||O.wk.w!==w){if(opsWkAny(O.wk)&&O.wk.w${esc(tr('ops.shift_report',{name:opsName()}))} ${esc(opsWeekLine(O.rep))}`,O.rep.rev>0?'good':'',[],{a:'tab',v:'noc'});}O.wk=opsWkNew(w);} + const X=opsShift(); // One order that trips over something (an odd save, a bug) is paused and noted; payday, goals and the save still happen. opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])try{OPS_RUN[k](X);}catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);}}); const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke]]); @@ -183,7 +197,9 @@ function opsDay(d){if(!opsHired())return;const O=S.ops,m=Math.floor(d/30);if(m!= // Declining an offer or stopping at a budget changes nothing a route depends on: no recompute for those. if(X.dirty)compute(); if(e.r.length||e.f!==undefined){O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);} - if(e.r.length||e.up||e.mo)logNote(`${esc(tr('ops.shift',{name:opsName()}))} ${esc(opsLine(e))}`,cash>S.cash?'':'good',[],{a:'tab',v:'noc'});} + // The day's detail stays in the Ops sheet; the NOC gets one notice a week (above). + const W=O.wk;for(const [k,n,ws] of e.r){W.n[k]=(W.n[k]||0)+n;const a=W.wh[k]||(W.wh[k]=[]);for(const x of ws)if(a.length<3&&!a.includes(x))a.push(x);} + W.up+=e.up||0;W.mo+=e.mo||0;W.rev+=Math.round(X.rev);if(e.f!==undefined)W.ff=Math.min(7,W.ff+1);} // New POP from the template: price the whole bundle first, then click through it in one go. function opsTplQuote(c){if(!S||S.pops[c]||!cityOn(c)||(cnCity(c)&&!cnOk()))return null;const T=S.ops.tpl,parts=[];let cost=popCost(c),net=null,ix=null,kit=null; if(T.bb){cost+=bbCost(c);parts.push(tr('ops.tpl_bb'));} diff --git a/src/game/90-actions/88-ops.js b/src/game/90-actions/88-ops.js index e76b13f..3d8115a 100644 --- a/src/game/90-actions/88-ops.js +++ b/src/game/90-actions/88-ops.js @@ -2,7 +2,7 @@ const opsCycle=(a,v)=>a[(a.indexOf(v)+1)%a.length]; Object.assign(ACT,{ opsOpen:()=>{if(S)opsModal();}, - opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO(),m=Math.floor(S.day/30);O.intern=id;O.hired=S.day; + opsHire:({id})=>{if(!S||opsHired()||!own(INTERNS,id)||!opsCanHire()||!rule('clock'))return;if(!spend(INTERN_MO))return;const O=opsO(),m=Math.floor(S.day/30);O.intern=id;O.hired=S.day;O.wk=null; // A new hire starts on a fresh month's budget, whatever the last one spent. if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} O.log.unshift({d:S.day,i:id,r:[]});toast(esc(tr('ops.hired',{name:opsName(true)})),'good',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);after();opsModal();}, diff --git a/src/i18n/en.js b/src/i18n/en.js index 356b390..8c625af 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2615,7 +2615,7 @@ "ops.per_pop_note":"Green orders run in this POP. Switch one off to decide here by hand.", "ops.really_fire":"Really let go?", "ops.salary":"Salary {price}/mo · since {d}", -"ops.shift":"{name}'s shift", +"ops.shift_report":"{name}'s week", "ops.spent_and_mo":"This month: {price} up front, {mo}/mo on the bill", "ops.standing_orders":"Standing orders", "ops.template":"New POP from template", @@ -2632,6 +2632,10 @@ "ops.tracy":"Tracy", "ops.tracy_d":"Follows every packet hop by hop. Gets there in the end, with a star or two on the way.", "ops.tracy_route":"Tracy Route", +"ops.w_line":"{name} {list}.", +"ops.w_money":"Week total: {cost} up front, {mo}/mo.", +"ops.w_oops":{"one":"made one small oops","other":"made {n} small oopses"}, +"ops.w_sales":{"one":"signed a customer ({rev}/mo)","other":"signed {n} customers ({rev}/mo)"}, "optic_counts.apply_price":"Apply · {price}", "optic_counts.count_for_model":"Number of {model} channels", "optic_counts.only_n_channels_free":"Only {n} channels are free on this fiber.", diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index 1f5e0d7..fcf2d8f 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -231,13 +231,32 @@ test('the shift runs inside dayTick, respects a stopped clock, batches its work assert.deepEqual(errors, []); }); -test('the daily log line is folded into one NOC notification', t => { +test('the NOC gets one notice a week, the shift report; the daily lines stay in the Ops sheet', t => { const { ev, errors } = game(t, "S.transit[0].hist=[600]"); - hire(ev); on(ev, 'transit', { x: 1.5 }); + ev('S.day=14'); + hire(ev); on(ev, 'transit', { x: 1.5 }); on(ev, 'sales', { acc: true, min: 5000 }); + ev('S.transit[0].tier=3;S.pops.fra.rgen=3;compute()'); const n0 = ev('S.log.length'); - shift(ev); - assert.equal(ev('S.log.length'), n0 + 1); - assert.match(ev('S.log[0].t'), /Kevin's shift Kevin topped up transit/); + for (let d = 14; d < 21; d++) { + if (d === 15) ev("S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:60},{id:'big',city:'fra',name:'Big',type:'dia',bw:10,rate:600,reqs:[],exp:60}]"); + ev(`S.day=${d}`); shift(ev); + } + assert.equal(ev('S.log.length'), n0, 'a whole week of shifts: no NOC notice yet'); + assert.ok(ev('S.ops.log.length') >= 2, 'the Ops sheet has the daily detail'); + ev('S.day=21'); shift(ev); + assert.equal(ev('S.log.length'), n0 + 1, 'one notice for the week'); + assert.match(ev('S.log[0].t'), /^Kevin's week Kevin signed a customer \(\+\$6\.0k\/mo\), topped up transit .*declined a tiny offer.*Week total: \$[\d.]+k up front, \+\$[\d.]+k\/mo\./); + assert.equal(ev('S.log[0].k'), 'good'); + ev('S.day=22'); shift(ev); + assert.equal(ev('S.log.length'), n0 + 1, 'and nothing more until the next week ends'); + // Only the sales order now: one tiny offer declined on day 23, reported when the week ends. + ev("for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.sales=true;S.offers=[{id:'t2',city:'fra',name:'T2',type:'dia',bw:1,rate:600,reqs:[],exp:60}];S.day=23");shift(ev); + ev("S.day=28");shift(ev); + assert.equal(ev('S.log.length'), n0 + 2); + assert.match(ev('S.log[0].t'), /declined a tiny offer\.$/, 'nothing spent: no money line'); + assert.equal(ev('S.log[0].k'), ''); + ev("S.day=35");shift(ev); + assert.equal(ev('S.log.length'), n0 + 2, 'an idle week: no notice'); assert.deepEqual(errors, []); }); @@ -292,6 +311,9 @@ test('saves: old saves load with no intern and everything off, settings survive assert.equal(ev("JSON.stringify(S.ops.skip)"), '{"fra":["transit"]}'); assert.equal(ev("JSON.stringify(S.ops.log)"), '[{"d":1,"i":"kevin","r":[["transit",2,["fra +1×100G"]]]}]'); assert.equal(ev('S.ops.floor===50000&&S.ops.tpl.bb===true'), true); + ev(`S.ops.wk={w:3,i:'kevin',n:{sales:2,evil:9,transit:'x'},wh:{transit:['fra +1×100G','']},up:-5,mo:'a',rev:41000,ff:99};S.ops.rep={i:'mallory'};S=migrate(S)`); + assert.equal(ev("JSON.stringify(S.ops.wk)"), '{"w":3,"i":"kevin","n":{"sales":2},"wh":{"transit":["fra +1×100G"]},"up":0,"mo":0,"rev":41000,"ff":7}'); + assert.equal(ev('S.ops.rep'), null); assert.deepEqual(errors, []); }); @@ -503,6 +525,6 @@ test('transit: the log line and budget line show the monthly cost a top-up adds' assert.equal(ev('S.ops.log[0].up'), c0 - cash(ev)); assert.equal(ev('S.ops.log[0].mo'), Math.round(mo)); assert.equal(ev('Math.round(S.ops.addMo.transit)'), Math.round(mo)); - assert.match(ev('S.log[0].t'), /Cost: \$[\d.]+k up front, \+\$[\d.]+k?\/mo\./); + assert.match(ev('opsEntry(S.ops.log[0])'), /Cost: \$[\d.]+k up front, \+\$[\d.]+k?\/mo\./); assert.deepEqual(errors, []); }); From 94e71beb1667055914ed78eb634e3badde8ce385 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:39:33 +0100 Subject: [PATCH 55/64] Standing orders: the Ops sheet opens with the intern's mood and a weekly shift report --- site/i18n/de.js | 13 +++++++++ site/i18n/es.js | 13 +++++++++ site/i18n/fr.js | 13 +++++++++ site/i18n/it.js | 13 +++++++++ site/i18n/pt.js | 13 +++++++++ src/game/60-features/95-standing-orders.js | 5 ++++ src/game/93-ui/57-ops-panel.js | 5 ++++ src/i18n/en.js | 13 +++++++++ src/styles/36-ops.css | 3 ++ tests/standing-orders.test.js | 34 ++++++++++++++++++++++ 10 files changed, 125 insertions(+) diff --git a/site/i18n/de.js b/site/i18n/de.js index ba24ef2..edc2675 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2578,6 +2578,17 @@ "ops.locked":"Das NOC stellt ab Kundenlevel {lv} Praktikanten ein.", "ops.lpm_off":"Die Peering-Inbox bleibt deine Sache. Dafür gibt es das Large Peering Model; {name} macht keine E-Mails.", "ops.lpm_on":"Das Large Peering Model beantwortet die Peering-Inbox. {name} geht ihm aus dem Weg.", +"ops.mood_annie":"Annie hat drei Fragen beantwortet, bevor du sie gestellt hast, vom nächstgelegenen Schreibtisch aus.", +"ops.mood_broke":"{name} hat schon eine Einkaufsliste für das Budget des nächsten Monats.", +"ops.mood_busy":"{name} hatte eine volle Woche und ist beim dritten Energydrink.", +"ops.mood_kevin":"Kevin sagt, 2001 war es ruhiger. War es nicht.", +"ops.mood_new":"{name} hat die Kaffeemaschine und die CLI gefunden, in dieser Reihenfolge. Bereit, wenn du es bist.", +"ops.mood_oops":"{name} ist heute sehr vorsichtig. Bitte niemand die Interface-Beschreibungen erwähnen.", +"ops.mood_outage":"{name} beobachtet die Störungsgraphen und lädt die Statusseite neu. Sehr oft.", +"ops.mood_quiet":"{name} liest in Ruhe RFCs. Die Graphen sind flach, genau wie es sein soll.", +"ops.mood_sales":"{name} läuft heute etwas aufrechter: In der eigenen Schicht hat jemand unterschrieben.", +"ops.mood_snag":"{name} ist auf etwas Seltsames gestoßen, hat den Auftrag pausiert und dir einen Zettel hingeklebt.", +"ops.mood_tracy":"Tracy ist drei Hops tief in einem Traceroute, bisher mit nur einem Sternchen.", "ops.never":"nie", "ops.no_cap":"kein Limit", "ops.no_clock":"Keine Uhr, keine Schichten: Bei diesen Regeln gibt es keine Tage, an denen ein Praktikant arbeiten könnte.", @@ -2615,6 +2626,8 @@ "ops.per_pop":"Pro POP", "ops.per_pop_note":"Grüne Aufträge laufen in diesem POP. Schalte einen aus, um hier selbst zu entscheiden.", "ops.really_fire":"Wirklich entlassen?", +"ops.report_last":"Schichtbericht der letzten Woche", +"ops.report_now":"Diese Woche bisher", "ops.salary":"Gehalt {price}/Monat · seit {d}", "ops.shift_report":"{name}s Woche", "ops.spent_and_mo":"Diesen Monat: {price} einmalig, {mo}/Monat auf der Rechnung", diff --git a/site/i18n/es.js b/site/i18n/es.js index 926231d..8ed5a83 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2576,6 +2576,17 @@ "ops.locked":"El NOC contrata becarios a partir del nivel de clientes {lv}.", "ops.lpm_off":"La bandeja de peering sigue siendo cosa tuya. Para eso está el Large Peering Model; {name} no contesta correos.", "ops.lpm_on":"El Large Peering Model contesta la bandeja de peering. {name} no se mete en su camino.", +"ops.mood_annie":"Annie respondió tres preguntas antes de que las hicieras, desde la mesa más cercana.", +"ops.mood_broke":"{name} ya tiene la lista de la compra para cuando llegue el presupuesto del mes que viene.", +"ops.mood_busy":"{name} ha tenido una semana movida y va por la tercera bebida energética.", +"ops.mood_kevin":"Kevin dice que en 2001 todo estaba más tranquilo. No lo estaba.", +"ops.mood_new":"{name} ha encontrado la cafetera y la CLI, en ese orden. Cuando quieras.", +"ops.mood_oops":"{name} va con mucho cuidado hoy. Que nadie mencione las descripciones de las interfaces.", +"ops.mood_outage":"{name} está mirando las gráficas de la avería y recargando la página de estado. Mucho.", +"ops.mood_quiet":"{name} lee RFCs tranquilamente. Las gráficas están planas, como debe ser.", +"ops.mood_sales":"{name} camina un poco más erguido hoy: alguien firmó en su turno.", +"ops.mood_snag":"{name} se topó con algo raro, pausó esa orden y te dejó un pósit.", +"ops.mood_tracy":"Tracy va por el tercer salto de un traceroute, con solo un asterisco de momento.", "ops.never":"nunca", "ops.no_cap":"sin límite", "ops.no_clock":"Sin reloj no hay turnos: con estas reglas no hay días en los que un becario pueda trabajar.", @@ -2613,6 +2624,8 @@ "ops.per_pop":"Por POP", "ops.per_pop_note":"Las órdenes en verde se ejecutan en este POP. Apaga una para decidir aquí a mano.", "ops.really_fire":"¿Despedir de verdad?", +"ops.report_last":"Informe del turno de la semana pasada", +"ops.report_now":"Esta semana, hasta ahora", "ops.salary":"Sueldo {price}/mes · desde {d}", "ops.shift_report":"La semana de {name}", "ops.spent_and_mo":"Este mes: {price} de entrada, {mo}/mes en la factura", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4f802ad..f47648d 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2576,6 +2576,17 @@ "ops.locked":"Le NOC recrute des stagiaires à partir du niveau clients {lv}.", "ops.lpm_off":"La boîte de peering reste à toi. Pour ça, il y a le Large Peering Model ; {name} ne fait pas les mails.", "ops.lpm_on":"Le Large Peering Model répond à la boîte de peering. {name} reste hors de son chemin.", +"ops.mood_annie":"Annie a répondu à trois questions avant que tu les poses, depuis le bureau le plus proche.", +"ops.mood_broke":"{name} a déjà sa liste de courses pour le budget du mois prochain.", +"ops.mood_busy":"{name} a eu une semaine chargée et en est à sa troisième boisson énergisante.", +"ops.mood_kevin":"Kevin dit que c'était plus calme en 2001. Ce n'était pas le cas.", +"ops.mood_new":"{name} a trouvé la machine à café et la CLI, dans cet ordre. Prêt quand tu veux.", +"ops.mood_oops":"{name} fait très attention aujourd'hui. Personne ne parle des descriptions d'interface.", +"ops.mood_outage":"{name} surveille les graphes de la panne et rafraîchit la page de statut. Beaucoup.", +"ops.mood_quiet":"{name} lit tranquillement des RFC. Les graphes sont plats, comme il se doit.", +"ops.mood_sales":"{name} marche un peu plus droit aujourd'hui : quelqu'un a signé pendant sa garde.", +"ops.mood_snag":"{name} est tombé sur un truc bizarre, a mis cet ordre en pause et t'a laissé un post-it.", +"ops.mood_tracy":"Tracy en est au troisième saut d'un traceroute, avec une seule étoile pour l'instant.", "ops.never":"jamais", "ops.no_cap":"sans limite", "ops.no_clock":"Pas d'horloge, pas de service : avec ces règles, il n'y a pas de jours où un stagiaire pourrait travailler.", @@ -2613,6 +2624,8 @@ "ops.per_pop":"Par POP", "ops.per_pop_note":"Les ordres en vert s'appliquent à ce POP. Désactive-en un pour décider ici à la main.", "ops.really_fire":"Vraiment remercier ?", +"ops.report_last":"Rapport de garde de la semaine dernière", +"ops.report_now":"Cette semaine, jusqu'ici", "ops.salary":"Salaire {price}/mois · depuis {d}", "ops.shift_report":"La semaine de {name}", "ops.spent_and_mo":"Ce mois-ci : {price} d'entrée, {mo}/mois sur la facture", diff --git a/site/i18n/it.js b/site/i18n/it.js index 3dd131c..2b237c1 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2576,6 +2576,17 @@ "ops.locked":"Il NOC assume stagisti dal livello clienti {lv}.", "ops.lpm_off":"La casella del peering resta tua. Per quella c'è il Large Peering Model; {name} non risponde alle email.", "ops.lpm_on":"Il Large Peering Model risponde alla casella del peering. {name} gli sta alla larga.", +"ops.mood_annie":"Annie ha risposto a tre domande prima che tu le facessi, dalla scrivania più vicina.", +"ops.mood_broke":"{name} ha già la lista della spesa per quando arriva il budget del mese prossimo.", +"ops.mood_busy":"{name} ha avuto una settimana piena ed è alla terza bevanda energetica.", +"ops.mood_kevin":"Kevin dice che nel 2001 era più tranquillo. Non lo era.", +"ops.mood_new":"{name} ha trovato la macchinetta del caffè e la CLI, in quest'ordine. Pronto quando vuoi.", +"ops.mood_oops":"{name} oggi va con i piedi di piombo. Nessuno nomini le descrizioni delle interfacce.", +"ops.mood_outage":"{name} guarda i grafici del guasto e ricarica la pagina di stato. Parecchio.", +"ops.mood_quiet":"{name} legge RFC in santa pace. I grafici sono piatti, come devono essere.", +"ops.mood_sales":"{name} cammina un po' più dritto oggi: qualcuno ha firmato nel suo turno.", +"ops.mood_snag":"{name} ha trovato qualcosa di strano, ha messo in pausa quell'ordine e ti ha lasciato un post-it.", +"ops.mood_tracy":"Tracy è al terzo hop di un traceroute, con un solo asterisco per ora.", "ops.never":"mai", "ops.no_cap":"nessun limite", "ops.no_clock":"Niente orologio, niente turni: con queste regole non ci sono giorni in cui uno stagista possa lavorare.", @@ -2613,6 +2624,8 @@ "ops.per_pop":"Per POP", "ops.per_pop_note":"Gli ordini in verde valgono per questo POP. Spegnine uno per decidere qui a mano.", "ops.really_fire":"Licenziare davvero?", +"ops.report_last":"Rapporto del turno della settimana scorsa", +"ops.report_now":"Questa settimana, finora", "ops.salary":"Stipendio {price}/mese · dal {d}", "ops.shift_report":"La settimana di {name}", "ops.spent_and_mo":"Questo mese: {price} subito, {mo}/mese in bolletta", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 98dd58f..3abf166 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2576,6 +2576,17 @@ "ops.locked":"O NOC contrata estagiários a partir do nível de clientes {lv}.", "ops.lpm_off":"A caixa de peering continua com você. Para isso existe o Large Peering Model; {name} não responde e-mail.", "ops.lpm_on":"O Large Peering Model responde a caixa de peering. {name} fica fora do caminho dele.", +"ops.mood_annie":"Annie respondeu três perguntas antes de você fazê-las, da mesa mais próxima.", +"ops.mood_broke":"{name} já tem a lista de compras para quando chegar o orçamento do mês que vem.", +"ops.mood_busy":"{name} teve uma semana cheia e está na terceira bebida energética.", +"ops.mood_kevin":"Kevin diz que em 2001 era mais tranquilo. Não era.", +"ops.mood_new":"{name} encontrou a máquina de café e a CLI, nessa ordem. Pronto quando você estiver.", +"ops.mood_oops":"{name} está tomando muito cuidado hoje. Ninguém fale das descrições das interfaces.", +"ops.mood_outage":"{name} está olhando os gráficos da pane e recarregando a página de status. Muito.", +"ops.mood_quiet":"{name} lê RFCs em paz. Os gráficos estão planos, como deve ser.", +"ops.mood_sales":"{name} está andando um pouco mais ereto hoje: alguém assinou no seu turno.", +"ops.mood_snag":"{name} encontrou algo estranho, pausou essa ordem e deixou um post-it para você.", +"ops.mood_tracy":"Tracy está no terceiro salto de um traceroute, com só um asterisco até agora.", "ops.never":"nunca", "ops.no_cap":"sem limite", "ops.no_clock":"Sem relógio, sem turnos: com estas regras não há dias para um estagiário trabalhar.", @@ -2613,6 +2624,8 @@ "ops.per_pop":"Por POP", "ops.per_pop_note":"As ordens em verde valem neste POP. Desligue uma para decidir aqui na mão.", "ops.really_fire":"Dispensar mesmo?", +"ops.report_last":"Relatório do turno da semana passada", +"ops.report_now":"Esta semana, até agora", "ops.salary":"Salário {price}/mês · desde {d}", "ops.shift_report":"A semana de {name}", "ops.spent_and_mo":"Este mês: {price} de entrada, {mo}/mês na fatura", diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 38e84d6..fa6cb2e 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -71,6 +71,11 @@ function opsWeekLine(x){const I=INTERNS[x.i],name=I?tr(I.s):'',ks=Object.keys(x. const parts=ks.map(k=>k==='sales'?trn('ops.w_sales',x.n[k],{rev:opsMo$(x.rev)}):trn(OPS_SAY[k],x.n[k],{where:(x.wh[k]||[]).map(opsWhere).join(', ')})); if(x.ff)parts.push(trn('ops.w_oops',x.ff)); return tr('ops.w_line',{name,list:parts.join(', ')})+(x.up||x.mo?' '+tr('ops.w_money',{cost:fmt$(x.up),mo:opsMo$(x.mo)}):'');} +// The intern's mood, from what the week has been like. No dice: the same day always reads the same. +function opsMood(){const O=S.ops,x=O.wk&&O.wk.w===Math.floor(S.day/7)?O.wk:null,n=x?x.n:{},jobs=Object.keys(n).filter(k=>k!=='broke'&&k!=='decline').reduce((a,k)=>a+n[k],0); + const k=S.day-O.hired<7?'new':x&&x.ff?'oops':n.snag?'snag':S.inc.some(i=>i.until>S.day&&i.type!=='ddos')?'outage':n.sales?'sales':n.broke?'broke':jobs>=5?'busy':S.day%2?'quiet':O.intern; + return tr({new:N_('ops.mood_new'),oops:N_('ops.mood_oops'),snag:N_('ops.mood_snag'),outage:N_('ops.mood_outage'),sales:N_('ops.mood_sales'),broke:N_('ops.mood_broke'),busy:N_('ops.mood_busy'),quiet:N_('ops.mood_quiet'), + annie:N_('ops.mood_annie'),kevin:N_('ops.mood_kevin'),tracy:N_('ops.mood_tracy')}[k],{name:opsName()});} // "fra +1×100G", "fra|ams", "ams~3", "transit" (an order, for the budget line) or "ggl" (a network). function opsWhere(w){const [a,x]=w.split(' '),nm=a.split('|').map(p=>own(OPSK,p)?tr(OPSK[p].t):isCity(p)?CITY[p].name:isNet(p)?NET[p].name:ixName(p)).join('–');return x?nm+' '+(isNet(x)?NET[x].name:x):nm;} function opsLine(e){const I=INTERNS[e.i],name=I?tr(I.s):'',parts=e.r.map(([k,n,w])=>trn(OPS_SAY[k],n,{where:w.map(opsWhere).join(', ')})); diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js index 58dc5d4..6311991 100644 --- a/src/game/93-ui/57-ops-panel.js +++ b/src/game/93-ui/57-ops-panel.js @@ -22,6 +22,7 @@ function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr(I.n)}
${tr('ops.salary',{price:fmt$(INTERN_MO),d:dateStr(O.hired)})}
${btn(UI.confirm==='opsFire'?tr('ops.really_fire'):tr('ops.fire'),'opsFire',{},'ghost sm')}
+

${esc(opsMood())}

${opsReportHtml()} ${O.log.length?`
${O.log.slice(0,6).map(e=>esc(tr('peering_inbox.day_d',{d:e.d})+': '+opsEntry(e))).join('\n')}
`:''}

${ibx().bot?tr('ops.lpm_on',{name:opsName()}):tr('ops.lpm_off',{name:opsName()})}

${btn(`${tr('ops.floor')}: ${O.floor?fmt$(O.floor):tr('ops.no_cap')}`,'opsFloor',{},'ghost sm')}
`; @@ -33,6 +34,10 @@ function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr('ops.per_pop_note')}

`; h+=`

${tr('ops.template')}

${tr('ops.template_note',{name:opsName()})}

${OPS_TPL.map(k=>``).join('')}
`; h+=opsOnceHtml();openModal(h,'ops');} +// The shift report: last week in one paragraph, and this week so far. The daily lines below are the detail. +function opsReportHtml(){const O=S.ops,w=Math.floor(S.day/7),cur=O.wk&&O.wk.w===w&&opsWkAny(O.wk)?O.wk:null,rep=O.rep&&O.rep.w===w-1?O.rep:null;if(!cur&&!rep)return ''; + const row=(t,x)=>`
${t}
${esc(opsWeekLine(x))}
`; + return (rep?row(tr('ops.report_last'),rep):'')+(cur?row(tr('ops.report_now'),cur):'');} // The big one-off batches (#181, #192) live here now, next to the orders that run them every week. const opsOnceHtml=()=>`

${tr('ops.by_hand')}

${tr('ops.by_hand_note')}

${btn(tr('utilities.title'),'utilities',{},'sm')}${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'sm')}
`; // On a city without a POP: open it from the template in one tap. diff --git a/src/i18n/en.js b/src/i18n/en.js index 8c625af..3961584 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2577,6 +2577,17 @@ "ops.locked":"The NOC hires interns from customer level {lv}.", "ops.lpm_off":"The peering inbox is still yours. Hire the Large Peering Model for that; {name} does not do email.", "ops.lpm_on":"The Large Peering Model answers the peering inbox. {name} keeps out of its way.", +"ops.mood_annie":"Annie answered three questions before you asked them, from whichever desk was closest.", +"ops.mood_broke":"{name} has a shopping list ready for when next month's budget comes in.", +"ops.mood_busy":"{name} has had a busy week and is on their third energy drink.", +"ops.mood_kevin":"Kevin says it was quieter back in 2001. It was not.", +"ops.mood_new":"{name} has found the coffee machine and the CLI, in that order. Ready when you are.", +"ops.mood_oops":"{name} is being very careful today. Nobody mention the interface descriptions.", +"ops.mood_outage":"{name} is watching the outage graphs and refreshing the status page. A lot.", +"ops.mood_quiet":"{name} is quietly reading RFCs. The graphs are flat, which is how they like them.", +"ops.mood_sales":"{name} is walking a little taller: someone signed on their shift.", +"ops.mood_snag":"{name} hit something odd, paused that order and left you a sticky note.", +"ops.mood_tracy":"Tracy is three hops into a traceroute, with only one star so far.", "ops.never":"never", "ops.no_cap":"no limit", "ops.no_clock":"No clock, no shifts: these rules have no days for an intern to work.", @@ -2614,6 +2625,8 @@ "ops.per_pop":"Per POP", "ops.per_pop_note":"Green orders run in this POP. Switch one off to decide here by hand.", "ops.really_fire":"Really let go?", +"ops.report_last":"Last week's shift report", +"ops.report_now":"This week so far", "ops.salary":"Salary {price}/mo · since {d}", "ops.shift_report":"{name}'s week", "ops.spent_and_mo":"This month: {price} up front, {mo}/mo on the bill", diff --git a/src/styles/36-ops.css b/src/styles/36-ops.css index 5dc6720..6a2cbf5 100644 --- a/src/styles/36-ops.css +++ b/src/styles/36-ops.css @@ -11,3 +11,6 @@ .ops-p{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} .ops-p .b{white-space:normal;text-align:left;min-height:36px} .ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto} +.ops-mood{margin:6px 0 0;font-style:italic;font-size:13px;color:var(--ink2)} +.ops-rep{border-left:3px solid #8E5CF7;background:#F7F2FF;border-radius:0 8px 8px 0;padding:6px 8px;margin:6px 0;font-size:13px;line-height:1.35;overflow-wrap:anywhere} +.ops-rep .eyebrow{margin-bottom:2px} diff --git a/tests/standing-orders.test.js b/tests/standing-orders.test.js index fcf2d8f..ecb4848 100644 --- a/tests/standing-orders.test.js +++ b/tests/standing-orders.test.js @@ -260,6 +260,40 @@ test('the NOC gets one notice a week, the shift report; the daily lines stay in assert.deepEqual(errors, []); }); +test('the Ops sheet opens with the intern\'s mood and the weekly shift report, at 360 px, in every language', t => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const h = load(lang === 'en' ? {} : { lang }); + const { ev, dom, errors } = h; + ev(BASE); ev('S.day=14'); dom.window.innerWidth = 360; + hire(ev); + ev('opsModal()'); + const mood = () => dom.window.document.querySelector('#modalCard .ops-mood').textContent; + assert.equal(mood(), ev("tr('ops.mood_new',{name:opsName()})"), lang + ': a new hire says so'); + on(ev, 'transit', { x: 1.5 }, 0); + ev("S.transit[0].hist=[600];S.day=21");shift(ev);ev("S.transit[0].hist=[6000];S.day=28");shift(ev);ev('opsModal()'); + const reps = [...dom.window.document.querySelectorAll('#modalCard .ops-rep')]; + assert.equal(reps.length, 2, lang + ': last week, and this week so far'); + assert.equal(reps[0].lastElementChild.textContent, ev('opsWeekLine(S.ops.rep)'), lang); + assert.ok(mood().length > 10, lang); + assert.doesNotMatch(dom.window.document.getElementById('modalCard').textContent, /\bops\.[a-z_]+/, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); + +test('the mood follows the week, with no dice', t => { + const { ev, errors } = game(t); + ev('S.day=100'); hire(ev); ev('S.day=110'); + const quiet = ev('opsMood()'); + assert.equal(ev('opsMood()'), quiet, 'the same day reads the same'); + assert.ok([ev("tr('ops.mood_quiet',{name:'Kevin'})"), ev("tr('ops.mood_kevin')")].includes(quiet)); + ev("S.ops.wk=opsWkNew(Math.floor(S.day/7));S.ops.wk.n.sales=1"); + assert.equal(ev('opsMood()'), ev("tr('ops.mood_sales',{name:'Kevin'})")); + ev("S.ops.wk.n.broke=1;delete S.ops.wk.n.sales"); + assert.equal(ev('opsMood()'), ev("tr('ops.mood_broke',{name:'Kevin'})")); + assert.deepEqual(errors, []); +}); + test('fat fingers: never under Change Freeze, rare and harmless in On-call and BGP at 3 a.m.', t => { const { ev, errors } = game(t); hire(ev); From 9a0fb48aa310199d89f3d8cb5a0b58a10407602f Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:40:14 +0100 Subject: [PATCH 56/64] Standing orders: the hiring pitch promises the weekly shift report --- site/i18n/de.js | 2 +- site/i18n/es.js | 2 +- site/i18n/fr.js | 2 +- site/i18n/it.js | 2 +- site/i18n/pt.js | 2 +- src/game/93-ui/57-ops-panel.js | 2 +- src/i18n/en.js | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index edc2675..7c8665b 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2549,8 +2549,8 @@ "ops.floor":"Mindestens behalten", "ops.hire_an_intern":"NOC-Praktikant einstellen", "ops.hire_mo":"Einstellen · {price}/Monat", -"ops.hire_pitch":"Keine Lust mehr, in jeder Stadt dieselben fünfzehn Buttons zu klicken? Stell einen NOC-Praktikanten ein. Du schreibst die Daueraufträge einmal; er arbeitet sie jeden Tag ab, zahlt genau das, was deine Klicks kosten würden, und hinterlässt eine Zeile im Log.", "ops.hire_pitch_short":"Regeln einmal festlegen, und ein Praktikant klickt jeden Tag die Buttons.", +"ops.hire_pitch_weekly":"Keine Lust mehr, in jeder Stadt dieselben fünfzehn Buttons zu klicken? Stell einen NOC-Praktikanten ein. Du schreibst die Daueraufträge einmal; er arbeitet sie jeden Tag ab, zahlt genau das, was deine Klicks kosten würden, und gibt dir jede Woche einen Schichtbericht.", "ops.hired":"{name} ist im NOC. Schreib ein paar Daueraufträge, morgen geht es los.", "ops.how_add":"Router dazu", "ops.how_auto":"erst dazu, dann tauschen", diff --git a/site/i18n/es.js b/site/i18n/es.js index 8ed5a83..b78ddf3 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2547,8 +2547,8 @@ "ops.floor":"Conservar al menos", "ops.hire_an_intern":"Contratar a un becario del NOC", "ops.hire_mo":"Contratar · {price}/mes", -"ops.hire_pitch":"¿Harto de pulsar los mismos quince botones en cada ciudad? Contrata a un becario del NOC. Escribes las órdenes permanentes una vez; las ejecuta cada día, paga exactamente lo que costarían tus clics y deja una línea en el registro.", "ops.hire_pitch_short":"Fija las reglas una vez y un becario pulsa los botones cada día.", +"ops.hire_pitch_weekly":"¿Harto de pulsar los mismos quince botones en cada ciudad? Contrata a un becario del NOC. Escribes las órdenes permanentes una vez; las ejecuta cada día, paga exactamente lo que costarían tus clics y te entrega un informe de turno cada semana.", "ops.hired":"{name} se ha unido al NOC. Escribe unas órdenes permanentes y mañana se pone a trabajar.", "ops.how_add":"añadir router", "ops.how_auto":"añadir y luego cambiar", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f47648d..af5de6f 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2547,8 +2547,8 @@ "ops.floor":"Garder au moins", "ops.hire_an_intern":"Recruter un stagiaire NOC", "ops.hire_mo":"Recruter · {price}/mois", -"ops.hire_pitch":"Marre de cliquer sur les mêmes quinze boutons dans chaque ville ? Recrute un stagiaire NOC. Tu écris les ordres permanents une fois ; il les exécute chaque jour, paie exactement ce que coûteraient tes clics et laisse une ligne dans le journal.", "ops.hire_pitch_short":"Fixe les règles une fois, un stagiaire clique sur les boutons chaque jour.", +"ops.hire_pitch_weekly":"Marre de cliquer sur les mêmes quinze boutons dans chaque ville ? Recrute un stagiaire NOC. Tu écris les ordres permanents une fois ; il les exécute chaque jour, paie exactement ce que coûteraient tes clics et te remet un rapport de garde chaque semaine.", "ops.hired":"{name} a rejoint le NOC. Écris quelques ordres permanents, et au travail dès demain.", "ops.how_add":"ajouter un routeur", "ops.how_auto":"ajouter, puis changer", diff --git a/site/i18n/it.js b/site/i18n/it.js index 2b237c1..bdcb22c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2547,8 +2547,8 @@ "ops.floor":"Tieni almeno", "ops.hire_an_intern":"Assumi uno stagista NOC", "ops.hire_mo":"Assumi · {price}/mese", -"ops.hire_pitch":"Stufo di cliccare gli stessi quindici pulsanti in ogni città? Assumi uno stagista NOC. Scrivi gli ordini permanenti una volta sola; lui li esegue ogni giorno, paga esattamente quanto costerebbero i tuoi clic e lascia una riga nel registro.", "ops.hire_pitch_short":"Fissa le regole una volta, e uno stagista clicca i pulsanti ogni giorno.", +"ops.hire_pitch_weekly":"Stufo di cliccare gli stessi quindici pulsanti in ogni città? Assumi uno stagista NOC. Scrivi gli ordini permanenti una volta sola; lui li esegue ogni giorno, paga esattamente quanto costerebbero i tuoi clic e ti consegna un rapporto del turno ogni settimana.", "ops.hired":"{name} è entrato nel NOC. Scrivi qualche ordine permanente e domani si comincia.", "ops.how_add":"aggiungi router", "ops.how_auto":"aggiungi, poi cambia", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 3abf166..68cbc2b 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2547,8 +2547,8 @@ "ops.floor":"Manter pelo menos", "ops.hire_an_intern":"Contratar um estagiário de NOC", "ops.hire_mo":"Contratar · {price}/mês", -"ops.hire_pitch":"Cansado de clicar nos mesmos quinze botões em cada cidade? Contrate um estagiário de NOC. Você escreve as ordens permanentes uma vez; ele as executa todo dia, paga exatamente o que seus cliques custariam e deixa uma linha no registro.", "ops.hire_pitch_short":"Defina as regras uma vez, e um estagiário clica nos botões todo dia.", +"ops.hire_pitch_weekly":"Cansado de clicar nos mesmos quinze botões em cada cidade? Contrate um estagiário de NOC. Você escreve as ordens permanentes uma vez; ele as executa todo dia, paga exatamente o que seus cliques custariam e entrega um relatório de turno toda semana.", "ops.hired":"{name} entrou no NOC. Escreva algumas ordens permanentes e amanhã começa o trabalho.", "ops.how_add":"adicionar roteador", "ops.how_auto":"adicionar, depois trocar", diff --git a/src/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js index 6311991..711c913 100644 --- a/src/game/93-ui/57-ops-panel.js +++ b/src/game/93-ui/57-ops-panel.js @@ -14,7 +14,7 @@ function opsOrderHtml(d){const k=d.k,on=S.ops.on[k],cap=d.cap?opsCap(k):0,sp=S.o ${sp||am?`
${tr('ops.spent_and_mo',{price:fmt$(sp),mo:opsMo$(am)})}
`:''} ${k==='ix'&&ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

`:''}`:''}
`;} function opsModal(){if(!S)return;const hired=opsHired();let h=`
${tr('ops.ops')}

${tr('ops.standing_orders')}

`; - if(!hired){h+=`

${tr('ops.hire_pitch')}

`; + if(!hired){h+=`

${tr('ops.hire_pitch_weekly')}

`; if(!rule('clock'))h+=`

${tr('ops.no_clock')}

`;else if(!opsCanHire())h+=`

${tr('ops.locked',{lv:2})}

`; else h+=Object.entries(INTERNS).map(([id,I])=>`
${tr(I.n)}
${tr(I.d)}
${btn(tr('ops.hire_mo',{price:fmt$(INTERN_MO)}),'opsHire',{id},'pink sm',S.cash
`).join(''); diff --git a/src/i18n/en.js b/src/i18n/en.js index 3961584..221aee5 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2548,8 +2548,8 @@ "ops.floor":"Keep at least", "ops.hire_an_intern":"Hire a NOC intern", "ops.hire_mo":"Hire · {price}/mo", -"ops.hire_pitch":"Tired of clicking the same fifteen buttons in every city? Hire a NOC intern. You write the standing orders once; they run them every day, pay exactly what your clicks would, and leave one line in the log.", "ops.hire_pitch_short":"Set the rules once, and an intern clicks the buttons every day.", +"ops.hire_pitch_weekly":"Tired of clicking the same fifteen buttons in every city? Hire a NOC intern. You write the standing orders once; they run them every day, pay exactly what your clicks would, and hand you a shift report every week.", "ops.hired":"{name} joined the NOC. Write some standing orders and they get to work tomorrow.", "ops.how_add":"add a router", "ops.how_auto":"add, then swap", From ec1cf7d3b559db63bdc6935e220cd7710980b238 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:40:25 +0100 Subject: [PATCH 57/64] CHANGELOG: standing orders as they ship (sales and repair orders credit #185, PNI batches in the Ops sheet, weekly report) --- CHANGELOG.md | 6 +++--- docs/ARCHITECTURE.md | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f13ceb4..540552c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,11 +29,11 @@ All notable changes to this project are documented here. The project follows - DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center. - Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation. - Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf. -- Order PNIs with one network or every network at all shared POPs from the NOC Traffic tab: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time. +- Order PNIs with one network or every network at all shared POPs from the Ops sheet: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time. - Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. -- Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, and the intern writes one line a day in the NOC (#98, #100, #102, #181, #185, #192, #177). +- Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, never breaks a customer's or a bank's transit requirement, and shows what it adds to your monthly bill. The Ops sheet opens with the intern's mood and a weekly shift report, which is also the one notice a week the intern leaves in the NOC (#98, #100, #102, #181, #185, #192, #177). - Open a new city from a template in one tap: POP, broadband, transit, an IX port and the redundancy kit, priced up front, with your standing orders taking it from there (#98, #192). -- Auto-accept and auto-pay repairs are now the intern's sales and repair orders and run once a game day; saved games keep both switched on, and they start working once you hire an intern. The bulk peering and PNI batches moved into the Ops sheet, next to the orders that repeat them (#185, #181, #192). +- The intern only signs a customer after a trial run shows the network can carry them without hurting anyone else, and rushes every repair that has a price, while the budget lasts (#185). The bulk peering and PNI batches live in the Ops sheet, next to the orders that repeat them (#181, #192). ## [1.36.0] — 2026-10-28 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1e23b3b..2fb2810 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -100,7 +100,8 @@ never freezes the game. 4. Rolls failures (`fireFailure()`) and events (`fireEvent()`) when their timers run out, and expires incidents. Then the NOC intern's standing orders (`opsDay()`), if one is hired: each order clicks the same `ACT` - actions a player would, muted, within its monthly budget, and the shift recomputes once at the end. + actions a player would, muted, within its monthly budget, and the shift recomputes once at the end, only if + a job changed the network. An order that throws is paused; the day goes on. The NOC gets one notice a week. 5. Updates customer mood, churn and new offers; IX members join; loans tick. 6. Every 30 days: bills the month (revenue minus costs) and checks for bankruptcy. 7. Checks goals, level, badges and scenario end conditions. From 34b72f6d444aaed3e88d235fa3a31c698eb39e79 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:42:37 +0100 Subject: [PATCH 58/64] Weekly puzzle: Sunday 06:00 Berlin weeks, published puzzle fetched when Puzzles opens, seeded fallback, countdown and door badge --- site/i18n/de.js | 34 ++++++++++ site/i18n/es.js | 34 ++++++++++ site/i18n/fr.js | 34 ++++++++++ site/i18n/it.js | 34 ++++++++++ site/i18n/pt.js | 34 ++++++++++ site/sw.js | 6 ++ src/game/60-features/92-puzzles.js | 8 +-- src/game/60-features/93-puzzles-weekly.js | 75 +++++++++++++++++++++++ src/game/90-actions/95-puzzles.js | 4 +- src/game/95-modals/40-title.js | 2 +- src/game/95-modals/95-puzzles.js | 16 +++-- src/i18n/en.js | 34 ++++++++++ src/styles/70-puzzles.css | 5 ++ 13 files changed, 307 insertions(+), 13 deletions(-) create mode 100644 src/game/60-features/93-puzzles-weekly.js diff --git a/site/i18n/de.js b/site/i18n/de.js index c6b6e91..f0b8670 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2874,14 +2874,18 @@ "puzzles.keep_building":"Weiterbauen", "puzzles.kiwi_fruit_salad":"Kiwi-Obstsalat", "puzzles.lease_a_wave_to":"Wave mieten nach", +"puzzles.loading_this_week_s_puzzle":"Lade das Puzzle dieser Woche…", "puzzles.more_puzzles":"Mehr Puzzles", "puzzles.n_1_club":"N-1-Club", "puzzles.n_1_connect_everything_first":"N-1: erst alles verbinden", "puzzles.n_g_links":"{n}G-Links", "puzzles.n_week_streak":{"one":"{n} Woche in Folge","other":"{n} Wochen in Folge"}, +"puzzles.new_this_sunday":"Neu diesen Sonntag!", "puzzles.new_zealand_is_far_from_everything":"Neuseeland ist weit weg von allem. Genau das ist der Witz, und das Problem.", "puzzles.next_pack_unlocks_at_n":"Nächstes Paket, {pack}, ab {n}⭐", "puzzles.next_puzzle":"Nächstes Puzzle", +"puzzles.next_weekly_in_d_h":"Nächstes Wochenpuzzle in {d} T. {h} Std.", +"puzzles.next_weekly_in_h_m":"Nächstes Wochenpuzzle in {h} Std. {m} Min.", "puzzles.no_budget":"kein Budget", "puzzles.no_budget_star_on_the_house":"kein Budget: ⭐ geht aufs Haus", "puzzles.no_cable_lands_in_both_try":"Kein Kabel landet in {a} und {b}. Versuch es mit einem Trittstein dazwischen.", @@ -2947,6 +2951,36 @@ "puzzles.with_the_pop_price":"mit POP: {price}", "puzzles.your_first_tubes_no_pressure":"Deine ersten Röhren. Kein Druck, kein Budget.", "puzzles.your_stars":"Deine Sterne", +"puzzles_weekly.detour":"Umleitung", +"puzzles_weekly.island_hopping":"Inselhüpfen", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Ein Ring übersteht jeden einzelnen Schnitt. Genau dafür ist er ein Ring.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Ein Roadtrip für Photonen. Proviant nicht inbegriffen.", +"puzzles_weekly.joke_a_to_b_under_ms":"{a} nach {b} in unter {ms} ms. Die Börsenhändler schauen zu.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Jeder Hop ist ein Kabel, und jedes Kabel ist eine lange Bootsfahrt.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} hat eine sehr teure Woche. Fahr drumherum.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} Städte, ein Kontinent und jede Menge Gräben zu buddeln.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Ein Ring durch jeden POP: je zwei Links, keine Abkürzungen, keine Stichleitungen.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Irgendwo zwischen {a} und {b} wartet schon ein Reparaturschiff. Plan es ein.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"Der billigste Weg zwischen zwei Inseln ist selten eine Gerade.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"Der naheliegende Weg führt durch {hub}. Der naheliegende Weg ist gesperrt.", +"puzzles_weekly.joke_the_ocean_is_big_and":"Der Ozean ist groß, und Anker gibt es viele. Nimm ein Ersatzkabel mit.", +"puzzles_weekly.joke_the_speed_of_light_is":"Die Lichtgeschwindigkeit ist kein Vorschlag. Nimm das geradeste Glas.", +"puzzles_weekly.latency_sprint":"Latenz-Sprint", +"puzzles_weekly.name_across_the_big_blue":"Übers große Blau", +"puzzles_weekly.name_anywhere_but_hub":"Überall, nur nicht {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"Sind wir schon da, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Hopp, Hopp, Seekabel", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms oder nichts", +"puzzles_weekly.name_one_ring_to_rule_reg":"Ein Ring, sie alle zu knechten: {reg}", +"puzzles_weekly.name_race_to_b":"Wettrennen nach {b}", +"puzzles_weekly.name_ring_around_reg":"Ringelreihen durch {reg}", +"puzzles_weekly.name_sea_you_in_b":"Wir sehen uns in {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sonne, Strand und Seekabel", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Wer braucht schon {hub}?", +"puzzles_weekly.ocean_crossing":"Ozeanüberquerung", +"puzzles_weekly.region_tour":"Rundreise", +"puzzles_weekly.ring":"Ring", "reach_and_subsea.premium_submarine_terminals":"Premium-Seekabel-Terminals", "release_notes.and_n_more_change":{"one":"… und {n} weitere Änderung","other":"… und {n} weitere Änderungen"}, "release_notes.read_the_full_notes_on_github":"Alle Hinweise auf GitHub lesen", diff --git a/site/i18n/es.js b/site/i18n/es.js index 4ab93d8..7d6d2c7 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2872,14 +2872,18 @@ "puzzles.keep_building":"Seguir construyendo", "puzzles.kiwi_fruit_salad":"Macedonia de kiwi", "puzzles.lease_a_wave_to":"Alquilar una onda hasta", +"puzzles.loading_this_week_s_puzzle":"Cargando el puzle de esta semana…", "puzzles.more_puzzles":"Más puzles", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1: primero conéctalo todo", "puzzles.n_g_links":"enlaces de {n}G", "puzzles.n_week_streak":{"one":"{n} semana seguida","other":"{n} semanas seguidas"}, +"puzzles.new_this_sunday":"¡Nuevo este domingo!", "puzzles.new_zealand_is_far_from_everything":"Nueva Zelanda está lejos de todo. Esa es la gracia, y el problema.", "puzzles.next_pack_unlocks_at_n":"El siguiente pack, {pack}, se desbloquea con {n}⭐", "puzzles.next_puzzle":"Siguiente puzle", +"puzzles.next_weekly_in_d_h":"Próximo puzle semanal en {d} d {h} h", +"puzzles.next_weekly_in_h_m":"Próximo puzle semanal en {h} h {m} min", "puzzles.no_budget":"sin presupuesto", "puzzles.no_budget_star_on_the_house":"sin presupuesto: ⭐ invita la casa", "puzzles.no_cable_lands_in_both_try":"Ningún cable llega a {a} y a {b}. Prueba con una escala entre medias.", @@ -2945,6 +2949,36 @@ "puzzles.with_the_pop_price":"con el POP: {price}", "puzzles.your_first_tubes_no_pressure":"Tus primeros tubos. Sin presión, sin presupuesto.", "puzzles.your_stars":"Tus estrellas", +"puzzles_weekly.detour":"Desvío", +"puzzles_weekly.island_hopping":"De isla en isla", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anillo sobrevive a cualquier corte. Para eso es un anillo.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Un viaje por carretera para fotones. Bocadillos no incluidos.", +"puzzles_weekly.joke_a_to_b_under_ms":"De {a} a {b} en menos de {ms} ms. Los traders están mirando.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Cada salto es un cable, y cada cable es un largo viaje en barco.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} tiene una semana carísima. Rodéalo.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} ciudades, un continente y muchas zanjas por cavar.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Un anillo por cada POP: dos enlaces cada uno, sin atajos ni ramales.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"En algún punto entre {a} y {b} ya espera un barco de reparación. Tenlo en cuenta.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"El camino más barato entre dos islas casi nunca es una línea recta.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"El camino obvio pasa por {hub}. El camino obvio está cerrado.", +"puzzles_weekly.joke_the_ocean_is_big_and":"El océano es grande y las anclas son muchas. Lleva un cable de repuesto.", +"puzzles_weekly.joke_the_speed_of_light_is":"La velocidad de la luz no es una sugerencia. Elige el vidrio más recto.", +"puzzles_weekly.latency_sprint":"Sprint de latencia", +"puzzles_weekly.name_across_the_big_blue":"A través del gran azul", +"puzzles_weekly.name_anywhere_but_hub":"Cualquier sitio menos {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"¿Falta mucho, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Salto, brinco y cable", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms o nada", +"puzzles_weekly.name_one_ring_to_rule_reg":"Un anillo para gobernar {reg}", +"puzzles_weekly.name_race_to_b":"Carrera a {b}", +"puzzles_weekly.name_ring_around_reg":"Anillo por {reg}", +"puzzles_weekly.name_sea_you_in_b":"Nos vemos en {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sol, playa y cable submarino", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"¿Quién necesita {hub}?", +"puzzles_weekly.ocean_crossing":"Cruzar el océano", +"puzzles_weekly.region_tour":"Gira regional", +"puzzles_weekly.ring":"Anillo", "reach_and_subsea.premium_submarine_terminals":"Terminales submarinas premium", "release_notes.and_n_more_change":{"one":"…y {n} cambio más","other":"…y {n} cambios más"}, "release_notes.read_the_full_notes_on_github":"Lee las notas completas en GitHub", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 26a6ad8..9d56fa0 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2872,14 +2872,18 @@ "puzzles.keep_building":"Continuer à construire", "puzzles.kiwi_fruit_salad":"Salade de kiwis", "puzzles.lease_a_wave_to":"Louer une longueur d’onde vers", +"puzzles.loading_this_week_s_puzzle":"Chargement du puzzle de la semaine…", "puzzles.more_puzzles":"Plus de puzzles", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1 : relie d’abord tout", "puzzles.n_g_links":"liens {n}G", "puzzles.n_week_streak":{"one":"{n} semaine d’affilée","other":"{n} semaines d’affilée"}, +"puzzles.new_this_sunday":"Nouveau ce dimanche !", "puzzles.new_zealand_is_far_from_everything":"La Nouvelle-Zélande est loin de tout. C’est tout l’intérêt, et tout le problème.", "puzzles.next_pack_unlocks_at_n":"Prochain pack, {pack}, à {n}⭐", "puzzles.next_puzzle":"Puzzle suivant", +"puzzles.next_weekly_in_d_h":"Prochain puzzle de la semaine dans {d} j {h} h", +"puzzles.next_weekly_in_h_m":"Prochain puzzle de la semaine dans {h} h {m} min", "puzzles.no_budget":"sans budget", "puzzles.no_budget_star_on_the_house":"sans budget : ⭐ offerte par la maison", "puzzles.no_cable_lands_in_both_try":"Aucun câble n’atterrit à la fois à {a} et à {b}. Essaie une escale entre les deux.", @@ -2945,6 +2949,36 @@ "puzzles.with_the_pop_price":"avec le POP : {price}", "puzzles.your_first_tubes_no_pressure":"Tes premiers tubes. Pas de pression, pas de budget.", "puzzles.your_stars":"Tes étoiles", +"puzzles_weekly.detour":"Détour", +"puzzles_weekly.island_hopping":"Saut d’île en île", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anneau survit à n’importe quelle coupure. C’est tout l’intérêt d’un anneau.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Un road trip pour photons. Casse-croûte non compris.", +"puzzles_weekly.joke_a_to_b_under_ms":"De {a} à {b} en moins de {ms} ms. Les traders regardent.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Chaque saut est un câble, et chaque câble est une longue traversée en bateau.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} passe une semaine très chère. Contourne-le.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} villes, un continent et beaucoup de tranchées à creuser.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Un anneau par chaque POP : deux liens chacun, pas de raccourci, pas d’antenne.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Quelque part entre {a} et {b}, un navire câblier attend déjà. Prévois-le.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"Le chemin le moins cher entre deux îles est rarement une ligne droite.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"Le chemin évident passe par {hub}. Le chemin évident est fermé.", +"puzzles_weekly.joke_the_ocean_is_big_and":"L’océan est grand et les ancres sont nombreuses. Prévois un câble de secours.", +"puzzles_weekly.joke_the_speed_of_light_is":"La vitesse de la lumière n’est pas une suggestion. Prends la fibre la plus droite.", +"puzzles_weekly.latency_sprint":"Sprint de latence", +"puzzles_weekly.name_across_the_big_blue":"Le Grand Bleu", +"puzzles_weekly.name_anywhere_but_hub":"Partout sauf {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"On arrive quand, {a} ?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Un saut, deux sauts, un câble", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms ou rien", +"puzzles_weekly.name_one_ring_to_rule_reg":"Un anneau pour gouverner {reg}", +"puzzles_weekly.name_race_to_b":"Course vers {b}", +"puzzles_weekly.name_ring_around_reg":"La ronde de {reg}", +"puzzles_weekly.name_sea_you_in_b":"Rendez-vous à {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Soleil, plage et câble sous-marin", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Qui a besoin de {hub} ?", +"puzzles_weekly.ocean_crossing":"Traversée de l’océan", +"puzzles_weekly.region_tour":"Tour de la région", +"puzzles_weekly.ring":"Anneau", "reach_and_subsea.premium_submarine_terminals":"Terminaux sous-marins premium", "release_notes.and_n_more_change":{"one":"…et {n} autre changement","other":"…et {n} autres changements"}, "release_notes.read_the_full_notes_on_github":"Lire les notes complètes sur GitHub", diff --git a/site/i18n/it.js b/site/i18n/it.js index b2547d1..2b8871b 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2872,14 +2872,18 @@ "puzzles.keep_building":"Continua a costruire", "puzzles.kiwi_fruit_salad":"Macedonia di kiwi", "puzzles.lease_a_wave_to":"Noleggia una wave verso", +"puzzles.loading_this_week_s_puzzle":"Carico il puzzle della settimana…", "puzzles.more_puzzles":"Altri puzzle", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_connect_everything_first":"N-1: prima collega tutto", "puzzles.n_g_links":"link da {n}G", "puzzles.n_week_streak":{"one":"{n} settimana di fila","other":"{n} settimane di fila"}, +"puzzles.new_this_sunday":"Nuovo questa domenica!", "puzzles.new_zealand_is_far_from_everything":"La Nuova Zelanda è lontana da tutto. È proprio questo il bello, e il problema.", "puzzles.next_pack_unlocks_at_n":"Il prossimo pacchetto, {pack}, si sblocca a {n}⭐", "puzzles.next_puzzle":"Prossimo puzzle", +"puzzles.next_weekly_in_d_h":"Prossimo puzzle settimanale tra {d} g {h} h", +"puzzles.next_weekly_in_h_m":"Prossimo puzzle settimanale tra {h} h {m} min", "puzzles.no_budget":"senza budget", "puzzles.no_budget_star_on_the_house":"senza budget: ⭐ offerta dalla casa", "puzzles.no_cable_lands_in_both_try":"Nessun cavo approda sia a {a} che a {b}. Prova con una tappa in mezzo.", @@ -2945,6 +2949,36 @@ "puzzles.with_the_pop_price":"con il POP: {price}", "puzzles.your_first_tubes_no_pressure":"I tuoi primi tubi. Niente pressione, niente budget.", "puzzles.your_stars":"Le tue stelle", +"puzzles_weekly.detour":"Deviazione", +"puzzles_weekly.island_hopping":"Di isola in isola", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Un anello sopravvive a qualsiasi taglio. È proprio il bello dell’anello.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Un viaggio on the road per fotoni. Panini non inclusi.", +"puzzles_weekly.joke_a_to_b_under_ms":"Da {a} a {b} in meno di {ms} ms. I trader ti guardano.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Ogni salto è un cavo, e ogni cavo è un lungo viaggio in barca.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} ha una settimana carissima. Giraci intorno.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} città, un continente e un sacco di scavi da fare.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Un anello per ogni POP: due link ciascuno, niente scorciatoie, niente diramazioni.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Da qualche parte tra {a} e {b} una nave posacavi sta già aspettando. Tienine conto.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"La strada più economica tra due isole raramente è una linea retta.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"La strada ovvia passa da {hub}. La strada ovvia è chiusa.", +"puzzles_weekly.joke_the_ocean_is_big_and":"L’oceano è grande e le ancore sono tante. Porta un cavo di scorta.", +"puzzles_weekly.joke_the_speed_of_light_is":"La velocità della luce non è un suggerimento. Scegli il vetro più dritto.", +"puzzles_weekly.latency_sprint":"Sprint di latenza", +"puzzles_weekly.name_across_the_big_blue":"Oltre il grande blu", +"puzzles_weekly.name_anywhere_but_hub":"Ovunque tranne {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"Quanto manca, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Un salto, un balzo e un cavo", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms o niente", +"puzzles_weekly.name_one_ring_to_rule_reg":"Un anello per domare {reg}", +"puzzles_weekly.name_race_to_b":"Corsa verso {b}", +"puzzles_weekly.name_ring_around_reg":"Girotondo in {reg}", +"puzzles_weekly.name_sea_you_in_b":"Ci vediamo a {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sole, mare e cavo sottomarino", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Chi ha bisogno di {hub}?", +"puzzles_weekly.ocean_crossing":"Traversata oceanica", +"puzzles_weekly.region_tour":"Giro della regione", +"puzzles_weekly.ring":"Anello", "reach_and_subsea.premium_submarine_terminals":"Terminali sottomarini avanzati", "release_notes.and_n_more_change":{"one":"…e {n} altra modifica","other":"…e altre {n} modifiche"}, "release_notes.read_the_full_notes_on_github":"Leggi le note complete su GitHub", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a05f651..641c8e5 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2872,14 +2872,18 @@ "puzzles.keep_building":"Continuar construindo", "puzzles.kiwi_fruit_salad":"Salada de kiwi", "puzzles.lease_a_wave_to":"Alugar uma wave até", +"puzzles.loading_this_week_s_puzzle":"Carregando o puzzle da semana…", "puzzles.more_puzzles":"Mais puzzles", "puzzles.n_1_club":"Clube N-1", "puzzles.n_1_connect_everything_first":"N-1: conecte tudo primeiro", "puzzles.n_g_links":"links de {n}G", "puzzles.n_week_streak":{"one":"{n} semana seguida","other":"{n} semanas seguidas"}, +"puzzles.new_this_sunday":"Novo neste domingo!", "puzzles.new_zealand_is_far_from_everything":"A Nova Zelândia fica longe de tudo. Essa é a graça, e o problema.", "puzzles.next_pack_unlocks_at_n":"O próximo pacote, {pack}, abre com {n}⭐", "puzzles.next_puzzle":"Próximo puzzle", +"puzzles.next_weekly_in_d_h":"Próximo puzzle semanal em {d} d {h} h", +"puzzles.next_weekly_in_h_m":"Próximo puzzle semanal em {h} h {m} min", "puzzles.no_budget":"sem orçamento", "puzzles.no_budget_star_on_the_house":"sem orçamento: ⭐ por conta da casa", "puzzles.no_cable_lands_in_both_try":"Nenhum cabo chega a {a} e a {b}. Tente uma escala no meio.", @@ -2945,6 +2949,36 @@ "puzzles.with_the_pop_price":"com o POP: {price}", "puzzles.your_first_tubes_no_pressure":"Seus primeiros tubos. Sem pressão, sem orçamento.", "puzzles.your_stars":"Suas estrelas", +"puzzles_weekly.detour":"Desvio", +"puzzles_weekly.island_hopping":"De ilha em ilha", +"puzzles_weekly.joke_a_ring_survives_one_cut":"Um anel sobrevive a qualquer corte. É para isso que serve um anel.", +"puzzles_weekly.joke_a_road_trip_for_photons":"Uma viagem de carro para fótons. Lanche não incluído.", +"puzzles_weekly.joke_a_to_b_under_ms":"De {a} a {b} em menos de {ms} ms. Os traders estão de olho.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Cada salto é um cabo, e cada cabo é uma longa viagem de barco.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} está numa semana caríssima. Dê a volta.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} cidades, um continente e muitas valas para cavar.", +"puzzles_weekly.joke_one_ring_through_every_pop":"Um anel por cada POP: dois links cada, sem atalhos, sem ramais.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Em algum lugar entre {a} e {b} um navio de reparo já está esperando. Planeje para isso.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"O caminho mais barato entre duas ilhas raramente é uma linha reta.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"O caminho óbvio passa por {hub}. O caminho óbvio está fechado.", +"puzzles_weekly.joke_the_ocean_is_big_and":"O oceano é grande e as âncoras são muitas. Leve um cabo reserva.", +"puzzles_weekly.joke_the_speed_of_light_is":"A velocidade da luz não é uma sugestão. Escolha o vidro mais reto.", +"puzzles_weekly.latency_sprint":"Corrida de latência", +"puzzles_weekly.name_across_the_big_blue":"Através do grande azul", +"puzzles_weekly.name_anywhere_but_hub":"Qualquer lugar menos {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"Já chegamos, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Um pulo, um salto e um cabo", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms ou nada", +"puzzles_weekly.name_one_ring_to_rule_reg":"Um anel para governar {reg}", +"puzzles_weekly.name_race_to_b":"Corrida até {b}", +"puzzles_weekly.name_ring_around_reg":"Ciranda por {reg}", +"puzzles_weekly.name_sea_you_in_b":"Te vejo em {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sol, mar e cabo submarino", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Quem precisa de {hub}?", +"puzzles_weekly.ocean_crossing":"Travessia do oceano", +"puzzles_weekly.region_tour":"Volta pela região", +"puzzles_weekly.ring":"Anel", "reach_and_subsea.premium_submarine_terminals":"Terminais submarinos premium", "release_notes.and_n_more_change":{"one":"…e mais {n} mudança","other":"…e mais {n} mudanças"}, "release_notes.read_the_full_notes_on_github":"Leia as notas completas no GitHub", diff --git a/site/sw.js b/site/sw.js index 3febeef..6c895f6 100644 --- a/site/sw.js +++ b/site/sw.js @@ -25,6 +25,12 @@ self.addEventListener('fetch', (e) => { } const local = url.origin === location.origin, fonts = /fonts\.(googleapis|gstatic)\.com$/.test(url.hostname); if (!local && !fonts) return; + // Weekly puzzles are published between releases: ask the network first, and keep a copy for playing offline. + if (local && url.pathname.startsWith('/puzzles/weekly/')) { + e.respondWith(fetch(req).then((r) => { if (r.ok) { const copy = r.clone(); caches.open(CACHE).then((c) => c.put(req, copy)); } return r; }) + .catch(() => caches.match(req).then((r) => r || Response.error()))); + return; + } e.respondWith(caches.open(CACHE).then((c) => c.match(req).then((hit) => { const net = fetch(req).then((r) => { if (r && (r.ok || r.type === 'opaque')) c.put(req, r.clone()); return r; }).catch(() => hit); return hit || net; diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index b0ca38e..30fdfcd 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -6,7 +6,7 @@ const PZ_KEY='sot-puzzles',PZ_YEAR=12; const pzOn=()=>!!(S&&S.mode==='puzzle'&&S.pz); const pzDef=id=>PZ.find(p=>p.id===id)||null; const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':null; -const pzName=d=>d.id==='weekly'?tr('puzzles.weekly_puzzle_key',{key:d.key}):d.n; +const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key',{key:d.key})):d.n; const pzStarStr=n=>'⭐'.repeat(n)+'⬜'.repeat(3-n); // ---------- progress (localStorage, never trusted) ---------- function pzClean(j){const o={s:{},wk:{},streak:{last:null,n:0,best:0}};if(!j||typeof j!=='object')return o; @@ -55,9 +55,7 @@ function pzEval(){const P=S.pz,ls=S.links,cs=P.cities,spend=pzSpend(); const weak=conn?units.filter(u=>{const g=pzComp(ls,u,cs[0]);return !cs.every(c=>g.has(c));}):[]; const n1=conn&&units.length>0&&!weak.length,cheap=!P.budget||spend<=P.budget; return {marks,conn,tw,goal,spend,cheap,n1,weak,stars:goal?1+(cheap?1:0)+(n1?1:0):0};} -// ---------- the weekly puzzle: the same for everyone, seeded by the ISO week like the weekly challenge ---------- -function pzWeekKey(dt){const {y,w}=isoWeek(dt);return `${y}-W${String(w).padStart(2,'0')}`;} -function pzPrevKey(key){const m=/^(\d{4})-W(\d{2})$/.exec(key);if(!m)return null;return pzWeekKey(new Date(+m[1],0,4+(+m[2]-2)*7));} +// ---------- the seeded weekly puzzle: the same for everyone, and the stand-in when the published one (93-puzzles-weekly.js) is not there ---------- function pzWeekly(dt){const key=pzWeekKey(dt||new Date());let r=hstr('puzzle|'+key)||1;const nx=()=>{r=(Math.imul(r,1103515245)+12345)>>>0;return r/4294967296;}; const pool=PZ_WEEK_POOLS[Math.floor(nx()*PZ_WEEK_POOLS.length)].slice(),n=4+Math.floor(nx()*2),cities=[]; while(cities.length{newGame(pzName(def),def.cities[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:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null}; + S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null}; UI.pzHist=[];UI.pzTop=0;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null; $('dash').hidden=true;$('bankBox').hidden=true;closeModal();document.body.classList.add('pz'); compute();pzCam();renderAll();track('puzzle_'+def.id); diff --git a/src/game/60-features/93-puzzles-weekly.js b/src/game/60-features/93-puzzles-weekly.js new file mode 100644 index 0000000..b262164 --- /dev/null +++ b/src/game/60-features/93-puzzles-weekly.js @@ -0,0 +1,75 @@ +/* ================= THE PUBLISHED WEEKLY PUZZLE ================= + A puzzle week runs from Sunday 06:00 Berlin time to the next Sunday 06:00. Its key is the ISO week of its Monday + (the week starting Sunday 1 Nov 2026 is 2026-W45), so keys look like the old ISO-week keys and old streaks carry on. + Every Sunday a GitHub workflow publishes puzzles/weekly/.json (scripts/weekly-puzzle.js): a static file next to + the page, fetched only when the player opens Puzzles. It is checked field by field; when it is missing, offline or + wrong, the seeded weekly in 92-puzzles.js stands in, so the weekly puzzle never breaks. */ +// Europe/Berlin is UTC+1, and UTC+2 from the last Sunday of March to the last Sunday of October, 01:00 UTC both times. +const pzLastSun=(y,m)=>{const d=new Date(Date.UTC(y,m+1,0));return Date.UTC(y,m,d.getUTCDate()-d.getUTCDay(),1);}; +const pzBerlinOff=t=>{const y=new Date(t).getUTCFullYear();return t>=pzLastSun(y,2)&&tsun+(6-pzBerlinOff(sun+4*3600e3))*3600e3; +function pzIso(t){const d=new Date(t);d.setUTCHours(0,0,0,0);d.setUTCDate(d.getUTCDate()+4-(d.getUTCDay()||7));const y=d.getUTCFullYear();return `${y}-W${String(Math.ceil(((d-Date.UTC(y,0,1))/864e5+1)/7)).padStart(2,'0')}`;} +// The key of the puzzle week holding this moment. +function pzWeekKey(dt){const t=+dt,d=new Date(t);let sun=Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate())-d.getUTCDay()*864e5; + if(t{const t=pzWeekStart(key);return t==null?null:pzWeekKey(t+n*7*864e5+3*3600e3);}; +const pzPrevKey=key=>pzKeyAdd(key,-1); +// ---------- themes and their text: labels, so the file names a label and the player reads their language ---------- +// A file may only use these labels (N_: kept whole in the shipped page, since the file names them in full). +const PZ_WK_THEMES={ + detour:{i:'🚧',t:N_('puzzles_weekly.detour'),names:[N_('puzzles_weekly.name_anywhere_but_hub'),N_('puzzles_weekly.name_who_needs_hub')],jokes:[N_('puzzles_weekly.joke_hub_is_having_a_very'),N_('puzzles_weekly.joke_the_obvious_path_goes_through')]}, + islands:{i:'🏝️',t:N_('puzzles_weekly.island_hopping'),names:[N_('puzzles_weekly.name_hop_skip_and_a_cable'),N_('puzzles_weekly.name_sun_sea_and_subsea')],jokes:[N_('puzzles_weekly.joke_every_hop_is_a_cable'),N_('puzzles_weekly.joke_the_cheapest_way_between_two')]}, + ocean:{i:'🌊',t:N_('puzzles_weekly.ocean_crossing'),names:[N_('puzzles_weekly.name_sea_you_in_b'),N_('puzzles_weekly.name_across_the_big_blue')],jokes:[N_('puzzles_weekly.joke_the_ocean_is_big_and'),N_('puzzles_weekly.joke_somewhere_between_a_and_b')]}, + ring:{i:'💍',t:N_('puzzles_weekly.ring'),names:[N_('puzzles_weekly.name_one_ring_to_rule_reg'),N_('puzzles_weekly.name_ring_around_reg')],jokes:[N_('puzzles_weekly.joke_one_ring_through_every_pop'),N_('puzzles_weekly.joke_a_ring_survives_one_cut')]}, + sprint:{i:'⚡',t:N_('puzzles_weekly.latency_sprint'),names:[N_('puzzles_weekly.name_race_to_b'),N_('puzzles_weekly.name_ms_ms_or_bust')],jokes:[N_('puzzles_weekly.joke_a_to_b_under_ms'),N_('puzzles_weekly.joke_the_speed_of_light_is')]}, + tour:{i:'🗺️',t:N_('puzzles_weekly.region_tour'),names:[N_('puzzles_weekly.name_tour_de_reg'),N_('puzzles_weekly.name_are_we_there_yet_a')],jokes:[N_('puzzles_weekly.joke_n_cities_one_landmass_and'),N_('puzzles_weekly.joke_a_road_trip_for_photons')]}, +}; +// What each {placeholder} in those labels holds: c a city id, r a region code, n a whole number. +const PZ_WK_P={a:'c',b:'c',hub:'c',reg:'r',ms:'n',n:'n'}; +const pzCityOk=c=>isCity(c)&&!CITY[c].off&&!CITY[c].cn; +const pzTxt=o=>{const v={};for(const k in o.p){const x=o.p[k],t=PZ_WK_P[k];v[k]=t==='c'?CITY[x].name:t==='r'?WAVE_NAME[x]:x;}return tr(o.l,v);}; +// ---------- the file: never trusted. Only known fields, known cities, known labels and sane numbers get through ---------- +const pzObj=o=>!!o&&typeof o==='object'&&!Array.isArray(o); +function pzWkTxt(o,list){if(!pzObj(o)||typeof o.l!=='string'||!list.includes(o.l))return null;const p=o.p==null?{}:o.p;if(!pzObj(p))return null; + const need=[...new Set([...String(EN[o.l]).matchAll(/\{(\w+)\}/g)].map(m=>m[1]))],out={}; + if(Object.keys(p).length!==need.length)return null; + for(const k of need){const t=PZ_WK_P[k],v=own(p,k)?p[k]:undefined; + if(t==='c'&&pzCityOk(v))out[k]=v;else if(t==='r'&&typeof v==='string'&&own(WAVE_NAME,v))out[k]=v;else if(t==='n'&&Number.isInteger(v)&&v>0&&v<1000)out[k]=v;else return null;} + return {l:o.l,p:out};} +const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref']; +function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==1||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null; + const T=PZ_WK_THEMES[j.theme],ids=(a,lo,hi)=>Array.isArray(a)&&a.length>=lo&&a.length<=hi&&a.every(pzCityOk)&&new Set(a).size===a.length?a.slice():null; + const cities=ids(j.cities,3,6),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2);if(!cities||!via||!avoid)return null; + const all=[...cities,...via,...avoid];if(new Set(all).size!==all.length)return null; + if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>1e7)return null; + const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['lat','ring','noSub','minG'].includes(k)))return null; + const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null}; + if(own(tw,'ring')){if(tw.ring!==true)return null;d.ring=true;} + if(own(tw,'noSub')){if(tw.noSub!==true)return null;d.noSub=true;} + if(own(tw,'minG')){if(![100,400].includes(tw.minG))return null;d.minG=tw.minG;} + if(own(tw,'lat')){const l=tw.lat;if(!Array.isArray(l)||l.length!==3||!cities.includes(l[0])||!cities.includes(l[1])||l[0]===l[1]||!Number.isInteger(l[2])||l[2]<1||l[2]>500)return null;d.lat=l.slice();} + d.wn=pzWkTxt(j.name,T.names);d.wj=pzWkTxt(j.joke,T.jokes);if(!d.wn||!d.wj)return null; + return d;} +// ---------- fetching it: when Puzzles opens, never on page load ---------- +function pzWkEnsure(){const key=pzWeekKey(new Date()),w=UI.pzWk; + if(w&&w.key===key&&(w.st!=='fb'||Date.now()-w.at<5*60e3))return; + const st=UI.pzWk={key,st:w&&w.key===key&&w.def?'ok':'load',def:w&&w.key===key?w.def:null,at:Date.now()}; + let done=false;const fin=def=>{if(done)return;done=true;clearTimeout(to);if(UI.pzWk!==st)return;if(def){st.def=def;st.st='ok';}else if(!st.def)st.st='fb';st.at=Date.now();pzWkRefresh();}; + const ac=window.AbortController?new AbortController():null,to=setTimeout(()=>{if(ac)ac.abort();fin(null);},5000); + if(!window.fetch||location.protocol==='file:'){fin(null);return;} + // Relative and same origin; each week has its own file name, so caches never serve last week's. + try{fetch(`puzzles/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>pzWkValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +// This week's puzzle: the published one when it came, else the seeded one. +function pzWkDef(){const key=pzWeekKey(new Date()),w=UI.pzWk;return w&&w.key===key&&w.def?w.def:pzWeekly();} +const pzWkLoading=()=>{const w=UI.pzWk;return !!w&&w.st==='load'&&w.key===pzWeekKey(new Date());}; +function pzWkRefresh(){const el=$('pzWk');if(el)el.outerHTML=pzWkRow();} +// "Next weekly puzzle in 2 d 14 h". +function pzWkNext(now){const key=pzWeekKey(now),t=pzWeekStart(pzKeyAdd(key,1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60); + return d?tr('puzzles.next_weekly_in_d_h',{d,h}):tr('puzzles.next_weekly_in_h_m',{h,m:m%60});} +// The Puzzles door says so when this week's puzzle has not been played yet. +function pzWkNew(){try{return !pzLoad().wk[pzWeekKey(new Date())];}catch(e){return false;}} diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 41667e0..f474358 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -2,8 +2,8 @@ Object.assign(ACT,{ // 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);}, - pzWeekly:()=>pzBegin(pzWeekly()), - pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWeekly():pzDef(S.pz.id));}, + pzWeekly:()=>{if(pzWkLoading())return;pzBegin(pzWkDef());}, + pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, pzLeave:()=>{if(pzOn())pzLeave();}, pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop();sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();}, pzRmPop:({city})=>{if(!pzOn()||!S.pops[city])return;pzSnap();delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);sfx('click');UI.sel=null;pzAfter();}, diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index 61ca3e3..d32be2c 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -38,7 +38,7 @@ function whatsNew(returning,force){ const DOORS=[['puzzle','🧩',tr('title.puzzles'),tr('title.one_network_one_knot_no_clock')],['sandbox','🏖️',tr('common.sandbox'),tr('title.a_billion_dollars_and_every_toy')],['normal','📟',tr('common.normal'),tr('title.the_real_game_climb_from_tier')],['scn','🏆',tr('title.scenarios_amp_weekly'),tr('title.hand_built_crises_and_one_world')]]; const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scenarios'}; function doorsHtml(){const m=UI.mode==='sandbox'?'sandbox':'normal',pr=own(PRESETS,UI.preset)&&NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall',ch=own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'; - return `
${DOORS.map(([k,i,n,d])=>``).join('')}
+ return `
${DOORS.map(([k,i,n,d])=>``).join('')}
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}
${Object.entries(CHAOS).map(([k,C])=>``).join('')}

🔒 ${tr('title.rules_are_picked_once_and_locked')}

`;} diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index 1ae57a6..59ee381 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -7,13 +7,13 @@ function pzTwistTxt(t){const P=S.pz; if(t.k==='avoid')return tr('puzzles.no_pop_in_list',{list:P.avoid.map(c=>CITY[c].name).join(', ')}); const [a,b,ms]=P.lat;return isFinite(t.ms)?tr('puzzles.a_to_b_under_ms_now',{a:CITY[a].name,b:CITY[b].name,ms,now:t.ms.toFixed(1)}):tr('puzzles.a_to_b_under_ms',{a:CITY[a].name,b:CITY[b].name,ms});} // The short version, for the puzzle list. -function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} +function pzTwistTag(d){const t=[];if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.lat)t.push(tr('puzzles.under_n_ms',{n:d.lat[2]}));if(d.minG)t.push(tr('puzzles.n_g_links',{n:d.minG}));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} const pzUnitName=u=>{const l=S.links.find(x=>pzUnit(x)===u);return l?`${CITY[l.a].name} ⇄ ${CITY[l.b].name}${l.cable?' ('+esc(CAB[l.cable].name)+')':''}`:'';}; function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false; const e=pzEval(),P=S.pz,d=pzDef(P.id),pk=d&&PZ_PACKS.find(x=>x.id===d.pack); const star=(on,l)=>`⭐${l}`; - let h=`
${pk?esc(pk.n):tr('puzzles.weekly_puzzle')}

${esc(pzName(d||P))}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; - if(d)h+=`

${esc(d.j)}

`; + let h=`
${pk?esc(pk.n):P.theme&&own(PZ_WK_THEMES,P.theme)?`${PZ_WK_THEMES[P.theme].i} ${tr('puzzles.weekly_puzzle')} · ${tr(PZ_WK_THEMES[P.theme].t)}`:tr('puzzles.weekly_puzzle')}

${esc(pzName(d||P))}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; + if(d)h+=`

${esc(d.j)}

`;else if(P.wj)h+=`

${esc(pzTxt(P.wj))}

`; h+=`
${star(e.goal,tr('puzzles.goal'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`; h+=`
${e.marks.map(m=>`${esc(CITY[m.c].name)}${m.st===2?' ✓':m.st===1?' ·':' …'}`).join('')}
`; for(const t of e.tw)h+=`
${t.ok?'✓':'✗'} ${pzTwistTxt(t)}
`; @@ -68,12 +68,18 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(); for(let i=prev;i{sfx('star');haptic(15);},Math.max(0,i-prev)*450+150); if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);} // ---------- the list ---------- -function pzMenu(){const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot),w=pzWeekly(),wr=p.wk[w.key],st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0; +// The weekly row: the published puzzle once it has come (or the seeded one), its countdown and the streak. +function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=p.wk[w.key],st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzTwistTag(w); + return `
📅 ${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})}${wr?'':` ${tr('puzzles.new_this_sunday')}`}
+
${load?tr('puzzles.loading_this_week_s_puzzle'):`${T?T.i+' ':''}${esc(pzName(w))}`} ${wr?`${pzStarStr(wr.st)}`:''}
${w.wj?`
${esc(pzTxt(w.wj))}
`:''} +
${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · '+tg.join(' · ')+'':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}
+
${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}
⏳ ${pzWkNext(Date.now())}
${btn(tr('common.play'),'pzWeekly',{},wr&&wr.st>=3?'ghost':'pink',load)}
`;} +function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.length*3,nxP=PZ_PACKS.find(x=>x.need>tot); let h=`
${tr('puzzles.puzzles')}

${tr('puzzles.small_calm_network_builds')}

${tr('puzzles.no_clock_no_bills_nothing_breaks')}

${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}
`; if(pzOn())h+=`
${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; - h+=`
${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})} ${wr?`${pzStarStr(wr.st)}`:''}
${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}
${tr('puzzles.same_puzzle_for_everyone_this_week')}${streak?' · 🔥 '+trn('puzzles.n_week_streak',streak):''}
${btn(tr('common.play'),'pzWeekly',{},'pink')}
`; + h+=pzWkRow(); for(const pk of PZ_PACKS){const open=tot>=pk.need,got=PZ.filter(x=>x.pack===pk.id).reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0),n=PZ.filter(x=>x.pack===pk.id).length; h+=`

${open?'':'🔒 '}${esc(pk.n)} ⭐ ${got}/${n*3}

${open?esc(pk.d):tr('puzzles.unlocks_at_n_stars',{n:pk.need})}

`; for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzTwistTag(d); diff --git a/src/i18n/en.js b/src/i18n/en.js index 9e5308b..a0e597c 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2873,14 +2873,18 @@ "puzzles.keep_building":"Keep building", "puzzles.kiwi_fruit_salad":"Kiwi Fruit Salad", "puzzles.lease_a_wave_to":"Lease a wave to", +"puzzles.loading_this_week_s_puzzle":"Loading this week's puzzle…", "puzzles.more_puzzles":"More puzzles", "puzzles.n_1_club":"N-1 Club", "puzzles.n_1_connect_everything_first":"N-1: connect everything first", "puzzles.n_g_links":"{n}G links", "puzzles.n_week_streak":{"one":"{n} week in a row","other":"{n} weeks in a row"}, +"puzzles.new_this_sunday":"New this Sunday!", "puzzles.new_zealand_is_far_from_everything":"New Zealand is far from everything. That is the point, and the problem.", "puzzles.next_pack_unlocks_at_n":"Next pack, {pack}, unlocks at {n}⭐", "puzzles.next_puzzle":"Next puzzle", +"puzzles.next_weekly_in_d_h":"Next weekly puzzle in {d} d {h} h", +"puzzles.next_weekly_in_h_m":"Next weekly puzzle in {h} h {m} min", "puzzles.no_budget":"no budget", "puzzles.no_budget_star_on_the_house":"no budget: ⭐ on the house", "puzzles.no_cable_lands_in_both_try":"No cable lands in both {a} and {b}. Try a stepping stone in between.", @@ -2946,6 +2950,36 @@ "puzzles.with_the_pop_price":"with the POP: {price}", "puzzles.your_first_tubes_no_pressure":"Your first tubes. No pressure, no budget.", "puzzles.your_stars":"Your stars", +"puzzles_weekly.detour":"Detour", +"puzzles_weekly.island_hopping":"Island hopping", +"puzzles_weekly.joke_a_ring_survives_one_cut":"A ring survives any one cut. That is the whole point of a ring.", +"puzzles_weekly.joke_a_road_trip_for_photons":"A road trip for photons. Snacks not included.", +"puzzles_weekly.joke_a_to_b_under_ms":"{a} to {b} in under {ms} ms. The traders are watching.", +"puzzles_weekly.joke_every_hop_is_a_cable":"Every hop is a cable, and every cable is a long boat trip.", +"puzzles_weekly.joke_hub_is_having_a_very":"{hub} is having a very expensive week. Route around it.", +"puzzles_weekly.joke_n_cities_one_landmass_and":"{n} cities, one landmass and a lot of trenches to dig.", +"puzzles_weekly.joke_one_ring_through_every_pop":"One ring through every POP: two links each, no shortcuts, no spurs.", +"puzzles_weekly.joke_somewhere_between_a_and_b":"Somewhere between {a} and {b} a repair ship is already waiting. Plan for it.", +"puzzles_weekly.joke_the_cheapest_way_between_two":"The cheapest way between two islands is rarely a straight line.", +"puzzles_weekly.joke_the_obvious_path_goes_through":"The obvious path goes through {hub}. The obvious path is closed.", +"puzzles_weekly.joke_the_ocean_is_big_and":"The ocean is big and the anchors are many. Bring a spare cable.", +"puzzles_weekly.joke_the_speed_of_light_is":"The speed of light is not a suggestion. Pick the straightest glass.", +"puzzles_weekly.latency_sprint":"Latency sprint", +"puzzles_weekly.name_across_the_big_blue":"Across the Big Blue", +"puzzles_weekly.name_anywhere_but_hub":"Anywhere but {hub}", +"puzzles_weekly.name_are_we_there_yet_a":"Are We There Yet, {a}?", +"puzzles_weekly.name_hop_skip_and_a_cable":"Hop, Skip and a Cable", +"puzzles_weekly.name_ms_ms_or_bust":"{ms} ms or Bust", +"puzzles_weekly.name_one_ring_to_rule_reg":"One Ring to Rule {reg}", +"puzzles_weekly.name_race_to_b":"Race to {b}", +"puzzles_weekly.name_ring_around_reg":"Ring Around {reg}", +"puzzles_weekly.name_sea_you_in_b":"Sea You in {b}", +"puzzles_weekly.name_sun_sea_and_subsea":"Sun, Sea and Subsea", +"puzzles_weekly.name_tour_de_reg":"Tour de {reg}", +"puzzles_weekly.name_who_needs_hub":"Who Needs {hub}?", +"puzzles_weekly.ocean_crossing":"Ocean crossing", +"puzzles_weekly.region_tour":"Region tour", +"puzzles_weekly.ring":"Ring", "reach_and_subsea.premium_submarine_terminals":"Premium submarine terminals", "release_notes.and_n_more_change":{"one":"…and {n} more change","other":"…and {n} more changes"}, "release_notes.read_the_full_notes_on_github":"Read the full notes on GitHub", diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index 20fa6b1..4b6461c 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -38,3 +38,8 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB body.pz #hint{bottom:12px !important;left:30% !important} body.pz #toasts{left:8px !important;transform:none !important;width:calc(48% - 16px) !important} } +/* The weekly puzzle: a badge on the Puzzles door and in the list while this week's puzzle is unplayed. */ +.pznew{display:inline-block;font:900 10.5px/1.2 var(--body);font-style:normal;text-transform:uppercase;letter-spacing:.04em;background:var(--me);color:#fff;border:2px solid var(--ink);border-radius:999px;padding:1px 7px;white-space:nowrap;vertical-align:1px} +.door .pznew{position:absolute;top:-9px;right:8px;transform:rotate(4deg);animation:pznew 2.4s ease-in-out infinite} +@keyframes pznew{50%{transform:rotate(-3deg) scale(1.08)}} +.scn.wk{flex-wrap:wrap}.scn.wk .grow{min-width:0;flex:1 1 200px}.pzcd{font-weight:800;color:var(--ink)} From 372893ec75a788a910f1c0cae1e44c8ce8697b8a Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:42:51 +0100 Subject: [PATCH 59/64] Weekly puzzle generator: themed, solver-budgeted, verified by the game's own stars; first three weeks --- scripts/weekly-puzzle.js | 346 ++++++++++++++++++++++++++++++ site/puzzles/weekly/2026-W44.json | 1 + site/puzzles/weekly/2026-W45.json | 1 + site/puzzles/weekly/2026-W46.json | 1 + site/puzzles/weekly/index.json | 1 + 5 files changed, 350 insertions(+) create mode 100644 scripts/weekly-puzzle.js create mode 100644 site/puzzles/weekly/2026-W44.json create mode 100644 site/puzzles/weekly/2026-W45.json create mode 100644 site/puzzles/weekly/2026-W46.json create mode 100644 site/puzzles/weekly/index.json diff --git a/scripts/weekly-puzzle.js b/scripts/weekly-puzzle.js new file mode 100644 index 0000000..c0b7e77 --- /dev/null +++ b/scripts/weekly-puzzle.js @@ -0,0 +1,346 @@ +#!/usr/bin/env node +// The weekly puzzle generator. Every Sunday .github/workflows/weekly-puzzle.yml runs it to publish that week's +// puzzle as a static file, site/puzzles/weekly/.json, which the game fetches when Puzzles opens +// (src/game/60-features/93-puzzles-weekly.js). It loads the real game headless (tests/harness.js), so it uses the +// game's own cities, cables, prices, week keys, file validator and star code. +// +// node scripts/weekly-puzzle.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing +// node scripts/weekly-puzzle.js --key 2026-W45 that week (--force replaces an existing file) +// node scripts/weekly-puzzle.js --next 3 this week and the next two +// node scripts/weekly-puzzle.js --check validate every file (and re-verify the stars of weeks not over yet) +// --page FILE play another build of the game (the live release), see the workflow +// --dir DIR where the files live (default site/puzzles/weekly) +// +// How a puzzle is made: pick a theme the last weeks did not have, choose 4-6 cities for it (avoiding last weeks' +// cities), then search for the cheapest build that connects them and the cheapest build that survives any single cut +// (a whole cable or a trench). The budget is that N-1 build plus a little, so three stars need the smart design, not +// the obvious "double everything". Both reference builds are then played through the game's own actions and must earn +// their stars, or the candidate is thrown away and another one tried. +const fs = require('node:fs'); +const path = require('node:path'); + +const ROOT = path.join(__dirname, '..'); +const SCHEMA = 1, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6; +const THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint']; + +// ---------- the game, headless ---------- +function game(file) { + const { load } = require('../tests/harness'); + let g = load(file ? { file } : {}); + if (file && !g.ev("typeof pzWkValid==='function'")) { + console.warn(`warning: ${file} has no published weekly puzzles yet; using src/ instead`); + g = load(); + } + // N-1 counts a whole cable as one failure: every segment of a cable shares its risk, as in the main game. A game + // that still counts each segment separately is checked under the whole-cable rule too, which is the stricter one, + // so a puzzle verified here keeps its stars under either. + if (g.ev("pzUnit({cable:'x',a:'a',b:'b'})") !== 'cab:x') { + g.ev("window.pzUnitW=l=>l.cable?'cab:'+l.cable:String(l.trench||l.id);for(const f of [pzComp,pzEval])window.eval(f.toString().replace(/\\bpzUnit\\b/g,'pzUnitW'))"); + if (!/pzUnitW/.test(g.ev('pzEval.toString()+pzComp.toString()'))) throw new Error('could not apply the whole-cable N-1 rule'); + } + return g; +} + +// ---------- small helpers ---------- +const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }; +function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } +const pick = (r, a) => a[Math.floor(r() * a.length)]; +const shuffle = (r, a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; }; +const ceil10k = (x) => Math.ceil(x / 10000) * 10000; +function perms(a) { if (a.length <= 1) return [a]; const out = []; a.forEach((x, i) => { for (const p of perms([...a.slice(0, i), ...a.slice(i + 1)])) out.push([x, ...p]); }); return out; } +function subsets(a) { const out = []; for (let m = 0; m < 1 << a.length; m++) out.push(a.filter((_, i) => m >> i & 1)); return out; } + +// ---------- the world, as the game prices it ---------- +function world(ev) { + const cities = JSON.parse(ev("JSON.stringify(Object.values(CITY).filter(c=>!c.off&&!c.cn).map(c=>({id:c.id,name:c.name,lands:lands(c),reg:c.reg,P:c.P,lon:c.lon,lat:c.lat,pop:pzPopCost(c.id)})))")); + const C = Object.fromEntries(cities.map((c) => [c.id, c])); + const cablePairs = JSON.parse(ev('JSON.stringify(CABLE_PAIRS.map(p=>[p.cid,p.a,p.b]))')).filter(([, a, b]) => C[a] && C[b]); + const cabs = {}; for (const [cid, a, b] of cablePairs) { (cabs[a] = cabs[a] || new Set()).add(cid); (cabs[b] = cabs[b] || new Set()).add(cid); } + const memo = new Map(); + // Every way to join a and b: overland (first wave, and a second one on a diverse route) and each cable. + const opts = (a, b) => { + const k = a < b ? a + '|' + b : b + '|' + a; if (memo.has(k)) return memo.get(k); + const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').filter(r=>!subWaveWhy(0,r.km,r.sub)).map(r=>({via:r.via,cab:r.cab,sub:r.sub,ms:r.ms,c:pzLinkCost(r,0,false),c2:r.sub?0:pzLinkCost(r,0,true)})))`)); + const out = []; + for (const r of rs) { + if (r.cab) out.push({ a, b, via: r.via, sub: true, ms: r.ms, cost: r.c, unit: 'cab:' + r.cab }); + else { out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c, unit: `land:${k}:1` }); out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c2, unit: `land:${k}:2`, second: true }); } + } + out.sort((x, y) => x.cost - y.cost || (x.unit < y.unit ? -1 : 1)); + memo.set(k, out); return out; + }; + const km = (a, b) => { const A = C[a], B = C[b], r = Math.PI / 180, h = Math.sin((B.lat - A.lat) * r / 2) ** 2 + Math.cos(A.lat * r) * Math.cos(B.lat * r) * Math.sin((B.lon - A.lon) * r / 2) ** 2; return 12742 * Math.asin(Math.sqrt(h)); }; + return { cities, C, cablePairs, cabs, opts, km }; +} + +// ---------- judging a build (the game has the last word; this steers the search) ---------- +function judge(W, P, links) { + const nodes = new Set(); for (const l of links) { nodes.add(l.a); nodes.add(l.b); } + // A second overland wave on a pair needs the first one. + for (const l of links) if (l.second && !links.some((x) => x !== l && !x.second && x.via === 'land' && x.unit === l.unit.replace(/2$/, '1'))) return null; + if (new Set(links.map((l) => l.unit)).size !== links.length) return null; + const cost = [...nodes].reduce((s, c) => s + W.C[c].pop, 0) + links.reduce((s, l) => s + l.cost, 0); + const comp = (skip) => { const adj = {}; for (const l of links) if (l.unit !== skip) { (adj[l.a] = adj[l.a] || []).push(l.b); (adj[l.b] = adj[l.b] || []).push(l.a); } + const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) { const u = q.pop(); for (const v of adj[u] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } } return seen; }; + const all = comp(null); + if (!P.cities.every((c) => all.has(c))) return { ok: false, cost }; + if (P.avoid.some((c) => nodes.has(c))) return { ok: false, cost }; + if (P.noSub && links.some((l) => l.sub)) return { ok: false, cost }; + if (P.ring) { const nb = {}; for (const l of links) { (nb[l.a] = nb[l.a] || new Set()).add(l.b); (nb[l.b] = nb[l.b] || new Set()).add(l.a); } + if (links.length !== nodes.size || ![...nodes].every((c) => nb[c].size === 2)) return { ok: false, cost }; } + if (P.lat) { const [a, b, ms] = P.lat, d = { [a]: 0 }, done = new Set(); + for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null || u === b) break; done.add(u); + for (const l of links) { const v = l.a === u ? l.b : l.b === u ? l.a : null; if (v && !(d[v] <= d[u] + l.ms)) d[v] = d[u] + l.ms; } } + if (!(d[b] <= ms)) return { ok: false, cost }; } + const weak = [...new Set(links.map((l) => l.unit))].filter((u) => { const g = comp(u); return !P.cities.every((c) => g.has(c)); }); + return { ok: true, cost, n1: weak.length === 0, weak }; +} + +// ---------- the solver ---------- +// Cheapest tree over a node set (Kruskal on each pair's cheapest way), with some links forced in. +function tree(W, nodes, forced = []) { + const par = Object.fromEntries(nodes.map((n) => [n, n])), f = (x) => (par[x] === x ? x : (par[x] = f(par[x]))); + const out = []; + for (const l of forced) { par[f(l.a)] = f(l.b); out.push(l); } + const es = []; + for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) { const o = W.opts(nodes[i], nodes[j]).filter((x) => !x.second); if (o.length) es.push(o[0]); } + es.sort((x, y) => x.cost - y.cost); + for (const e of es) if (f(e.a) !== f(e.b)) { par[f(e.a)] = f(e.b); out.push(e); } + return out.length - forced.length === nodes.length - 1 - forced.length ? out : null; +} +// Add the link that removes the most single points of failure per dollar, until none are left. +function harden(W, P, nodes, links) { + links = links.slice(); + for (let guard = 0; guard < 12; guard++) { + const j = judge(W, P, links); if (!j || !j.ok) return null; if (j.n1) return links; + let best = null; + for (let i = 0; i < nodes.length; i++) for (let k = i + 1; k < nodes.length; k++) for (const o of W.opts(nodes[i], nodes[k])) { + if (links.some((l) => l.unit === o.unit)) continue; + const jj = judge(W, P, [...links, o]); if (!jj || !jj.ok) continue; + const gain = j.weak.length - jj.weak.length; if (gain <= 0) continue; + const score = gain / o.cost; if (!best || score > best.score) best = { score, o }; + } + if (!best) return null; links.push(best.o); + } + return null; +} +// Every simple cycle through the node set, each hop by one of its three cheapest ways, cheapest first. +function cycles(W, P, nodes, bound) { + let best = null; const [h, ...rest] = nodes; + if (nodes.length < 3) return null; + for (const p of perms(rest)) { + if (p[0] > p[p.length - 1]) continue; // each cycle once + const ring = [h, ...p], hops = ring.map((x, i) => W.opts(x, ring[(i + 1) % ring.length]).filter((o) => !o.second).slice(0, 3)); + if (hops.some((o) => !o.length)) continue; + const pop = ring.reduce((s, c) => s + W.C[c].pop, 0); + const go = (i, acc, cost) => { + if (cost >= Math.min(bound, best ? best.cost : Infinity)) return; + if (i === hops.length) { const j = judge(W, P, acc); if (j && j.ok && j.n1) best = { cost: j.cost, links: acc.slice() }; return; } + for (const o of hops[i]) { if (acc.some((l) => l.unit === o.unit)) continue; acc.push(o); go(i + 1, acc, cost + o.cost); acc.pop(); } + }; + go(0, [], pop); + } + return best; +} +function solve(W, P) { + const vias = P.via.filter((c) => !P.avoid.includes(c)); + let one = null, three = null, naive = null; + const keep = (cur, links) => { if (!links) return cur; const j = judge(W, P, links); if (!j || !j.ok) return cur; return !cur || j.cost < cur.cost ? { cost: j.cost, links, n1: j.n1 } : cur; }; + for (const sub of subsets(vias)) { + const nodes = [...P.cities, ...sub]; + const forced = P.lat ? [W.opts(P.lat[0], P.lat[1]).filter((o) => !o.second).sort((x, y) => x.ms - y.ms)[0]].filter(Boolean) : []; + const ts = [tree(W, nodes), forced.length ? tree(W, nodes, forced) : null].filter(Boolean) + // A via city left as a leaf is money for nothing. + .filter((t) => sub.every((v) => t.filter((l) => l.a === v || l.b === v).length >= 2)); + if (!P.ring) for (const t of ts) { + one = keep(one, t); + // The obvious way to survive a cut: a second, different way along every hop of the tree. + const dbl = t.slice(); let okd = true; + for (const l of t) { const alt = W.opts(l.a, l.b).find((o) => o.unit !== l.unit && !dbl.some((x) => x.unit === o.unit)); if (!alt) { okd = false; break; } dbl.push(alt); } + if (okd) { const j = judge(W, P, dbl); if (j && j.ok && j.n1 && (!naive || j.cost < naive.cost)) naive = { cost: j.cost, links: dbl }; if (j && j.ok && j.n1) three = keep(three, dbl); } + const hd = harden(W, P, nodes, t); if (hd) three = keep(three, hd); + } + if (nodes.length <= 7) { const c = cycles(W, P, nodes, three ? three.cost : Infinity); if (c) { three = keep(three, c.links); if (P.ring) one = keep(one, c.links); } } + } + return { one, three, naive }; +} + +// ---------- themes: which cities, which twist ---------- +function pools(W) { + const byLand = {}; + for (const c of W.cities) { const k = c.lands[0] + '/' + c.reg; (byLand[k] = byLand[k] || []).push(c.id); } + const big = Object.values(byLand).map((g) => g.filter((c) => W.C[c].P >= 100)).filter((g) => g.length >= 6); + const isl = W.cities.filter((c) => byLand[c.lands[0] + '/' + c.reg].length === 1 && c.lands.length === 1 && (W.cabs[c.id] || new Set()).size >= 2).map((c) => c.id); + return { big, isl }; +} +const near = (W, c, from, n) => from.filter((x) => x !== c).sort((a, b) => W.km(c, a) - W.km(c, b)).slice(0, n); +function draft(W, theme, r, banned) { + const { big, isl } = pools(W), free = (c) => !banned.has(c); + const P = { theme, cities: [], via: [], avoid: [], noSub: false, ring: false, lat: null }; + if (theme === 'tour' || theme === 'ring' || theme === 'detour') { + const g = pick(r, big).filter(free); + if (g.length < 6) return null; + if (theme === 'detour') { + const hub = pick(r, g.slice().sort((a, b) => W.C[b].P - W.C[a].P).slice(0, 4)), around = near(W, hub, g, 8); + if (around.length < 6) return null; + const sh = shuffle(r, around); P.cities = sh.slice(0, 4); P.via = sh.slice(4, 6); P.avoid = [hub]; + } else { + const seed = pick(r, g), n = theme === 'ring' ? 4 + Math.floor(r() * 2) : 4 + Math.floor(r() * 3); + P.cities = [seed, ...shuffle(r, near(W, seed, g, n + 2)).slice(0, n - 1)]; + if (theme === 'tour') P.via = near(W, seed, g, n + 4).filter((c) => !P.cities.includes(c)).slice(0, 1); + P.ring = theme === 'ring'; + } + } else if (theme === 'ocean') { + const land = (c) => W.C[c].lands[0], ok = W.cablePairs.filter(([, a, b]) => land(a) !== land(b) && free(a) && free(b) && big.some((g) => g.includes(a)) && big.some((g) => g.includes(b))); + if (!ok.length) return null; + const [, a, b] = pick(r, ok), ga = big.find((g) => g.includes(a)).filter(free), gb = big.find((g) => g.includes(b)).filter(free); + const a2 = pick(r, near(W, a, ga, 3)), b2 = pick(r, near(W, b, gb, 3)); + if (!a2 || !b2) return null; + P.cities = [a, a2, b, b2]; + // Other landing points on either shore that cross the same ocean: the stepping stones to a second crossing. + const shores = W.cablePairs.filter(([, x, y]) => (land(x) === land(a) && land(y) === land(b)) || (land(x) === land(b) && land(y) === land(a))).flatMap(([, x, y]) => [x, y]); + P.via = shuffle(r, [...new Set(shores)].filter((c) => free(c) && !P.cities.includes(c))).slice(0, 2); + } else if (theme === 'islands') { + const i0 = pick(r, isl.filter(free)); if (!i0) return null; + const hops = W.cablePairs.filter(([, x, y]) => x === i0 || y === i0).map(([, x, y]) => (x === i0 ? y : x)); + const islN = near(W, i0, isl.filter((c) => free(c) && W.km(i0, c) < 4500), 3), main = near(W, i0, [...new Set(hops)].filter((c) => free(c) && !isl.includes(c)), 2); + if (!islN.length || !main.length) return null; + P.cities = [i0, ...shuffle(r, islN).slice(0, 1 + Math.floor(r() * 2)), main[0]]; + P.via = [...new Set([...islN, ...main, ...hops])].filter((c) => !P.cities.includes(c) && free(c)).sort((x, y) => W.km(i0, x) - W.km(i0, y)).slice(0, 3); + } else if (theme === 'sprint') { + const ok = []; + for (const [, a, b] of W.cablePairs) { if (!free(a) || !free(b) || W.C[a].P < 100 || W.C[b].P < 100) continue; + const o = W.opts(a, b).filter((x) => !x.second); if (o.length < 2) continue; + const fast = o.slice().sort((x, y) => x.ms - y.ms)[0], cheap = o[0]; + if (fast.unit !== cheap.unit && fast.ms < cheap.ms * 0.94 && fast.ms >= 5) ok.push([a, b, fast.ms, cheap.ms]); } + if (!ok.length) return null; + const [a, b, fms, cms] = pick(r, ok.sort((x, y) => (x[0] + x[1] < y[0] + y[1] ? -1 : 1))); + const ms = Math.ceil(fms * 1.04 + 0.5); if (ms >= cms) return null; + const ga = big.find((g) => g.includes(a)) || [], gb = big.find((g) => g.includes(b)) || []; + const extra = [...near(W, a, ga.filter(free), 2), ...near(W, b, gb.filter(free), 2)]; + P.cities = [a, b, ...shuffle(r, extra).slice(0, 1 + Math.floor(r() * 2))]; + P.via = W.cablePairs.filter(([, x, y]) => [x, y].includes(a) || [x, y].includes(b)).flatMap(([, x, y]) => [x, y]).filter((c, i, s) => s.indexOf(c) === i && free(c) && !P.cities.includes(c)).sort((x, y) => W.km(a, x) - W.km(a, y)).slice(0, 2); + P.lat = [a, b, ms]; + } + if (new Set([...P.cities, ...P.via, ...P.avoid]).size !== P.cities.length + P.via.length + P.avoid.length) return null; + if (P.cities.length < 3 || P.cities.length > 6) return null; + return P; +} + +// ---------- names and jokes: labels and their fill-ins ---------- +function words(ev, W, P, r) { + const T = JSON.parse(ev(`JSON.stringify(PZ_WK_THEMES['${P.theme}'])`)), c = P.cities, last = c[c.length - 1]; + const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], p = {}; + for (const k of need) p[k] = k === 'hub' ? P.avoid[0] : k === 'reg' ? W.C[c[0]].reg : k === 'ms' ? P.lat[2] : k === 'n' ? c.length : k === 'a' ? (P.lat ? P.lat[0] : P.theme === 'tour' ? last : c[0]) : k === 'b' ? (P.lat ? P.lat[1] : c[2] || last) : null; + return { l, p }; }; + return { name: fill(pick(r, T.names)), joke: fill(pick(r, T.jokes)) }; +} + +// ---------- one week ---------- +function history(dir, key) { + const keys = list(dir).filter((k) => k < key).slice(-HISTORY); + const files = keys.map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8'))); + return { cities: new Set(files.flatMap((f) => [...(f.cities || []), ...(f.via || []), ...(f.avoid || [])])), themes: files.slice(-THEME_GAP).map((f) => f.theme), + regs: files.slice(-REG_GAP).map((f) => f.cities && f.cities[0]).filter(Boolean) }; +} +const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []); + +// Plays a build through the game's own actions and returns the stars it earns. +function play(ev, def, links) { + ev(`localStorage.removeItem('sot-puzzles');pzBegin(${JSON.stringify(def)})`); + for (const l of links) { + if (!ev(`!!S.pops['${l.a}']`)) ev(`ACT.pzPop({city:'${l.a}'})`); + ev(`ACT.pzLinkTo({a:'${l.a}',b:'${l.b}'});ACT.pzVia({v:'${l.via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:0})`); + } + ev('closeModal()'); + return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))')); +} +const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, via: P.via, avoid: P.avoid, budget, + twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}, P.lat ? { lat: P.lat } : {}), + name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } }); +// The game's own validator decides what a puzzle is; then both references must earn their stars. +function verify(g, W, j, key) { + const { ev } = g, def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${key}'))`)); + if (!def) return { ok: false, why: 'the game rejects the file' }; + const P = { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: def.lat }; + const sol = solve(W, P); + if (!sol.one || !sol.three) return { ok: false, why: 'no build reaches the goal and survives a cut' }; + if (sol.three.cost > def.budget) return { ok: false, why: `the cheapest N-1 build found costs ${sol.three.cost}, over the budget ${def.budget}` }; + const s1 = play(ev, def, sol.one.links), s3 = play(ev, def, sol.three.links); + if (s1.stars < 1 || (!P.ring && s1.stars !== 2)) return { ok: false, why: `the one-star reference earns ${s1.stars} stars` }; + if (s3.stars !== 3) return { ok: false, why: `the three-star reference earns ${s3.stars} stars (${JSON.stringify(s3)})` }; + return { ok: true, sol, s1, s3 }; +} + +function generate(g, key, dir) { + const { ev } = g, W = world(ev); + if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`); + // Themes take turns (none of the last weeks' again); the week's own theme first, the others only if it finds nothing. + const hist = history(dir, key), free = THEMES.filter((t) => !hist.themes.includes(t)), h = hash(key); + const order = free.map((_, i) => free[(h + i) % free.length]); + for (const theme of order) { + const cands = []; + for (let at = 0; at < ATTEMPTS && cands.length < KEEP; at++) { + const r = rng(hash(`${key}|${theme}|${at}`)), P = draft(W, theme, r, hist.cities); + // Not the same part of the world as the last two weeks. + if (!P || hist.regs.some((c) => W.C[c] && W.C[c].reg === W.C[P.cities[0]].reg && W.C[c].lands[0] === W.C[P.cities[0]].lands[0])) continue; + const sol = solve(W, P); + if (!sol.one || !sol.three) continue; + // Three stars need the smart design: the budget sits just above the cheapest N-1 build found, and below the + // obvious one (a second way along every hop) whenever there is room. + let budget = ceil10k(sol.three.cost * 1.05); + if (sol.naive && budget >= sol.naive.cost) budget = Math.max(ceil10k(sol.three.cost), Math.floor((sol.naive.cost - 1) / 10000) * 10000); + const smart = sol.naive ? sol.naive.cost / budget : 1.05, slack = budget / sol.one.cost; + const score = Math.min(smart, 1.6) + Math.min(slack, 2) * 0.2 + r() * 0.05; + cands.push({ P, sol, budget, score, w: words(ev, W, P, r) }); + } + cands.sort((a, b) => b.score - a.score); + for (const c of cands) { + const j = fileOf(key, c.P, c.budget, c.w, c.sol), v = verify(g, W, j, key); + if (v.ok) return j; + console.warn(`${key}: rejected a ${theme} puzzle: ${v.why}`); + } + } + throw new Error(`${key}: no puzzle survived verification`); +} + +// --check: every file is what the game accepts, under its own name, and the weeks still to come are solvable. +function check(g, dir, now = Date.now()) { + const { ev } = g, W = world(ev), bad = [], keys = list(dir); + for (const k of keys) { + let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; } + if (!ev(`!!pzWkValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; } + if (!j.ref || !Number.isInteger(j.ref.one) || !Number.isInteger(j.ref.three) || j.ref.one > j.ref.three || j.ref.three > j.budget) { bad.push(`${k}: bad ref`); continue; } + if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, W, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); } + } + const ip = path.join(dir, 'index.json'); + if (keys.length) { + let idx = null; try { idx = JSON.parse(fs.readFileSync(ip, 'utf8')); } catch (e) { /* reported below */ } + if (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys)) bad.push('index.json does not list exactly the weekly files'); + } + return bad; +} +const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n'); +const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); }; + +module.exports = { game, generate, check, solve, world, writeWeek, writeIndex, list }; + +if (require.main === module) { + const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; }; + const dir = path.resolve(ROOT, opt('--dir', 'site/puzzles/weekly')), g = game(opt('--page') && path.resolve(opt('--page'))); + if (args.includes('--check')) { + const bad = check(g, dir); + for (const b of bad) console.error(`error: ${b}`); + console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly puzzle(s) OK`); + process.exit(bad.length ? 1 : 0); + } + // By default the week that holds "12 hours from now": run early on Sunday, that is the week starting that morning. + const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1); + for (let i = 0; i < n; i++) { + const key = g.ev(`pzKeyAdd('${first}',${i})`); + if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); } + if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; } + const j = generate(g, key, dir); writeWeek(dir, j); + console.log(`${key}: ${j.theme}, ${j.cities.join(' ')}${j.via.length ? ' via ' + j.via.join(' ') : ''}${j.avoid.length ? ' avoid ' + j.avoid.join(' ') : ''}, budget ${j.budget} (1★ ${j.ref.one}, 3★ ${j.ref.three})`); + } +} diff --git a/site/puzzles/weekly/2026-W44.json b/site/puzzles/weekly/2026-W44.json new file mode 100644 index 0000000..128937c --- /dev/null +++ b/site/puzzles/weekly/2026-W44.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W44","theme":"ring","cities":["mil","vie","rom","mrs","stg"],"via":[],"avoid":[],"budget":240000,"twist":{"ring":true},"name":{"l":"puzzles_weekly.name_ring_around_reg","p":{"reg":"EU"}},"joke":{"l":"puzzles_weekly.joke_one_ring_through_every_pop","p":{}},"ref":{"one":226300,"three":226300}} diff --git a/site/puzzles/weekly/2026-W45.json b/site/puzzles/weekly/2026-W45.json new file mode 100644 index 0000000..52503ed --- /dev/null +++ b/site/puzzles/weekly/2026-W45.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"via":["lag"],"avoid":[],"budget":730000,"twist":{},"name":{"l":"puzzles_weekly.name_tour_de_reg","p":{"reg":"AF"}},"joke":{"l":"puzzles_weekly.joke_a_road_trip_for_photons","p":{}},"ref":{"one":452584,"three":691168}} diff --git a/site/puzzles/weekly/2026-W46.json b/site/puzzles/weekly/2026-W46.json new file mode 100644 index 0000000..d7b9f26 --- /dev/null +++ b/site/puzzles/weekly/2026-W46.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W46","theme":"ocean","cities":["for","ssa","lad","lun"],"via":["dla","sao"],"avoid":[],"budget":2060000,"twist":{},"name":{"l":"puzzles_weekly.name_across_the_big_blue","p":{}},"joke":{"l":"puzzles_weekly.joke_somewhere_between_a_and_b","p":{"a":"for","b":"lad"}},"ref":{"one":943664,"three":1959268}} diff --git a/site/puzzles/weekly/index.json b/site/puzzles/weekly/index.json new file mode 100644 index 0000000..8955841 --- /dev/null +++ b/site/puzzles/weekly/index.json @@ -0,0 +1 @@ +{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]} From 2ac9143db99553bff6b6dc01e5e536a154e2e56d Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:44:28 +0100 Subject: [PATCH 60/64] Weekly puzzle workflow: Sunday 03:37 UTC, commit the data to main, redeploy the live release with it through release.yml; releases ship every weekly from main --- .github/workflows/release.yml | 28 +++++++++- .github/workflows/weekly-puzzle.yml | 80 +++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/weekly-puzzle.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index da224da..801aee4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,7 +4,8 @@ name: Release to GitHub Pages # Pushes to main run CI but never deploy. To ship: bump "version" in # package.json and date its CHANGELOG section; auto-release.yml then tags, # publishes the release and starts this workflow from the tag. Publishing a -# release by hand works too. +# release by hand works too. Every Sunday weekly-puzzle.yml redeploys the live +# release from its tag with the new weekly puzzle added (input weekly). on: release: # "released" also fires when a pre-release is promoted to a full release. @@ -18,6 +19,10 @@ on: description: Allow deploying a version older than what is live (rollback) type: boolean default: false + weekly: + description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped + type: boolean + default: false # Least privilege: only the deploy job can write to Pages. permissions: @@ -63,8 +68,28 @@ jobs: if [ "$ALLOW_OLDER" != "true" ] && [ "$(printf '%s\n%s\n' "$live" "$new" | sort -V | tail -n1)" != "$new" ]; then echo "::error::$new is older than the live $live. Re-run with allow_older to roll back on purpose."; exit 1 fi + # Weekly puzzles are published on main between releases (weekly-puzzle.yml). Every deploy ships all of them, + # so neither a release nor a weekly redeploy ever drops a week that is already out. + - name: Weekly puzzles from main + run: | + set -euo pipefail + git fetch --no-tags --depth=1 origin main + if git cat-file -e FETCH_HEAD:site/puzzles/weekly 2>/dev/null; then + rm -rf site/puzzles/weekly + git checkout FETCH_HEAD -- site/puzzles/weekly + echo "Weekly puzzles: $(ls site/puzzles/weekly | grep -c '^[0-9].*\.json$')" + fi - run: npm ci - run: npm test + if: ${{ !inputs.weekly }} + - name: Check the weekly puzzles against this release + if: ${{ inputs.weekly }} + run: | + set -euo pipefail + # A release from before the weekly puzzles ships the files without reading them: nothing to check. + if [ ! -f scripts/weekly-puzzle.js ]; then echo "This release does not read weekly puzzles yet."; exit 0; fi + node scripts/weekly-puzzle.js --check + npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build - uses: actions/upload-pages-artifact@v5 @@ -88,6 +113,7 @@ jobs: # the site is live. indexnow: needs: deploy + if: ${{ !inputs.weekly }} runs-on: ubuntu-latest env: # IndexNow keys are public by design (also served at /.txt). diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml new file mode 100644 index 0000000..09cf814 --- /dev/null +++ b/.github/workflows/weekly-puzzle.yml @@ -0,0 +1,80 @@ +name: Weekly puzzle + +# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), commit it to main as a data-only +# change, and redeploy the live release with it. Puzzle weeks start Sunday 06:00 Berlin time; 03:37 UTC is +# 04:37 in winter and 05:37 in summer, so the file is live before the week starts either way. +# +# No version bump, so no release: auto-release.yml only runs when package.json changes (and pushes made with +# the workflow token start no workflows at all). The deploy itself is release.yml, still the only workflow +# that can write to Pages, started from the live release's tag with weekly=true: it rebuilds exactly that +# release with every weekly puzzle from main added, in the same "pages" concurrency group as any release. +on: + schedule: + - cron: '37 3 * * 0' + workflow_dispatch: + inputs: + key: + description: Week to make, e.g. 2026-W45 (default the week starting this Sunday) + required: false + deploy: + description: Redeploy the live release with it + type: boolean + default: true + +permissions: + contents: write # commit the puzzle to main + actions: write # start release.yml + +concurrency: + group: weekly-puzzle + cancel-in-progress: false + +jobs: + puzzle: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + GH_TOKEN: ${{ github.token }} + KEY: ${{ inputs.key }} + steps: + - uses: actions/checkout@v7 + with: + ref: main + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Make the puzzle + run: | + set -euo pipefail + if [ -n "$KEY" ]; then + [[ "$KEY" =~ ^[0-9]{4}-W[0-9]{2}$ ]] || { echo "::error::$KEY is not a week key"; exit 1; } + node scripts/weekly-puzzle.js --key "$KEY" + else + node scripts/weekly-puzzle.js + fi + - name: Check every weekly puzzle + run: node scripts/weekly-puzzle.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js + - name: Commit it to main + run: | + set -euo pipefail + git add site/puzzles/weekly + # Data only: anything else changed means something is wrong. + if git status --porcelain | grep -v ' site/puzzles/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi + if git diff --cached --quiet; then echo "Nothing new to commit."; exit 0; fi + git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -m "Weekly puzzle $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')" + git push origin HEAD:main + - name: Redeploy the live release with it + if: github.event_name == 'schedule' || inputs.deploy + run: | + set -euo pipefail + tag=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --exclude-drafts --limit 1 --json tagName -q '.[0].tagName') + [ -n "$tag" ] || { echo "::error::no release to redeploy"; exit 1; } + # Releases from before the weekly puzzles cannot take them (and their game would not read them). + if ! git fetch --no-tags --depth=1 origin "refs/tags/$tag" || ! git show FETCH_HEAD:.github/workflows/release.yml | grep -q '^ weekly:'; then + echo "::notice::$tag predates weekly puzzles; the puzzle is on main and ships with the next release."; exit 0 + fi + gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$tag" -f tag="$tag" -f weekly=true + echo "Redeploying $tag with the weekly puzzles." From 587d50decf497252ed3cd5a64c057523798ab596 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:50:17 +0100 Subject: [PATCH 61/64] Weekly puzzle: tests, CHANGELOG, architecture and deploy notes --- .claude/skills/github-pages/SKILL.md | 8 + .claude/skills/release/SKILL.md | 9 + CHANGELOG.md | 1 + docs/ARCHITECTURE.md | 30 +++- tests/weekly-puzzle.test.js | 237 +++++++++++++++++++++++++++ 5 files changed, 284 insertions(+), 1 deletion(-) create mode 100644 tests/weekly-puzzle.test.js diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index 3eafcfb..f57d959 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -40,6 +40,14 @@ publishes the GitHub release and starts `release.yml`: test, `REQUIRE_NOTES=1 np `pages: write`. Pushes to `main` and pull requests build but never deploy. The `release` skill has the steps. +**The one exception: the weekly puzzle.** Every Sunday at 03:37 UTC `weekly-puzzle.yml` commits the new +`site/puzzles/weekly/.json` to `main` (data only, no version bump) and starts `release.yml` for the **live +release tag** with `weekly=true`. That run rebuilds exactly the live release, with every weekly file from `main` +added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in the same `pages` concurrency group. +Players get no update banner (the version does not change). Every release build also copies all weekly files from +`main`, so a release never drops a published week. Weekly files are plain JSON the game fetches only when the +Puzzles list opens and never trusts; the service worker serves them network-first. See `docs/ARCHITECTURE.md`. + ## Before you hand back a change that touches the build, deploy or loading ```bash diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 79087df..0378f48 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -12,6 +12,15 @@ that version's CHANGELOG section as notes, and dispatches `release.yml`, which b to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the `github-pages` skill. +## Weekly puzzles are not releases + +`weekly-puzzle.yml` publishes a new puzzle every Sunday morning without a release: it commits the JSON under +`site/puzzles/weekly/` to `main` and redeploys the live tag through `release.yml` (`weekly=true`). Never bump the +version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly-puzzle.js --key 2026-W45 --force`, +`node scripts/weekly-puzzle.js --check`, commit to `main`, then run the "Weekly puzzle" workflow (or +`gh workflow run release.yml --ref -f tag= -f weekly=true`). A release includes every weekly +file on `main` when it builds. + ## Only release when Frederic says so Never bump the version on your own. Finished work is committed and pushed with its diff --git a/CHANGELOG.md b/CHANGELOG.md index f13ceb4..23f7831 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own. - A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before. - Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips the peering inbox, hardware shortages and sold-out routes. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. - Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1e23b3b..853b52c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -29,7 +29,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) | | `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) | | `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` | -| `60-features/` | Banks and loans, scenarios and the weekly challenge, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`) | +| `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 inbox, peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | | `80-simulation/` | Dijkstra, RouteScript, `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, geography pricing and latency, second sites and service | | `85-incidents/` | `addInc()`, DDoS and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()` | @@ -72,6 +72,8 @@ Development runs on `npm run dev` (assembles on every request, reloads on save); | `.github/workflows/ci.yml` | Tests and build on every push and PR | | `.github/workflows/auto-release.yml` | On a `package.json` version bump on `main`: test, tag, GitHub release from the CHANGELOG, start the deploy | | `.github/workflows/release.yml` | Builds and deploys to GitHub Pages, the only workflow that can | +| `.github/workflows/weekly-puzzle.yml` | Sunday 03:37 UTC: makes the week's puzzle, commits it to `main` (data only, no release) and starts `release.yml` for the live release tag with `weekly=true` | +| `scripts/weekly-puzzle.js`, `site/puzzles/weekly/` | The weekly puzzle generator and its output, one `.json` per week plus `index.json` (see below) | | `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) | ## Globals @@ -146,6 +148,32 @@ Served share per city (`sfOf`) drives eyeball revenue and customer mood. - The map is a canvas drawn every frame by `draw()`. Zoomed out (`lodFar()`) it uses a simplified style; parallel waves are grouped by `linkGroups()`. +## The weekly puzzle + +A puzzle week runs from Sunday 06:00 Berlin time to the next Sunday 06:00, and is named after the ISO week of +its Monday (the week starting Sunday 1 November 2026 is `2026-W45`); `pzWeekKey()` and `pzWeekStart()` in +`src/game/60-features/93-puzzles-weekly.js` handle summer time and the year boundary. + +Every Sunday `weekly-puzzle.yml` runs `scripts/weekly-puzzle.js`, which loads the real game headless, picks a +theme the last three weeks did not have (region tour, ring, detour around a hub, ocean crossing, island hopping, +latency sprint) and cities the last four weeks did not use, and searches for the cheapest build that connects +them and the cheapest one that survives any single cut (a whole cable, or a trench). The budget sits just above +that N-1 build and, where there is room, below the obvious "second path along every hop", so three stars take +some thought. Both reference builds are then played through the game's own actions and must earn one and three +stars, or the puzzle is thrown away. The file holds only ids, numbers and translation labels with their fill-ins +(`{"v":1,"key","theme","cities","via","avoid","budget","twist","name":{"l","p"},"joke":{"l","p"},"ref"}`). +`--check` re-validates every file the way the game does. + +The game fetches `puzzles/weekly/.json` (relative, same origin) only when the Puzzles list opens, and checks +it field by field (`pzWkValid()`): known fields, playable cities, labels from the theme's own list, sane numbers. +When it is missing, offline or wrong, the seeded weekly (`pzWeekly()`) stands in, so the weekly puzzle always +works. The service worker fetches these files network-first and keeps a copy for offline play. + +The weekly ships without a release: the workflow commits only `site/puzzles/weekly/` to `main` (no version bump, +so `auto-release.yml` stays quiet) and starts `release.yml` from the live release's tag with `weekly=true`, which +rebuilds that exact release with every weekly file from `main` and deploys it. Every release build takes the +weekly files from `main` too, so no deploy ever drops a published week. + ## Saves, imports and migration - `save()` writes `S` to localStorage every few seconds and after actions. diff --git a/tests/weekly-puzzle.test.js b/tests/weekly-puzzle.test.js new file mode 100644 index 0000000..a183a4b --- /dev/null +++ b/tests/weekly-puzzle.test.js @@ -0,0 +1,237 @@ +// The published weekly puzzle: Sunday 06:00 Berlin weeks, the generator (scripts/weekly-puzzle.js), its --check, +// and the game's fetch: only when Puzzles opens, validated strictly, with the seeded weekly as the fallback. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { load } = require('./harness'); +const G = require('../scripts/weekly-puzzle'); + +const DIR = path.join(__dirname, '..', 'site', 'puzzles', 'weekly'); +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-weekly-')); +const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8'))); +const tick = () => new Promise((r) => setTimeout(r, 30)); + +test('weeks start Sunday 06:00 Berlin, in winter and in summer, and keys run across New Year', () => { + const { ev, errors } = load(); + const key = (iso) => ev(`pzWeekKey(new Date('${iso}'))`), start = (k) => ev(`new Date(pzWeekStart('${k}')).toISOString()`); + // Winter (CET, UTC+1): 06:00 Berlin is 05:00 UTC. + assert.equal(key('2026-11-01T04:59:59Z'), '2026-W44'); + assert.equal(key('2026-11-01T05:00:00Z'), '2026-W45', 'the week starting Sunday 1 Nov is named after its Monday'); + assert.equal(key('2026-11-07T23:00:00Z'), '2026-W45', 'Saturday night is still the same week'); + assert.equal(start('2026-W45'), '2026-11-01T05:00:00.000Z'); + // Summer (CEST, UTC+2): 06:00 Berlin is 04:00 UTC. + assert.equal(key('2026-07-05T03:59:00Z'), '2026-W27'); + assert.equal(key('2026-07-05T04:00:00Z'), '2026-W28'); + // The weekends the clocks change: the change is at 01:00 UTC that same Sunday, before the week starts. + assert.equal(start('2026-W14'), '2026-03-29T04:00:00.000Z', 'spring forward: first CEST Sunday'); + assert.equal(start('2026-W13'), '2026-03-22T05:00:00.000Z'); + assert.equal(start('2026-W44'), '2026-10-25T05:00:00.000Z', 'fall back: first CET Sunday'); + assert.equal(start('2026-W43'), '2026-10-18T04:00:00.000Z'); + assert.equal(key('2026-03-29T03:59:00Z'), '2026-W13'); + assert.equal(key('2026-03-29T04:00:00Z'), '2026-W14'); + assert.equal(key('2026-10-25T04:59:00Z'), '2026-W43'); + assert.equal(key('2026-10-25T05:00:00Z'), '2026-W44'); + // New Year: 2026 has 53 ISO weeks, 2027 has 52. + assert.equal(key('2026-12-27T05:00:00Z'), '2026-W53'); + assert.equal(key('2027-01-03T04:59:00Z'), '2026-W53'); + assert.equal(key('2027-01-03T05:00:00Z'), '2027-W01'); + assert.equal(key('2027-12-26T05:00:00Z'), '2027-W52'); + assert.equal(key('2028-01-02T05:00:00Z'), '2028-W01'); + assert.equal(ev("pzKeyAdd('2026-W53',1)"), '2027-W01'); + assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53'); + assert.equal(ev("pzPrevKey('2028-W01')"), '2027-W52'); + assert.equal(ev("pzWeekStart('2027-W53')"), null, '2027 has no week 53'); + assert.equal(ev("pzWeekStart('2026-W00')"), null); + assert.equal(ev("pzWeekStart('nope')"), null); + // Every week of ten years: 7 days apart (give or take the DST hour), keys round-trip, never two Sundays the same key. + let k = '2026-W01', seen = new Set(); + for (let i = 0; i < 522; i++) { + const t = ev(`pzWeekStart('${k}')`), n = ev(`pzKeyAdd('${k}',1)`), tn = ev(`pzWeekStart('${n}')`); + assert.equal(new Date(t).getUTCDay(), 0, `${k} starts on a Sunday`); + assert.ok([7 * 864e5, 7 * 864e5 - 3600e3, 7 * 864e5 + 3600e3].includes(tn - t), `${k} → ${n}`); + assert.equal(ev(`pzWeekKey(${t})`), k); + assert.equal(ev(`pzWeekKey(${t - 1})`), ev(`pzPrevKey('${k}')`)); + assert.ok(!seen.has(k)); seen.add(k); k = n; + } + // The countdown. + assert.equal(ev("pzWkNext(Date.parse('2026-10-29T14:00:00Z'))"), 'Next weekly puzzle in 2 d 15 h'); + assert.equal(ev("pzWkNext(Date.parse('2026-11-01T03:20:00Z'))"), 'Next weekly puzzle in 1 h 40 min'); + assert.deepEqual(errors, []); +}); + +test('generator: deterministic for a week, and the committed weeks are what it makes', () => { + const g = G.game(), a = tmp(), b = tmp(); + const first = G.list(DIR)[0]; + const keys = G.list(DIR).length; + for (const d of [a, b]) for (let i = 0; i < keys; i++) G.writeWeek(d, G.generate(g, g.ev(`pzKeyAdd('${first}',${i})`), d)); + for (const k of G.list(a)) { + assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(b, k + '.json'), 'utf8'), `${k} twice the same`); + assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(DIR, k + '.json'), 'utf8'), `${k} as committed`); + } + assert.ok(keys >= 3, 'the release ships with weeklies in place'); +}); + +test('generator: a quarter of weeks, all verified, varied, small and in the schema', () => { + const g = G.game(), d = tmp(); + let k = '2027-W10'; + const out = []; + for (let i = 0; i < 12; i++, k = g.ev(`pzKeyAdd('${k}',1)`)) { const j = G.generate(g, k, d); G.writeWeek(d, j); out.push(j); } + assert.deepEqual(G.check(g, d, 0), [], 'every week verifies: both references earn their stars in the game'); + for (let i = 1; i < out.length; i++) { + assert.notEqual(out[i].theme, out[i - 1].theme, `${out[i].key}: not last week's theme`); + for (const c of out[i].cities) assert.ok(!out[i - 1].cities.includes(c), `${out[i].key}: ${c} was a city last week too`); + } + assert.ok(new Set(out.map((j) => j.theme)).size >= 5, 'most themes come round in a quarter'); + for (const j of out) { + assert.ok(j.cities.length >= 3 && j.cities.length <= 6); + assert.ok(j.ref.one <= j.ref.three && j.ref.three <= j.budget && j.budget <= j.ref.three * 1.06 + 10000, `${j.key}: budget ${j.budget} just above the N-1 build ${j.ref.three}`); + assert.ok(JSON.stringify(j).length < 600, 'small file'); + assert.deepEqual(Object.keys(j), ['v', 'key', 'theme', 'cities', 'via', 'avoid', 'budget', 'twist', 'name', 'joke', 'ref']); + } + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(d, 'index.json'), 'utf8')).weeks, out.map((j) => j.key)); +}); + +test('--check passes on the committed files and rejects tampered ones', () => { + const g = G.game(); + assert.deepEqual(G.check(g, DIR, 0), [], 'committed weeklies verify'); + const bad = (edit, why) => { + const d = tmp(); + for (const f of fs.readdirSync(DIR)) fs.copyFileSync(path.join(DIR, f), path.join(d, f)); + const k = G.list(d)[0], f = path.join(d, k + '.json'), j = JSON.parse(fs.readFileSync(f, 'utf8')); + const r = edit(j, d, k); fs.writeFileSync(f, typeof r === 'string' ? r : JSON.stringify(j)); + assert.notDeepEqual(G.check(g, d, 0), [], why); + }; + bad((j) => { j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1; }, 'a budget nobody can earn three stars under'); + bad((j) => { j.cities[0] = 'xxx'; }, 'an unknown city'); + bad((j) => { j.name.l = 'puzzles.hello_world'; }, 'a label that is not a weekly name'); + bad((j) => { j.joke.p = { hub: 'fra' }; }, 'parameters the label does not take'); + bad((j) => { j.extra = ''; }, 'an unknown field'); + bad((j) => { j.key = '2030-W01'; }, 'a file under another week\'s name'); + bad((j) => { j.twist = { lat: [j.cities[0], j.cities[1], 0.5] }; }, 'an impossible latency target'); + bad(() => '{nope', 'not JSON'); + bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks'); +}); + +test('the page never asks for a weekly puzzle on load, only when Puzzles opens', async () => { + const { ev, errors } = load(); + ev("window.__f=[];window.fetch=(u,o)=>{__f.push(String(u));return Promise.resolve({ok:false,json:()=>Promise.reject()})}"); + ev("showTitle();for(let i=0;i<5;i++)frame(performance.now()+i*1000);renderAll()"); + assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing on the title screen'); + assert.equal(ev("UI.pzWk===undefined"), true); + ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()"); + assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing while playing'); + ev('ACT.puzzleMenu({})'); + const key = ev('pzWeekKey(new Date())'); + assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/puzzles/.test(u)))"), JSON.stringify([`puzzles/weekly/${key}.json`]), 'one relative, same-origin request'); + ev('closeModal();ACT.puzzleMenu({})'); + assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 1, 'once is enough while it is loading'); + await tick(); + assert.deepEqual(errors, []); +}); + +test('the published puzzle is played when it is good, the seeded one when it is missing, offline or bad', async () => { + const src = committed()[1], { ev, dom, errors } = load(); + const key = ev('pzWeekKey(new Date())'), good = { ...src, key }; + const serve = (how) => { ev(`UI.pzWk=null;window.fetch=()=>${how}`); ev('ACT.puzzleMenu({})'); }; + const seeded = JSON.parse(ev('JSON.stringify(pzWeekly())')); + for (const [how, why] of [ + ["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'], + ["Promise.reject(new TypeError('offline'))", 'offline'], + ["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'], + [`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, cities: ['fra', 'nope', 'ams'] })})})`, 'an unknown city'], + [`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'], + ]) { + serve(how); + await tick(); + assert.equal(ev('UI.pzWk.st'), 'fb', why); + assert.deepEqual(JSON.parse(ev('JSON.stringify(pzWkDef().cities)')), seeded.cities, `${why}: the seeded weekly stands in`); + assert.match(ev("document.getElementById('pzWk').textContent"), new RegExp(`Weekly puzzle ${key}`)); + assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), false); + } + // While it loads, the button waits a moment. + ev("UI.pzWk=null;window.fetch=()=>new Promise(()=>{})"); + ev('ACT.puzzleMenu({})'); + assert.match(ev("document.getElementById('pzWk').textContent"), /Loading this week/); + assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), true); + // The good one. + serve(`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(good)})})`); + await tick(); + assert.equal(ev('UI.pzWk.st'), 'ok'); + const row = ev("document.getElementById('pzWk').textContent"); + assert.ok(row.includes(ev('pzName(pzWkDef())')), 'its pun name'); + assert.ok(row.includes(ev('pzTxt(pzWkDef().wj)')), 'its joke'); + assert.match(row, /New this Sunday!/); + assert.match(row, /Next weekly puzzle in \d+ (d \d+ h|h \d+ min)/); + ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()"); + assert.equal(ev('S.pz.key'), key); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.pz.cities)')), good.cities); + assert.equal(ev('S.pz.budget'), good.budget); + assert.match(ev("document.getElementById('pzBox').textContent"), new RegExp(ev('pzTxt(S.pz.wj)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); + // Solve it with three stars: the share line and the streak use the published key. + const sol = G.solve(G.world(ev), { cities: good.cities, via: good.via, avoid: good.avoid, ring: !!good.twist.ring, noSub: false, lat: good.twist.lat || null }).three; + for (const l of sol.links) { + if (!ev(`!!S.pops['${l.a}']`)) ev(`ACT.pzPop({city:'${l.a}'})`); + ev(`ACT.pzLinkTo({a:'${l.a}',b:'${l.b}'});ACT.pzVia({v:'${l.via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:0})`); + } + assert.equal(ev('pzEval().stars'), 3); + assert.match(ev('pzShareText(pzEval())'), new RegExp(`^Series of Tubes puzzle ${key} ⭐⭐⭐ \\$[\\d.]+[kM] · seriesoftub\\.es$`)); + const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); + assert.equal(p.wk[key].st, 3); + assert.equal(p.streak.last, key); + ev('ACT.pzLeave({})'); + assert.doesNotMatch(ev("document.querySelector('.door[data-door=puzzle]').textContent"), /New this Sunday/, 'played: no badge'); + void dom; + assert.deepEqual(errors, []); +}); + +test('the file is checked field by field', () => { + const { ev, errors } = load(); + const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`); + assert.ok(ok(j)); + const no = (edit, why) => { const o = JSON.parse(JSON.stringify(j)); edit(o); assert.equal(ok(o), false, why); }; + no((o) => { o.v = 2; }, 'a newer schema'); + no((o) => { o.theme = 'constructor'; }, 'an unknown theme'); + no((o) => { o.cities = ['fra']; }, 'too few cities'); + no((o) => { o.cities = [...o.cities, o.cities[0]]; }, 'a city twice'); + no((o) => { o.via = [o.cities[0]]; }, 'a goal city as a stepping stone'); + no((o) => { o.cities[0] = 'pek'; }, 'a city that needs a licence'); + no((o) => { o.budget = '240000'; }, 'a budget as text'); + no((o) => { o.budget = 1e9; }, 'a silly budget'); + no((o) => { o.twist = { ring: 'yes' }; }, 'a twist that is not true'); + no((o) => { o.twist = { avoidAll: true }; }, 'an unknown twist'); + no((o) => { o.name = { l: 'puzzles_weekly.name_tour_de_reg', p: { reg: 'XX' } }; }, 'an unknown region'); + no((o) => { o.name = { l: 'puzzles_weekly.name_race_to_b', p: { b: '' } }; }, 'markup as a city'); + no((o) => { o.joke = 'Ha ha'; }, 'raw English'); + no((o) => { o.__proto__ = { budget: 1 }; o.extra = 1; }, 'extra fields'); + assert.equal(ev(`pzWkValid(null,'${k}')`), null); + assert.equal(ev(`pzWkValid([],'${k}')`), null); + // Every label a theme may use exists in English, and every file names its text in the player's language. + assert.ok(ev("Object.values(PZ_WK_THEMES).every(T=>[T.t,...T.names,...T.jokes].every(l=>typeof EN[l]==='string'))")); + for (const f of committed()) { + const d = ev(`JSON.stringify(pzWkValid(${JSON.stringify(f)},'${f.key}'))`); + assert.ok(d, f.key); + assert.doesNotMatch(ev(`(d=>pzTxt(d.wn)+' '+pzTxt(d.wj))(${d})`), /\{|puzzles_weekly\./, `${f.key}: filled in`); + } + assert.deepEqual(errors, []); +}); + +test('weekly puzzle in every language and on a 360 px phone', async () => { + const f = committed()[0]; + for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { + const { ev, errors } = load({ lang }); + const key = ev('pzWeekKey(new Date())'); + ev(`window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...f, key })})})`); + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()"); + ev('ACT.puzzleMenu({})'); + await tick(); + const row = ev("document.getElementById('pzWk').textContent"); + assert.doesNotMatch(row, /puzzles(_weekly)?\.|\{/, `${lang}: no raw labels or placeholders`); + assert.notEqual(ev('pzName(pzWkDef())'), ev("EN[pzWkDef().wn.l]"), `${lang}: translated name`); + ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()"); + assert.equal(ev("document.getElementById('pzBox').hidden"), false); + assert.doesNotMatch(ev("document.getElementById('pzBox').textContent"), /puzzles(_weekly)?\./); + assert.deepEqual(errors, [], lang); + } +}); From 201131108415a69654bca236d75b0a8ea24aa02e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:52:59 +0100 Subject: [PATCH 62/64] Weekly puzzle 2026-W45 at the merged prices; determinism test compares two fresh runs --- site/puzzles/weekly/2026-W45.json | 2 +- tests/weekly-puzzle.test.js | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/site/puzzles/weekly/2026-W45.json b/site/puzzles/weekly/2026-W45.json index 52503ed..413d8ac 100644 --- a/site/puzzles/weekly/2026-W45.json +++ b/site/puzzles/weekly/2026-W45.json @@ -1 +1 @@ -{"v":1,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"via":["lag"],"avoid":[],"budget":730000,"twist":{},"name":{"l":"puzzles_weekly.name_tour_de_reg","p":{"reg":"AF"}},"joke":{"l":"puzzles_weekly.joke_a_road_trip_for_photons","p":{}},"ref":{"one":452584,"three":691168}} +{"v":1,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"via":["lag"],"avoid":[],"budget":740000,"twist":{},"name":{"l":"puzzles_weekly.name_tour_de_reg","p":{"reg":"AF"}},"joke":{"l":"puzzles_weekly.joke_a_road_trip_for_photons","p":{}},"ref":{"one":457084,"three":695668}} diff --git a/tests/weekly-puzzle.test.js b/tests/weekly-puzzle.test.js index a183a4b..7689ad0 100644 --- a/tests/weekly-puzzle.test.js +++ b/tests/weekly-puzzle.test.js @@ -61,14 +61,15 @@ test('weeks start Sunday 06:00 Berlin, in winter and in summer, and keys run acr assert.deepEqual(errors, []); }); -test('generator: deterministic for a week, and the committed weeks are what it makes', () => { +// Weeks already out are not compared with a fresh run: a later release may change prices, and a published week stays as +// it was (--check still makes sure the weeks not over yet can be solved). +test('generator: deterministic for a week', () => { const g = G.game(), a = tmp(), b = tmp(); const first = G.list(DIR)[0]; const keys = G.list(DIR).length; for (const d of [a, b]) for (let i = 0; i < keys; i++) G.writeWeek(d, G.generate(g, g.ev(`pzKeyAdd('${first}',${i})`), d)); for (const k of G.list(a)) { assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(b, k + '.json'), 'utf8'), `${k} twice the same`); - assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(DIR, k + '.json'), 'utf8'), `${k} as committed`); } assert.ok(keys >= 3, 'the release ships with weeklies in place'); }); From 023114103deb43e5d49550f58504a86fc640c8d6 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:54:34 +0100 Subject: [PATCH 63/64] Weekly puzzle tests: look at the last three weeks only, so they stay fast as weeks pile up --- tests/weekly-puzzle.test.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/weekly-puzzle.test.js b/tests/weekly-puzzle.test.js index 7689ad0..f8107f5 100644 --- a/tests/weekly-puzzle.test.js +++ b/tests/weekly-puzzle.test.js @@ -65,13 +65,13 @@ test('weeks start Sunday 06:00 Berlin, in winter and in summer, and keys run acr // it was (--check still makes sure the weeks not over yet can be solved). test('generator: deterministic for a week', () => { const g = G.game(), a = tmp(), b = tmp(); - const first = G.list(DIR)[0]; - const keys = G.list(DIR).length; + const first = G.list(DIR).slice(-3)[0]; + const keys = Math.min(3, G.list(DIR).length); for (const d of [a, b]) for (let i = 0; i < keys; i++) G.writeWeek(d, G.generate(g, g.ev(`pzKeyAdd('${first}',${i})`), d)); for (const k of G.list(a)) { assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(b, k + '.json'), 'utf8'), `${k} twice the same`); } - assert.ok(keys >= 3, 'the release ships with weeklies in place'); + assert.ok(G.list(DIR).length >= 3, 'the release ships with weeklies in place'); }); test('generator: a quarter of weeks, all verified, varied, small and in the schema', () => { @@ -96,10 +96,12 @@ test('generator: a quarter of weeks, all verified, varied, small and in the sche test('--check passes on the committed files and rejects tampered ones', () => { const g = G.game(); - assert.deepEqual(G.check(g, DIR, 0), [], 'committed weeklies verify'); + // Weeks still to come are re-solved; past ones are checked the way the game reads them. + assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify'); const bad = (edit, why) => { const d = tmp(); - for (const f of fs.readdirSync(DIR)) fs.copyFileSync(path.join(DIR, f), path.join(d, f)); + for (const k of G.list(DIR).slice(-3)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json')); + G.writeIndex(d); const k = G.list(d)[0], f = path.join(d, k + '.json'), j = JSON.parse(fs.readFileSync(f, 'utf8')); const r = edit(j, d, k); fs.writeFileSync(f, typeof r === 'string' ? r : JSON.stringify(j)); assert.notDeepEqual(G.check(g, d, 0), [], why); From 8d722595006753cf18024b964657c006d9ea4e0d Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:00:34 +0100 Subject: [PATCH 64/64] Weekly puzzle generator: v2 counts a whole cable as one failure, so require it instead of patching it in --- scripts/weekly-puzzle.js | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/scripts/weekly-puzzle.js b/scripts/weekly-puzzle.js index c0b7e77..93b6edd 100644 --- a/scripts/weekly-puzzle.js +++ b/scripts/weekly-puzzle.js @@ -31,13 +31,8 @@ function game(file) { console.warn(`warning: ${file} has no published weekly puzzles yet; using src/ instead`); g = load(); } - // N-1 counts a whole cable as one failure: every segment of a cable shares its risk, as in the main game. A game - // that still counts each segment separately is checked under the whole-cable rule too, which is the stricter one, - // so a puzzle verified here keeps its stars under either. - if (g.ev("pzUnit({cable:'x',a:'a',b:'b'})") !== 'cab:x') { - g.ev("window.pzUnitW=l=>l.cable?'cab:'+l.cable:String(l.trench||l.id);for(const f of [pzComp,pzEval])window.eval(f.toString().replace(/\\bpzUnit\\b/g,'pzUnitW'))"); - if (!/pzUnitW/.test(g.ev('pzEval.toString()+pzComp.toString()'))) throw new Error('could not apply the whole-cable N-1 rule'); - } + // N-1 counts a whole cable as one failure (every segment of a cable shares its risk), as the solver does. + if (g.ev("pzUnit({cable:'x',a:'a',b:'b'})") !== 'cab:x') throw new Error('this game counts cable segments separately; the solver would not match its N-1 check'); return g; }