From 13a29c2c2a7562a649e0cb1869d191e79dd20f2d Mon Sep 17 00:00:00 2001 From: Florian Krieger Date: Sun, 25 Oct 2026 15:38:10 +0100 Subject: [PATCH 001/181] 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 002/181] 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 003/181] 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 004/181] 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 005/181] 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 006/181] 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 007/181] 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 008/181] 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 009/181] 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 010/181] 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 011/181] 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 012/181] 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 013/181] 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 531f90f107bbcea142d2b12536b6eafe4b148092 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 15:27:00 +0100 Subject: [PATCH 014/181] One game, four doors: a per-save ruleset with Change Freeze, On-call and BGP at 3 a.m., a real Sandbox, and a new start screen --- CHANGELOG.md | 3 + site/i18n/de.js | 40 +++- site/i18n/es.js | 40 +++- site/i18n/fr.js | 40 +++- site/i18n/it.js | 40 +++- site/i18n/pt.js | 40 +++- src/game/10-catalog/30-supply-chain.js | 4 +- src/game/10-catalog/50-dark-fiber.js | 2 +- src/game/40-progress/10-businesses.js | 3 +- src/game/40-progress/30-rules.js | 42 ++++ src/game/60-features/20-scenarios.js | 10 +- src/game/60-features/60-share-card.js | 2 +- src/game/60-features/80-new-game.js | 2 +- src/game/70-rules/30-pnis.js | 2 +- src/game/70-rules/40-peering-inbox.js | 2 +- src/game/70-rules/70-sold-out.js | 2 +- src/game/80-simulation/50-sanitize.js | 2 + .../80-simulation/70-customers-and-events.js | 2 +- .../85-incidents/10-incidents-and-ddos.js | 2 +- src/game/85-incidents/20-failures.js | 3 +- src/game/85-incidents/30-events.js | 4 +- src/game/88-days/10-day-tick.js | 15 +- src/game/90-actions/10-interface.js | 6 +- src/game/90-actions/87-fiber-and-hardware.js | 4 +- src/game/90-actions/89-game-and-settings.js | 10 +- src/game/93-ui/20-phone.js | 4 +- src/game/93-ui/40-hud-and-panels.js | 8 +- src/game/93-ui/70-link-panels.js | 2 +- src/game/94-dashboard/50-lease-swaps.js | 2 +- src/game/95-modals/40-title.js | 13 +- src/game/95-modals/60-help.js | 2 +- src/game/95-modals/70-link-modal.js | 2 +- src/game/95-modals/80-own-cable.js | 10 +- src/game/95-modals/90-fiber-modals.js | 2 +- src/game/96-map/90-input.js | 2 +- src/game/96-map/95-clicks.js | 2 +- src/i18n/en.js | 40 +++- src/styles/40-modal.css | 17 ++ src/styles/60-phone.css | 8 + tests/rules.test.js | 191 ++++++++++++++++++ 40 files changed, 560 insertions(+), 67 deletions(-) create mode 100644 src/game/40-progress/30-rules.js create mode 100644 tests/rules.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index aa39a98..bee37c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- 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. - 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/site/i18n/de.js b/site/i18n/de.js index 0b751b2..9c859db 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1760,7 +1760,7 @@ "fiber_modals.for_comparison_a_leased_1_6t":"Zum Vergleich: Eine gemietete 1.6T-Wave kostet auf dieser Strecke {price}/Monat. Optiken kommen als Nächstes, im Link-Panel.", "fiber_modals.from_city":"Von {city}", "fiber_modals.km_km_is_longer_than_any":"{km} km sind länger, als jede Optik mit voller Geschwindigkeit reicht. Transponder laufen im Langstreckenmodus (1.2T, 800G oder 400G pro Kanal), oder du fügst unterwegs Regen-Standorte hinzu, um wieder volle Geschwindigkeit zu bekommen.", -"fiber_modals.lease_an_iru_price_mo_ready":"IRU mieten {price}/Monat · fertig in 30 Tagen", +"fiber_modals.lease_an_iru_price_mo_ready_n":"IRU mieten {price}/Monat · fertig in {n} Tagen", "fiber_modals.level_n":"Level {n}", "fiber_modals.no_dark_fiber_inside_the_uae":"Keine Dark Fiber innerhalb der VAE. Nur die zwei lizenzierten Betreiber dürfen hier Glasfaser verlegen, und die verkaufen nur Waves.", "fiber_modals.no_install_fee_live_in_minutes":"Keine Einrichtungsgebühr, live in Minuten, monatlich abgerechnet. Günstiger als eine Wave für kleine Kapazitäten, aber sie läuft über die Fabric von jemand anderem, und diese Fabric kann ausfallen.", @@ -1871,6 +1871,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) ist transitfrei. Du peerst mit jedem Riesen auf dem Planeten und zahlst niemandem etwas, um das Internet zu erreichen. Hat dich {days} Tage und {n} Störungen gekostet.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG und Co. kommen jedes Jahr vorbei. Melde dich im Tab Deals für $8k an. In den 45 Tagen danach brauchen selektive Netze mit Präsenz in dieser Region nur halb so viel Traffic wie sonst, bevor sie mit dir peeren. Manchmal gewinnst du auch die Tombola.", "help.once_auto_te_is_installed_you":"Sobald Auto-TE installiert ist, kannst du es im Tab NOC programmieren. Zu den Regeln gehören spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams und blackhole ddos. Prüfen spielt einen Probelauf mit dem Live-Traffic durch; Deployen macht es echt, Fehler inklusive.", +"help.one_game_four_doors_puzzles_are":"Ein Spiel, vier Türen, und die Regeln wählst du beim Start eines Netzes, danach sind sie festgelegt. Rätsel sind kleine Knoten zum Entwirren, ohne Uhr. Sandbox gibt dir eine Milliarde Dollar, alle Freischaltungen (dein eigenes Seekabel inklusive) und so viel Chaos, wie du willst, aber keine Abzeichen. Normal gibt es dreifach: Change Freeze (wenige Ausfälle, Lieferungen in Tagen, kein Postfach, keine Engpässe), Rufbereitschaft (das klassische Spiel) und BGP um 3 Uhr nachts (mehr und längere Ausfälle, mehr DDoS). Szenarien sind handgebaute Herausforderungen mit Ziel und Frist, und die Wochen-Challenge gibt allen eine Woche lang dieselbe Welt. Teile dein Ergebnis mit der Karte im Menü.", "help.open_peers_with_anyone_selective":"Offene Netze peeren mit allen. Selektive wollen erst Traffic sehen. Restriktive (Tier 1s) peeren nur mit Riesen, über PNIs. Paid Peering heißt genau das: Du zahlst. Große selektive Netze haben auch Launen: In manchen Städten lehnen sie ein paar Monate lang neue Peers ab oder nehmen nur PNIs, und ab und zu bauen sie eine Session ab, die du schon hattest. Versuch es in einer anderen Stadt oder mit einem PNI und frag später nochmal.", "help.out_of_port_speed_bundle_up":"Port zu langsam? Bündle bis zu 8 identische Ports zum selben Transit-Anbieter, IX oder PNI zu einem LAG. Jedes Mitglied kostet einen vollen Port; Flow-Hashing ist nie perfekt gleichmäßig, also trägt ein Bündel etwa 95 % der Summe.", "help.pni_lead_times":"PNI-Lieferzeiten", @@ -1879,7 +1880,6 @@ "help.reach_an_ix_over_a_fabric":"Erreiche einen IX über eine Fabric-Verbindung, ohne dort einen POP zu haben. Das funktioniert, und der Route Server bringt dir trotzdem jedes offene Netz, aber es wird nicht empfohlen: Der Reseller verlangt das 1,5-Fache für den Port und überbucht ihn auf 80 %, die Latenz läuft über die Fabric, ein Fabric-Ausfall reißt jede Session runter, und viele selektive Netze lehnen Remote-Mitglieder rundheraus ab.", "help.routers_optics_and_new_builds_get":"Router, Optiken und Neubauten werden mit den Jahren teurer, nach den ersten sechs Monaten etwa 4 % pro Jahr, und ab und zu macht ein Engpass eins davon für einen oder zwei Monate deutlich teurer. Was du schon besitzt, behält seinen Preis. Ersatzteile im Regal und eine jährliche Preisbindung aus dem Tab NOC verringern den Preisschock.", "help.rules_for_your_auto_te_controller":"Regeln für deinen Auto-TE-Controller: welche Ausgänge bevorzugt, welche gemieden werden und wann auf den nächsten übergelaufen wird. Die Hilfe im Editor erklärt jede Regel und hat fertige Skripte.", -"help.sandbox_gives_you_a_billion_dollars":"Sandbox gibt dir eine Milliarde Dollar, alle Freischaltungen und keine Ausfälle, aber keine Abzeichen. Szenarien sind handgebaute Herausforderungen mit Ziel und Frist, und die Wochen-Challenge gibt allen eine Woche lang dieselbe Welt. Teile dein Ergebnis mit der Karte im Menü.", "help.share_my_network":"Mein Netz teilen", "help.some_customers_come_with_conditions":"Manche Kunden kommen mit Bedingungen: nirgends Cogentle, keine Seekabel wegen Haien, zwei Router, ein Generator, NetChill on-net, verlustarme Erreichbarkeit nach China und mehr. Jede bringt einen Bonus. Nicht erfüllte machen sie grantig, bis du es behebst oder sie gehen.", "help.some_routers_take_forever_to_boot":"Manche Router brauchen ewig zum Booten. Der Tab Infra zeigt, wie lange deiner braucht. Langsame Booter lassen Abstürze länger dauern und machen aus einem Router-Tausch einen dreitägigen Ausfall. Größere Chassis, vor allem alles mit einem PacketOinker™ drin, sind öfter langsam. Zwillingsrouter machen das zum Problem von jemand anderem.", @@ -2842,6 +2842,29 @@ "routing_and_routers.the_model_won_t_fit_why":"Der {model} passt nicht.
{why}", "routing_and_routers.the_new_routers_in_city_are":"Die neuen Router in {city} werden noch eingebaut.
Ein Tausch pro Tag: Versuch es morgen nochmal.", "routing_and_routers.unplug_something_first_used_ports":"Steck zuerst etwas aus.
{used} Ports sind belegt, und mit einem Router weniger gibt es nur {max}.", +"rules.a_billion_dollars_every_unlock_your":"Eine Milliarde Dollar, alles freigeschaltet, dein eigenes Seekabel.", +"rules.a_cut_now_and_then":"Ab und zu ein Bagger.", +"rules.bgp_at_3_a_m":"BGP um 3 Uhr nachts", +"rules.change_freeze":"Change Freeze", +"rules.chaos_calm":"Ruhig", +"rules.chaos_none":"Keins", +"rules.chaos_normal":"Normal", +"rules.chaos_spicy":"Scharf", +"rules.everything_is_on_fire_and_it":"Alles brennt, und du hast Bereitschaft.", +"rules.fewer_outages_pnis_and_builds_in":"Ein Drittel der Ausfälle, kein DDoS. PNIs und Bauten in Tagen. Kein Postfach, keine Lieferengpässe, keine ausverkauften Routen.", +"rules.infinite_money_everything_unlocked_quick":"Endlos Geld, alles freigeschaltet, kurze Lieferzeiten. Keine Abzeichen.", +"rules.like_the_real_game":"Wie im echten Spiel.", +"rules.more_and_longer_outages_more_ddos":"Fast doppelt so viele Ausfälle, anderthalbmal so lang, doppelt so viel DDoS. Alles an.", +"rules.no_clock_no_bills_nothing_breaks":"Keine Uhr, keine Rechnungen, nichts geht kaputt.", +"rules.nobody_touches_prod_even_the_backhoes":"Niemand fasst Prod an. Sogar die Bagger sind im Urlaub.", +"rules.nothing_ever_breaks":"Nichts geht je kaputt.", +"rules.on_call":"Rufbereitschaft", +"rules.one_small_network_one_tricky_goal":"Ein kleines Netz, ein kniffliges Ziel.", +"rules.puzzle":"Rätsel", +"rules.real_lead_times_real_outages_a":"Echte Lieferzeiten, echte Ausfälle, ein volles Peering-Postfach. Das klassische Spiel.", +"rules.rules_are_locked_for_this_network":"{rules}: Die Regeln sind für dieses Netz festgelegt.", +"rules.the_real_thing_your_pager_has":"Das echte Spiel. Dein Pager hat Meinungen.", +"rules.your_pager_never_sleeps":"Dein Pager schläft nie.", "save.cash_in_the_bank":"{cash} auf der Bank", "save.import_failed_err":"Import fehlgeschlagen.
{err}", "save.load_name":"{name} laden?", @@ -2899,6 +2922,7 @@ "scenarios.reach_45_of_the_internet_and":"Erreiche 45 % 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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Sandbox-Modus
Eine Milliarde Dollar, alles freigeschaltet, und nichts geht jemals kaputt. Bau das Internet, das du schon immer wolltest.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Brasilien ist ein Kontinent: vierzig IX.brrr-Exchanges, Tausende Provedores und der Amazonas zwischen dir und dem Norden.", "scenarios.seoul_the_fastest_hungriest_eyeballs":"Seoul. Die schnellsten, hungrigsten Privatkunden der Welt, Transit zum vierfachen Preis und drei Platzhirsche, die dir jedes Gigabit in Rechnung stellen, das du ihnen schickst.", @@ -3017,24 +3041,34 @@ "supply_chain.until_date_at_p":"bis {date}, zu +{p}", "supply_chain.what_p_n_days_left":"{what} +{p} · noch {n} Tage", "supply_chain.your_price_lock_covers_you_until":"Deine Preisgarantie gilt bis {date}.", +"title.a_billion_dollars_and_every_toy":"Eine Milliarde Dollar und jedes Spielzeug im Laden.", "title.anywhere_else":"Irgendwo anders", "title.asia_hub_great_peering_far_from":"Asien-Drehkreuz. Tolles Peering, weit weg von zu Hause.", "title.back_to_my_network":"Zurück zu meinem Netz", "title.big_hungry_market_few_providers":"Großer, hungriger Markt, wenige Anbieter.", "title.build_an_internet_lay_fiber_between":"Baue deinen eigenen ISP auf. Verlege Glasfaser zwischen Städten, kauf Transit, peere an Exchanges, gewinne Geschäftskunden und halte deine Privatkunden bei Laune, während Bagger, Haie und Route Leaks alles tun, um dich aufzuhalten.", +"title.chaos_in_your_sandbox":"Chaos in deinem Sandkasten", "title.chat_on_signal":"Chat auf Signal", "title.choose":"Auswählen …", "title.continue_name_date":"{name} fortsetzen · {date}", "title.cookieless_stats_no_tracking":"Statistik ohne Cookies, kein Tracking", "title.crossroads_of_europe_de_kicks_ix":"Drehkreuz Europas. DE-KICKS IX, günstiger Transit.", +"title.hand_built_crises_and_one_world":"Handgebaute Krisen, und jede Woche eine Welt für alle.", "title.hard_mode_pricey_everything":"Schwerer Modus. Alles teuer, und die Tierwelt will dich tot sehen.", +"title.how_much_trouble":"Wie viel Ärger darf’s sein?", "title.huge_eyeball_market_pricey":"Riesiger Privatkundenmarkt. Teure Nachbarn.", "title.n_more_cities_with_transit":{"one":"{n} weitere Stadt mit Transit zum Kaufen","other":"{n} weitere Städte mit Transit zum Kaufen"}, "title.name_your_network":"Gib deinem Netz einen Namen", "title.new_in_series_of_tubes_v":"Neu in Series of Tubes {v}", +"title.one_network_one_knot_no_clock":"Ein Netz, ein Knoten zum Entwirren. Keine Uhr.", +"title.pick_a_door":"Wähl eine Tür", "title.pick_your_home_city":"Wähle deine Heimatstadt", -"title.scenarios_amp_weekly_challenge":"Szenarien & Wochen-Challenge →", +"title.puzzles":"Rätsel", +"title.puzzles_are_coming_soon":"Rätsel kommen bald.
Die Knoten werden noch geknüpft.", +"title.rules_are_picked_once_and_locked":"Die Regeln wählst du einmal, danach sind sie für dieses Netz festgelegt. Kein Nachverhandeln mitten im Spiel.", +"title.scenarios_amp_weekly":"Szenarien & Woche", "title.source_on_github":"Quellcode auf GitHub", +"title.the_real_game_climb_from_tier":"Das echte Spiel: von Tier 3 hoch zu Tier 1.", "title.your_network_name_was_saved_and":"Dein Netz {name} wurde gespeichert und wartet auf dich.", "traceroute.across_the_ix_switch":"über den Switch des {ix}", "traceroute.as_path_path":"AS-Pfad: {path}", diff --git a/site/i18n/es.js b/site/i18n/es.js index 2f2a645..d81e36e 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1758,7 +1758,7 @@ "fiber_modals.for_comparison_a_leased_1_6t":"A modo de comparación, una onda alquilada de 1.6T en esta ruta cuesta {price}/mes. Las ópticas vienen después, desde el panel del enlace.", "fiber_modals.from_city":"Desde {city}", "fiber_modals.km_km_is_longer_than_any":"{km} km es más de lo que alcanza cualquier óptica a toda velocidad. Los transpondedores funcionarán en modo de larga distancia (1.2T, 800G o 400G por canal), o añade sitios regeneradores por el camino para recuperar la velocidad completa.", -"fiber_modals.lease_an_iru_price_mo_ready":"Alquilar una IRU {price}/mes · lista en 30 días", +"fiber_modals.lease_an_iru_price_mo_ready_n":"Alquilar un IRU {price}/mes · lista en {n} días", "fiber_modals.level_n":"nivel {n}", "fiber_modals.no_dark_fiber_inside_the_uae":"No hay fibra oscura dentro de los EAU. Solo los dos operadores con licencia pueden tender fibra aquí, y solo venden ondas.", "fiber_modals.no_install_fee_live_in_minutes":"Sin cuota de instalación, activo en minutos, facturado mensualmente. Más barato que una onda para poca capacidad, pero viaja por la fabric de otro, y esa fabric puede fallar.", @@ -1869,6 +1869,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) es libre de tránsito. Haces peering con todos los gigantes del planeta y no pagas a nadie por llegar a internet. Te llevó {days} días y {n} incidentes.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG y compañía vienen cada año. Regístrate en la pestaña Tratos por $8k. Durante 45 días después, las redes selectivas con presencia en esa región solo piden la mitad del tráfico habitual antes de hacer peering contigo. A veces también ganas la rifa.", "help.once_auto_te_is_installed_you":"Una vez instalado Auto-TE, puedes programarlo desde la pestaña NOC. Las reglas incluyen spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams y blackhole ddos. Check hace una prueba en seco con tráfico real; Deploy lo hace de verdad, errores incluidos.", +"help.one_game_four_doors_puzzles_are":"Un juego, cuatro puertas, y las reglas se eligen al empezar una red y quedan fijadas después. Los puzles son pequeños nudos que deshacer, sin reloj. Sandbox te da mil millones de dólares, todo desbloqueado (tu propio cable submarino incluido) y el caos que elijas, pero sin insignias. Normal viene de tres maneras: Congelación de cambios (pocas caídas, entregas en días, sin bandeja ni escasez), De guardia (el juego clásico) y BGP a las 3 de la mañana (más caídas y más largas, más DDoS). Los escenarios son retos hechos a mano con un objetivo y un plazo, y el reto semanal da a todos el mismo mundo durante una semana. Comparte tu resultado con la tarjeta del menú.", "help.open_peers_with_anyone_selective":"Open hace peering con cualquiera. Selective quiere ver tráfico primero. Restrictive (los Tier 1) solo hace peering con gigantes, por PNIs. Paid significa justo eso. Las grandes redes selectivas también tienen sus rachas: en algunas ciudades rechazan peers nuevos durante unos meses, o solo aceptan PNIs, y de vez en cuando tumban una sesión que ya tenías. Prueba otra ciudad o un PNI, y vuelve a preguntar más tarde.", "help.out_of_port_speed_bundle_up":"¿Te quedas sin velocidad de puerto? Agrupa hasta 8 puertos idénticos al mismo proveedor de tránsito, IX o PNI en un LAG. Cada miembro cuesta un puerto entero; el hash de flujos nunca es perfectamente uniforme, así que un paquete transporta cerca del 95 % de la suma.", "help.pni_lead_times":"Plazos de los PNI", @@ -1877,7 +1878,6 @@ "help.reach_an_ix_over_a_fabric":"Llega a un IX por un circuito de fabric sin tener POP allí. Funciona, y el route server te sigue dando todas las redes abiertas, pero no se recomienda: el revendedor cobra 1,5× por el puerto y lo sobresuscribe al 80 %, la latencia viaja por la fabric, una caída de la fabric tumba todas las sesiones, y muchas redes selectivas rechazan de plano a los miembros remotos.", "help.routers_optics_and_new_builds_get":"Los routers, las ópticas y las obras nuevas se encarecen con los años, un 4 % anual tras los primeros seis meses, y de vez en cuando una escasez encarece mucho alguno durante un mes o dos. Lo que ya tienes conserva su precio. Los repuestos en el estante y un precio fijo anual desde la pestaña NOC amortiguan el golpe.", "help.rules_for_your_auto_te_controller":"Reglas para tu controlador Auto-TE: qué salidas preferir, cuáles evitar y cuándo desbordar hacia la siguiente. La ayuda del editor explica cada regla y trae scripts ya hechos.", -"help.sandbox_gives_you_a_billion_dollars":"El sandbox te da mil millones de dólares, todos los desbloqueos y ningún fallo, pero sin insignias. Los escenarios son desafíos hechos a mano con un objetivo y un plazo, y el desafío semanal da a todos el mismo mundo durante una semana. Comparte tu resultado con la tarjeta del menú.", "help.share_my_network":"Compartir mi red", "help.some_customers_come_with_conditions":"Algunos clientes traen condiciones: sin Cogentle en ningún sitio, sin cables submarinos por los tiburones, dos routers, un generador, NetChill on-net, buen alcance a China con poca pérdida y más. Cada una paga un bono. Las incumplidas los ponen de mal humor hasta que lo arreglas o se van.", "help.some_routers_take_forever_to_boot":"Algunos routers tardan una eternidad en arrancar. La pestaña Infra muestra cuánto tarda el tuyo. Los de arranque lento alargan las caídas y convierten el cambio de un router en una caída de tres días. Los chasis grandes, sobre todo los que llevan un PacketOinker™ dentro, son lentos más a menudo. Los routers gemelos lo convierten en problema de otro.", @@ -2840,6 +2840,29 @@ "routing_and_routers.the_model_won_t_fit_why":"El {model} no cabe.
{why}", "routing_and_routers.the_new_routers_in_city_are":"Los routers nuevos de {city} aún se están montando en el rack.
Un cambio al día: prueba mañana.", "routing_and_routers.unplug_something_first_used_ports":"Desconecta algo primero.
Hay {used} puertos en uso, y con un router menos solo hay {max}.", +"rules.a_billion_dollars_every_unlock_your":"Mil millones de dólares, todo desbloqueado, tu propio cable submarino.", +"rules.a_cut_now_and_then":"Algún corte de vez en cuando.", +"rules.bgp_at_3_a_m":"BGP a las 3 de la mañana", +"rules.change_freeze":"Congelación de cambios", +"rules.chaos_calm":"Tranquilo", +"rules.chaos_none":"Nada", +"rules.chaos_normal":"Normal", +"rules.chaos_spicy":"Picante", +"rules.everything_is_on_fire_and_it":"Todo está ardiendo, y te toca a ti.", +"rules.fewer_outages_pnis_and_builds_in":"Un tercio de las caídas, sin DDoS. PNI y obras en días. Sin bandeja de entrada, sin escasez, sin rutas agotadas.", +"rules.infinite_money_everything_unlocked_quick":"Dinero sin fin, todo desbloqueado, plazos cortos. Sin insignias.", +"rules.like_the_real_game":"Como el juego de verdad.", +"rules.more_and_longer_outages_more_ddos":"Casi el doble de caídas, la mitad más largas, el doble de DDoS. Todo activado.", +"rules.no_clock_no_bills_nothing_breaks":"Sin reloj, sin facturas, nada se rompe.", +"rules.nobody_touches_prod_even_the_backhoes":"Nadie toca producción. Hasta las excavadoras están de vacaciones.", +"rules.nothing_ever_breaks":"Nunca se rompe nada.", +"rules.on_call":"De guardia", +"rules.one_small_network_one_tricky_goal":"Una red pequeña, un objetivo con truco.", +"rules.puzzle":"Puzle", +"rules.real_lead_times_real_outages_a":"Plazos reales, caídas reales, una bandeja de peering llena. El juego clásico.", +"rules.rules_are_locked_for_this_network":"{rules}: las reglas están fijadas para esta red.", +"rules.the_real_thing_your_pager_has":"El juego de verdad. Tu busca tiene opiniones.", +"rules.your_pager_never_sleeps":"Tu busca no duerme nunca.", "save.cash_in_the_bank":"{cash} en el banco", "save.import_failed_err":"Falló la importación.
{err}", "save.load_name":"¿Cargar {name}?", @@ -2897,6 +2920,7 @@ "scenarios.reach_45_of_the_internet_and":"Llega al 45 % 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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Modo sandbox
Mil millones de dólares, todos los desbloqueos y nada se rompe nunca. Construye el internet que siempre quisiste.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Brasil es un continente: cuarenta intercambios IX.brrr, miles de provedores, y el Amazonas entre tú y el norte.", "scenarios.seoul_the_fastest_hungriest_eyeballs":"Seúl. Los eyeballs más rápidos y hambrientos de la Tierra, tránsito a cuatro veces el precio, y tres operadores históricos que te facturan cada gigabit que les mandas.", @@ -3015,24 +3039,34 @@ "supply_chain.until_date_at_p":"hasta {date}, a +{p}", "supply_chain.what_p_n_days_left":"{what} +{p} · quedan {n} días", "supply_chain.your_price_lock_covers_you_until":"Tu precio fijo te cubre hasta {date}.", +"title.a_billion_dollars_and_every_toy":"Mil millones de dólares y todos los juguetes de la tienda.", "title.anywhere_else":"En otro lugar", "title.asia_hub_great_peering_far_from":"Hub de Asia. Gran peering, lejos de casa.", "title.back_to_my_network":"Volver a mi red", "title.big_hungry_market_few_providers":"Mercado enorme y hambriento, pocos proveedores.", "title.build_an_internet_lay_fiber_between":"Construye un internet. Tiende fibra entre ciudades, compra tránsito, haz peering en intercambios, firma con empresas y mantén contentos a los eyeballs mientras retroexcavadoras, tiburones y fugas de rutas hacen lo posible por detenerte.", +"title.chaos_in_your_sandbox":"Caos en tu sandbox", "title.chat_on_signal":"Chatea en Signal", "title.choose":"Elegir…", "title.continue_name_date":"Continuar {name} · {date}", "title.cookieless_stats_no_tracking":"Estadísticas sin cookies, sin rastreo", "title.crossroads_of_europe_de_kicks_ix":"La encrucijada de Europa. DE-KICKS IX, tránsito barato.", +"title.hand_built_crises_and_one_world":"Crisis hechas a mano, y cada semana un mismo mundo para todos.", "title.hard_mode_pricey_everything":"Modo difícil. Todo carísimo, y la fauna te quiere muerto.", +"title.how_much_trouble":"¿Cuántos problemas quieres?", "title.huge_eyeball_market_pricey":"Mercado enorme de eyeballs. Vecinos caros.", "title.n_more_cities_with_transit":{"one":"{n} ciudad más con tránsito a la venta","other":"{n} ciudades más con tránsito a la venta"}, "title.name_your_network":"Ponle nombre a tu red", "title.new_in_series_of_tubes_v":"Novedades de Series of Tubes {v}", +"title.one_network_one_knot_no_clock":"Una red, un nudo que deshacer. Sin reloj.", +"title.pick_a_door":"Elige una puerta", "title.pick_your_home_city":"Elige tu ciudad de origen", -"title.scenarios_amp_weekly_challenge":"Escenarios y desafío semanal →", +"title.puzzles":"Puzles", +"title.puzzles_are_coming_soon":"Los puzles llegan pronto.
Todavía estamos atando los nudos.", +"title.rules_are_picked_once_and_locked":"Las reglas se eligen una vez y quedan fijadas para esta red. Nada de cambiar el trato a mitad de partida.", +"title.scenarios_amp_weekly":"Escenarios y semanal", "title.source_on_github":"Código en GitHub", +"title.the_real_game_climb_from_tier":"El juego de verdad: sube de Tier 3 a Tier 1.", "title.your_network_name_was_saved_and":"Tu red {name} se guardó y te está esperando.", "traceroute.across_the_ix_switch":"a través del switch de {ix}", "traceroute.as_path_path":"AS path: {path}", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 413ae5f..c1ceb68 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1758,7 +1758,7 @@ "fiber_modals.for_comparison_a_leased_1_6t":"Pour comparer, une longueur d’onde 1.6T louée sur ce trajet coûte {price}/mois. Les optiques viennent ensuite, depuis le panneau du lien.", "fiber_modals.from_city":"Depuis {city}", "fiber_modals.km_km_is_longer_than_any":"{km} km, c’est plus long que la portée de n’importe quelle optique à plein débit. Les transpondeurs tourneront en mode longue distance (1.2T, 800G ou 400G par canal), ou ajoute des sites de régénération en route pour retrouver le plein débit.", -"fiber_modals.lease_an_iru_price_mo_ready":"Louer un IRU {price}/mois · prêt en 30 jours", +"fiber_modals.lease_an_iru_price_mo_ready_n":"Louer un IRU {price}/mois · prêt dans {n} jours", "fiber_modals.level_n":"niveau {n}", "fiber_modals.no_dark_fiber_inside_the_uae":"Pas de fibre noire aux Émirats. Seuls les deux opérateurs licenciés peuvent poser de la fibre ici, et ils ne vendent que des longueurs d’onde.", "fiber_modals.no_install_fee_live_in_minutes":"Pas de frais d’installation, actif en quelques minutes, facturé au mois. Moins cher qu’une longueur d’onde pour une petite capacité, mais ça passe par le fabric de quelqu’un d’autre, et ce fabric peut tomber en panne.", @@ -1869,6 +1869,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) est transit-free. Tu fais du peering avec tous les géants de la planète et tu ne paies personne pour atteindre Internet. Il t’a fallu {days} jours et {n} incidents.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG et compagnie reviennent chaque année. Inscris-toi dans l’onglet Offres pour $8k. Pendant les 45 jours suivants, les réseaux sélectifs présents dans cette région ne demandent que la moitié du trafic habituel avant de faire du peering avec toi. Parfois, tu gagnes aussi la tombola.", "help.once_auto_te_is_installed_you":"Une fois Auto-TE installé, tu peux le programmer depuis l’onglet NOC. Parmi les règles : spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams et blackhole ddos. Vérifier fait un essai à blanc sur le trafic réel ; Déployer le rend réel, erreurs comprises.", +"help.one_game_four_doors_puzzles_are":"Un jeu, quatre portes, et les règles se choisissent au démarrage d’un réseau puis restent verrouillées. Les casse-têtes sont de petits nœuds à défaire, sans horloge. Le bac à sable te donne un milliard de dollars, tout débloqué (ton propre câble sous-marin compris) et autant de chaos que tu veux, mais pas de badges. Normal existe en trois versions : Gel des changements (peu de pannes, livraisons en quelques jours, ni boîte de réception ni pénurie), D’astreinte (le jeu classique) et BGP à 3 h du matin (plus de pannes, plus longues, plus de DDoS). Les scénarios sont des défis faits main avec un objectif et une échéance, et le défi de la semaine donne à tous le même monde pendant une semaine. Partage ton résultat avec la carte du menu.", "help.open_peers_with_anyone_selective":"Ouverte : peering avec tout le monde. Sélective : veut d’abord voir du trafic. Restrictive (les Tier 1) : peering uniquement avec les géants, via PNI. Payante : tout est dans le nom. Les gros réseaux sélectifs ont aussi leurs humeurs : dans certaines villes, ils refusent les nouveaux peers pendant quelques mois, ou n’acceptent que des PNI, et de temps en temps ils coupent une session que tu avais déjà. Essaie une autre ville ou un PNI, et redemande plus tard.", "help.out_of_port_speed_bundle_up":"Port trop petit ? Regroupe jusqu’à 8 ports identiques vers le même fournisseur de transit, IX ou PNI en un LAG. Chaque membre coûte un port complet ; le hachage des flux n’est jamais parfaitement équilibré, donc un bundle transporte environ 95 % de la somme.", "help.pni_lead_times":"Délais des PNI", @@ -1877,7 +1878,6 @@ "help.reach_an_ix_over_a_fabric":"Rejoindre un IX via un circuit fabric sans POP sur place. Ça marche, et le route server te donne quand même tous les réseaux ouverts, mais c’est déconseillé : le revendeur facture le port 1,5× et le survend à 80 %, la latence dépend du fabric, une panne du fabric fait tomber toutes les sessions, et beaucoup de réseaux sélectifs refusent tout net les membres distants.", "help.routers_optics_and_new_builds_get":"Routeurs, optiques et nouvelles constructions coûtent plus cher avec les années, environ 4 % par an après les six premiers mois, et de temps en temps une pénurie rend l’un d’eux bien plus cher pendant un mois ou deux. Ce que vous possédez déjà garde son prix. Des pièces de rechange sur l’étagère et un blocage annuel des prix depuis l’onglet NOC amortissent le choc.", "help.rules_for_your_auto_te_controller":"Des règles pour votre contrôleur Auto-TE : quelles sorties préférer, lesquelles éviter et quand déborder sur la suivante. L’aide de l’éditeur explique chaque règle et propose des scripts tout prêts.", -"help.sandbox_gives_you_a_billion_dollars":"Le bac à sable te donne un milliard de dollars, tout débloqué et zéro panne, mais pas de badges. Les scénarios sont des défis faits main avec un objectif et une échéance, et le défi de la semaine donne à tout le monde le même monde pendant une semaine. Partage ton résultat avec la carte du menu.", "help.share_my_network":"Partager mon réseau", "help.some_customers_come_with_conditions":"Certains clients viennent avec des conditions : pas de Cogentle nulle part, pas de câbles sous-marins à cause des requins, deux routeurs, un groupe électrogène, NetChill on-net, accès à la Chine avec peu de pertes, et plus encore. Chacune rapporte un bonus. Celles qui ne sont pas remplies les rendent grognons jusqu’à ce que tu corriges le tir ou qu’ils partent.", "help.some_routers_take_forever_to_boot":"Certains routeurs mettent une éternité à démarrer. L’onglet Infra montre combien de temps met le tien. Les routeurs lents au boot font durer les crashs plus longtemps et transforment le remplacement d’un routeur unique en panne de trois jours. Les gros châssis, surtout ceux avec un PacketOinker™ dedans, sont plus souvent lents. Avec des routeurs jumeaux, ça devient le problème de quelqu’un d’autre.", @@ -2840,6 +2840,29 @@ "routing_and_routers.the_model_won_t_fit_why":"Le {model} ne rentre pas.
{why}", "routing_and_routers.the_new_routers_in_city_are":"Les nouveaux routeurs de {city} sont encore en cours de montage en baie.
Un remplacement par jour : réessaie demain.", "routing_and_routers.unplug_something_first_used_ports":"Débranche d’abord quelque chose.
{used} ports sont utilisés, et avec un routeur de moins tu n’en aurais que {max}.", +"rules.a_billion_dollars_every_unlock_your":"Un milliard de dollars, tout débloqué, ton propre câble sous-marin.", +"rules.a_cut_now_and_then":"Une coupure de temps en temps.", +"rules.bgp_at_3_a_m":"BGP à 3 h du matin", +"rules.change_freeze":"Gel des changements", +"rules.chaos_calm":"Calme", +"rules.chaos_none":"Aucun", +"rules.chaos_normal":"Normal", +"rules.chaos_spicy":"Épicé", +"rules.everything_is_on_fire_and_it":"Tout brûle, et c’est ton tour d’astreinte.", +"rules.fewer_outages_pnis_and_builds_in":"Un tiers des pannes, pas de DDoS. PNI et chantiers en quelques jours. Pas de boîte de réception, pas de pénurie, pas de routes épuisées.", +"rules.infinite_money_everything_unlocked_quick":"Argent infini, tout débloqué, délais courts. Pas de badges.", +"rules.like_the_real_game":"Comme le vrai jeu.", +"rules.more_and_longer_outages_more_ddos":"Presque deux fois plus de pannes, moitié plus longues, deux fois plus de DDoS. Tout activé.", +"rules.no_clock_no_bills_nothing_breaks":"Pas d’horloge, pas de factures, rien ne casse.", +"rules.nobody_touches_prod_even_the_backhoes":"Personne ne touche à la prod. Même les pelleteuses sont en vacances.", +"rules.nothing_ever_breaks":"Rien ne casse jamais.", +"rules.on_call":"D’astreinte", +"rules.one_small_network_one_tricky_goal":"Un petit réseau, un objectif retors.", +"rules.puzzle":"Casse-tête", +"rules.real_lead_times_real_outages_a":"De vrais délais, de vraies pannes, une boîte de peering pleine. Le jeu classique.", +"rules.rules_are_locked_for_this_network":"{rules} : les règles sont verrouillées pour ce réseau.", +"rules.the_real_thing_your_pager_has":"Le vrai jeu. Ton bipeur a des opinions.", +"rules.your_pager_never_sleeps":"Ton bipeur ne dort jamais.", "save.cash_in_the_bank":"{cash} en banque", "save.import_failed_err":"Échec de l’import.
{err}", "save.load_name":"Charger {name} ?", @@ -2897,6 +2920,7 @@ "scenarios.reach_45_of_the_internet_and":"Couvre 45 % 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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Mode bac à sable
Un milliard de dollars, tout débloqué, et rien ne casse jamais. Construis l’Internet dont tu as toujours rêvé.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Le Brésil est un continent : quarante IX.brrr, des milliers de provedores, et l’Amazonie entre toi et le nord.", "scenarios.seoul_the_fastest_hungriest_eyeballs":"Séoul. Les eyeballs les plus rapides et les plus voraces de la planète, du transit à quatre fois le prix, et trois opérateurs historiques qui te facturent chaque gigabit que tu leur envoies.", @@ -3015,24 +3039,34 @@ "supply_chain.until_date_at_p":"jusqu’au {date}, à +{p}", "supply_chain.what_p_n_days_left":"{what} +{p} · encore {n} jours", "supply_chain.your_price_lock_covers_you_until":"Votre blocage des prix vous couvre jusqu’au {date}.", +"title.a_billion_dollars_and_every_toy":"Un milliard de dollars et tous les jouets du magasin.", "title.anywhere_else":"Ailleurs", "title.asia_hub_great_peering_far_from":"Hub de l’Asie. Super peering, loin de chez soi.", "title.back_to_my_network":"Retour à mon réseau", "title.big_hungry_market_few_providers":"Gros marché affamé, peu d’opérateurs.", "title.build_an_internet_lay_fiber_between":"Construis un Internet. Pose de la fibre entre les villes, achète du transit, fais du peering aux IX, signe des entreprises et garde les eyeballs contents pendant que pelleteuses, requins et fuites de routes font tout pour t’arrêter.", +"title.chaos_in_your_sandbox":"Du chaos dans ton bac à sable", "title.chat_on_signal":"Discuter sur Signal", "title.choose":"Choisir…", "title.continue_name_date":"Continuer {name} · {date}", "title.cookieless_stats_no_tracking":"Stats sans cookies, sans pistage", "title.crossroads_of_europe_de_kicks_ix":"Carrefour de l’Europe. IX DE-KICKS, transit pas cher.", +"title.hand_built_crises_and_one_world":"Des crises faites main, et chaque semaine un même monde pour tous.", "title.hard_mode_pricey_everything":"Mode difficile. Tout coûte cher, et la faune veut ta peau.", +"title.how_much_trouble":"Combien d’ennuis ?", "title.huge_eyeball_market_pricey":"Énorme marché d’eyeballs. Voisins chers.", "title.n_more_cities_with_transit":{"one":"{n} autre ville où acheter du transit","other":"{n} autres villes où acheter du transit"}, "title.name_your_network":"Nomme ton réseau", "title.new_in_series_of_tubes_v":"Nouveautés de Series of Tubes {v}", +"title.one_network_one_knot_no_clock":"Un réseau, un nœud à défaire. Pas d’horloge.", +"title.pick_a_door":"Choisis une porte", "title.pick_your_home_city":"Choisis ta ville de départ", -"title.scenarios_amp_weekly_challenge":"Scénarios et défi de la semaine →", +"title.puzzles":"Casse-têtes", +"title.puzzles_are_coming_soon":"Les casse-têtes arrivent bientôt.
On est encore en train de nouer les nœuds.", +"title.rules_are_picked_once_and_locked":"Les règles se choisissent une fois et restent verrouillées pour ce réseau. Pas de renégociation en pleine partie.", +"title.scenarios_amp_weekly":"Scénarios & hebdo", "title.source_on_github":"Code source sur GitHub", +"title.the_real_game_climb_from_tier":"Le vrai jeu : grimpe de Tier 3 à Tier 1.", "title.your_network_name_was_saved_and":"Ton réseau {name} a été sauvegardé et t’attend.", "traceroute.across_the_ix_switch":"via le switch de {ix}", "traceroute.as_path_path":"AS path : {path}", diff --git a/site/i18n/it.js b/site/i18n/it.js index 103bc61..e47f8c2 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1758,7 +1758,7 @@ "fiber_modals.for_comparison_a_leased_1_6t":"Per confronto, una wave 1.6T in affitto su questa rotta costa {price}/mese. Le ottiche vengono dopo, dal pannello del link.", "fiber_modals.from_city":"Da {city}", "fiber_modals.km_km_is_longer_than_any":"{km} km sono più di quanto qualsiasi ottica raggiunga a piena velocità. I transponder andranno in modalità long-haul (1.2T, 800G o 400G per canale), oppure aggiungi siti di rigenerazione lungo il percorso per tornare alla piena velocità.", -"fiber_modals.lease_an_iru_price_mo_ready":"Affitta un IRU {price}/mese · pronta in 30 giorni", +"fiber_modals.lease_an_iru_price_mo_ready_n":"Affitta un IRU {price}/mese · pronta in {n} giorni", "fiber_modals.level_n":"livello {n}", "fiber_modals.no_dark_fiber_inside_the_uae":"Niente dark fiber dentro gli Emirati. Qui solo i due operatori con licenza possono posare fibra, e vendono solo wave.", "fiber_modals.no_install_fee_live_in_minutes":"Nessun costo di attivazione, attivo in pochi minuti, fatturato a mese. Più economico di una wave per piccole capacità, ma viaggia sul fabric di qualcun altro, e quel fabric può guastarsi.", @@ -1869,6 +1869,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) è transit-free. Fai peering con ogni gigante del pianeta e non paghi nessuno per raggiungere internet. Ci hai messo {days} giorni e {n} incidenti.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG e compagnia tornano ogni anno. Iscriviti nella scheda Offerte per $8k. Nei 45 giorni successivi, le reti selective presenti in quella regione chiedono solo metà del traffico abituale prima di fare peering con te. A volte vinci pure la lotteria.", "help.once_auto_te_is_installed_you":"Una volta installato Auto-TE, puoi programmarlo dalla scheda NOC. Tra le regole ci sono spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams e blackhole ddos. Check fa una prova a secco sul traffico reale; Deploy la rende vera, errori compresi.", +"help.one_game_four_doors_puzzles_are":"Un gioco, quattro porte, e le regole si scelgono quando nasce una rete e poi restano bloccate. I rompicapi sono piccoli nodi da sciogliere, senza orologio. La sandbox ti dà un miliardo di dollari, tutto sbloccato (compreso il tuo cavo sottomarino) e tutto il caos che scegli, ma niente medaglie. Normale ha tre varianti: Change freeze (pochi guasti, consegne in pochi giorni, niente posta né carenze), Reperibile (il gioco classico) e BGP alle 3 di notte (guasti più frequenti e più lunghi, più DDoS). Gli scenari sono sfide fatte a mano con un obiettivo e una scadenza, e la sfida settimanale dà a tutti lo stesso mondo per una settimana. Condividi il risultato con la scheda nel menu.", "help.open_peers_with_anyone_selective":"Open: fa peering con chiunque. Selective: vuole prima vedere traffico. Restrictive (i Tier 1): fa peering solo con i giganti, tramite PNI. Paid: esattamente quello che sembra, si paga. Le grandi reti selective hanno anche i loro umori: in certe città rifiutano nuovi peer per qualche mese, o accettano solo PNI, e ogni tanto abbattono una sessione che avevi già. Prova un’altra città o un PNI, e richiedi più avanti.", "help.out_of_port_speed_bundle_up":"Porte al limite? Raggruppa fino a 8 porte identiche verso lo stesso provider di transit, IX o PNI in un LAG. Ogni membro costa una porta intera; il flow hashing non è mai perfettamente uniforme, quindi un bundle trasporta circa il 95% della somma.", "help.pni_lead_times":"Tempi di consegna delle PNI", @@ -1877,7 +1878,6 @@ "help.reach_an_ix_over_a_fabric":"Raggiungi un IX con un circuito su fabric senza avere un POP lì. Funziona, e il route server ti dà comunque tutte le reti aperte, ma è sconsigliato: il rivenditore ti fa pagare la porta 1,5× e la vende in oversubscription all’80%, la latenza dipende dal fabric, un disservizio del fabric fa cadere tutte le sessioni, e molte reti selective rifiutano i membri remoti senza appello.", "help.routers_optics_and_new_builds_get":"Router, ottiche e nuove costruzioni rincarano con gli anni, circa il 4% all’anno dopo i primi sei mesi, e ogni tanto una carenza ne fa rincarare uno parecchio per un mese o due. Quello che possiedi già mantiene il suo prezzo. Le scorte sullo scaffale e un blocco annuale dei prezzi dalla scheda NOC attutiscono il colpo.", "help.rules_for_your_auto_te_controller":"Regole per il tuo controller Auto-TE: quali uscite preferire, quali evitare e quando passare alla successiva. L’aiuto dell’editor spiega ogni regola e ha script pronti.", -"help.sandbox_gives_you_a_billion_dollars":"La Sandbox ti dà un miliardo di dollari, tutto sbloccato e nessun guasto, ma niente badge. Gli Scenari sono sfide costruite a mano con un obiettivo e una scadenza, e la sfida settimanale dà a tutti lo stesso mondo per una settimana. Condividi il tuo risultato con la card nel menu.", "help.share_my_network":"Condividi la mia rete", "help.some_customers_come_with_conditions":"Alcuni clienti arrivano con delle condizioni: niente Cogentle da nessuna parte, niente cavi sottomarini per colpa degli squali, due router, un generatore, NetChill on-net, accesso alla Cina con poche perdite e altro. Ognuna paga un bonus. Quelle non rispettate li rendono scontrosi finché non rimedi o se ne vanno.", "help.some_routers_take_forever_to_boot":"Alcuni router ci mettono una vita ad avviarsi. La scheda Infra mostra quanto ci mette il tuo. I router lenti al boot allungano i crash e trasformano la sostituzione di un router singolo in un disservizio di tre giorni. Gli chassis più grandi, soprattutto quelli con dentro un PacketOinker™, sono lenti più spesso. Con due router diventa un problema di qualcun altro.", @@ -2840,6 +2840,29 @@ "routing_and_routers.the_model_won_t_fit_why":"Il {model} non ci sta.
{why}", "routing_and_routers.the_new_routers_in_city_are":"I nuovi router a {city} li stanno ancora montando nel rack.
Un cambio al giorno: riprova domani.", "routing_and_routers.unplug_something_first_used_ports":"Prima stacca qualcosa.
Ci sono {used} porte in uso, e con un router in meno ne avresti solo {max}.", +"rules.a_billion_dollars_every_unlock_your":"Un miliardo di dollari, tutto sbloccato, il tuo cavo sottomarino.", +"rules.a_cut_now_and_then":"Un taglio ogni tanto.", +"rules.bgp_at_3_a_m":"BGP alle 3 di notte", +"rules.change_freeze":"Change freeze", +"rules.chaos_calm":"Calmo", +"rules.chaos_none":"Nessuno", +"rules.chaos_normal":"Normale", +"rules.chaos_spicy":"Piccante", +"rules.everything_is_on_fire_and_it":"Va tutto a fuoco, e tocca a te.", +"rules.fewer_outages_pnis_and_builds_in":"Un terzo dei guasti, niente DDoS. PNI e cantieri in pochi giorni. Niente posta, niente carenze, niente rotte esaurite.", +"rules.infinite_money_everything_unlocked_quick":"Soldi infiniti, tutto sbloccato, consegne rapide. Niente medaglie.", +"rules.like_the_real_game":"Come il gioco vero.", +"rules.more_and_longer_outages_more_ddos":"Quasi il doppio dei guasti, lunghi una volta e mezza, il doppio dei DDoS. Tutto acceso.", +"rules.no_clock_no_bills_nothing_breaks":"Niente orologio, niente bollette, non si rompe niente.", +"rules.nobody_touches_prod_even_the_backhoes":"Nessuno tocca la produzione. Anche le ruspe sono in ferie.", +"rules.nothing_ever_breaks":"Non si rompe mai niente.", +"rules.on_call":"Reperibile", +"rules.one_small_network_one_tricky_goal":"Una piccola rete, un obiettivo insidioso.", +"rules.puzzle":"Rompicapo", +"rules.real_lead_times_real_outages_a":"Tempi di consegna veri, guasti veri, una casella di peering piena. Il gioco classico.", +"rules.rules_are_locked_for_this_network":"{rules}: le regole sono bloccate per questa rete.", +"rules.the_real_thing_your_pager_has":"Il gioco vero. Il tuo cercapersone ha delle opinioni.", +"rules.your_pager_never_sleeps":"Il tuo cercapersone non dorme mai.", "save.cash_in_the_bank":"{cash} in cassa", "save.import_failed_err":"Importazione fallita.
{err}", "save.load_name":"Caricare {name}?", @@ -2897,6 +2920,7 @@ "scenarios.reach_45_of_the_internet_and":"Raggiungi il 45% 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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Modalità sandbox
Un miliardo di dollari, tutto sbloccato e non si rompe mai niente. Costruisci l’internet che hai sempre sognato.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Il Brasile è un continente: quaranta exchange IX.brrr, migliaia di provedores e l’Amazzonia tra te e il nord.", "scenarios.seoul_the_fastest_hungriest_eyeballs":"Seoul. Gli eyeball più veloci e affamati della Terra, transit a quattro volte il prezzo, e tre incumbent che ti fatturano ogni gigabit che gli mandi.", @@ -3015,24 +3039,34 @@ "supply_chain.until_date_at_p":"fino al {date}, a +{p}", "supply_chain.what_p_n_days_left":"{what} +{p} · {n} giorni rimasti", "supply_chain.your_price_lock_covers_you_until":"Il tuo blocco dei prezzi ti copre fino al {date}.", +"title.a_billion_dollars_and_every_toy":"Un miliardo di dollari e tutti i giocattoli del negozio.", "title.anywhere_else":"Altrove", "title.asia_hub_great_peering_far_from":"Hub dell’Asia. Ottimo peering, lontano da casa.", "title.back_to_my_network":"Torna alla mia rete", "title.big_hungry_market_few_providers":"Mercato grande e affamato, pochi provider.", "title.build_an_internet_lay_fiber_between":"Costruisci un internet. Posa fibra tra le città, compra transit, fai peering agli exchange, metti sotto contratto le aziende e tieni contenti gli eyeball, mentre ruspe, squali e route leak fanno di tutto per fermarti.", +"title.chaos_in_your_sandbox":"Caos nella tua sandbox", "title.chat_on_signal":"Chat su Signal", "title.choose":"Scegli…", "title.continue_name_date":"Continua {name} · {date}", "title.cookieless_stats_no_tracking":"Statistiche senza cookie, nessun tracciamento", "title.crossroads_of_europe_de_kicks_ix":"Crocevia d’Europa. IX DE-KICKS, transit economico.", +"title.hand_built_crises_and_one_world":"Crisi fatte a mano, e ogni settimana lo stesso mondo per tutti.", "title.hard_mode_pricey_everything":"Modalità difficile. Tutto carissimo, e la fauna ti vuole morto.", +"title.how_much_trouble":"Quanti guai vuoi?", "title.huge_eyeball_market_pricey":"Enorme mercato di eyeball. Vicini costosi.", "title.n_more_cities_with_transit":{"one":"Ancora {n} città dove comprare transit","other":"Altre {n} città dove comprare transit"}, "title.name_your_network":"Dai un nome alla tua rete", "title.new_in_series_of_tubes_v":"Novità di Series of Tubes {v}", +"title.one_network_one_knot_no_clock":"Una rete, un nodo da sciogliere. Niente orologio.", +"title.pick_a_door":"Scegli una porta", "title.pick_your_home_city":"Scegli la tua città di partenza", -"title.scenarios_amp_weekly_challenge":"Scenari e sfida settimanale →", +"title.puzzles":"Rompicapi", +"title.puzzles_are_coming_soon":"I rompicapi arrivano presto.
Stiamo ancora annodando i nodi.", +"title.rules_are_picked_once_and_locked":"Le regole si scelgono una volta e restano bloccate per questa rete. Niente cambi di accordo a metà partita.", +"title.scenarios_amp_weekly":"Scenari e sfida settimanale", "title.source_on_github":"Codice su GitHub", +"title.the_real_game_climb_from_tier":"Il gioco vero: sali da Tier 3 a Tier 1.", "title.your_network_name_was_saved_and":"La tua rete {name} è stata salvata e ti sta aspettando.", "traceroute.across_the_ix_switch":"attraverso lo switch di {ix}", "traceroute.as_path_path":"AS path: {path}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 046f9a8..eeccb26 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1758,7 +1758,7 @@ "fiber_modals.for_comparison_a_leased_1_6t":"Para comparar, uma wave alugada de 1.6T nesta rota sai {price}/mês. A óptica vem depois, pelo painel do link.", "fiber_modals.from_city":"De {city}", "fiber_modals.km_km_is_longer_than_any":"{km} km é mais do que qualquer óptico alcança em velocidade máxima. Os transponders vão rodar em modo long-haul (1.2T, 800G ou 400G por canal), ou adicione sites de regeneração no caminho para recuperar a velocidade máxima.", -"fiber_modals.lease_an_iru_price_mo_ready":"Alugar um IRU {price}/mês · pronto em 30 dias", +"fiber_modals.lease_an_iru_price_mo_ready_n":"Alugar um IRU {price}/mês · pronto em {n} dias", "fiber_modals.level_n":"nível {n}", "fiber_modals.no_dark_fiber_inside_the_uae":"Nada de dark fiber dentro dos Emirados. Só as duas operadoras licenciadas podem passar fibra aqui, e elas só vendem waves.", "fiber_modals.no_install_fee_live_in_minutes":"Sem taxa de instalação, no ar em minutos, cobrado por mês. Mais barato que uma wave para pouca capacidade, mas roda no fabric de outra pessoa, e esse fabric pode falhar.", @@ -1869,6 +1869,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) é transit-free. Você faz peering com todos os gigantes do planeta e não paga ninguém para chegar à internet. Levou {days} dias e {n} incidentes.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG e a turma aparecem todo ano. Inscreva-se na aba Negócios por $8k. Nos 45 dias seguintes, redes seletivas presentes naquela região pedem só metade do tráfego de sempre antes de fazer peering com você. Às vezes você ainda ganha o sorteio.", "help.once_auto_te_is_installed_you":"Com o Auto-TE instalado, você pode programá-lo pela aba NOC. As regras incluem spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams e blackhole ddos. Verificar faz um dry run contra o tráfego real; Aplicar torna tudo real, erros incluídos.", +"help.one_game_four_doors_puzzles_are":"Um jogo, quatro portas, e as regras são escolhidas quando uma rede começa e ficam travadas depois. Os quebra-cabeças são pequenos nós para desatar, sem relógio. A sandbox dá um bilhão de dólares, tudo desbloqueado (incluindo o seu próprio cabo submarino) e o caos que você escolher, mas sem medalhas. O Normal vem de três jeitos: Congelamento de mudanças (poucas falhas, entregas em dias, sem caixa de entrada nem escassez), De plantão (o jogo clássico) e BGP às 3 da manhã (mais falhas e mais longas, mais DDoS). Os cenários são desafios feitos à mão com um objetivo e um prazo, e o desafio semanal dá a todos o mesmo mundo durante uma semana. Compartilhe o seu resultado com o cartão no menu.", "help.open_peers_with_anyone_selective":"Open faz peering com qualquer um. Selective quer ver tráfego antes. Restrictive (Tier 1s) só faz peering com gigantes, via PNI. Paid é exatamente isso. Redes seletivas grandes também têm seus humores: em algumas cidades recusam novos peers por alguns meses, ou só aceitam PNI, e de vez em quando derrubam uma sessão que você já tinha. Tente outra cidade ou um PNI, e peça de novo mais tarde.", "help.out_of_port_speed_bundle_up":"Sem velocidade de porta? Junte até 8 portas idênticas para o mesmo provedor de transit, IX ou PNI num LAG. Cada membro custa uma porta inteira; o hashing de fluxos nunca é perfeitamente uniforme, então o bundle carrega cerca de 95% da soma.", "help.pni_lead_times":"Prazos de PNI", @@ -1877,7 +1878,6 @@ "help.reach_an_ix_over_a_fabric":"Chegue a um IX por um circuito de fabric sem ter POP lá. Funciona, e o route server ainda te dá todas as redes abertas, mas não é recomendado: o revendedor cobra 1,5× pela porta e faz oversubscription a 80%, a latência depende do fabric, uma queda do fabric derruba todas as sessões, e muitas redes seletivas recusam membros remotos na hora.", "help.routers_optics_and_new_builds_get":"Roteadores, ópticas e novas obras ficam mais caros com os anos, cerca de 4% ao ano depois dos primeiros seis meses, e de vez em quando uma falta deixa um deles bem mais caro por um ou dois meses. O que você já tem mantém o preço. Sobressalentes na prateleira e um congelamento anual de preços na aba NOC amortecem o golpe.", "help.rules_for_your_auto_te_controller":"Regras para o seu controlador Auto-TE: quais saídas preferir, quais evitar e quando passar para a próxima. A ajuda do editor explica cada regra e tem scripts prontos.", -"help.sandbox_gives_you_a_billion_dollars":"O Sandbox te dá um bilhão de dólares, tudo desbloqueado e nenhuma falha, mas nada de medalhas. Cenários são desafios feitos à mão com uma meta e um prazo, e o desafio semanal dá a todo mundo o mesmo mundo por uma semana. Compartilhe seu resultado com o cartão no menu.", "help.share_my_network":"Compartilhar minha rede", "help.some_customers_come_with_conditions":"Alguns clientes vêm com condições: nada de Cogentle em lugar nenhum, nada de cabo submarino por causa dos tubarões, dois routers, um gerador, NetChill on-net, acesso à China com pouca perda e mais. Cada uma paga um bônus. As não atendidas deixam o cliente rabugento até você resolver ou ele ir embora.", "help.some_routers_take_forever_to_boot":"Alguns routers levam uma eternidade para dar boot. A aba Infra mostra quanto o seu demora. Os lentos fazem os crashes durarem mais e transformam a troca de um router único numa queda de três dias. Chassis maiores, principalmente qualquer coisa com um PacketOinker™ dentro, são lentos com mais frequência. Routers gêmeos fazem disso problema de outra pessoa.", @@ -2840,6 +2840,29 @@ "routing_and_routers.the_model_won_t_fit_why":"O {model} não cabe.
{why}", "routing_and_routers.the_new_routers_in_city_are":"Os novos routers em {city} ainda estão sendo montados no rack.
Uma troca por dia: tente de novo amanhã.", "routing_and_routers.unplug_something_first_used_ports":"Desconecte algo primeiro.
Há {used} portas em uso, e com um router a menos só teria {max}.", +"rules.a_billion_dollars_every_unlock_your":"Um bilhão de dólares, tudo desbloqueado, o seu próprio cabo submarino.", +"rules.a_cut_now_and_then":"Um corte de vez em quando.", +"rules.bgp_at_3_a_m":"BGP às 3 da manhã", +"rules.change_freeze":"Congelamento de mudanças", +"rules.chaos_calm":"Calmo", +"rules.chaos_none":"Nenhum", +"rules.chaos_normal":"Normal", +"rules.chaos_spicy":"Apimentado", +"rules.everything_is_on_fire_and_it":"Está tudo pegando fogo, e o plantão é seu.", +"rules.fewer_outages_pnis_and_builds_in":"Um terço das falhas, sem DDoS. PNIs e obras em dias. Sem caixa de entrada, sem escassez, sem rotas esgotadas.", +"rules.infinite_money_everything_unlocked_quick":"Dinheiro sem fim, tudo desbloqueado, prazos curtos. Sem medalhas.", +"rules.like_the_real_game":"Como o jogo de verdade.", +"rules.more_and_longer_outages_more_ddos":"Quase o dobro de falhas, metade mais longas, o dobro de DDoS. Tudo ligado.", +"rules.no_clock_no_bills_nothing_breaks":"Sem relógio, sem contas, nada quebra.", +"rules.nobody_touches_prod_even_the_backhoes":"Ninguém mexe em produção. Até as retroescavadeiras estão de férias.", +"rules.nothing_ever_breaks":"Nada quebra nunca.", +"rules.on_call":"De plantão", +"rules.one_small_network_one_tricky_goal":"Uma rede pequena, um objetivo traiçoeiro.", +"rules.puzzle":"Quebra-cabeça", +"rules.real_lead_times_real_outages_a":"Prazos reais, falhas reais, uma caixa de peering cheia. O jogo clássico.", +"rules.rules_are_locked_for_this_network":"{rules}: as regras estão travadas para esta rede.", +"rules.the_real_thing_your_pager_has":"O jogo de verdade. O seu pager tem opiniões.", +"rules.your_pager_never_sleeps":"O seu pager nunca dorme.", "save.cash_in_the_bank":"{cash} no banco", "save.import_failed_err":"Falha na importação.
{err}", "save.load_name":"Carregar {name}?", @@ -2897,6 +2920,7 @@ "scenarios.reach_45_of_the_internet_and":"Alcance 45% 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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Modo sandbox
Um bilhão de dólares, tudo desbloqueado e nada nunca quebra. Construa a internet que você sempre quis.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. O Brasil é um continente: quarenta exchanges IX.brrr, milhares de provedores e a Amazônia entre você e o norte.", "scenarios.seoul_the_fastest_hungriest_eyeballs":"Seoul. Os eyeballs mais rápidos e famintos da Terra, transit a quatro vezes o preço, e três incumbentes que te cobram por cada gigabit que você manda.", @@ -3015,24 +3039,34 @@ "supply_chain.until_date_at_p":"até {date}, a +{p}", "supply_chain.what_p_n_days_left":"{what} +{p} · faltam {n} dias", "supply_chain.your_price_lock_covers_you_until":"Seu congelamento de preços te cobre até {date}.", +"title.a_billion_dollars_and_every_toy":"Um bilhão de dólares e todos os brinquedos da loja.", "title.anywhere_else":"Outro lugar", "title.asia_hub_great_peering_far_from":"Hub da Ásia. Ótimo peering, longe de casa.", "title.back_to_my_network":"Voltar para minha rede", "title.big_hungry_market_few_providers":"Mercado grande e faminto, poucos provedores.", "title.build_an_internet_lay_fiber_between":"Construa uma internet. Lance fibra entre cidades, compre transit, faça peering nos exchanges, feche contratos com empresas e mantenha os eyeballs felizes enquanto retroescavadeiras, tubarões e route leaks fazem de tudo para te parar.", +"title.chaos_in_your_sandbox":"Caos na sua sandbox", "title.chat_on_signal":"Chat no Signal", "title.choose":"Escolha…", "title.continue_name_date":"Continuar {name} · {date}", "title.cookieless_stats_no_tracking":"Estatísticas sem cookies, sem rastreamento", "title.crossroads_of_europe_de_kicks_ix":"Encruzilhada da Europa. IX DE-KICKS, transit barato.", +"title.hand_built_crises_and_one_world":"Crises feitas à mão, e toda semana o mesmo mundo para todos.", "title.hard_mode_pricey_everything":"Modo difícil. Tudo caro, e a fauna quer te ver morto.", +"title.how_much_trouble":"Quanta encrenca?", "title.huge_eyeball_market_pricey":"Mercado enorme de eyeballs. Vizinhos caros.", "title.n_more_cities_with_transit":{"one":"Mais {n} cidade com transit à venda","other":"Mais {n} cidades com transit à venda"}, "title.name_your_network":"Dê um nome à sua rede", "title.new_in_series_of_tubes_v":"Novidades no Series of Tubes {v}", +"title.one_network_one_knot_no_clock":"Uma rede, um nó para desatar. Sem relógio.", +"title.pick_a_door":"Escolha uma porta", "title.pick_your_home_city":"Escolha sua cidade natal", -"title.scenarios_amp_weekly_challenge":"Cenários e desafio semanal →", +"title.puzzles":"Quebra-cabeças", +"title.puzzles_are_coming_soon":"Os quebra-cabeças chegam em breve.
Ainda estamos dando os nós.", +"title.rules_are_picked_once_and_locked":"As regras são escolhidas uma vez e ficam travadas para esta rede. Nada de mudar o combinado no meio do jogo.", +"title.scenarios_amp_weekly":"Cenários e semanal", "title.source_on_github":"Código no GitHub", +"title.the_real_game_climb_from_tier":"O jogo de verdade: suba de Tier 3 a Tier 1.", "title.your_network_name_was_saved_and":"Sua rede {name} foi salva e está te esperando.", "traceroute.across_the_ix_switch":"pelo switch do {ix}", "traceroute.as_path_path":"AS path: {path}", diff --git a/src/game/10-catalog/30-supply-chain.js b/src/game/10-catalog/30-supply-chain.js index d59b599..07f79e7 100644 --- a/src/game/10-catalog/30-supply-chain.js +++ b/src/game/10-catalog/30-supply-chain.js @@ -9,12 +9,12 @@ const HW_SHOCK={opt:{mul:1.5,n:N_('common.optics'),msg:N_('supply_chain.laser_sh build:{mul:1.3,n:N_('supply_chain.new_fiber_and_cable_builds'),msg:N_('supply_chain.every_cable_ship_is_booked')}}; const hwTrend=d=>Math.min(HW_CAP,1+HW_YR*Math.max(0,(d-HW_FREE)/365)); const hwShock=()=>{const s=S&&S.hw&&S.hw.shock;return s&&s.until>S.day?s:null;},hwLock=()=>{const l=S&&S.hw&&S.hw.lock;return l&&l.until>S.day?l:null;}; -function hwMul(k){if(!S)return 1;const l=hwLock();if(l)return l.mul;const s=hwShock();return hwTrend(S.day)*(s&&s.k===k?s.mul:1);} +function hwMul(k){if(!S||!rule('market'))return 1;const l=hwLock();if(l)return l.mul;const s=hwShock();return hwTrend(S.day)*(s&&s.k===k?s.mul:1);} // A lock costs a little more for a bigger network, and twice as much in the middle of a shortage. const hwLockCost=()=>Math.round((80000+30000*Object.keys(S.pops).length)*(hwShock()?2:1)/1000)*1000; function hwShockStart(){const k=pick(Object.keys(HW_SHOCK)),n=45+Math.floor(Math.random()*31);S.hw=S.hw||{};S.hw.shock={k,until:S.day+n,mul:HW_SHOCK[k].mul}; toast(tr(HW_SHOCK[k].msg,{n})+(hwLock()?'
'+tr('supply_chain.your_price_lock_covers_you_until',{date:dateStr(hwLock().until)}):''),hwLock()?'':'bad');sfx('alert');} -function hwCard(){if(!S||(S.day<=HW_FREE&&!hwShock()&&!hwLock()))return '';const t=hwTrend(S.day),s=hwShock(),l=hwLock(); +function hwCard(){if(!S||!rule('market')||(S.day<=HW_FREE&&!hwShock()&&!hwLock()))return '';const t=hwTrend(S.day),s=hwShock(),l=hwLock(); return `
📦 ${tr('common.supply_chain')}
${tr('common.hardware_prices')}${t>1.005?tr('supply_chain.p_since_you_started',{p:pct(t-1)}):tr('supply_chain.as_when_you_started')}
${s?`
${tr('common.shortage')}${tr('supply_chain.what_p_n_days_left',{what:tr(HW_SHOCK[s.k].n),p:pct(s.mul-1),n:s.until-S.day})}
`:''} diff --git a/src/game/10-catalog/50-dark-fiber.js b/src/game/10-catalog/50-dark-fiber.js index 3e08603..e5daead 100644 --- a/src/game/10-catalog/50-dark-fiber.js +++ b/src/game/10-catalog/50-dark-fiber.js @@ -18,7 +18,7 @@ const OPT={ }; const dfLeaseMo=km=>Math.round(400+km*1.0); const dfBuildCost=km=>Math.round((25000+km*120)*hwMul('build')); -const dfBuildDays=km=>Math.round(120+km*0.25); +const dfBuildDays=km=>leadDays(Math.round(120+km*0.25)),IRU_DAYS=30; const ampCount=km=>Math.max(0,Math.floor(km/AMP_EVERY)); const fmtCap=g=>g>=1000?(+(g/1000).toFixed(1))+'T':g+'G'; const WAVECO=['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','Bolt Technology','youNetworks','G&T (Gin and Transit)']; diff --git a/src/game/40-progress/10-businesses.js b/src/game/40-progress/10-businesses.js index ca8b368..e67681f 100644 --- a/src/game/40-progress/10-businesses.js +++ b/src/game/40-progress/10-businesses.js @@ -50,7 +50,8 @@ const LEVELS=[ // What each level asks for (peak Gbps, POPs, continents). Continents carry over to the levels above. const LV_REQ=[null,{pk:200,pops:3},{pk:1000,pops:6},{pk:3000,pops:10,reg:3},{pk:6000,pops:15,reg:4},{pk:9000,pops:20},{pk:12000,pops:25,reg:5},{pk:16000,pops:32},{pk:21000,pops:40,reg:6},{pk:26000,pops:50},{pk:33000,pops:60},{pk:40000,pops:70},{pk:50000,pops:80}]; const lvReg=i=>Math.max(0,...LV_REQ.slice(1,i+1).map(q=>q.reg||0)); -const lvl=()=>(S&&S.lvl)||1; +// Open gates (sandbox, puzzles): every level's unlocks are there from the start. +const lvl=()=>S&&S.rules&&S.rules.gates==='open'?LEVELS.length:(S&&S.lvl)||1; // Lower-case just the first word for mid-sentence use, so names like Tel-Mess or AGI keep their capitals. const lc1=t=>/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t; function custLevel(){const pops=Object.keys(S.pops).length,pk=S.stats.peak,rc=regionsCount();let lv=1;for(let i=1;i=q.pk&&pops>=q.pops&&rc>=lvReg(i))lv=i+1;else break;}return lv;} diff --git a/src/game/40-progress/30-rules.js b/src/game/40-progress/30-rules.js new file mode 100644 index 0000000..928a462 --- /dev/null +++ b/src/game/40-progress/30-rules.js @@ -0,0 +1,42 @@ +/* ---------- The ruleset: one game, many doors ---------- + Every network carries its own rules (S.rules), picked when it starts and locked from then on. Modes are presets of + these rules, not separate code: Normal comes as Change Freeze, On-call (the classic game) and BGP at 3 a.m.; + Sandbox and Puzzles are presets too. Saves without rules load as On-call, so nothing changes for them. + Scenarios and the weekly challenge run on On-call plus their own S.scn.rules (scnRule()). */ +const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder',mods:[]}; +const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],inbox:[true,false],money:['normal','infinite'],gates:['ladder','open']}; +// i: icon, n: name, d: the one-line joke, x: what is different, in small print. +const PRESETS={ + freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.fewer_outages_pnis_and_builds_in'),clock:true,chaos:'calm',lead:'quick',market:false,inbox:false,money:'normal',gates:'ladder'}, + oncall:{i:'📟',n:tr('rules.on_call'),d:tr('rules.the_real_thing_your_pager_has'),x:tr('rules.real_lead_times_real_outages_a'),clock:true,chaos:'normal',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder'}, + bgp:{i:'🔥',n:tr('rules.bgp_at_3_a_m'),d:tr('rules.everything_is_on_fire_and_it'),x:tr('rules.more_and_longer_outages_more_ddos'),clock:true,chaos:'spicy',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder'}, + sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,inbox:true,money:'infinite',gates:'open'}, + puzzle:{i:'🧩',n:tr('rules.puzzle'),d:tr('rules.one_small_network_one_tricky_goal'),x:tr('rules.no_clock_no_bills_nothing_breaks'),clock:false,chaos:'none',lead:'quick',market:false,inbox:false,money:'normal',gates:'open'}, +}; +const NORMAL_PRESETS=['freeze','oncall','bgp']; +// How often things break, against the classic game. Spicy outages also last half as long again. +const CHAOS={none:{i:'😴',n:tr('rules.chaos_none'),d:tr('rules.nothing_ever_breaks'),m:0},calm:{i:'🧊',n:tr('rules.chaos_calm'),d:tr('rules.a_cut_now_and_then'),m:0.35},normal:{i:'📟',n:tr('rules.chaos_normal'),d:tr('rules.like_the_real_game'),m:1},spicy:{i:'🔥',n:tr('rules.chaos_spicy'),d:tr('rules.your_pager_never_sleeps'),m:1.8}}; +const SPICY_LONG=1.5,LEAD_QUICK=10; +function rule(k){const r=S&&S.rules;return r&&r[k]!==undefined?r[k]:RULE_DEF[k];} +function rulePreset(){const p=S&&S.rules&&S.rules.preset;return p&&Object.prototype.hasOwnProperty.call(PRESETS,p)?p:'oncall';} +function gatesOpen(){return rule('gates')==='open';} +function chaosMul(){const c=CHAOS[rule('chaos')];return c?c.m:1;} +// Days until something ordered arrives: as quoted, or a tenth of it (at least a day) with quick lead times. +function leadDays(n){return rule('lead')==='quick'?Math.max(1,Math.round(n/LEAD_QUICK)):n;} +// A fresh, valid rules object: the preset's values, with any valid overrides on top. +function makeRules(preset,o){const p=Object.prototype.hasOwnProperty.call(PRESETS,preset)?preset:'oncall',P=PRESETS[p],r={preset:p};o=o&&typeof o==='object'?o:{}; + for(const k of Object.keys(RULE_OK)){const d=P[k]!==undefined?P[k]:RULE_DEF[k];r[k]=RULE_OK[k].includes(o[k])?o[k]:d;} + r.mods=Array.isArray(o.mods)?[...new Set(o.mods.filter(m=>typeof m==='string'&&/^[a-z0-9_-]{1,24}$/.test(m)))].slice(0,16):[]; + return r;} +// What the HUD and the share card say about the rules. On-call says nothing: it is the game. +function ruleTag(){const p=rulePreset();if(S&&S.mode==='sandbox'){const c=CHAOS[rule('chaos')];return tr('common.sandbox')+(c&&rule('chaos')!=='none'?' '+c.i:'');} + return p==='oncall'||p==='sandbox'?'':PRESETS[p].i+' '+PRESETS[p].n;} +/* Spicy outages last longer: stretch a fresh incident, and whatever it holds down until the same day, by half. */ +function stretchInc(i){if(rule('chaos')!=='spicy'||!i||!(i.until>S.day)||i.start!==S.day)return;const U=i.until,V=S.day+Math.ceil((U-S.day)*SPICY_LONG);if(V===U)return;i.until=V; + const f=(o,k)=>{if(o&&o[k]===U)o[k]=V;},E=S.ev; + for(const l of S.links){f(l,'cut');f(l,'eqDown');f(l,'deg');f(l.loss,'until');f(l.chFail,'until');} + for(const c in S.pops){const p=S.pops[c];f(p,'down');f(p,'ringcut');f(p,'hot');} + for(const t of S.transit){f(t,'down');f(t.lacp,'until');}for(const p of S.pni)f(p.lacp,'until'); + for(const k of ['ixdown','fab'])if(E[k])for(const x in E[k])if(E[k][x]===U)E[k][x]=V; + if(E.ixlacp)for(const x in E.ixlacp)f(E.ixlacp[x],'until'); + for(const k of ['leak','rpki','pmtud','ddos'])f(E[k],'until');} diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 935eb4b..abd4507 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -31,12 +31,14 @@ function weekly(){const {y,w}=isoWeek(new Date());let r=(y*100+w)*2654435761>>>0 const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}newGame(nm,city);S.mode=o.mode||'normal'; - if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;S.nextFail=1e9;S.nextEvent=1e9;} + // The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules. + {const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);} + if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}} if(o.scn){const sc=o.scn;S.scn={id:sc.id,rules:sc.rules||{},days:sc.days,name:sc.n||tr('features.weekly_challenge_key',{key:sc.key}),key:sc.key||null,mods:(sc.mods||[]).map(m=>m.id)};S.rng=(o.seed||hstr(sc.id))|0;S.mode='scenario';S.asn=200000+Math.floor(Math.random()*15000); if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup(); for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}} // Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen. - UI.speed=UI.lastSpeed=0.5;UI.resumeSpeed=null; + UI.speed=UI.lastSpeed=rule('clock')?0.5:0;UI.resumeSpeed=null; track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city); - toast(S.scn?`${esc(S.scn.name)}
${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?tr('scenarios.sandbox_mode_a_billion_dollars_every'):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal'); - renderAll();save();if(!S.scn&&S.mode!=='sandbox')tutorialStart();} + toast(S.scn?`${esc(S.scn.name)}
${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal'); + renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle')tutorialStart();} diff --git a/src/game/60-features/60-share-card.js b/src/game/60-features/60-share-card.js index 2178751..bb94a3e 100644 --- a/src/game/60-features/60-share-card.js +++ b/src/game/60-features/60-share-card.js @@ -13,7 +13,7 @@ function shareCanvas(){const Wc=1200,Hc=630,cv=document.createElement('canvas'); g.restore();g.strokeStyle='#1E2640';g.lineWidth=5;g.strokeRect(mx,my,mw,mh); // header g.fillStyle='#1E2640';g.font='900 54px "Baloo 2", sans-serif';g.textBaseline='top';g.fillText(S.name,40,28); - g.font='800 26px Nunito, sans-serif';g.fillText(`AS${S.asn} · ${tierLabel()} · ${dateStr(S.day)}${S.mode==='sandbox'?' · '+tr('common.sandbox'):''}`,42,92); + g.font='800 26px Nunito, sans-serif';g.fillText(`AS${S.asn} · ${tierLabel()} · ${dateStr(S.day)}${ruleTag()?' · '+ruleTag():''}`,42,92); // stats const got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined),rk={l:0,e:1,r:2,c:3},top=got.slice().sort((a,b)=>rk[a.r]-rk[b.r]).slice(0,8); const rows=[[tr('common.peak_traffic'),fmtG(S.stats.peak||0)],[tr('common.peered'),pct(R.peerShare||0)],[tr('common.pops'),tr('share_card.n_in_r_regions',{n:Object.keys(S.pops).length,r:regionsCount()})],[tr('common.links'),String(S.links.length)],[tr('common.customers'),String(S.biz.length)],[tr('common.incidents_survived'),String(S.stats.survived||0)],[tr('common.shark_bites'),String(S.stats.sharks||0)],[tr('common.badges'),`${got.length}/${BADGES.length}`]]; diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 6a368e3..98e1433 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:{},pairMet:{}, - 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:{}}; + 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:{},rules:makeRules('oncall')}; } diff --git a/src/game/70-rules/30-pnis.js b/src/game/70-rules/30-pnis.js index a0963be..b3ed71f 100644 --- a/src/game/70-rules/30-pnis.js +++ b/src/game/70-rules/30-pnis.js @@ -5,7 +5,7 @@ const pniBig=id=>{const n=NET[id];return n.type==='t1'||(n.type==='cdn'&&n.pol!= const pniMin=id=>{const n=NET[id];return n.type==='t1'||(n.type==='cdn'&&n.pol!=='open')?1:0;}; const pniG1=id=>id==='dtk'; // A beer with their peering coordinator at a conference halves the wait. It is how it really works. -const PNI_SLOW=0.15,pniLead=id=>{const n=pniBig(id)?(Math.random()S.day?Math.round(n/2):n;}; +const PNI_SLOW=0.15,pniLead=id=>{const n=pniBig(id)?(Math.random()S.day?Math.round(n/2):n);}; const pniG=p=>p.g1?1:PORT[p.tier].g,pniPN=p=>p.g1?'1G':PORT[p.tier].n,pniOn=p=>!(p.ready>S.day); const pniEta=id=>pniBig(id)?tr('pnis.delivery_about_a_month_sometimes_6'):tr('pnis.delivery_2_to_6_weeks'); const PNI_G1_COST=1200,pniWhen=n=>n>=60?tr('pnis.their_team_quotes_m_months',{m:Math.round(n/30)}):tr('pnis.ready_in_about_n_days',{n}); diff --git a/src/game/70-rules/40-peering-inbox.js b/src/game/70-rules/40-peering-inbox.js index a32f13e..d679f32 100644 --- a/src/game/70-rules/40-peering-inbox.js +++ b/src/game/70-rules/40-peering-inbox.js @@ -18,7 +18,7 @@ const ibxOpen=()=>S.inbox?S.inbox.items.length:0,ibxUrgent=()=>S.inbox?S.inbox.i const mpDown=(id,c)=>{const t=S.inbox&&S.inbox.down[id+'@'+c];return !!t&&t>S.day;}; const ibxWho=x=>x.net?NET[x.net].name:x.nm,ibxAsn=x=>x.net?NET[x.net].asn:x.asn; function ibxLog(m,a){const I=ibx();I.log.unshift({d:S.day,m,a:a||{}});I.log.length=Math.min(I.log.length,40);} -function inboxDay(d){const I=ibx(),ixs=Object.keys(S.ixp); +function inboxDay(d){if(!rule('inbox'))return;const I=ibx(),ixs=Object.keys(S.ixp); // new peering requests: more exchange ports, more mail if(ixs.length&&Math.random(){const n=NET[id];return !set.has(id)&&!merged(id)&&n.type!=='t1'&&n.type!=='cdn'&&n.pol!=='paid'&&n.share<=0.006&&!I.items.some(x=>x.net===id&&x.ix===c);}); diff --git a/src/game/70-rules/70-sold-out.js b/src/game/70-rules/70-sold-out.js index b603864..748ae49 100644 --- a/src/game/70-rules/70-sold-out.js +++ b/src/game/70-rules/70-sold-out.js @@ -3,7 +3,7 @@ const SOLD_WIN=90,SOLD_WHY=[N_('sold_out.a_hyperscaler_bought_every_wave_of'),N_('sold_out.the_carrier_is_out_of_spectrum'),N_('sold_out.the_transponders_for_this_route_are'),N_('sold_out.the_capacity_is_available_in_the'),N_('sold_out.their_capacity_planner_is_on_holiday'),N_('sold_out.the_upgrade_is_planned_for_q3')]; const soldP=tier=>Math.min(0.1,0.02+0.012*tier); // Never in the first 90 days: a new network has enough on its plate. Never in the tutorial or a scenario's first quarter either. -function soldOut(a,b,tier,via){if(!S||S.day=soldP(tier)*1000)return null;return {why:SOLD_WHY[(h>>>10)%SOLD_WHY.length],until:(ep+1)*SOLD_WIN-off};} function snubWhy(sn){const d=Math.max(1,sn.until-S.day);return sn.why+' '+trn('sold_out.they_will_reconsider_in_n_day',d);} // Paid-peering giants drop the fee for networks too big to ignore (freeLv: the customer level that does it). diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 8961762..2bc0bb4 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -64,6 +64,8 @@ function sanitize(s){ 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);}}} s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews; 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, 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':own(PRESETS,r.preset)?r.preset:'oncall';s.rules=makeRules(p,own(PRESETS,r.preset)?r:{});} 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;} function migrate(s){sanitize(s); diff --git a/src/game/80-simulation/70-customers-and-events.js b/src/game/80-simulation/70-customers-and-events.js index 06988e1..7b15279 100644 --- a/src/game/80-simulation/70-customers-and-events.js +++ b/src/game/80-simulation/70-customers-and-events.js @@ -30,7 +30,7 @@ function spawnMega(t,T,nm,mine){ if(t==='pairs'){const ls=S.links.filter(l=>l.kind==='df'&&l.own&&l.ready<=S.day&&!S.biz.some(b=>(b.type==='pairs'||b.type==='dfpair')&&b.link===l.id)&&!S.offers.some(o=>o.link===l.id));if(!ls.length)return;const l=pick(ls),n=100+50*Math.floor(Math.random()*7); S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('customers_and_events.n_fiber_pairs_in_your_a',{n,a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*n*0.2),reqs:[],exp:S.day+30,mega:true});} } -function spawnSpecial(t){const T=BIZ_T[t],mine=Object.keys(S.pops),lv=S.lvl||1; +function spawnSpecial(t){const T=BIZ_T[t],mine=Object.keys(S.pops),lv=lvl(); const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n));const n=list.length?pick(list):pick(T.names);useName(n);return n;}; if(T.mega){spawnMega(t,T,nm,mine);return;} if(T.event){const city=Math.random()<0.85&&mine.length?pick(mine):pick(OFFC);const bw=pick(T.opts.slice(0,Math.min(T.opts.length,lv+2)));const dur=3+Math.floor(Math.random()*5),start=S.day+12+Math.floor(Math.random()*14); diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js index 285ce6a..d9f5b92 100644 --- a/src/game/85-incidents/10-incidents-and-ddos.js +++ b/src/game/85-incidents/10-incidents-and-ddos.js @@ -1,6 +1,6 @@ /* ---------- failures & events ---------- */ // A few badges read the incident text: callers whose message mentions a shark, anchor, crocodile or llama pass its English as en. -function addInc(o,en=o.msg||''){if(S.loans&&S.loans.some(l=>(l.covs||[]).includes('pizza'))){S.cash-=COVS.pizza.each;S.stats.pizza=(S.stats.pizza||0)+1;}o.id=uid();o.start=S.day;S.inc.push(o);S.stats.incidents++;S.stats.by=S.stats.by||{};S.stats.by[o.type]=(S.stats.by[o.type]||0)+1;if(/shark/i.test(en))S.stats.sharks=(S.stats.sharks||0)+1;const f=S.stats.f=S.stats.f||{};if(/anchor/i.test(en))f.anchor=1;if(/crocodile/i.test(en))f.croc=1;if(/beaver/i.test(en))f.beaver=1;if(/llama/i.test(en))f.llama=1;} +function addInc(o,en=o.msg||''){if(S.loans&&S.loans.some(l=>(l.covs||[]).includes('pizza'))){S.cash-=COVS.pizza.each;S.stats.pizza=(S.stats.pizza||0)+1;}o.id=uid();o.start=S.day;S.inc.push(o);S.stats.incidents++;S.stats.by=S.stats.by||{};S.stats.by[o.type]=(S.stats.by[o.type]||0)+1;if(/shark/i.test(en))S.stats.sharks=(S.stats.sharks||0)+1;const f=S.stats.f=S.stats.f||{};if(/anchor/i.test(en))f.anchor=1;if(/crocodile/i.test(en))f.croc=1;if(/beaver/i.test(en))f.beaver=1;if(/llama/i.test(en))f.llama=1;if(S.rules&&S.rules.chaos==='spicy')stretchInc(o);} const HARMLESS=[ [tr('common.certificate_expired'),tr('incidents_and_ddos.the_tls_certificate_on_your_noc')], [tr('incidents_and_ddos.it_was_dns'),tr('incidents_and_ddos.someone_deleted_the_dns_record_for')], diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index e7546eb..6dbe6f0 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -7,7 +7,8 @@ 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 + // Flood Season brings its own; Change Freeze has none, BGP at 3 a.m. twice as many. + if(S.day>40&&!scnRule('ddos')&&rule('chaos')!=='calm')opts.push(['ddos',rule('chaos')==='spicy'?4:2]); 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]); diff --git a/src/game/85-incidents/30-events.js b/src/game/85-incidents/30-events.js index 60fbeba..e5a70dc 100644 --- a/src/game/85-incidents/30-events.js +++ b/src/game/85-incidents/30-events.js @@ -1,7 +1,9 @@ function fireEvent(){ const opts=['viral','price','grant']; if(S.day>50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic'); - if(S.day>HW_FREE&&!hwShock())opts.push('hwshock'); + // Without a market (Change Freeze), no shortages and no trade war on optics. + if(!rule('market')&&opts.includes('tariff'))opts.splice(opts.indexOf('tariff'),1); + if(S.day>HW_FREE&&!hwShock()&&rule('market'))opts.push('hwshock'); if(S.day>90&&S.links.filter(l=>l.kind==='wave'&&!l.sub).length>=3)opts.push('ctrlplane'); if(Object.keys(S.pops).some(ruCity))opts.push('runet','runet'); if(S.pops.doh&&Object.keys(S.pops).some(c=>CITY[c].gcc||CITY[c].uae)&&!(S.ev.gulf>S.day))opts.push('gulf'); diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 655a387..47bbb2a 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -1,6 +1,6 @@ /* ---------- daily tick ---------- */ function dayTick(){ - if(!S||S.lost)return; + if(!S||S.lost||!rule('clock'))return; // no clock (puzzles): no days, no bills, nothing fires S.day++; const d=S.day; dkTick(d);ixPriceWar(d);inboxDay(d);pniDay(d);mergerDay(d); @@ -31,7 +31,7 @@ function dayTick(){ {const top=custLevel();if(top>(S.lvl||1)){for(let lv=(S.lvl||1)+1;lv<=top;lv++){track('level_'+lv);toast(tr('day_tick.customer_level_lv_name_new_customers',{lv,name:LEVELS[lv-1].n,unlock:LEVELS[lv-1].unlock})+`
${esc(LEVELS[lv-1].q)}`,'goal');}S.lvl=top;sfx('coin');}} for(const l of S.links){if(l.kind!=='df')continue; if(l.ready===d){toast(`${l.own?tr('day_tick.your_fiber_is_finished_a_b',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('day_tick.dark_fiber_handed_over_a_b',{a:CITY[l.a].name,b:CITY[l.b].name})}
${(l.ch||[]).length?tr('day_tick.channels_are_lighting_up_now'):tr('day_tick.it_is_dark_add_optics_to')}`,'goal',[{l:tr('common.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('day_tick.construction_delay_n_days_why_a',{n:extra,why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('day_tick.archaeologists_found_a_roman'),tr('day_tick.a_protected_hamster_species_lives'),tr('day_tick.the_railway_changed_its_mind_about'),tr('day_tick.the_drilling_crew_hit_a_granite'),tr('day_tick.a_town_council_wants_a_public'),tr('day_tick.somebody_else_s_gas_main_was'),tr('day_tick.the_permit_office_lost_your_permit')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}} + if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+leadDays(extra));toast(tr('day_tick.construction_delay_n_days_why_a',{n:leadDays(extra),why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('day_tick.archaeologists_found_a_roman'),tr('day_tick.a_protected_hamster_species_lives'),tr('day_tick.the_railway_changed_its_mind_about'),tr('day_tick.the_drilling_crew_hit_a_granite'),tr('day_tick.a_town_council_wants_a_public'),tr('day_tick.somebody_else_s_gas_main_was'),tr('day_tick.the_permit_office_lost_your_permit')]),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){ @@ -53,14 +53,15 @@ function dayTick(){ if(cands.length){cands.sort((a,b)=>(a.pol==='open'?0:1)-(b.pol==='open'?0:1)||b.share-a.share);const n=Math.random()<.6?cands[0]:pick(cands);m.members.push(n.id);toast(tr('day_tick.net_joined_ix_another_member_paying',{net:esc(n.name),ix:esc(m.name),fee:fmt$(MYIX_FEE)}),'good');sfx('coin');} m.next=d+8+Math.floor(Math.random()*10);}} loanTick(d); - if(S.mode==='sandbox'&&S.cash<1e8)S.cash=1e9; + if(rule('money')==='infinite'&&S.cash<1e8)S.cash=1e9; // offers S.offers=S.offers.filter(o=>o.exp>d); if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1))spawnOffer(); // failures & events - let dirty=false; - if(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));} - if(d>=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+45+Math.floor(Math.random()*45);} + // Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never. + let dirty=false;const cm=chaosMul(); + if(cm&&d>=S.nextFail){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} + if(cm&&d>=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} if(dirty)compute(); // 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');} @@ -75,7 +76,7 @@ function dayTick(){ if(d%10===0)save(); } function spawnOffer(){ - const mine=spMine(Object.keys(S.pops)),lv=S.lvl||1; + const mine=spMine(Object.keys(S.pops)),lv=lvl(); const types=['dia','dia','game','host'];if(mine.length>=2)types.push('l2vpn','l2vpn');if(S.day>60)types.push('scrub'); if(lv>=2)types.push('isp','stream','edu','host','hft','bulk','event','event');if(mine.length>=3&&lv>=2)types.push('sdwan','sdwan'); if(S.links.some(l=>l.kind==='df'&&l.ready<=S.day))types.push('wwave','wwave');if(S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('dfpair');if(lv>=3)types.push('gpu','gpu','onramp','onramp');if(lv>=4)types.push('ai','ai','hyper','hyper'); diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index daedd0f..b565c89 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -1,7 +1,7 @@ /* ================= ACTIONS ================= */ function spend(c){if(S.cash{v=+v;if(![0,0.5,1,2,4,8].includes(v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();}, + speed:({v})=>{v=+v;if(![0,0.5,1,2,4,8].includes(v)||(S&&!rule('clock')&&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();}, dashClose:()=>{$('dash').hidden=true;}, @@ -33,8 +33,8 @@ const ACT={ meetGo:({city})=>{if(!isCity(city))return;$('dash').hidden=true;ACT.focusCity({city});if(S.pops[city]){UI.tab='peer';renderPanel();}}, 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();}, - 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();}, + phonePlay:()=>{if(S&&!rule('clock'))return;haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();}, + phoneSpeed:()=>{if(S&&!rule('clock'))return;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;} openModal(pitchHtml(false));}, pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();}, diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js index af3a450..d51e5ce 100644 --- a/src/game/90-actions/87-fiber-and-hardware.js +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -1,7 +1,7 @@ Object.assign(ACT,{ dfMode:({m})=>{UI.lmode=m;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, seaPackage:({k})=>{if(!own(SUB_UPGRADES,k))return;UI['sea'+k]=!UI['sea'+k];if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, - subUpgrade:({id,k})=>{const l=S.links.find(l=>l.id===id);if(!l||l.kind!=='df'||!l.own||!l.sub||!own(SUB_UPGRADES,k)||lvl()<4||l['sub'+k]!==undefined)return;if(!spend(subUpgradeCost(l,k)))return;l.paid=(l.paid>0?l.paid:ownCabCost(l.km))+subUpgradeCost(l,k);l['sub'+k]=Math.max(S.day,l.ready||0)+SUB_UPGRADES[k].days;after();}, + subUpgrade:({id,k})=>{const l=S.links.find(l=>l.id===id);if(!l||l.kind!=='df'||!l.own||!l.sub||!own(SUB_UPGRADES,k)||lvl()<4||l['sub'+k]!==undefined)return;if(!spend(subUpgradeCost(l,k)))return;l.paid=(l.paid>0?l.paid:ownCabCost(l.km))+subUpgradeCost(l,k);l['sub'+k]=Math.max(S.day,l.ready||0)+leadDays(SUB_UPGRADES[k].days);after();}, seaDesign:({v})=>{if(!own(SEA_DESIGNS,v))return;UI.seaDesign=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, ownCab:()=>{UI.lmode='df';UI.dfSrc='cable';UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, dfSrc:({v})=>{UI.dfSrc=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, @@ -18,7 +18,7 @@ Object.assign(ACT,{ const up=(own?dfBuildCost(km):0)+DF_SYS[sys].cost+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return; if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}; const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),id=uid(); - const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):30),spares:false}; + const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false}; S.links.push(l);closeModal();UI.sel={type:'link',id}; toast(own?tr('fiber_and_hardware.groundbreaking_your_own_fiber_from_a',{a:CITY[a].name,b:CITY[b].name,n:dfBuildDays(km)}):tr('fiber_and_hardware.dark_fiber_iru_signed_a_b',{a:CITY[a].name,b:CITY[b].name}),'goal');after();}, regen:({id,d})=>{d=+d;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||l.sub||(d!==1&&d!==-1))return;const n=(l.regen|0)+d;if(n<0||n>REGEN_MAX)return; diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 3ec2894..622d022 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -1,7 +1,13 @@ Object.assign(ACT,{ randomName:()=>{const input=$('nmIn');if(input)input.value=UI.nm=randomNetworkName(input.value);}, - start:()=>{const nm=(($('nmIn')&&$('nmIn').value)||randomNetworkName()).slice(0,24);beginGame(nm,homeOk(UI.startCity)?UI.startCity:'fra',{mode:UI.mode==='sandbox'?'sandbox':'normal'});}, - modeSet:({m})=>{UI.mode=m;document.querySelectorAll('.modeb').forEach(b=>b.classList.toggle('pink',b.dataset.m===m));document.querySelectorAll('.modeb').forEach(b=>b.classList.toggle('ghost',b.dataset.m!==m));}, + start:()=>{const nm=(($('nmIn')&&$('nmIn').value)||randomNetworkName()).slice(0,24),sb=UI.mode==='sandbox'; + beginGame(nm,homeOk(UI.startCity)?UI.startCity:'fra',sb?{mode:'sandbox',rules:{chaos:own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'}}:{mode:'normal',preset:NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall'});}, + // Title-screen doors and their options toggle in place, so the name being typed and the city stay as they are. + modeSet:({m})=>{if(m!=='sandbox'&&m!=='normal')return;UI.mode=m;document.querySelectorAll('.door').forEach(b=>b.classList.toggle('on',b.dataset.door===m));const n=$('doorNormal'),x=$('doorSandbox');if(n)n.hidden=m!=='normal';if(x)x.hidden=m!=='sandbox';}, + presetSet:({p})=>{if(!NORMAL_PRESETS.includes(p))return;UI.preset=p;ACT.modeSet({m:'normal'});document.querySelectorAll('.preset').forEach(b=>b.classList.toggle('on',b.dataset.preset===p));}, + chaosSet:({c})=>{if(!own(CHAOS,c))return;UI.sbChaos=c;ACT.modeSet({m:'sandbox'});document.querySelectorAll('.chs').forEach(b=>b.classList.toggle('on',b.dataset.chaos===c));}, + // Puzzles live in their own module; until it ships, the door says so. + puzzleDoor:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||randomNetworkName()).slice(0,24);if(typeof ACT.puzzleMenu==='function')ACT.puzzleMenu();else toast(tr('title.puzzles_are_coming_soon'),'goal');}, scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();}, startScn:({id,sure})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`

${tr('game_and_settings.start_name',{name:esc(sc.n)})}

${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}

${btn(tr('game_and_settings.start_the_scenario'),'startScn',{id,sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);return;}beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});}, startWeekly:({sure}={})=>{if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`

${tr('game_and_settings.start_the_weekly_challenge')}

${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}

${btn(tr('game_and_settings.start_the_challenge'),'startWeekly',{sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);return;}const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, diff --git a/src/game/93-ui/20-phone.js b/src/game/93-ui/20-phone.js index 3f601ca..288921a 100644 --- a/src/game/93-ui/20-phone.js +++ b/src/game/93-ui/20-phone.js @@ -4,8 +4,8 @@ const SPEEDS=[0.5,1,2,4,8]; function renderTabbar(){const tb=$('tabbar');if(!tb||(pressing&&UI.ticking))return;if(!isPhone()||!S||!UI.started){tb.hidden=true;document.body.classList.remove('sheet-open');return;}tb.hidden=false; const open=UI.leftOpen&&!UI.sel,cur=UI.left||'goals',ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length; const tab=(k,ic,l,cnt,red)=>``; - const h=``+ - ``+ + const h=(rule('clock')?``+ + ``:'')+ (()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length||(UI.left==='noc'&&UI.leftOpen?'':logUnread())||'',S.inc.length>0)+tab('nets','🌐',tr('common.networks'),ibxOpen()||'',ibxUrgent()>0); if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;} document.body.classList.toggle('sheet-open',!!(UI.sel||UI.leftOpen));} diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 2a98394..af40150 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -2,10 +2,12 @@ function fitHud(){const h=$('hud');if(!h)return;h.classList.remove('fit1','fit2' const row=()=>{let m=0;for(const c of h.children)if(c.offsetParent)m=Math.max(m,c.offsetHeight);return m;}; for(const c of ['fit1','fit2','fit3']){if(h.offsetHeight<=row()*1.5)break;h.classList.add(c);}} function renderHUD(){ - for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b)b.classList.toggle('on',UI.speed===v);} + // No clock (puzzles): there is no time to speed up, so the speed buttons go. + {const ck=!S||rule('clock');for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',UI.speed===v);b.hidden=!ck;}}} $('muteBtn').style.opacity=UI.muted?.4:1; if(!S)return; - $('hName').textContent=S.name;$('hAsn').textContent='AS'+S.asn+(S.mode==='sandbox'?' · '+tr('common.sandbox'):S.scn?' · '+(scnName())+(S.scn.done||S.scn.failed?'':` · ${tr('ui.n_d_left',{n:Math.max(0,S.scn.days-S.day)})}`):''); + {const rt=ruleTag(),ha=$('hAsn');ha.title=rt?tr('rules.rules_are_locked_for_this_network',{rules:rt}):'';} + $('hName').textContent=S.name;$('hAsn').textContent='AS'+S.asn+(S.mode==='sandbox'||ruleTag()&&!S.scn?' · '+ruleTag():S.scn?' · '+(scnName())+(S.scn.done||S.scn.failed?'':` · ${tr('ui.n_d_left',{n:Math.max(0,S.scn.days-S.day)})}`):''); $('hCash').textContent=fmt$(S.cash);$('hCash').style.color=S.cash<0?'var(--bad)':''; const net=R.revMo-R.costMo;$('hRate').innerHTML=`${net>=0?'▲':'▼'} ${tr('common.price_mo',{price:fmt$(Math.abs(net))})}`; $('hTraffic').textContent=`${fmtG(R.served)}`; @@ -68,7 +70,7 @@ function renderLeft(){checkLayer(); if(!S.inc.length&&!hot.length&&!hotR.length&&!slow.length)h+=`

${tr('hud_and_panels.all_systems_green_enjoy_it_while')}

`; h+=`
${tr('hud_and_panels.incidents_so_far')}${S.stats.incidents}
${tr('hud_and_panels.survived_with_no_impact')}${S.stats.survived}
`; }else{ - if(Object.keys(S.ixp).length||ibxOpen()||(S.inbox&&S.inbox.bot)){const n=ibxOpen(),u=ibxUrgent();h+=`
📬 ${tr('common.peering_inbox')} ${n?`${n}`:''}
${S.inbox&&S.inbox.bot?tr('hud_and_panels.large_peering_model_is_on_it'):u?trn('hud_and_panels.n_session_is_down_on_its',u):n?trn('hud_and_panels.n_message_waiting_for_an_answer',n):tr('common.inbox_zero')}
${btn(tr('common.open_inbox'),'inbox',{},'sm')}
`;} + if(rule('inbox')&&(Object.keys(S.ixp).length||ibxOpen()||(S.inbox&&S.inbox.bot))){const n=ibxOpen(),u=ibxUrgent();h+=`
📬 ${tr('common.peering_inbox')} ${n?`${n}`:''}
${S.inbox&&S.inbox.bot?tr('hud_and_panels.large_peering_model_is_on_it'):u?trn('hud_and_panels.n_session_is_down_on_its',u):n?trn('hud_and_panels.n_message_waiting_for_an_answer',n):tr('common.inbox_zero')}
${btn(tr('common.open_inbox'),'inbox',{},'sm')}
`;} h+=`

${tr('hud_and_panels.every_network_on_the_map_traffic')}

`; {const nc=conns().length;if(nc)h+=`
${btn(tr('hud_and_panels.all_connections_n',{n:nc}),'connOpen',{},'pink sm')}
`;} const where=netWhereIdx(),tl=NETS.filter(n=>n.tail),tlOn=tl.filter(n=>where(n.id).some(x=>x[2]==='ix')).length; diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 0378b3f..5502dbb 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -67,7 +67,7 @@ function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.d return h+``;} function subUpgradePanel(l){return `

${tr('common.submarine_transmission')}

${tr('common.better_terminals_and_optical_tuning')}

`+Object.entries(SUB_UPGRADES).map(([k,U])=>{ const at=l['sub'+k],done=subUpgradeReady(l,k),cost=subUpgradeCost(l,k),preview={...l,['sub'+k]:S.day}; - const status=done?tr('common.installed'):at!==undefined?tr('link_panels.ready_in_n_days',{n:Math.max(0,at-S.day)}):tr('link_panels.price_n_days',{price:fmt$(cost),n:U.days}); + const status=done?tr('common.installed'):at!==undefined?tr('link_panels.ready_in_n_days',{n:Math.max(0,at-S.day)}):tr('link_panels.price_n_days',{price:fmt$(cost),n:leadDays(U.days)}); return `
${tr(U.n)}
${status}
${tr('common.up_to_g_per_channel',{g:fmtG(submarineRate(preview))})}
${at===undefined?btn(tr('common.install'),'subUpgrade',{id:l.id,k},'sm',lvl()<4||S.cash`;}).join('');} function dfPanel(l){ const load=R.load[l.id]||0,cap=dfCap(l),u=cap?load/cap:0,bld=l.ready>S.day,A=CITY[l.a].name,B=CITY[l.b].name,inc=S.inc.find(i=>i.ref===l.id||i.ref===(l.trench||l.id)),amps=ampCount(l.km),sysD=DF_SYS[l.sys]; diff --git a/src/game/94-dashboard/50-lease-swaps.js b/src/game/94-dashboard/50-lease-swaps.js index c8ffe46..155489b 100644 --- a/src/game/94-dashboard/50-lease-swaps.js +++ b/src/game/94-dashboard/50-lease-swaps.js @@ -17,7 +17,7 @@ function leaseSwaps(){const by={}; const ws=ls.filter(l=>l.kind!=='df'),wmo=ws.reduce((s,l)=>s+(l.mo||0),0),sc=sub?subDfCable(a,b):null;x.iru=ls.find(l=>l.kind==='df'); if(ws.length&&x.iru){x.fit=litOn(x.iru,leaseCap(ws));if(x.fit.fits)x.lit=wmo;} else if(ws.length&&lvl()>=2&&(sub?sc:dfAllowed(a,b))){const km=sc?sc.km:kmBetween(a,b),sys=lvl()>=3?'roadm':'lite',wc=leaseCap(ws),op=swapOptics(km,wc,sub,sys); - if(op&&op.n<=DF_SYS[sys].max)x.opts.push(swapOpt('iru',DF_SYS[sys].cost+ampCount(km)*AMP_COST+op.up,dfLeaseMo(km)+ampCount(km)*AMP_MO+op.mo,30,wmo));} + if(op&&op.n<=DF_SYS[sys].max)x.opts.push(swapOpt('iru',DF_SYS[sys].cost+ampCount(km)*AMP_COST+op.up,dfLeaseMo(km)+ampCount(km)*AMP_MO+op.mo,leadDays(IRU_DAYS),wmo));} // Dig on land, lay a cable between landing stations (even ones that share a landmass), or both. const whys=[];for(const cab of [false,true]){if(cab?!seaCab(a,b):sub)continue; const why=cab?ownCabWhy(a,b):!dfAllowed(a,b)?tr('lease_swaps.nobody_lets_you_dig_on_this'):lvl()<3?tr('lease_swaps.digging_your_own_fiber_unlocks_at'):''; diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index 86683e7..61ca3e3 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -15,9 +15,9 @@ function showTitle(){

Series
of Tubes

${tr('title.build_an_internet_lay_fiber_between')}

${plugHtml(false)}${isPhone()?installRow():''} ${sv?`
${btn(tr('title.continue_name_date',{name:esc(sv.name),date:dateStr(sv.day)}),'cont',{},'pink big')}
`:''} + ${doorsHtml()}
${btn(tr('common.another_one'),'randomName',{},'ghost sm')}
-
${starts.map(([c,d])=>``).join('')}
-
${[['normal',tr('common.normal')],['sandbox',tr('common.sandbox')]].map(([m,l])=>``).join('')}${btn(tr('title.scenarios_amp_weekly_challenge'),'scenarios',{},'sm')}
+
${starts.map(([c,d])=>``).join('')}
${langPick('langTitle')}
${btn(sv?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); $('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;}); @@ -33,3 +33,12 @@ function whatsNew(returning,force){ ${returning&&S?`

${tr('title.your_network_name_was_saved_and',{name:esc(S.name)})}

`:''}
${btn(UI.started?tr('title.back_to_my_network'):tr('common.got_it'),UI.started?'closeModal':'helpClose',{},'pink big')}${notesLong(RELEASE_NOTES)?'':`${tr('common.full_changelog')}`}
`); return true;} +/* The four doors: one game, its rules picked here and locked for the network's life. Normal and Sandbox stay on this + screen (presets / chaos below), Puzzles and Scenarios open their own lists. Choices toggle in place (no re-render). */ +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('')}
+
${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/60-help.js b/src/game/95-modals/60-help.js index e8e5e51..31c3000 100644 --- a/src/game/95-modals/60-help.js +++ b/src/game/95-modals/60-help.js @@ -16,7 +16,7 @@ function showHelp(){
${tr('common.embedded_cache')}
${tr('help.a_cdn_s_server_in_your')}
DE-KICKS
${tr('help.the_group_behind_several_big')}
${tr('common.remote_peering')}
${tr('help.reach_an_ix_over_a_fabric')}
${tr('common.peering_policy')}
${tr('help.open_peers_with_anyone_selective')}
${tr('common.waves')}
${tr('help.your_fiber_links_are_leased_waves')}
${tr('common.95th_percentile')}
${tr('help.transit_bills_sample_your_usage')}
${tr('common.routers')}
${tr('help.each_pop_s_router_model_caps')}
${tr('common.dark_fiber')}
${tr('help.lease_an_iru_or_build_your')}
${tr('common.subsea_cables')}
${tr('help.subsea_waves_can_only_follow_cable')}
${tr('common.latency')}
${tr('help.every_link_has_latency_high')}
${tr('common.noc_dashboard')}
${tr('help.the_chart_button_at_the_top')}
${tr('common.asia')}
${tr('help.a_weird_underserved_market_transit')}
${tr('common.russia')}
${tr('help.moscow_needs_a_mandatory_government')}
${tr('help.events_chains_and_wholesale')}
${tr('help.event_networks_a_final_a_festival')}
${tr('common.bank')}
${tr('help.tap_your_cash_to_open_the')}
${tr('common.lags')}
${tr('help.out_of_port_speed_bundle_up')}
${tr('common.traffic_engineering')}
${tr('help.tap_a_link_to_see_which')}
${tr('common.china')}
${tr('help.mainland_china_needs_a_license_and')}
${tr('common.weird_requirements')}
${tr('help.some_customers_come_with_conditions')}
${tr('common.customer_levels')}
${tr('help.as_your_peak_traffic_and_footprint')}
${tr('help.l2vpn_ddos_protection')}
${tr('help.businesses_may_want_a_private')}
${tr('common.scrubbing_centers')}
${tr('help.build_one_in_as_many_pops')}
${tr('common.nni_fabrics')}
${tr('help.megapork_pocketfabric_and')}
-
${tr('common.conferences')}
${tr('help.nanog_ripe_denog_and_friends_come')}
${tr('common.modes')}
${tr('help.sandbox_gives_you_a_billion_dollars')}
${tr('common.traceroute')}
${tr('help.tap_traceroute_on_any_of_your')}
${tr('common.badges')}
${tr('help.below_your_goals_sits_a_wall')}
${tr('common.the_giants')}
${tr('help.at_customer_level_3_and_4')}
RouteScript
${tr('help.once_auto_te_is_installed_you')}
Auto-TE
${tr('help.traffic_follows_the_shortest_path_by')}
${tr('common.metro_diversity')}
${tr('help.a_pop_is_one_building_until')}
${tr('common.wave_markets')}
${tr('help.what_a_wave_costs_depends_on')}
${tr('common.regional_quirks')}
${tr('help.in_the_gulf_saudi_pops_need')}
${tr('common.boot_times')}
${tr('help.some_routers_take_forever_to_boot')}
${tr('common.failures')}
${tr('help.things_break_all_the_time_fiber')}
+
${tr('common.conferences')}
${tr('help.nanog_ripe_denog_and_friends_come')}
${tr('common.modes')}
${tr('help.one_game_four_doors_puzzles_are')}
${tr('common.traceroute')}
${tr('help.tap_traceroute_on_any_of_your')}
${tr('common.badges')}
${tr('help.below_your_goals_sits_a_wall')}
${tr('common.the_giants')}
${tr('help.at_customer_level_3_and_4')}
RouteScript
${tr('help.once_auto_te_is_installed_you')}
Auto-TE
${tr('help.traffic_follows_the_shortest_path_by')}
${tr('common.metro_diversity')}
${tr('help.a_pop_is_one_building_until')}
${tr('common.wave_markets')}
${tr('help.what_a_wave_costs_depends_on')}
${tr('common.regional_quirks')}
${tr('help.in_the_gulf_saudi_pops_need')}
${tr('common.boot_times')}
${tr('help.some_routers_take_forever_to_boot')}
${tr('common.failures')}
${tr('help.things_break_all_the_time_fiber')}
RouteScript
${tr('help.rules_for_your_auto_te_controller')}

${tr('help.want_to_know_how_it_really')}

${plugHtml(true)}${chatHtml()}${issueHtml()}
${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}
`); } diff --git a/src/game/95-modals/70-link-modal.js b/src/game/95-modals/70-link-modal.js index d8342f3..876de5a 100644 --- a/src/game/95-modals/70-link-modal.js +++ b/src/game/95-modals/70-link-modal.js @@ -9,7 +9,7 @@ function openLinkModal(a,b){ const mode=UI.lmode==='df'?'df':'wave',tabs=`
${btn(tr('link_modal.lease_a_wave'),'dfMode',{m:'wave'},mode==='wave'?'pink':'ghost')}${btn(tr('common.dark_fiber'),'dfMode',{m:'df'},mode==='df'?'pink':'ghost')}
`; const head=`
${sub?tr('common.subsea_a6be'):tr('common.terrestrial_19e4')} · ${km.toLocaleString()} km

${CITY[a].name} → ${CITY[b].name}

${tabs}`; if(mode==='df'){openModal(head+dfModalBody(a,b,km,pop));return;} - if(sub&&!cablesOk(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))],dry=[a,b].find(c=>!landing(c));openModal(head+`

${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}

${S.won&&!ownCabWhy(a,b)?ownCabTeaser(a,b):''}`);return;} + if(sub&&!cablesOk(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))],dry=[a,b].find(c=>!landing(c));openModal(head+`

${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}

${cabOpen()&&!ownCabWhy(a,b)?ownCabTeaser(a,b):''}`);return;} if(isSub(a,b)&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city)){openModal(head+`

${tr('link_modal.the_landing_permit_dispute_in_city',{city:CITY[S.ev.landban.city].name,n:S.ev.landban.until-S.day})}

`);return;} if(uaePair(a,b)||andesPair(a,b)||rainPair(a,b)||borderPair(a,b))route+=`

${landWhy(a,b)}

`; route+=`

📈 ${esc(marketNote(a,b,sub))}

`; diff --git a/src/game/95-modals/80-own-cable.js b/src/game/95-modals/80-own-cable.js index aaa986e..7179655 100644 --- a/src/game/95-modals/80-own-cable.js +++ b/src/game/95-modals/80-own-cable.js @@ -10,7 +10,7 @@ const nearLanding=c=>CITIES.filter(x=>x.id!==c&&landing(x.id)).sort((x,y)=>kmBet const ownCabKm=(a,b)=>seaRoutes(a,b)[0]?.km||Infinity; const ownCabCost=km=>Math.round((2*OWNCAB_LAND+km*OWNCAB_KM+DF_SYS.roadm.cost)*hwMul('build')); const ownCabMo=km=>Math.round(km*OWNCAB_OM)+ampCount(km)*AMP_MO; -const ownCabDays=km=>Math.round(300+km*0.05); +const ownCabDays=km=>leadDays(Math.round(300+km*0.05)); // Marine routing uses the same coastline as the map, in geographic coordinates. // A quarter-degree grid keeps narrow passages open; edges are checked against // coastline segments as well as water cells, so diagonal steps cannot cut land. @@ -179,7 +179,7 @@ function seaQuote(a,b,design='standard',upgrades={}){ const base=routes[0]?.km||Infinity,km=route?.km||Infinity; // Higher survey and permitting costs dominate any savings from shorter glass. let cost=Math.round(ownCabCost(Math.max(base,km))*D.cost),days=Math.round(ownCabDays(Math.max(base,km))*D.time); - for(const k of Object.keys(SUB_UPGRADES))if(upgrades[k]){cost+=subUpgradeCost({km},k);days+=SUB_UPGRADES[k].days;} + for(const k of Object.keys(SUB_UPGRADES))if(upgrades[k]){cost+=subUpgradeCost({km},k);days+=leadDays(SUB_UPGRADES[k].days);} const ms=linkLat({a,b,kind:'df',own:true,sub:true,km,seaDesign:design}); return {km,cost,days,ms,pts:route?.pts,shore:route?.shore,cor:!!cor&&route===cor}; } @@ -190,15 +190,17 @@ const seaCab=(a,b)=>isSub(a,b)||(landing(a)&&landing(b)&&cablesFor(a,b).length>0 // one still being laid returns most of the part not laid yet, a working one is yours for good. const cabBack=l=>{if(!l||l.kind!=='df'||!l.own||!l.sub)return 0;const c=l.paid>0?l.paid:ownCabCost(l.km);if(!subNeed(l.km))return c; if(l.ready>S.day){const tot=Math.max(1,l.ready-(l.day||0));return Math.round(c*0.75*Math.min(1,(l.ready-S.day)/tot));}return 0;}; +// Your own subsea cable is a Tier 1 privilege, or a sandbox toy (open gates). +const cabOpen=()=>!!S.won||gatesOpen(); function ownCabWhy(a,b){if(!seaCab(a,b))return tr('own_cable.this_route_is_on_land_build'); - if(!S.won)return tr('own_cable.laying_your_own_subsea_cable_is'); + if(!cabOpen())return tr('own_cable.laying_your_own_subsea_cable_is'); for(const c of [a,b])if(!landing(c))return tr('own_cable.city_has_no_cable_landing_station',{city:CITY[c].name}); if(cnCity(a)||cnCity(b))return tr('own_cable.nobody_gives_a_foreign_network_a'); if(!seaReady(a,b))return tr('own_cable.surveying_a_sea_route'); const routes=seaRoutes(a,b);if(!routes.length)return tr('own_cable.no_navigable_sea_route_connects'); const km=Math.min(...routes.map(r=>r.km));if(!subNeed(km))return tr('own_cable.km_km_is_more_than_any',{km:km.toLocaleString(),max:Math.round(SUB_MAXKM()).toLocaleString()}); return '';} -function ownCabTeaser(a,b){const why=ownCabWhy(a,b);return `
${btn(S.won?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},S.won&&!why?'pink':'ghost',!!why)}
${why&&S.won?`

${esc(why)}

`:''}`;} +function ownCabTeaser(a,b){const why=ownCabWhy(a,b);return `
${btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},cabOpen()&&!why?'pink':'ghost',!!why)}
${why&&cabOpen()?`

${esc(why)}

`:''}`;} function ownCabBody(a,b,pop){const why=ownCabWhy(a,b);if(why)return `

${esc(why)}

${btn(tr('common.back'),'dfSrc',{v:'lease'},'ghost sm')}`; const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',upgrades={terminal:!!UI.seaterminal,engineering:!!UI.seaengineering},q=seaQuote(a,b,design,upgrades),{km,cost,days}=q,lack=seaLack(km,upgrades),mo=ownCabMo(km),wt=subMaxTier(km),w=Math.round(waveMo(km,true,wt)*waveMarket(a,b,true).m),save=10*w*LT[4].g/LT[wt].g-mo,pay=save>0?Math.ceil(cost/save):0; return `

${tr('own_cable.your_very_own_subsea_cable_a')}

diff --git a/src/game/95-modals/90-fiber-modals.js b/src/game/95-modals/90-fiber-modals.js index d05d01e..bfeed30 100644 --- a/src/game/95-modals/90-fiber-modals.js +++ b/src/game/95-modals/90-fiber-modals.js @@ -11,7 +11,7 @@ function dfModalBody(a,b,km,pop){ const up=(src==='build'?dfBuildCost(km):0)+DF_SYS[sys].cost+amps*AMP_COST+pop,mo=(src==='build'?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO; const w=Math.round(waveMo(km,false,4)); return `

${tr('fiber_modals.a_fiber_pair_of_your_own',{km:AMP_EVERY})}

-

${tr('common.the_glass')}

${btn(tr('fiber_modals.lease_an_iru_price_mo_ready',{price:fmt$(dfLeaseMo(km))}),'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${sc?btn(S.won?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):btn(lvl()>=3?tr('fiber_modals.build_your_own_price_n_days',{price:fmt$(dfBuildCost(km)),n:dfBuildDays(km)}):tr('fiber_modals.build_your_own_level_3'),'dfSrc',{v:'build'},src==='build'?'pink':'ghost',lvl()<3)}${sea?btn(S.won?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):''}
${sc?`

${tr('fiber_modals.a_fiber_pair_on_cable_km',{cable:esc(CAB[sc.cid].name),km:sc.km.toLocaleString()})}

`:''} +

${tr('common.the_glass')}

${btn(tr('fiber_modals.lease_an_iru_price_mo_ready_n',{price:fmt$(dfLeaseMo(km)),n:leadDays(IRU_DAYS)}),'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${sc?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):btn(lvl()>=3?tr('fiber_modals.build_your_own_price_n_days',{price:fmt$(dfBuildCost(km)),n:dfBuildDays(km)}):tr('fiber_modals.build_your_own_level_3'),'dfSrc',{v:'build'},src==='build'?'pink':'ghost',lvl()<3)}${sea?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):''}
${sc?`

${tr('fiber_modals.a_fiber_pair_on_cable_km',{cable:esc(CAB[sc.cid].name),km:sc.km.toLocaleString()})}

`:''} ${src==='build'?`

${tr('fiber_modals.your_own_trench_almost_no_rent')}

`:''}

${tr('common.line_system')}

${Object.keys(DF_SYS).map(k=>btn(`${DF_SYS[k].n} ${DF_SYS[k].lvl>lvl()?tr('fiber_modals.level_n',{n:DF_SYS[k].lvl}):fmt$(DF_SYS[k].cost)}`,'dfSys',{v:k},sys===k?'pink':'ghost',DF_SYS[k].lvl>lvl())).join('')}

${esc(DF_SYS[sys].blurb)} ${trn('fiber_modals.plus_n_in_line_amplifier_price',amps,{price:fmt$(AMP_COST),mo:fmt$(AMP_MO)})}

${km>reachOn(OPT.tp16.reach,!!sc)?`

${tr('fiber_modals.km_km_is_longer_than_any',{km:km.toLocaleString()})}

`:''} diff --git a/src/game/96-map/90-input.js b/src/game/96-map/90-input.js index 7165959..6ca8d0c 100644 --- a/src/game/96-map/90-input.js +++ b/src/game/96-map/90-input.js @@ -38,5 +38,5 @@ cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',canc const ZMIN=0.35,ZMAX=16; function zoomAt(mx,my,f){const wx=cam.x+(mx-CW/2)/cam.z,wy=cam.y+(my-CH/2)/cam.z;cam.z=clamp(cam.z*f,ZMIN,ZMAX);cam.x=wx-(mx-CW/2)/cam.z;cam.y=wy-(my-CH/2)/cam.z;wrapCam();} cv.addEventListener('wheel',e=>{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.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'&&(!S||rule('clock'))){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();}}}); diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index e486276..34711e3 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/i18n/en.js b/src/i18n/en.js index 008cdfd..8acccb3 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1759,7 +1759,7 @@ "fiber_modals.for_comparison_a_leased_1_6t":"For comparison, a leased 1.6T wave on this route is {price}/mo. Optics come next, from the link panel.", "fiber_modals.from_city":"From {city}", "fiber_modals.km_km_is_longer_than_any":"{km} km is longer than any optic reaches at full speed. Transponders will run in long-haul mode (1.2T, 800G or 400G per channel), or add regen sites along the way to get full speed back.", -"fiber_modals.lease_an_iru_price_mo_ready":"Lease an IRU {price}/mo · ready in 30 days", +"fiber_modals.lease_an_iru_price_mo_ready_n":"Lease an IRU {price}/mo · ready in {n} days", "fiber_modals.level_n":"level {n}", "fiber_modals.no_dark_fiber_inside_the_uae":"No dark fiber inside the UAE. Only the two licensed operators may run fiber here, and they only sell waves.", "fiber_modals.no_install_fee_live_in_minutes":"No install fee, live in minutes, billed monthly. Cheaper than a wave for small capacity, but it rides someone else's fabric, and that fabric can fail.", @@ -1870,6 +1870,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) is transit-free. You peer with every giant on the planet and pay nobody to reach the internet. Took you {days} days and {n} incidents.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG and friends come round every year. Register in the Deals tab for $8k. For 45 days after, selective networks with a presence in that region need only half the usual traffic before they peer with you. Sometimes you also win the raffle.", "help.once_auto_te_is_installed_you":"Once Auto-TE is installed, you can program it from the NOC tab. Rules include spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams and blackhole ddos. Check runs a dry run against live traffic; Deploy makes it real, mistakes included.", +"help.one_game_four_doors_puzzles_are":"One game, four doors, and the rules are picked when a network starts and locked after that. Puzzles are small knots to untie, with no clock. Sandbox gives you a billion dollars, every unlock (your own subsea cable included) and as much chaos as you pick, but no badges. Normal comes three ways: Change Freeze (few outages, deliveries in days, no inbox or shortages), On-call (the classic game) and BGP at 3 a.m. (more and longer outages, more DDoS). Scenarios are hand-built challenges with a goal and a deadline, and the weekly challenge gives everyone the same world for a week. Share your result with the card in the menu.", "help.open_peers_with_anyone_selective":"Open peers with anyone. Selective wants to see traffic first. Restrictive (Tier 1s) only peers with giants, over PNIs. Paid means exactly that. Big selective networks also have moods: in some cities they refuse new peers for a few months, or only take PNIs, and now and then they tear down a session you already had. Try another city or a PNI, and ask again later.", "help.out_of_port_speed_bundle_up":"Out of port speed? Bundle up to 8 identical ports to the same transit provider, IX or PNI into a LAG. Each member costs a full port; flow hashing is never perfectly even, so a bundle carries about 95% of the sum.", "help.pni_lead_times":"PNI lead times", @@ -1878,7 +1879,6 @@ "help.reach_an_ix_over_a_fabric":"Reach an IX over a fabric circuit without a POP there. It works, and the route server still gets you every open network, but it is discouraged: the reseller charges 1.5× for the port and oversubscribes it to 80%, latency rides the fabric, one fabric outage drops every session, and many selective networks refuse remote members outright.", "help.routers_optics_and_new_builds_get":"Routers, optics and new builds get dearer over the years, about 4% a year after the first six months, and now and then a shortage makes one of them a lot dearer for a month or two. What you already own keeps its price. Spares on the shelf and a yearly price lock from the NOC tab soften the blow.", "help.rules_for_your_auto_te_controller":"Rules for your Auto-TE controller: which exits to prefer, which to avoid, and when to spill onto the next one. The editor’s help explains every rule and has ready-made scripts.", -"help.sandbox_gives_you_a_billion_dollars":"Sandbox gives you a billion dollars, every unlock and no failures, but no badges. Scenarios are hand-built challenges with a goal and a deadline, and the weekly challenge gives everyone the same world for a week. Share your result with the card in the menu.", "help.share_my_network":"Share my network", "help.some_customers_come_with_conditions":"Some customers come with conditions: no Cogentle anywhere, no subsea cables because of sharks, two routers, a generator, NetChill on-net, low-loss China reach and more. Each pays a bonus. Unmet ones make them grumpy until you fix it or they leave.", "help.some_routers_take_forever_to_boot":"Some routers take forever to boot. The Infra tab shows how long yours takes. Slow booters make crashes last longer and turn a one-router swap into a three-day outage. Bigger chassis, especially anything with a PacketOinker™ inside, are slow more often. Twin routers make it someone else’s problem.", @@ -2841,6 +2841,29 @@ "routing_and_routers.the_model_won_t_fit_why":"The {model} won't fit.
{why}", "routing_and_routers.the_new_routers_in_city_are":"The new routers in {city} are still being racked.
One swap a day: try again tomorrow.", "routing_and_routers.unplug_something_first_used_ports":"Unplug something first.
{used} ports are in use, and one router fewer only has {max}.", +"rules.a_billion_dollars_every_unlock_your":"A billion dollars, every unlock, your own subsea cable.", +"rules.a_cut_now_and_then":"A cut now and then.", +"rules.bgp_at_3_a_m":"BGP at 3 a.m.", +"rules.change_freeze":"Change Freeze", +"rules.chaos_calm":"Calm", +"rules.chaos_none":"None", +"rules.chaos_normal":"Normal", +"rules.chaos_spicy":"Spicy", +"rules.everything_is_on_fire_and_it":"Everything is on fire, and it's your turn.", +"rules.fewer_outages_pnis_and_builds_in":"A third of the outages, no DDoS. PNIs and builds in days. No inbox, no shortages, no sold-out routes.", +"rules.infinite_money_everything_unlocked_quick":"Endless money, everything unlocked, quick lead times. No badges.", +"rules.like_the_real_game":"Like the real game.", +"rules.more_and_longer_outages_more_ddos":"Almost twice the outages, half as long again, twice the DDoS. Everything on.", +"rules.no_clock_no_bills_nothing_breaks":"No clock, no bills, nothing breaks.", +"rules.nobody_touches_prod_even_the_backhoes":"Nobody touches prod. Even the backhoes are on holiday.", +"rules.nothing_ever_breaks":"Nothing ever breaks.", +"rules.on_call":"On-call", +"rules.one_small_network_one_tricky_goal":"One small network, one tricky goal.", +"rules.puzzle":"Puzzle", +"rules.real_lead_times_real_outages_a":"Real lead times, real outages, a full peering inbox. The classic game.", +"rules.rules_are_locked_for_this_network":"{rules}: rules are locked for this network.", +"rules.the_real_thing_your_pager_has":"The real thing. Your pager has opinions.", +"rules.your_pager_never_sleeps":"Your pager never sleeps.", "save.cash_in_the_bank":"{cash} in the bank", "save.import_failed_err":"Import failed.
{err}", "save.load_name":"Load {name}?", @@ -2898,6 +2921,7 @@ "scenarios.reach_45_of_the_internet_and":"Reach 45% 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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Sandbox mode
A billion dollars, every unlock, and nothing ever breaks. Build the internet you always wanted.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Brazil is a continent: forty IX.brrr exchanges, thousands of provedores, and the Amazon between you and the north.", "scenarios.seoul_the_fastest_hungriest_eyeballs":"Seoul. The fastest, hungriest eyeballs on Earth, transit at four times the price, and three incumbents who bill you for every gigabit you send them.", @@ -3016,24 +3040,34 @@ "supply_chain.until_date_at_p":"until {date}, at +{p}", "supply_chain.what_p_n_days_left":"{what} +{p} · {n} days left", "supply_chain.your_price_lock_covers_you_until":"Your price lock covers you until {date}.", +"title.a_billion_dollars_and_every_toy":"A billion dollars and every toy in the shop.", "title.anywhere_else":"Anywhere else", "title.asia_hub_great_peering_far_from":"Asia hub. Great peering, far from home.", "title.back_to_my_network":"Back to my network", "title.big_hungry_market_few_providers":"Big hungry market, few providers.", "title.build_an_internet_lay_fiber_between":"Build an internet. Lay fiber between cities, buy transit, peer at exchanges, sign up businesses, and keep the eyeballs happy while backhoes, sharks and route leaks do their best to stop you.", +"title.chaos_in_your_sandbox":"Chaos in your sandbox", "title.chat_on_signal":"Chat on Signal", "title.choose":"Choose…", "title.continue_name_date":"Continue {name} · {date}", "title.cookieless_stats_no_tracking":"Cookieless stats, no tracking", "title.crossroads_of_europe_de_kicks_ix":"Crossroads of Europe. DE-KICKS IX, cheap transit.", +"title.hand_built_crises_and_one_world":"Hand-built crises, and one world for everyone each week.", "title.hard_mode_pricey_everything":"Hard mode. Pricey everything, and the wildlife wants you dead.", +"title.how_much_trouble":"How much trouble?", "title.huge_eyeball_market_pricey":"Huge eyeball market. Pricey neighbours.", "title.n_more_cities_with_transit":{"one":"{n} more city with transit to buy","other":"{n} more cities with transit to buy"}, "title.name_your_network":"Name your network", "title.new_in_series_of_tubes_v":"New in Series of Tubes {v}", +"title.one_network_one_knot_no_clock":"One network, one knot to untie. No clock.", +"title.pick_a_door":"Pick a door", "title.pick_your_home_city":"Pick your home city", -"title.scenarios_amp_weekly_challenge":"Scenarios & weekly challenge →", +"title.puzzles":"Puzzles", +"title.puzzles_are_coming_soon":"Puzzles are coming soon.
The knots are still being tied.", +"title.rules_are_picked_once_and_locked":"The rules are picked once and locked for this network. No changing the deal mid-game.", +"title.scenarios_amp_weekly":"Scenarios & weekly", "title.source_on_github":"Source on GitHub", +"title.the_real_game_climb_from_tier":"The real game: climb from Tier 3 to Tier 1.", "title.your_network_name_was_saved_and":"Your network {name} was saved and is waiting for you.", "traceroute.across_the_ix_switch":"across the {ix} switch", "traceroute.as_path_path":"AS path: {path}", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 4e1845f..50a239d 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -106,6 +106,23 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .start b{font-family:var(--display);font-size:17px;display:block} .start span{font-size:12px;color:var(--ink2);line-height:1.3;display:block} /* Home cities: compact tiles stacked in one column, the dropdown for any other city last. */ +/* Title screen doors (modes), Normal's presets and Sandbox's chaos: chunky sticker tiles, one tap each. */ +.doors{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} +.door,.preset,.chs{position:relative;border:3px solid var(--ink);border-radius:16px;background:var(--paper);box-shadow:0 4px 0 var(--ink);cursor:pointer;text-align:left;padding:9px 11px 8px;display:flex;flex-direction:column;gap:1px;min-width:0;transition:transform .08s ease,box-shadow .08s ease} +.door:active,.preset:active,.chs:active{transform:translateY(3px);box-shadow:0 1px 0 var(--ink)} +.door i,.preset i,.chs i{font-style:normal;font-size:26px;line-height:1.1} +.door b,.preset b,.chs b{font-family:var(--display);font-size:18px;line-height:1.1} +.door span,.preset span,.chs span{font-size:12.5px;color:var(--ink2);line-height:1.3} +.door.on,.preset.on,.chs.on{background:#FFE3F0;border-color:var(--me);box-shadow:0 4px 0 var(--me)} +.door.on::after,.preset.on::after,.chs.on::after{content:"✓";position:absolute;top:6px;right:9px;font:900 15px var(--display);color:var(--me)} +.door[data-door=puzzle],.door[data-door=scn]{background:var(--soft)} +.presets{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px} +.preset small{font-size:11px;color:var(--ink2);line-height:1.3;margin-top:4px;border-top:2px dashed var(--line);padding-top:4px} +.preset[data-preset=bgp].on{background:#FFE9D6;border-color:#FF6A2B;box-shadow:0 4px 0 #FF6A2B}.preset[data-preset=bgp].on::after{color:#FF6A2B} +.preset[data-preset=freeze].on{background:#E2F5FF;border-color:var(--sea2);box-shadow:0 4px 0 var(--sea2)}.preset[data-preset=freeze].on::after{color:var(--sea2)} +.chaos{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px} +.chs{padding:7px 8px 6px}.chs i{font-size:20px}.chs b{font-size:15px}.chs span{font-size:11px} +.lockn{margin:8px 0 0} .starts.homes{display:flex;flex-direction:column;gap:6px} .homes .start{display:flex;flex-wrap:wrap;align-items:baseline;column-gap:10px;row-gap:2px;padding:6px 12px;box-shadow:0 2px 0 var(--ink)} .homes .start.on{box-shadow:0 2px 0 var(--me)} diff --git a/src/styles/60-phone.css b/src/styles/60-phone.css index f761b4c..fee7bda 100644 --- a/src/styles/60-phone.css +++ b/src/styles/60-phone.css @@ -57,6 +57,12 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #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} + .door{padding:7px 9px 6px}.door i{font-size:22px}.door b{font-size:16px}.door span{font-size:11.5px} + .presets{grid-template-columns:1fr;gap:6px} + .preset{display:grid;grid-template-columns:auto 1fr;column-gap:9px;align-items:center;padding:6px 10px} + .preset i{grid-row:1/4;font-size:24px}.preset b{font-size:16px}.preset span,.preset small{grid-column:2} + .preset small{border-top:0;padding-top:0;margin-top:1px} + .chaos{grid-template-columns:repeat(2,minmax(0,1fr))} #modal .card{box-sizing:border-box;width:100%;max-height:calc(100% - env(safe-area-inset-top,0px) - 24px);border-radius:22px 22px 0 0;padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px));border-bottom:0} #dash{padding:calc(env(safe-area-inset-top,0px) + 6px) 0 0} #dash>.card{border-radius:20px 20px 0 0;min-height:100%} @@ -71,6 +77,8 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #left,#panel{left:auto !important;right:0 !important;width:min(440px,58%) !important;top:calc(env(safe-area-inset-top,0px) + 50px) !important;max-height:none !important;border-radius:20px 0 0 0 !important;border-right:0 !important} #left.full,#panel.full{width:min(640px,80%) !important} #tabbar button .ic{font-size:16px} + .doors{grid-template-columns:repeat(4,minmax(0,1fr))}.chaos{grid-template-columns:repeat(4,minmax(0,1fr))} + .presets{grid-template-columns:repeat(3,minmax(0,1fr))}.preset{display:flex} body.sheet-open #coach{bottom:calc(var(--tabbar) + 8px);left:8px;transform:none;width:calc(42% - 16px)} } /* Installed as an app: no browser chrome, so leave room for the notch and the home indicator. */ diff --git a/tests/rules.test.js b/tests/rules.test.js new file mode 100644 index 0000000..aab6864 --- /dev/null +++ b/tests/rules.test.js @@ -0,0 +1,191 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = (ev, o) => ev(`beginGame('Rule Testers','fra',${JSON.stringify(o)});if(UI.pendGame)ACT.pitchSkip()`); +// Days of a quiet-ish network until n failures have fired, on a fixed seed. +const fails = (ev, days) => { ev("S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242)"); ev(`for(let i=0;i<${days};i++)dayTick()`); return ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)'); }; + +test('an old save without rules loads as On-call, a sandbox save as Sandbox', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + const old = JSON.parse(ev('JSON.stringify(S)')); delete old.rules; + ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(old))}))`); + assert.equal(ev('rulePreset()'), 'oncall'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.rules)')), JSON.parse(ev("JSON.stringify(makeRules('oncall'))"))); + assert.equal(ev("rule('chaos')"), 'normal'); + assert.equal(ev('chaosMul()'), 1); + old.mode = 'sandbox'; + ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(old))}))`); + assert.equal(ev('rulePreset()'), 'sandbox'); + assert.equal(ev("rule('money')"), 'infinite'); + assert.deepEqual(errors, []); +}); + +test('rules survive save and load, and junk is repaired', () => { + const { ev, errors } = load(); + start(ev, { mode: 'normal', preset: 'bgp' }); + assert.equal(ev('rulePreset()'), 'bgp'); + ev("const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))"); + assert.equal(ev('rulePreset()'), 'bgp'); + assert.equal(ev("rule('chaos')"), 'spicy'); + ev("S.rules={preset:'freeze',chaos:'apocalypse',lead:42,market:'yes',mods:['ok',7,'']};sanitize(S)"); + assert.equal(ev('rulePreset()'), 'freeze'); + assert.equal(ev("rule('chaos')"), 'calm', 'a bad value falls back to the preset'); + assert.equal(ev("rule('lead')"), 'quick'); + assert.equal(ev("rule('market')"), false); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.rules.mods)')), ['ok']); + ev("S.rules={preset:'nope'};sanitize(S)"); + assert.equal(ev('rulePreset()'), 'oncall'); + ev("S.rules='hello';sanitize(S)"); + assert.equal(ev('rulePreset()'), 'oncall'); + // a scenario always runs on On-call, whatever was asked for + ev("beginGame('X','nyc',{scn:SCN.find(s=>s.id==='spat'),preset:'freeze'})"); + assert.equal(ev('rulePreset()'), 'oncall'); + assert.deepEqual(errors, []); +}); + +test('the title screen: four doors, three Normal presets, a chaos picker for Sandbox, at 360 px', () => { + const { ev, dom, errors } = load(); + const doc = dom.window.document; + ev('window.innerWidth=360;showTitle()'); + assert.equal(doc.querySelectorAll('#modal .door').length, 4); + assert.equal(doc.querySelectorAll('#modal .preset').length, 3); + assert.equal(doc.querySelectorAll('#modal .chs').length, 4); + assert.equal(doc.getElementById('doorSandbox').hidden, true); + assert.ok(doc.querySelector('.preset[data-preset=oncall].on'), 'On-call is the default'); + doc.querySelector('.preset[data-preset=freeze]').click(); + assert.ok(doc.querySelector('.preset[data-preset=freeze].on')); + doc.querySelector('.door[data-door=sandbox]').click(); + assert.equal(doc.getElementById('doorSandbox').hidden, false); + assert.equal(doc.getElementById('doorNormal').hidden, true); + doc.querySelector('.chs[data-chaos=spicy]').click(); + doc.querySelector('.door[data-door=puzzle]').click(); + assert.match(doc.getElementById('toasts').textContent, /coming soon/, 'puzzles are not here yet'); + doc.querySelector('.door[data-door=normal]').click(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('rulePreset()'), 'freeze'); + assert.match(ev("document.getElementById('hAsn').textContent"), /Change Freeze/); + assert.match(ev("document.getElementById('hAsn').title"), /locked/); + ev('showTitle()'); + doc.querySelector('.door[data-door=sandbox]').click(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('S.mode'), 'sandbox'); + assert.equal(ev("rule('chaos')"), 'spicy', 'the sandbox remembers the chaos it was given'); + ev('showTitle()'); + doc.querySelector('.door[data-door=scn]').click(); + assert.match(doc.getElementById('modalCard').textContent, /Weekly challenge/); + assert.deepEqual(errors, []); +}); + +test('On-call shows no extra tag; the share card names other presets', () => { + const { ev, errors } = load(); + start(ev, { mode: 'normal' }); + assert.equal(ev('ruleTag()'), ''); + assert.match(ev("document.getElementById('hAsn').textContent"), /^AS\d+$/); + start(ev, { mode: 'normal', preset: 'bgp' }); + assert.match(ev('ruleTag()'), /BGP at 3/); + ev('ACT.share()'); + assert.deepEqual(errors, []); +}); + +test('Sandbox lays its own subsea cable without being Tier 1, and passes the level gates', () => { + const { ev, errors } = load(); + start(ev, { mode: 'sandbox' }); + assert.equal(ev('gatesOpen()'), true); + assert.equal(ev('S.won'), false); + assert.equal(ev('lvl()'), ev('LEVELS.length')); + ev("ACT.buildPop({city:'lon'});ACT.buildPop({city:'nyc'});compute()"); + assert.equal(ev("ownCabWhy('lon','nyc')"), ''); + ev("UI.lmode='df';UI.via=null;openLinkModal('lon','nyc');ACT.ownCab()"); + assert.match(ev("document.getElementById('modalCard').textContent"), /frankly rude amount of money/); + ev('ACT.orderCable()'); + assert.ok(ev("S.links.some(l=>l.own&&l.sub)"), 'the cable is being laid'); + // and the normal game still says Tier 1 only + start(ev, { mode: 'normal' }); + assert.match(ev("ownCabWhy('lon','nyc')"), /Tier 1/); + assert.equal(ev('lvl()'), 1); + assert.deepEqual(errors, []); +}); + +test('Sandbox chaos: none by default, but it can be asked for', () => { + const { ev, errors } = load(); + start(ev, { mode: 'sandbox' }); + assert.equal(ev("rule('chaos')"), 'none'); + ev('S.cash=5;for(let i=0;i<150;i++)dayTick()'); + assert.equal(ev('S.stats.incidents'), 0); + assert.ok(ev('S.cash') >= 1e8); + start(ev, { mode: 'sandbox', rules: { chaos: 'spicy' } }); + assert.equal(ev("rule('chaos')"), 'spicy'); + ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<200;i++)dayTick()"); + assert.ok(ev('S.stats.incidents') > 0, 'spicy sandboxes break'); + assert.deepEqual(errors, []); +}); + +test('Change Freeze breaks less than On-call, BGP at 3 a.m. more, on the same seed', () => { + const n = {}; + for (const p of ['freeze', 'oncall', 'bgp']) { + const { ev, errors } = load(); + start(ev, { mode: 'normal', preset: p }); + n[p] = fails(ev, 720); + assert.deepEqual(errors, []); + } + assert.ok(n.freeze < n.oncall, `freeze ${n.freeze} < on-call ${n.oncall}`); + assert.ok(n.bgp > n.oncall, `bgp ${n.bgp} > on-call ${n.oncall}`); +}); + +test('chaos stretches spicy outages and leaves On-call ones alone', () => { + const { ev, errors } = load(); + start(ev, { mode: 'normal', preset: 'bgp' }); + ev("S.day=10;S.pops.fra.down=12;addInc({type:'crash',ref:'fra',until:12,msg:'x',cost:0})"); + assert.equal(ev('S.inc[0].until'), 13); + assert.equal(ev('S.pops.fra.down'), 13, 'what it holds down lasts as long'); + start(ev, { mode: 'normal' }); + ev("S.day=10;S.pops.fra.down=12;addInc({type:'crash',ref:'fra',until:12,msg:'x',cost:0})"); + assert.equal(ev('S.inc[0].until'), 12); + assert.deepEqual(errors, []); +}); + +test('quick lead times: PNIs, dark fiber and own builds arrive in days (#151)', () => { + const { ev, errors } = load(); + start(ev, { mode: 'normal', preset: 'freeze' }); + ev("S.cash=1e9;S.lvl=4;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})"); + const p = JSON.parse(ev("JSON.stringify(S.pni.find(x=>x.net==='nfx'))")); + assert.ok(p && p.ready - ev('S.day') <= 37, `PNI in days (${p && p.ready - ev('S.day')})`); + assert.ok(ev('dfBuildDays(500)') <= 40); + assert.equal(ev('leadDays(30)'), 3); + // On-call: as quoted + start(ev, { mode: 'normal' }); + assert.equal(ev('leadDays(30)'), 30); + assert.equal(ev('dfBuildDays(500)'), 245); + assert.deepEqual(errors, []); +}); + +test('Change Freeze: no peering inbox, no hardware market, no sold-out routes', () => { + const { ev, errors } = load(); + start(ev, { mode: 'normal', preset: 'freeze' }); + ev("S.cash=1e9;ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<60;i++)inboxDay(S.day+i)"); + assert.equal(ev('S.inbox.items.length+S.inbox.seq'), 0, 'no mail'); + ev('S.day=2000'); + assert.equal(ev("hwMul('rt')"), 1, 'no inflation'); + assert.equal(ev("hwCard()"), ''); + assert.equal(ev("[0,1,2,3,4,5,6].some(t=>CITIES.slice(0,60).some(c=>soldOut('fra',c.id,t)))"), false); + start(ev, { mode: 'normal' }); + ev('S.day=2000'); + assert.ok(ev("hwMul('rt')") > 1, 'On-call keeps the market'); + assert.deepEqual(errors, []); +}); + +test('no clock: dayTick advances no days, sends no bills, and the speed buttons hide', () => { + const { ev, errors } = load(); + start(ev, { mode: 'normal' }); + ev("S.rules=makeRules('puzzle');S.mode='puzzle';const c=S.cash;window.__c=c;for(let i=0;i<50;i++)dayTick();renderHUD()"); + assert.equal(ev('S.day'), 0); + assert.equal(ev('S.cash'), ev('__c')); + assert.equal(ev("document.getElementById('sp1').hidden"), true); + ev("ACT.speed({v:4})"); + assert.notEqual(ev('UI.speed'), 4); + ev("window.innerWidth=360;renderTabbar()"); + assert.equal(ev("!!document.querySelector('#tabbar [data-act=phonePlay]')"), false); + assert.deepEqual(errors, []); +}); From 66e13d2fc3da771f956eec4263372cd09c5964b9 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 15:29:22 +0100 Subject: [PATCH 015/181] Saves made as puzzles load with the puzzle rules --- src/game/80-simulation/50-sanitize.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 2bc0bb4..e055d10 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -64,8 +64,8 @@ function sanitize(s){ 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);}}} s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews; 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, 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':own(PRESETS,r.preset)?r.preset:'oncall';s.rules=makeRules(p,own(PRESETS,r.preset)?r:{});} + // 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:{});} 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;} function migrate(s){sanitize(s); From 33c84964fa26d0e6067524a5409cd662aa5af623 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 15:30:13 +0100 Subject: [PATCH 016/181] Architecture: where the ruleset lives --- docs/ARCHITECTURE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b3eb5ec..d856f63 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -27,7 +27,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `10-catalog/` | Prices and gear: POP and port costs, routers (`RG`), supply chain, port slots, dark fiber systems and optics (`OPT`), reach and subsea upgrades | | `20-world/` | Map projection, landmasses, coastline, city coordinates (`CITY_LL`), `CITIES`, `CABLES` | | `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` | +| `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()` | | `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 | From 7fc8d0f0807672fb24b8a5263fe2870dc1934938 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 16:21:25 +0100 Subject: [PATCH 017/181] Puzzles: small, calm network builds with stars, packs and a weekly puzzle (#190) --- site/i18n/de.js | 116 +++++++++ site/i18n/es.js | 116 +++++++++ site/i18n/fr.js | 116 +++++++++ site/i18n/it.js | 116 +++++++++ site/i18n/pt.js | 116 +++++++++ src/game/60-features/90-puzzles-data.js | 39 +++ src/game/60-features/92-puzzles.js | 104 ++++++++ src/game/80-simulation/50-sanitize.js | 2 + src/game/90-actions/10-interface.js | 10 +- src/game/90-actions/89-game-and-settings.js | 3 +- src/game/90-actions/95-puzzles.js | 26 ++ src/game/91-save.js | 7 +- src/game/92-audio.js | 2 + src/game/93-ui/10-dom.js | 2 +- src/game/93-ui/20-phone.js | 5 +- src/game/93-ui/40-hud-and-panels.js | 5 +- src/game/94-dashboard/80-hint.js | 1 + src/game/95-modals/40-title.js | 2 +- src/game/95-modals/95-puzzles.js | 81 +++++++ src/game/96-map/60-draw.js | 2 +- src/game/96-map/85-puzzle-cities.js | 10 + src/game/96-map/90-input.js | 6 +- src/game/96-map/95-clicks.js | 4 +- src/game/99-loop.js | 4 +- src/i18n/en.js | 116 +++++++++ src/index.html | 1 + src/styles/70-puzzles.css | 39 +++ tests/puzzles.test.js | 255 ++++++++++++++++++++ 28 files changed, 1283 insertions(+), 23 deletions(-) create mode 100644 src/game/60-features/90-puzzles-data.js create mode 100644 src/game/60-features/92-puzzles.js create mode 100644 src/game/90-actions/95-puzzles.js create mode 100644 src/game/95-modals/95-puzzles.js create mode 100644 src/game/96-map/85-puzzle-cities.js create mode 100644 src/styles/70-puzzles.css create mode 100644 tests/puzzles.test.js diff --git a/site/i18n/de.js b/site/i18n/de.js index 0b751b2..0257216 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2661,6 +2661,122 @@ "progress.under_attack_now":"Gerade unter Beschuss", "progress.your_score_peak_traffic":"Dein Ergebnis: Spitzen-Traffic", "progress.your_traffic_to_and_from_asia":"Dein Traffic von und nach Asien", +"puzzles.a_backhoe_walks_into_your_network":"Kommt ein Bagger in dein Netz. Nichts passiert.", +"puzzles.a_pop_costs_setup_plus_a_year":"Ein POP kostet {setup} Einrichtung, dann {mo}/Monat. Puzzles rechnen die Einrichtung und ein Jahr Miete.", +"puzzles.a_tiny_island_where_half_the":"Eine winzige Insel, auf der die halbe Pazifik-Verkabelung Kaffeepause macht.", +"puzzles.a_to_b_under_ms":"{a} → {b} unter {ms} ms", +"puzzles.a_to_b_under_ms_now":"{a} → {b} unter {ms} ms (jetzt {now} ms)", +"puzzles.aloha_latency":"Aloha Latenz", +"puzzles.avoid_list":"ohne {list}", +"puzzles.back_to_my_network":"Zurück zu meinem Netz", +"puzzles.back_to_the_title":"Zurück zum Startbildschirm", +"puzzles.beat_the_clock_light_in_glass":"Licht in Glasfaser schafft 200 km pro Millisekunde. Wähl deine Kabel, als ob es darauf ankäme.", +"puzzles.belt_and_braces":"Gürtel und Hosenträger", +"puzzles.best_x":"Bestwert {x}", +"puzzles.budget":"Budget", +"puzzles.budget_x":"Budget {x}", +"puzzles.connect_list":"Verbinde {list}.", +"puzzles.connected":"Verbunden", +"puzzles.copied_paste_it_anywhere":"Kopiert! Füg es irgendwo ein:
{t}", +"puzzles.de_kicks_sales_has_your_number":"Der DE-KICKS-Vertrieb hat deine Nummer. Verbinde Deutschland ohne Frankfurt.", +"puzzles.diverse_route_40_survives_a_backhoe":"Getrennte Trasse (+40 %, übersteht einen Bagger)", +"puzzles.down_under_up_and_running":"Down Under, up and running", +"puzzles.drag_from_a_pink_pop_to":"Zieh von einem pinken POP zu einer anderen Stadt, um eine Wave zu mieten", +"puzzles.drag_from_this_pop_onto_another":"Zieh von diesem POP auf eine andere Puzzle-Stadt oder wähl eine hier.", +"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.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.", +"puzzles.four_capitals_one_very_long_winter":"Vier Hauptstädte, ein sehr langer Winter, null Ausreden für Ausfälle.", +"puzzles.four_cities_four_cables_one_ring":"Vier Städte, ein Ring. Tolkien wäre begeistert, dein NOC sowieso.", +"puzzles.four_cities_one_continent_and_a":"Vier Städte, ein Kontinent und dazwischen sehr viel Mais.", +"puzzles.frankfurt_to_singapore_the_short_way":"Frankfurt nach Singapur auf dem kurzen Weg. Der lange führt über Land, und das merkt man.", +"puzzles.free":"Gratis", +"puzzles.goal":"Ziel", +"puzzles.goal_city":"Zielstadt", +"puzzles.guam_slam":"Guam Slam", +"puzzles.hello_world":"Hallo, Welt", +"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: der malerischste Regenerator-Standort der Welt.", +"puzzles.includes_a_new_pop_in_city":"Mit neuem POP in {city} ({price} für ein Jahr).", +"puzzles.it_works_finance_and_the_backhoe":"Läuft! Die Buchhaltung und der Bagger hätten da noch Fragen.", +"puzzles.keep_building":"Weiterbauen", +"puzzles.kiwi_fruit_salad":"Kiwi-Obstsalat", +"puzzles.lease_a_wave_to":"Wave mieten nach", +"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_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.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.", +"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.", +"puzzles.not_this_one_find_a_way_around":"Die nicht. Such dir einen Weg drumherum.", +"puzzles.not_through_frankfurt":"Nicht über Frankfurt", +"puzzles.off_limits":"Tabu", +"puzzles.on_the_house":"Aufs Haus", +"puzzles.one_backhoe_away_from_a_very":"Ein Bagger trennt dich von einer sehr langen Nacht. Ein zweiter Weg gibt ⭐⭐⭐.", +"puzzles.one_cut_splits_it":"Ein Schnitt trennt es", +"puzzles.one_cut_splits_it_where":"Ein Schnitt trennt es: {where}", +"puzzles.one_ring_through_every_pop":"Ein Ring durch jeden POP", +"puzzles.one_very_big_island_and_a":"Eine sehr große Insel und sehr viel sehr leere Glasfaser.", +"puzzles.open_a_pop_cost":"POP eröffnen · {cost}", +"puzzles.pacific_rim_shot":"Pacific Rim Shot", +"puzzles.ping_pong_to_tokyo":"Ping-Pong nach Tokio", +"puzzles.price_per_year":"{price}/Jahr", +"puzzles.puzzle":"Puzzle", +"puzzles.puzzle_solved":"Puzzle gelöst", +"puzzles.puzzles":"Puzzles", +"puzzles.remove_this_link":"Diesen Link entfernen", +"puzzles.remove_this_pop":"Diesen POP entfernen", +"puzzles.reset":"Zurücksetzen", +"puzzles.retry_for_3_stars":"Nochmal für ⭐⭐⭐", +"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.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)", +"puzzles.sao_paulo_to_miami_before_the":"São Paulo nach Miami, bevor der Caipirinha warm wird.", +"puzzles.sea_to_shining_sea":"Von Küste zu Küste", +"puzzles.seattle_to_singapore_with_a_stop":"Seattle nach Singapur, mit Zwischenstopp für Sushi und Dim Sum.", +"puzzles.share_line":"Series of Tubes Puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.size":"Größe", +"puzzles.small_calm_network_builds":"Kleine, entspannte Netzbauten", +"puzzles.smorgasbord":"Smörgåsbord", +"puzzles.speed_runs":"Speedruns", +"puzzles.spent_x":"Ausgegeben {x}", +"puzzles.spent_x_of_y":"Ausgegeben {x} / {y}", +"puzzles.stepping_stone_optional":"Trittstein (optional)", +"puzzles.suez_you_later":"Suez bald", +"puzzles.survives_any_single_cut":"Übersteht jeden einzelnen Schnitt", +"puzzles.tap_a_goal_city_to_open":"Tipp auf eine leuchtende Stadt für deinen ersten POP", +"puzzles.that_city_is_not_part_of":"Diese Stadt gehört nicht zu diesem Puzzle.", +"puzzles.the_pacific_is_big_light_is":"Der Pazifik ist groß. Licht ist schnell. Dein Budget ist beides nicht.", +"puzzles.the_pacific_rim_where_every_hop":"Der Pazifikrand, wo jeder Hop ein Ozean ist.", +"puzzles.the_shark_tank":"Das Haifischbecken", +"puzzles.the_sharks_have_been_biting_again":"Die Haie haben wieder zugebissen. Bleib auf dem Trockenen.", +"puzzles.the_sharks_say_no":"Die Haie sagen nein.", +"puzzles.three_cities_two_currencies_one_very":"Drei Städte, zwei Währungen, ein sehr kurzer Tunnel unter dem Meer.", +"puzzles.traders_paid_millions_to_shave_milliseconds":"Trader haben Millionen bezahlt, um hier Millisekunden zu sparen. Du schaffst es billiger.", +"puzzles.two_cables_across_the_atlantic_because":"Zwei Kabel über den Atlantik, denn eins ist eine Hoffnung, kein Plan.", +"puzzles.under_n_ms":"unter {n} ms", +"puzzles.undo":"Rückgängig", +"puzzles.unlocks_at_n_stars":"Ab {n}⭐", +"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_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"}, "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 2f2a645..89a1a02 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2659,6 +2659,122 @@ "progress.under_attack_now":"Bajo ataque ahora", "progress.your_score_peak_traffic":"Tu puntuación: tráfico pico", "progress.your_traffic_to_and_from_asia":"Tu tráfico desde y hacia Asia", +"puzzles.a_backhoe_walks_into_your_network":"Una retroexcavadora entra en tu red. No pasa nada.", +"puzzles.a_pop_costs_setup_plus_a_year":"Un POP cuesta {setup} de instalación y luego {mo}/mes. Los puzles cuentan la instalación y un año de alquiler.", +"puzzles.a_tiny_island_where_half_the":"Una isla diminuta donde medio Pacífico de cables para a tomar café.", +"puzzles.a_to_b_under_ms":"{a} → {b} en menos de {ms} ms", +"puzzles.a_to_b_under_ms_now":"{a} → {b} en menos de {ms} ms (ahora {now} ms)", +"puzzles.aloha_latency":"Aloha, latencia", +"puzzles.avoid_list":"sin {list}", +"puzzles.back_to_my_network":"Volver a mi red", +"puzzles.back_to_the_title":"Volver a la pantalla de inicio", +"puzzles.beat_the_clock_light_in_glass":"La luz en la fibra hace 200 km por milisegundo. Elige tus cables como si importara.", +"puzzles.belt_and_braces":"Cinturón y tirantes", +"puzzles.best_x":"mejor {x}", +"puzzles.budget":"Presupuesto", +"puzzles.budget_x":"presupuesto {x}", +"puzzles.connect_list":"Conecta {list}.", +"puzzles.connected":"Conectado", +"puzzles.copied_paste_it_anywhere":"¡Copiado! Pégalo donde quieras:
{t}", +"puzzles.de_kicks_sales_has_your_number":"Ventas de DE-KICKS tiene tu número. Conecta Alemania sin pasar por Fráncfort.", +"puzzles.diverse_route_40_survives_a_backhoe":"Ruta diversa (+40 %, sobrevive a una retroexcavadora)", +"puzzles.down_under_up_and_running":"Down Under, en marcha", +"puzzles.drag_from_a_pink_pop_to":"Arrastra desde un POP rosa a otra ciudad para alquilar una onda", +"puzzles.drag_from_this_pop_onto_another":"Arrastra desde este POP a otra ciudad del puzle, o elige una aquí.", +"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.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.", +"puzzles.four_capitals_one_very_long_winter":"Cuatro capitales, un invierno larguísimo y cero excusas para caerse.", +"puzzles.four_cities_four_cables_one_ring":"Cuatro ciudades, un anillo. Tolkien lo aprobaría; tu NOC, seguro.", +"puzzles.four_cities_one_continent_and_a":"Cuatro ciudades, un continente y mucho maíz entre medias.", +"puzzles.frankfurt_to_singapore_the_short_way":"De Fráncfort a Singapur por el camino corto. El largo va por tierra, y se nota.", +"puzzles.free":"Gratis", +"puzzles.goal":"Objetivo", +"puzzles.goal_city":"Ciudad objetivo", +"puzzles.guam_slam":"Guam Slam", +"puzzles.hello_world":"Hola, mundo", +"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: el sitio de regeneración más bonito del mundo.", +"puzzles.includes_a_new_pop_in_city":"Incluye un POP nuevo en {city} ({price} por un año).", +"puzzles.it_works_finance_and_the_backhoe":"¡Funciona! Finanzas y la retroexcavadora quieren hablar contigo.", +"puzzles.keep_building":"Seguir construyendo", +"puzzles.kiwi_fruit_salad":"Macedonia de kiwi", +"puzzles.lease_a_wave_to":"Alquilar una onda hasta", +"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_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.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.", +"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.", +"puzzles.not_this_one_find_a_way_around":"Esta no. Busca otro camino.", +"puzzles.not_through_frankfurt":"Sin pasar por Fráncfort", +"puzzles.off_limits":"Prohibida", +"puzzles.on_the_house":"Invita la casa", +"puzzles.one_backhoe_away_from_a_very":"A una retroexcavadora de una noche muy larga. Añade un segundo camino para ⭐⭐⭐.", +"puzzles.one_cut_splits_it":"Un corte la parte en dos", +"puzzles.one_cut_splits_it_where":"Un corte la parte en dos: {where}", +"puzzles.one_ring_through_every_pop":"Un anillo por todos los POP", +"puzzles.one_very_big_island_and_a":"Una isla enorme y muchísima fibra vacía.", +"puzzles.open_a_pop_cost":"Abrir un POP · {cost}", +"puzzles.pacific_rim_shot":"Pacific Rim Shot", +"puzzles.ping_pong_to_tokyo":"Ping-pong a Tokio", +"puzzles.price_per_year":"{price}/año", +"puzzles.puzzle":"Puzle", +"puzzles.puzzle_solved":"Puzle resuelto", +"puzzles.puzzles":"Puzles", +"puzzles.remove_this_link":"Quitar este enlace", +"puzzles.remove_this_pop":"Quitar este POP", +"puzzles.reset":"Reiniciar", +"puzzles.retry_for_3_stars":"Reintentar para ⭐⭐⭐", +"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.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)", +"puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes de que se caliente la caipiriña.", +"puzzles.sea_to_shining_sea":"De costa a costa", +"puzzles.seattle_to_singapore_with_a_stop":"De Seattle a Singapur, con parada para sushi y dim sum.", +"puzzles.share_line":"Series of Tubes puzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.size":"Tamaño", +"puzzles.small_calm_network_builds":"Redes pequeñas y tranquilas", +"puzzles.smorgasbord":"Smörgåsbord", +"puzzles.speed_runs":"Contrarreloj", +"puzzles.spent_x":"Gastado {x}", +"puzzles.spent_x_of_y":"Gastado {x} / {y}", +"puzzles.stepping_stone_optional":"Escala (opcional)", +"puzzles.suez_you_later":"Suez luego", +"puzzles.survives_any_single_cut":"Sobrevive a cualquier corte", +"puzzles.tap_a_goal_city_to_open":"Toca una ciudad brillante para abrir tu primer POP", +"puzzles.that_city_is_not_part_of":"Esa ciudad no forma parte de este puzle.", +"puzzles.the_pacific_is_big_light_is":"El Pacífico es grande. La luz es rápida. Tu presupuesto no es ninguna de las dos cosas.", +"puzzles.the_pacific_rim_where_every_hop":"El borde del Pacífico, donde cada salto es un océano.", +"puzzles.the_shark_tank":"La pecera de tiburones", +"puzzles.the_sharks_have_been_biting_again":"Los tiburones vuelven a morder. Quédate en tierra firme.", +"puzzles.the_sharks_say_no":"Los tiburones dicen que no.", +"puzzles.three_cities_two_currencies_one_very":"Tres ciudades, dos monedas y un túnel muy corto bajo el mar.", +"puzzles.traders_paid_millions_to_shave_milliseconds":"Los traders pagaron millones por arañar milisegundos a esta ruta. Tú lo harás por menos.", +"puzzles.two_cables_across_the_atlantic_because":"Dos cables cruzando el Atlántico, porque uno es una esperanza, no un plan.", +"puzzles.under_n_ms":"menos de {n} ms", +"puzzles.undo":"Deshacer", +"puzzles.unlocks_at_n_stars":"Se desbloquea con {n}⭐", +"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_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"}, "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 413ae5f..8cf97ca 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2659,6 +2659,122 @@ "progress.under_attack_now":"Sous attaque", "progress.your_score_peak_traffic":"Ton score : pic de trafic", "progress.your_traffic_to_and_from_asia":"Ton trafic vers et depuis l’Asie", +"puzzles.a_backhoe_walks_into_your_network":"C’est une pelleteuse qui entre dans ton réseau. Il ne se passe rien.", +"puzzles.a_pop_costs_setup_plus_a_year":"Un POP coûte {setup} à installer, puis {mo}/mois. Les puzzles comptent l’installation et un an de loyer.", +"puzzles.a_tiny_island_where_half_the":"Une île minuscule où la moitié des câbles du Pacifique s’arrêtent pour un café.", +"puzzles.a_to_b_under_ms":"{a} → {b} en moins de {ms} ms", +"puzzles.a_to_b_under_ms_now":"{a} → {b} en moins de {ms} ms (actuellement {now} ms)", +"puzzles.aloha_latency":"Aloha la latence", +"puzzles.avoid_list":"sans {list}", +"puzzles.back_to_my_network":"Retour à mon réseau", +"puzzles.back_to_the_title":"Retour à l’écran titre", +"puzzles.beat_the_clock_light_in_glass":"La lumière dans la fibre fait 200 km par milliseconde. Choisis tes câbles comme si ça comptait.", +"puzzles.belt_and_braces":"Ceinture et bretelles", +"puzzles.best_x":"record {x}", +"puzzles.budget":"Budget", +"puzzles.budget_x":"budget {x}", +"puzzles.connect_list":"Relie {list}.", +"puzzles.connected":"Relié", +"puzzles.copied_paste_it_anywhere":"Copié ! Colle-le où tu veux :
{t}", +"puzzles.de_kicks_sales_has_your_number":"Les commerciaux de DE-KICKS ont ton numéro. Relie l’Allemagne sans passer par Francfort.", +"puzzles.diverse_route_40_survives_a_backhoe":"Route diverse (+40 %, survit à une pelleteuse)", +"puzzles.down_under_up_and_running":"Down Under, ça tourne", +"puzzles.drag_from_a_pink_pop_to":"Glisse depuis un POP rose vers une autre ville pour louer une longueur d’onde", +"puzzles.drag_from_this_pop_onto_another":"Glisse depuis ce POP vers une autre ville du puzzle, ou choisis-en une ici.", +"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.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.", +"puzzles.four_capitals_one_very_long_winter":"Quatre capitales, un très long hiver, zéro excuse pour une panne.", +"puzzles.four_cities_four_cables_one_ring":"Quatre villes, un anneau. Tolkien approuverait ; ton NOC, à coup sûr.", +"puzzles.four_cities_one_continent_and_a":"Quatre villes, un continent et beaucoup de maïs entre les deux.", +"puzzles.frankfurt_to_singapore_the_short_way":"Francfort–Singapour par le chemin court. Le long passe par la terre, et ça se voit.", +"puzzles.free":"Gratuit", +"puzzles.goal":"Objectif", +"puzzles.goal_city":"Ville objectif", +"puzzles.guam_slam":"Guam Slam", +"puzzles.hello_world":"Hello, World", +"puzzles.honolulu_the_world_s_most_scenic":"Honolulu : le site de régénération le plus pittoresque du monde.", +"puzzles.includes_a_new_pop_in_city":"Inclut un nouveau POP à {city} ({price} pour un an).", +"puzzles.it_works_finance_and_the_backhoe":"Ça marche ! La compta et la pelleteuse aimeraient te dire un mot.", +"puzzles.keep_building":"Continuer à construire", +"puzzles.kiwi_fruit_salad":"Salade de kiwis", +"puzzles.lease_a_wave_to":"Louer une longueur d’onde vers", +"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_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.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.", +"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.", +"puzzles.not_this_one_find_a_way_around":"Pas celle-là. Trouve un détour.", +"puzzles.not_through_frankfurt":"Pas par Francfort", +"puzzles.off_limits":"Interdite", +"puzzles.on_the_house":"Offert par la maison", +"puzzles.one_backhoe_away_from_a_very":"À une pelleteuse d’une très longue nuit. Ajoute un deuxième chemin pour ⭐⭐⭐.", +"puzzles.one_cut_splits_it":"Une coupure le divise", +"puzzles.one_cut_splits_it_where":"Une coupure le divise : {where}", +"puzzles.one_ring_through_every_pop":"Un anneau qui passe par chaque POP", +"puzzles.one_very_big_island_and_a":"Une très grande île, et beaucoup de fibre très vide.", +"puzzles.open_a_pop_cost":"Ouvrir un POP · {cost}", +"puzzles.pacific_rim_shot":"Pacific Rim Shot", +"puzzles.ping_pong_to_tokyo":"Ping-pong jusqu’à Tokyo", +"puzzles.price_per_year":"{price}/an", +"puzzles.puzzle":"Puzzle", +"puzzles.puzzle_solved":"Puzzle résolu", +"puzzles.puzzles":"Puzzles", +"puzzles.remove_this_link":"Supprimer ce lien", +"puzzles.remove_this_pop":"Supprimer ce POP", +"puzzles.reset":"Recommencer", +"puzzles.retry_for_3_stars":"Réessayer pour ⭐⭐⭐", +"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.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)", +"puzzles.sao_paulo_to_miami_before_the":"São Paulo–Miami avant que la caïpirinha ne tiédisse.", +"puzzles.sea_to_shining_sea":"D’une côte à l’autre", +"puzzles.seattle_to_singapore_with_a_stop":"Seattle–Singapour, avec une escale sushis et dim sum.", +"puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.size":"Taille", +"puzzles.small_calm_network_builds":"Petits réseaux, tranquillement", +"puzzles.smorgasbord":"Smörgåsbord", +"puzzles.speed_runs":"Contre la montre", +"puzzles.spent_x":"Dépensé {x}", +"puzzles.spent_x_of_y":"Dépensé {x} / {y}", +"puzzles.stepping_stone_optional":"Escale (facultative)", +"puzzles.suez_you_later":"Suez la prochaine", +"puzzles.survives_any_single_cut":"Survit à n’importe quelle coupure", +"puzzles.tap_a_goal_city_to_open":"Touche une ville lumineuse pour ouvrir ton premier POP", +"puzzles.that_city_is_not_part_of":"Cette ville ne fait pas partie de ce puzzle.", +"puzzles.the_pacific_is_big_light_is":"Le Pacifique est grand. La lumière est rapide. Ton budget n’est ni l’un ni l’autre.", +"puzzles.the_pacific_rim_where_every_hop":"Le pourtour du Pacifique, où chaque saut est un océan.", +"puzzles.the_shark_tank":"L’aquarium à requins", +"puzzles.the_sharks_have_been_biting_again":"Les requins ont encore mordu. Reste sur la terre ferme.", +"puzzles.the_sharks_say_no":"Les requins disent non.", +"puzzles.three_cities_two_currencies_one_very":"Trois villes, deux monnaies, un tout petit tunnel sous la mer.", +"puzzles.traders_paid_millions_to_shave_milliseconds":"Des traders ont payé des millions pour gratter des millisecondes sur cette route. Toi, tu le fais pour moins cher.", +"puzzles.two_cables_across_the_atlantic_because":"Deux câbles à travers l’Atlantique, parce qu’un seul, c’est un espoir, pas un plan.", +"puzzles.under_n_ms":"moins de {n} ms", +"puzzles.undo":"Annuler", +"puzzles.unlocks_at_n_stars":"À partir de {n}⭐", +"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_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"}, "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 103bc61..202474d 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2659,6 +2659,122 @@ "progress.under_attack_now":"Sotto attacco ora", "progress.your_score_peak_traffic":"Il tuo punteggio: picco di traffico", "progress.your_traffic_to_and_from_asia":"Il tuo traffico da e per l’Asia", +"puzzles.a_backhoe_walks_into_your_network":"Una ruspa entra nella tua rete. Non succede niente.", +"puzzles.a_pop_costs_setup_plus_a_year":"Un POP costa {setup} di attivazione, poi {mo}/mese. I puzzle contano l’attivazione e un anno di canone.", +"puzzles.a_tiny_island_where_half_the":"Un’isoletta dove metà dei cavi del Pacifico si ferma per un caffè.", +"puzzles.a_to_b_under_ms":"{a} → {b} sotto i {ms} ms", +"puzzles.a_to_b_under_ms_now":"{a} → {b} sotto i {ms} ms (ora {now} ms)", +"puzzles.aloha_latency":"Aloha latenza", +"puzzles.avoid_list":"senza {list}", +"puzzles.back_to_my_network":"Torna alla mia rete", +"puzzles.back_to_the_title":"Torna alla schermata iniziale", +"puzzles.beat_the_clock_light_in_glass":"La luce nella fibra fa 200 km al millisecondo. Scegli i cavi come se contasse.", +"puzzles.belt_and_braces":"Cintura e bretelle", +"puzzles.best_x":"record {x}", +"puzzles.budget":"Budget", +"puzzles.budget_x":"budget {x}", +"puzzles.connect_list":"Collega {list}.", +"puzzles.connected":"Collegato", +"puzzles.copied_paste_it_anywhere":"Copiato! Incollalo dove vuoi:
{t}", +"puzzles.de_kicks_sales_has_your_number":"Il commerciale di DE-KICKS ha il tuo numero. Collega la Germania senza passare da Francoforte.", +"puzzles.diverse_route_40_survives_a_backhoe":"Percorso diverso (+40%, sopravvive a una ruspa)", +"puzzles.down_under_up_and_running":"Down Under, operativi", +"puzzles.drag_from_a_pink_pop_to":"Trascina da un POP rosa a un’altra città per noleggiare una wave", +"puzzles.drag_from_this_pop_onto_another":"Trascina da questo POP su un’altra città del puzzle, o scegline una qui.", +"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.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.", +"puzzles.four_capitals_one_very_long_winter":"Quattro capitali, un inverno lunghissimo, zero scuse per i disservizi.", +"puzzles.four_cities_four_cables_one_ring":"Quattro città, un anello. Tolkien approverebbe; il tuo NOC di sicuro.", +"puzzles.four_cities_one_continent_and_a":"Quattro città, un continente e tantissimo mais in mezzo.", +"puzzles.frankfurt_to_singapore_the_short_way":"Da Francoforte a Singapore per la via corta. Quella lunga è via terra, e si vede.", +"puzzles.free":"Gratis", +"puzzles.goal":"Obiettivo", +"puzzles.goal_city":"Città obiettivo", +"puzzles.guam_slam":"Guam Slam", +"puzzles.hello_world":"Ciao, mondo", +"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: il sito di rigenerazione più panoramico del mondo.", +"puzzles.includes_a_new_pop_in_city":"Include un nuovo POP a {city} ({price} per un anno).", +"puzzles.it_works_finance_and_the_backhoe":"Funziona! L’amministrazione e la ruspa vorrebbero parlarti.", +"puzzles.keep_building":"Continua a costruire", +"puzzles.kiwi_fruit_salad":"Macedonia di kiwi", +"puzzles.lease_a_wave_to":"Noleggia una wave verso", +"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_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.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.", +"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.", +"puzzles.not_this_one_find_a_way_around":"Questa no. Trova un altro giro.", +"puzzles.not_through_frankfurt":"Non da Francoforte", +"puzzles.off_limits":"Vietata", +"puzzles.on_the_house":"Offre la casa", +"puzzles.one_backhoe_away_from_a_very":"A una ruspa da una nottata lunghissima. Aggiungi un secondo percorso per ⭐⭐⭐.", +"puzzles.one_cut_splits_it":"Un taglio la divide", +"puzzles.one_cut_splits_it_where":"Un taglio la divide: {where}", +"puzzles.one_ring_through_every_pop":"Un anello che passa per ogni POP", +"puzzles.one_very_big_island_and_a":"Un’isola enorme e tantissima fibra vuota.", +"puzzles.open_a_pop_cost":"Apri un POP · {cost}", +"puzzles.pacific_rim_shot":"Pacific Rim Shot", +"puzzles.ping_pong_to_tokyo":"Ping pong fino a Tokyo", +"puzzles.price_per_year":"{price}/anno", +"puzzles.puzzle":"Puzzle", +"puzzles.puzzle_solved":"Puzzle risolto", +"puzzles.puzzles":"Puzzle", +"puzzles.remove_this_link":"Rimuovi questo link", +"puzzles.remove_this_pop":"Rimuovi questo POP", +"puzzles.reset":"Ricomincia", +"puzzles.retry_for_3_stars":"Riprova per ⭐⭐⭐", +"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.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)", +"puzzles.sao_paulo_to_miami_before_the":"Da São Paulo a Miami prima che la caipirinha si scaldi.", +"puzzles.sea_to_shining_sea":"Da costa a costa", +"puzzles.seattle_to_singapore_with_a_stop":"Da Seattle a Singapore, con una sosta per sushi e dim sum.", +"puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.size":"Taglia", +"puzzles.small_calm_network_builds":"Piccole reti, con calma", +"puzzles.smorgasbord":"Smörgåsbord", +"puzzles.speed_runs":"Corse contro il tempo", +"puzzles.spent_x":"Speso {x}", +"puzzles.spent_x_of_y":"Speso {x} / {y}", +"puzzles.stepping_stone_optional":"Tappa (facoltativa)", +"puzzles.suez_you_later":"Suez la prossima", +"puzzles.survives_any_single_cut":"Sopravvive a qualsiasi taglio", +"puzzles.tap_a_goal_city_to_open":"Tocca una città illuminata per aprire il tuo primo POP", +"puzzles.that_city_is_not_part_of":"Quella città non fa parte di questo puzzle.", +"puzzles.the_pacific_is_big_light_is":"Il Pacifico è grande. La luce è veloce. Il tuo budget non è né l’uno né l’altro.", +"puzzles.the_pacific_rim_where_every_hop":"Il bordo del Pacifico, dove ogni hop è un oceano.", +"puzzles.the_shark_tank":"La vasca degli squali", +"puzzles.the_sharks_have_been_biting_again":"Gli squali hanno ricominciato a mordere. Resta sulla terraferma.", +"puzzles.the_sharks_say_no":"Gli squali dicono di no.", +"puzzles.three_cities_two_currencies_one_very":"Tre città, due valute, un tunnel cortissimo sotto il mare.", +"puzzles.traders_paid_millions_to_shave_milliseconds":"I trader hanno pagato milioni per limare millisecondi su questa rotta. Tu ci riesci spendendo meno.", +"puzzles.two_cables_across_the_atlantic_because":"Due cavi attraverso l’Atlantico, perché uno solo è una speranza, non un piano.", +"puzzles.under_n_ms":"sotto i {n} ms", +"puzzles.undo":"Annulla", +"puzzles.unlocks_at_n_stars":"Si sblocca a {n}⭐", +"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_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"}, "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 046f9a8..515c3b7 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2659,6 +2659,122 @@ "progress.under_attack_now":"Sob ataque agora", "progress.your_score_peak_traffic":"Sua pontuação: pico de tráfego", "progress.your_traffic_to_and_from_asia":"Seu tráfego de e para a Ásia", +"puzzles.a_backhoe_walks_into_your_network":"Uma retroescavadeira entra na sua rede. Nada acontece.", +"puzzles.a_pop_costs_setup_plus_a_year":"Um POP custa {setup} de instalação e depois {mo}/mês. Os puzzles contam a instalação e um ano de aluguel.", +"puzzles.a_tiny_island_where_half_the":"Uma ilhota onde metade dos cabos do Pacífico para pra tomar um café.", +"puzzles.a_to_b_under_ms":"{a} → {b} abaixo de {ms} ms", +"puzzles.a_to_b_under_ms_now":"{a} → {b} abaixo de {ms} ms (agora {now} ms)", +"puzzles.aloha_latency":"Aloha, latência", +"puzzles.avoid_list":"sem {list}", +"puzzles.back_to_my_network":"Voltar à minha rede", +"puzzles.back_to_the_title":"Voltar à tela inicial", +"puzzles.beat_the_clock_light_in_glass":"A luz na fibra faz 200 km por milissegundo. Escolha seus cabos como se isso importasse.", +"puzzles.belt_and_braces":"Cinto e suspensórios", +"puzzles.best_x":"recorde {x}", +"puzzles.budget":"Orçamento", +"puzzles.budget_x":"orçamento {x}", +"puzzles.connect_list":"Conecte {list}.", +"puzzles.connected":"Conectado", +"puzzles.copied_paste_it_anywhere":"Copiado! Cole onde quiser:
{t}", +"puzzles.de_kicks_sales_has_your_number":"O comercial da DE-KICKS tem seu número. Conecte a Alemanha sem passar por Frankfurt.", +"puzzles.diverse_route_40_survives_a_backhoe":"Rota diversa (+40%, sobrevive a uma retroescavadeira)", +"puzzles.down_under_up_and_running":"Down Under, no ar", +"puzzles.drag_from_a_pink_pop_to":"Arraste de um POP rosa até outra cidade para alugar uma wave", +"puzzles.drag_from_this_pop_onto_another":"Arraste deste POP até outra cidade do puzzle, ou escolha uma aqui.", +"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.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.", +"puzzles.four_capitals_one_very_long_winter":"Quatro capitais, um inverno longuíssimo, zero desculpas para cair.", +"puzzles.four_cities_four_cables_one_ring":"Quatro cidades, um anel. Tolkien aprovaria; seu NOC, com certeza.", +"puzzles.four_cities_one_continent_and_a":"Quatro cidades, um continente e muito milho no meio.", +"puzzles.frankfurt_to_singapore_the_short_way":"De Frankfurt a Singapura pelo caminho curto. O longo vai por terra, e dá pra notar.", +"puzzles.free":"Grátis", +"puzzles.goal":"Objetivo", +"puzzles.goal_city":"Cidade objetivo", +"puzzles.guam_slam":"Guam Slam", +"puzzles.hello_world":"Olá, mundo", +"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: o ponto de regeneração mais bonito do mundo.", +"puzzles.includes_a_new_pop_in_city":"Inclui um POP novo em {city} ({price} por um ano).", +"puzzles.it_works_finance_and_the_backhoe":"Funciona! O financeiro e a retroescavadeira querem uma palavrinha.", +"puzzles.keep_building":"Continuar construindo", +"puzzles.kiwi_fruit_salad":"Salada de kiwi", +"puzzles.lease_a_wave_to":"Alugar uma wave até", +"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_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.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.", +"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.", +"puzzles.not_this_one_find_a_way_around":"Essa não. Dê a volta.", +"puzzles.not_through_frankfurt":"Sem passar por Frankfurt", +"puzzles.off_limits":"Proibida", +"puzzles.on_the_house":"Por conta da casa", +"puzzles.one_backhoe_away_from_a_very":"A uma retroescavadeira de uma noite muito longa. Adicione um segundo caminho para ⭐⭐⭐.", +"puzzles.one_cut_splits_it":"Um corte divide a rede", +"puzzles.one_cut_splits_it_where":"Um corte divide a rede: {where}", +"puzzles.one_ring_through_every_pop":"Um anel passando por todos os POPs", +"puzzles.one_very_big_island_and_a":"Uma ilha enorme e muita fibra vazia.", +"puzzles.open_a_pop_cost":"Abrir um POP · {cost}", +"puzzles.pacific_rim_shot":"Pacific Rim Shot", +"puzzles.ping_pong_to_tokyo":"Pingue-pongue até Tóquio", +"puzzles.price_per_year":"{price}/ano", +"puzzles.puzzle":"Puzzle", +"puzzles.puzzle_solved":"Puzzle resolvido", +"puzzles.puzzles":"Puzzles", +"puzzles.remove_this_link":"Remover este link", +"puzzles.remove_this_pop":"Remover este POP", +"puzzles.reset":"Recomeçar", +"puzzles.retry_for_3_stars":"Tentar de novo por ⭐⭐⭐", +"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.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)", +"puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes que a caipirinha esquente.", +"puzzles.sea_to_shining_sea":"De costa a costa", +"puzzles.seattle_to_singapore_with_a_stop":"De Seattle a Singapura, com parada para sushi e dim sum.", +"puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.size":"Tamanho", +"puzzles.small_calm_network_builds":"Redes pequenas, com calma", +"puzzles.smorgasbord":"Smörgåsbord", +"puzzles.speed_runs":"Contra o relógio", +"puzzles.spent_x":"Gasto {x}", +"puzzles.spent_x_of_y":"Gasto {x} / {y}", +"puzzles.stepping_stone_optional":"Escala (opcional)", +"puzzles.suez_you_later":"Suez mais tarde", +"puzzles.survives_any_single_cut":"Sobrevive a qualquer corte", +"puzzles.tap_a_goal_city_to_open":"Toque numa cidade brilhante para abrir seu primeiro POP", +"puzzles.that_city_is_not_part_of":"Essa cidade não faz parte deste puzzle.", +"puzzles.the_pacific_is_big_light_is":"O Pacífico é grande. A luz é rápida. Seu orçamento não é nenhum dos dois.", +"puzzles.the_pacific_rim_where_every_hop":"A borda do Pacífico, onde cada salto é um oceano.", +"puzzles.the_shark_tank":"O aquário dos tubarões", +"puzzles.the_sharks_have_been_biting_again":"Os tubarões voltaram a morder. Fique em terra firme.", +"puzzles.the_sharks_say_no":"Os tubarões dizem não.", +"puzzles.three_cities_two_currencies_one_very":"Três cidades, duas moedas e um túnel bem curtinho debaixo do mar.", +"puzzles.traders_paid_millions_to_shave_milliseconds":"Traders pagaram milhões para tirar milissegundos desta rota. Você faz por menos.", +"puzzles.two_cables_across_the_atlantic_because":"Dois cabos atravessando o Atlântico, porque um só é esperança, não plano.", +"puzzles.under_n_ms":"abaixo de {n} ms", +"puzzles.undo":"Desfazer", +"puzzles.unlocks_at_n_stars":"Abre com {n}⭐", +"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_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"}, "release_notes.read_the_full_notes_on_github":"Leia as notas completas no GitHub", diff --git a/src/game/60-features/90-puzzles-data.js b/src/game/60-features/90-puzzles-data.js new file mode 100644 index 0000000..1d7ede6 --- /dev/null +++ b/src/game/60-features/90-puzzles-data.js @@ -0,0 +1,39 @@ +/* Puzzles: one entry per line, in play order. A puzzle is data: + id, pack, n (name), j (one-line joke), cities (all must end up connected), via (optional stepping stones), + budget (setup + a year of monthly, 0 = no budget star to chase: it is given), and at most a twist or two: + 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:'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}, +]; +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'],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:'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}, +]; +// Weekly puzzle pools: each is one landmass and one region, so every pair has an overland route. +const PZ_WEEK_POOLS=[ + ['fra','ams','par','mad','mil','ber','waw','vie','sto','cph','prg','zrh','bcn','mrs','muc','bud'], + ['nyc','chi','dal','sea','sjc','lax','mia','ash','atn','den','bos','hou','phx','tor','mtl'], + ['sao','rio','bsb','bhz','cwb','poa','ssa','rec','for','cpq'], + ['syd','mel','bne','adl','cbr','per'], + ['bom','del','maa','blr','hyd'], +]; diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js new file mode 100644 index 0000000..bcb34db --- /dev/null +++ b/src/game/60-features/92-puzzles.js @@ -0,0 +1,104 @@ +/* ================= PUZZLES (#190) ================= + Small, calm builds: connect a few cities, earn up to three stars. A puzzle runs as its own S (S.mode='puzzle'): + no clock, no bills, no incidents, links up at once. That S is never saved. Only progress (stars and best spend per + puzzle, weekly results and the weekly streak) is kept, under its own key, so the main save is never touched. */ +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 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; + const rec=r=>r&&typeof r==='object'?{st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)}:null; + if(j.s&&typeof j.s==='object')for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;} + if(j.wk&&typeof j.wk==='object')for(const k of Object.keys(j.wk)){const r=rec(j.wk[k]);if(/^\d{4}-W\d{2}$/.test(k)&&r)o.wk[k]=r;} + const st=j.streak;if(st&&typeof st==='object'){o.streak.last=typeof st.last==='string'&&/^\d{4}-W\d{2}$/.test(st.last)?st.last:null;o.streak.n=int(st.n,0,9999,0);o.streak.best=int(st.best,0,9999,0);} + return o;} +function pzLoad(){try{return pzClean(JSON.parse(localStorage.getItem(PZ_KEY)||'{}'));}catch(e){return pzClean(null);}} +function pzStore(p){try{localStorage.setItem(PZ_KEY,JSON.stringify(p));}catch(e){}} +const pzStarsTotal=p=>PZ.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0); +const pzPackOpen=(k,p)=>{const P=PZ_PACKS.find(x=>x.id===k);return !!P&&pzStarsTotal(p||pzLoad())>=P.need;}; +// ---------- prices: the real game's waves, on day 0, for a year ---------- +const pzMood=(a,b,sub)=>{const k=waveMarket(a,b,sub);return k.m/k.ero;}; +// Overland (when the two cities share a landmass) and every cable between them, each with its price factor and latency. +function pzRoutes(a,b){const out=[],sub=isSub(a,b); + if(!sub){const km=kmBetween(a,b);out.push({via:'land',cab:null,km,sub:false,f:landMult(a,b)*pzMood(a,b,false),ms:km*1.3/200});} + for(const c of cablesFor(a,b))if(!out.some(r=>r.via===c.cid))out.push({via:c.cid,cab:c.cid,km:c.km,sub:true,f:CAB[c.cid].price*pzMood(a,b,true),ms:c.km*(CAB[c.cid].lat||1)/200}); + 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 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); +// ---------- 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;} +function pzRingOk(ls){const nb={};for(const l of ls){(nb[l.a]=nb[l.a]||new Set()).add(l.b);(nb[l.b]=nb[l.b]||new Set()).add(l.a);} + const ns=Object.keys(nb);if(ns.length<3||!S.pz.cities.every(c=>nb[c])||!Object.keys(S.pops).every(c=>nb[c])||!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 cur===ns[0]&&n===ns.length;} +function pzEval(){const P=S.pz,ls=S.links,cs=P.cities,spend=pzSpend(); + // The checklist ticks the goal cities that are already joined up: the group holding the most of them. + let best=new Set();for(const c of cs){if(!S.pops[c]||best.has(c))continue;const g=pzComp(ls,null,c);if(cs.filter(x=>g.has(x)).length>cs.filter(x=>best.has(x)).length)best=g;} + const joined=cs.filter(c=>best.has(c)).length>=2?best:new Set(); + const marks=cs.map(c=>({c,st:joined.has(c)?2:S.pops[c]?1:0})); + const conn=cs.every(c=>joined.has(c)); + const tw=[];if(P.noSub)tw.push({k:'sub',ok:!S.links.some(l=>l.sub)}); + if(P.ring)tw.push({k:'ring',ok:pzRingOk(ls)}); + if(P.lat){const ms=S.pops[P.lat[0]]&&S.pops[P.lat[1]]?bestLat(P.lat[0],P.lat[1]):Infinity;tw.push({k:'lat',ok:ms<=P.lat[2],ms});} + 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. + 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));} +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};} +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 ---------- +// 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;} +function pzBegin(def){if(!def)return; + const go=()=>{newGame(pzName(def),def.cities[0]);S.pops={};S.mode='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'); + 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; + 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();} +// The camera frames the puzzle's cities, leaving room for the puzzle card (left on wide screens, a bottom sheet on phones). +function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity; + for(const C of cs){const x=x0+wrapDx(x0,C.x);a=Math.min(a,x);b=Math.max(b,x);c=Math.min(c,C.y);d=Math.max(d,C.y);} + const ph=isPhone(),pl=ph?0:330,pb=ph?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-pl-90),ah=Math.max(120,CH-pb-150); + cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();} +// ---------- building ---------- +function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links}));if(h.length>60)h.shift();} +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;} +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);} +// The next puzzle in the list whose pack is open. +function pzNextDef(){const p=pzLoad(),i=PZ.findIndex(x=>x.id===S.pz.id);for(let j=i+1;j{v=+v;return Number.isFinite(v)?v:d;},int=(v,lo,hi,d)=>{v=Mat /* Saves come from localStorage or from imported files, so treat them as untrusted: fill in anything missing, drop references to cities, networks or types that do not exist, and force numbers to be numbers. */ function sanitize(s){ + // A puzzle is never saved; a save that says otherwise is played as a normal game. + if(s.mode==='puzzle')s.mode='normal';delete s.pz; const arr=k=>{if(!Array.isArray(s[k]))s[k]=[];},obj=k=>{if(!s[k]||typeof s[k]!=='object'||Array.isArray(s[k]))s[k]={};}; ['links','nni','transit','pni','caches','biz','offers','inc','usedNames','loans','loanOffers','hist','log'].forEach(arr); ['pops','ixp','rs','peers','myIx','done','ev','stats','ixn','ixPref','ixSite','confReg','ach','pairMet'].forEach(obj); diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index daedd0f..6bb11a5 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -1,13 +1,13 @@ /* ================= ACTIONS ================= */ function spend(c){if(S.cash{v=+v;if(![0,0.5,1,2,4,8].includes(v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();}, + speed:({v})=>{v=+v;if(pzOn())return;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();}, + dash:()=>{if(!S||pzOn())return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();}, dashClose:()=>{$('dash').hidden=true;}, dashTab:({k})=>{if(!DTABS.includes(k))return;UI.dtab=k;renderDash();const d=$('dash');if(d)d.scrollTop=0;}, dashSort:({k})=>{if(!['name','asn','type','traffic','cost','lost'].includes(k))return;if(UI.dashSort===k)UI.dashDir=-(UI.dashDir||-1);else{UI.dashSort=k;UI.dashDir=k==='name'||k==='type'||k==='asn'?1:-1;}renderDash();}, - bank:()=>{if(!S)return;UI.confirm=null;$('dash').hidden=true;const b=$('bankBox');b.hidden=false;UI._bh=null;renderBank();}, + bank:()=>{if(!S||pzOn())return;UI.confirm=null;$('dash').hidden=true;const b=$('bankBox');b.hidden=false;UI._bh=null;renderBank();}, bankClose:()=>{UI.confirm=null;$('bankBox').hidden=true;}, takeLoan:({id})=>{const o=S.loanOffers.find(x=>x.id===id);if(!o)return;S.stats.loans=(S.stats.loans||0)+1;const B=BANKS[o.bank];let got=o.amount,note=''; if(B.crypto){const f=0.55+Math.random()*0.8;got=Math.round(o.amount*f);note=' '+(f>=1?tr('interface.tubecoin_moved_up_p_on_the',{p:Math.round(Math.abs(f-1)*100)}):tr('interface.tubecoin_moved_down_p_on_the',{p:Math.round(Math.abs(f-1)*100)}));} @@ -33,8 +33,8 @@ const ACT={ meetGo:({city})=>{if(!isCity(city))return;$('dash').hidden=true;ACT.focusCity({city});if(S.pops[city]){UI.tab='peer';renderPanel();}}, 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();}, - 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();}, + phonePlay:()=>{if(pzOn())return;haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();}, + phoneSpeed:()=>{if(pzOn())return;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;} openModal(pitchHtml(false));}, pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();}, diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 3ec2894..e9a877b 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -13,7 +13,7 @@ Object.assign(ACT,{ exportSave:()=>exportSave(), importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();}, importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;try{S=migrate(JSON.parse(JSON.stringify(s0)));compute();checkGoals();renderAll();}catch(e){S=prev;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;compute();renderAll();save();toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, - menu:()=>{if(!S||!UI.started){showTitle();return;}openModal(`
AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}

${esc(S.name)}

+ menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`
AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}

${esc(S.name)}

${saveFailing()?`

${saveFailMsg()}

`:`

${tr('game_and_settings.your_game_saves_itself_every_few')}

`}${isPhone()?installRow():''} ';} + const l=S.links.find(x=>x.id===sel.id);if(!l)return ''; + let h=head(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`${capName(l)}${l.km.toLocaleString()} km${linkLat(l).toFixed(1)} ms${tr('puzzles.price_per_year',{price:fmt$(l.mo*PZ_YEAR)})}`)+'
'; + h+=`

${tr('puzzles.size')}

${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=subWaveWhy(i,l.km,l.sub);return btn(`${LT[i].n} ${tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
`; + return h+`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} +// The link picker: overland or one of the real cables between the two cities, and a size. Prices are for a year. +function pzLinkModal(a,b,keep){const kb=pzKind(b); + if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.that_city_is_not_part_of'),'bad');sfx('err');return;} + if(!keep){UI.pzVia=null;UI.pzDiv=true;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz; + const head=`
${kmBetween(a,b).toLocaleString()} km

${esc(CITY[a].name)} → ${esc(CITY[b].name)}

`; + if(!rs.length){openModal(head+`

${tr('puzzles.no_cable_lands_in_both_try',{a:esc(CITY[a].name),b:esc(CITY[b].name)})}

`);return;} + const r=rs.find(x=>x.via===UI.pzVia)||rs.find(x=>!(P.noSub&&x.sub))||rs[0];UI.pzVia=r.via; + const land=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b); + let h=head+`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${x.cab&&CAB[x.cab].age==='old'?'':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}
`; + if(P.noSub&&r.sub)h+=`

${tr('puzzles.the_sharks_say_no')}

`; + if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}

`; + if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; + if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; + 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 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(); + 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)}

+ ${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')}
`); + 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; + 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')}
`; + 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); + h+=`
${esc(d.n)} ${pzStarStr(r?r.st:0)}
${esc(d.j)}
${d.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · '+tg.join(' · ')+'':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}
${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}
`;}} + openModal(h);} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index fe22967..de49bd3 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -85,7 +85,7 @@ function drawFrame(now){ // Which cities show an offer bubble (a big one?) or an incident marker, worked out once for all of them. CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; - for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); + if(pzOn())for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); // floaters for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;} for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}} diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js new file mode 100644 index 0000000..3c2a0f0 --- /dev/null +++ b/src/game/96-map/85-puzzle-cities.js @@ -0,0 +1,10 @@ +/* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring, stepping stones with a dashed one, cities to + avoid crossed out); every other city stays on the map, faded and untappable. */ +function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); + if(!k){ctx.save();ctx.globalAlpha=0.3;drawCity(v.C,v.sx,v.sy,sc,now,null);ctx.restore();return;} + const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc),p=S.pops[v.C.id]; + ctx.save();ctx.lineWidth=3; + if(k==='avoid'){ctx.strokeStyle='#FF4D5E';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.moveTo(v.sx-r*.7,y-r*.7);ctx.lineTo(v.sx+r*.7,y+r*.7);ctx.stroke();} + else{const a=animOn()?.55+.35*Math.sin(now/300):.8;ctx.strokeStyle=k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(k==='via')ctx.setLineDash([5,5]); + ctx.fillStyle=k==='goal'&&!p?'rgba(255,210,63,.35)':'rgba(255,255,255,.25)';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.fill();ctx.stroke();ctx.setLineDash([]);} + ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);} diff --git a/src/game/96-map/90-input.js b/src/game/96-map/90-input.js index 7165959..9e9f604 100644 --- a/src/game/96-map/90-input.js +++ b/src/game/96-map/90-input.js @@ -1,5 +1,5 @@ /* ---------- hit tests & input ---------- */ -function hitCity(x,y,r=28){let best=null,bd=r*iconScale();const KS=visibleKs();for(const C of CITIES){if(C.off&&!cityOn(C.id))continue;for(const k of KS){const [sx,sy]=toS(C.x,C.y,k);const d=Math.hypot(sx-x,sy+4-y);if(d{ function endPtr(e){ ptrs.delete(e.pointerId);const d=UI.drag;if(!d)return; if(d.mode==='pinch'){if(ptrs.size===0){UI.drag=null;UI.snap=null;cv.classList.remove('linking');}return;} - if(d.mode==='link'){if(UI.snap&&UI.snap.id!==d.from){openLinkModal(d.from,UI.snap.id);sfx('click');}} + if(d.mode==='link'){if(UI.snap&&UI.snap.id!==d.from){if(pzOn())pzLinkModal(d.from,UI.snap.id);else openLinkModal(d.from,UI.snap.id);sfx('click');}} else if(!d.moved&&S){const h=pickCity(e.clientX,e.clientY); if(h){selectCity(h.id);renderLeft();sfx('click');} else{const l=hitLink(e.clientX,e.clientY);if(l){selectLink(l);sfx('click');}else{UI.sel=null;renderPanel();renderLeft();}}} @@ -38,5 +38,5 @@ cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',canc const ZMIN=0.35,ZMAX=16; function zoomAt(mx,my,f){const wx=cam.x+(mx-CW/2)/cam.z,wy=cam.y+(my-CH/2)/cam.z;cam.z=clamp(cam.z*f,ZMIN,ZMAX);cam.x=wx-(mx-CW/2)/cam.z;cam.y=wy-(my-CH/2)/cam.z;wrapCam();} cv.addEventListener('wheel',e=>{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.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();if(!pzOn()){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();}}}); diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index e486276..0466276 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -1,6 +1,6 @@ /* ---------- click delegation ---------- */ let pressing=false; -document.addEventListener('pointerdown',e=>{if(e.target.closest('#panel,#left,#dash,#bankBox,#modal,#tabbar,#toasts'))pressing=true;}); +document.addEventListener('pointerdown',e=>{if(e.target.closest('#panel,#left,#dash,#bankBox,#modal,#tabbar,#toasts,#pzBox'))pressing=true;}); addEventListener('pointerup',()=>setTimeout(()=>pressing=false,0)); addEventListener('pointercancel',()=>{pressing=false;});addEventListener('blur',()=>{pressing=false;}); document.addEventListener('change',e=>{const el=e.target.closest('[data-chg]');if(!el||(!S&&!['langSet','pickHome'].includes(el.dataset.chg)))return;const fn=ACT[el.dataset.chg];if(fn)fn({v:el.value});}); @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','puzzleMenu','pzStart','pzWeekly'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 7f1b386..84ea6d9 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -8,9 +8,9 @@ function frame(now){ if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save(); // The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them. 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(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){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;}} - if(UI.speed&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ + if((UI.speed||pzOn())&&!(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 008cdfd..5745c4b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2660,6 +2660,122 @@ "progress.under_attack_now":"Under attack now", "progress.your_score_peak_traffic":"Your score: peak traffic", "progress.your_traffic_to_and_from_asia":"Your traffic to and from Asia", +"puzzles.a_backhoe_walks_into_your_network":"A backhoe walks into your network. Nothing happens.", +"puzzles.a_pop_costs_setup_plus_a_year":"A POP costs {setup} to set up, then {mo}/mo. Puzzles count the setup and a year of rent.", +"puzzles.a_tiny_island_where_half_the":"A tiny island where half the Pacific's cables stop for coffee.", +"puzzles.a_to_b_under_ms":"{a} → {b} under {ms} ms", +"puzzles.a_to_b_under_ms_now":"{a} → {b} under {ms} ms (now {now} ms)", +"puzzles.aloha_latency":"Aloha Latency", +"puzzles.avoid_list":"avoid {list}", +"puzzles.back_to_my_network":"Back to my network", +"puzzles.back_to_the_title":"Back to the title screen", +"puzzles.beat_the_clock_light_in_glass":"Light in glass does 200 km per millisecond. Pick your cables like it matters.", +"puzzles.belt_and_braces":"Belt and Braces", +"puzzles.best_x":"best {x}", +"puzzles.budget":"Budget", +"puzzles.budget_x":"budget {x}", +"puzzles.connect_list":"Connect {list}.", +"puzzles.connected":"Connected", +"puzzles.copied_paste_it_anywhere":"Copied! Paste it anywhere:
{t}", +"puzzles.de_kicks_sales_has_your_number":"DE-KICKS sales has your number. Connect Germany without Frankfurt.", +"puzzles.diverse_route_40_survives_a_backhoe":"Diverse route (+40%, survives a backhoe)", +"puzzles.down_under_up_and_running":"Down Under, Up and Running", +"puzzles.drag_from_a_pink_pop_to":"Drag from a pink POP to another city to lease a wave", +"puzzles.drag_from_this_pop_onto_another":"Drag from this POP onto another puzzle city, or pick one here.", +"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.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.", +"puzzles.four_capitals_one_very_long_winter":"Four capitals, one very long winter, zero excuses for downtime.", +"puzzles.four_cities_four_cables_one_ring":"Four cities, one ring. Tolkien would approve; your NOC definitely does.", +"puzzles.four_cities_one_continent_and_a":"Four cities, one continent and a lot of corn between them.", +"puzzles.frankfurt_to_singapore_the_short_way":"Frankfurt to Singapore the short way. The long way is overland, and it shows.", +"puzzles.free":"Free", +"puzzles.goal":"Goal", +"puzzles.goal_city":"Goal city", +"puzzles.guam_slam":"Guam Slam", +"puzzles.hello_world":"Hello, World", +"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: the world's most scenic regeneration site.", +"puzzles.includes_a_new_pop_in_city":"Includes a new POP in {city} ({price} for a year).", +"puzzles.it_works_finance_and_the_backhoe":"It works! Finance and the backhoe would like a word.", +"puzzles.keep_building":"Keep building", +"puzzles.kiwi_fruit_salad":"Kiwi Fruit Salad", +"puzzles.lease_a_wave_to":"Lease a wave to", +"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_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.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.", +"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.", +"puzzles.not_this_one_find_a_way_around":"Not this one. Find a way around.", +"puzzles.not_through_frankfurt":"Not Through Frankfurt", +"puzzles.off_limits":"Off limits", +"puzzles.on_the_house":"On the house", +"puzzles.one_backhoe_away_from_a_very":"One backhoe away from a very long night. Add a second path for ⭐⭐⭐.", +"puzzles.one_cut_splits_it":"One cut splits it", +"puzzles.one_cut_splits_it_where":"One cut splits it: {where}", +"puzzles.one_ring_through_every_pop":"One ring through every POP", +"puzzles.one_very_big_island_and_a":"One very big island, and a lot of very empty fiber.", +"puzzles.open_a_pop_cost":"Open a POP · {cost}", +"puzzles.pacific_rim_shot":"Pacific Rim Shot", +"puzzles.ping_pong_to_tokyo":"Ping Pong to Tokyo", +"puzzles.price_per_year":"{price}/yr", +"puzzles.puzzle":"Puzzle", +"puzzles.puzzle_solved":"Puzzle solved", +"puzzles.puzzles":"Puzzles", +"puzzles.remove_this_link":"Remove this link", +"puzzles.remove_this_pop":"Remove this POP", +"puzzles.reset":"Reset", +"puzzles.retry_for_3_stars":"Retry for ⭐⭐⭐", +"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.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)", +"puzzles.sao_paulo_to_miami_before_the":"São Paulo to Miami before the caipirinha gets warm.", +"puzzles.sea_to_shining_sea":"Sea to Shining Sea", +"puzzles.seattle_to_singapore_with_a_stop":"Seattle to Singapore, with a stop for sushi and dim sum.", +"puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.size":"Size", +"puzzles.small_calm_network_builds":"Small, calm network builds", +"puzzles.smorgasbord":"Smörgåsbord", +"puzzles.speed_runs":"Speed Runs", +"puzzles.spent_x":"Spent {x}", +"puzzles.spent_x_of_y":"Spent {x} / {y}", +"puzzles.stepping_stone_optional":"Stepping stone (optional)", +"puzzles.suez_you_later":"Suez You Later", +"puzzles.survives_any_single_cut":"Survives any single cut", +"puzzles.tap_a_goal_city_to_open":"Tap a glowing city to open your first POP", +"puzzles.that_city_is_not_part_of":"That city is not part of this puzzle.", +"puzzles.the_pacific_is_big_light_is":"The Pacific is big. Light is fast. Your budget is neither.", +"puzzles.the_pacific_rim_where_every_hop":"The Pacific rim, where every hop is an ocean.", +"puzzles.the_shark_tank":"The Shark Tank", +"puzzles.the_sharks_have_been_biting_again":"The sharks have been biting again. Keep it on dry land.", +"puzzles.the_sharks_say_no":"The sharks say no.", +"puzzles.three_cities_two_currencies_one_very":"Three cities, two currencies, one very short tunnel under the sea.", +"puzzles.traders_paid_millions_to_shave_milliseconds":"Traders paid millions to shave milliseconds off this route. You get to do it for less.", +"puzzles.two_cables_across_the_atlantic_because":"Two cables across the Atlantic, because one is a hope, not a plan.", +"puzzles.under_n_ms":"under {n} ms", +"puzzles.undo":"Undo", +"puzzles.unlocks_at_n_stars":"Unlocks at {n}⭐", +"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_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"}, "release_notes.read_the_full_notes_on_github":"Read the full notes on GitHub", diff --git a/src/index.html b/src/index.html index 2f8bfa9..4b97816 100644 --- a/src/index.html +++ b/src/index.html @@ -143,6 +143,7 @@
+
diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css new file mode 100644 index 0000000..2b152d7 --- /dev/null +++ b/src/styles/70-puzzles.css @@ -0,0 +1,39 @@ +/* Puzzles (#190): one card for the goal, the stars and the budget; on phones a bottom sheet you can shrink. */ +body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteBtn),body.pz #leftToggle,body.pz #left{display:none !important} +#pzBox{position:fixed;top:calc(env(safe-area-inset-top,0px) + 76px);left:max(12px,env(safe-area-inset-left,0px));width:300px;max-height:calc(100% - 96px - env(safe-area-inset-top,0px));overflow:auto;z-index:4;padding:10px 14px 12px;box-sizing:border-box} +#pzBox .pzh{display:flex;align-items:center;gap:8px}#pzBox h3{font-size:19px} +.pzj{margin:4px 0 6px;font-size:12.5px;color:var(--ink2);line-height:1.35} +.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.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)} +.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)} +@keyframes pzglow{50%{box-shadow:0 0 0 4px rgba(34,196,122,.25)}} +#pzBox .btns{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} +#pzBox .grab{display:none} +.pzprog{margin:6px 0 4px}.pzpack{font-size:17px;margin:14px 0 2px}.pzst{font-size:12px;letter-spacing:-1px;white-space:nowrap} +.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} +.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} +.pzconf i{position:absolute;top:-12px;left:var(--x);width:8px;height:12px;background:var(--c);border:1.5px solid var(--ink);border-radius:2px;animation:pzfall var(--t) ease-in var(--dl) both} +@keyframes pzfall{0%{transform:translateY(0) rotate(0);opacity:1}100%{transform:translateY(420px) rotate(var(--r));opacity:0}} +@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.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} + body.pz #panel{bottom:0 !important} + body.pz #hint{bottom:calc(min(46%,330px) + 8px) !important} + .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} + body.pz #hint{bottom:12px !important;left:30% !important} +} diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js new file mode 100644 index 0000000..c3338c1 --- /dev/null +++ b/tests/puzzles.test.js @@ -0,0 +1,255 @@ +// Puzzle mode (#190): small builds with stars, no clock, and a main save that is never touched. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Reference solutions: [a, b, route ('land' or a cable id), tier (0 = 10G, 1 = 100G)]. +// `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']] }, + 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']] }, + 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']] }, + 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]] }, +}; + +// Builds links the way a player does: POP at the first city, then the link picker for each hop. +function build(ev, links) { + for (const [a, b, via, tier] of links) { + if (!ev(`!!S.pops['${a}']`)) ev(`ACT.pzPop({city:'${a}'})`); + ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:${tier || 0}})`); + } + ev('closeModal()'); +} +const evalP = (ev) => JSON.parse(ev('JSON.stringify(pzEval())')); + +test('puzzle data: every puzzle is valid, solvable, and its 3-star reference earns three stars', () => { + const { ev, errors } = load(); + const ids = JSON.parse(ev('JSON.stringify(PZ.map(p=>p.id))')); + assert.ok(ids.length >= 16, 'at least 16 puzzles'); + assert.equal(new Set(ids).size, ids.length, 'ids are unique'); + assert.deepEqual(Object.keys(REF).sort(), ids.slice().sort(), 'every puzzle has a reference solution'); + assert.ok(ev("PZ.every(p=>PZ_PACKS.some(k=>k.id===p.pack)&&p.n&&p.j&&p.cities.length>=2&&p.cities.length<=6&&[...p.cities,...(p.via||[]),...(p.avoid||[])].every(c=>isCity(c)&&!CITY[c].off&&!CITY[c].cn))"), 'cities exist and are playable'); + assert.ok(ev("PZ.every(p=>!p.budget||(p.budget>=100000&&p.budget<=5e6))"), 'budgets are sane'); + assert.ok(ev("PZ_PACKS[0].need===0&&PZ_PACKS.every((k,i)=>!i||k.need>PZ_PACKS[i-1].need)"), 'packs unlock in order'); + assert.ok(ev("PZ.filter(p=>p.pack==='hello'&&!p.budget).length>=2"), 'the first puzzles give the budget star away'); + for (const id of ids) { + ev(`pzBegin(pzDef('${id}'))`); + build(ev, REF[id].one); + let e = evalP(ev); + assert.ok(e.goal, `${id}: the one-star reference reaches the goal`); + assert.ok(e.stars >= 1, `${id}: one star`); + ev('ACT.pzReset({})'); + assert.equal(evalP(ev).stars, 0, `${id}: reset clears it`); + build(ev, REF[id].three); + e = evalP(ev); + assert.equal(e.stars, 3, `${id}: three stars (spend ${e.spend} of ${ev('S.pz.budget')}, n1 ${e.n1}, twists ${JSON.stringify(e.tw)})`); + } + assert.deepEqual(errors, []); +}); + +test('stars: goal, budget, N-1 and twists each count', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('braces'))"); + build(ev, REF.braces.one); + let e = evalP(ev); + assert.equal(e.stars, 2, 'connected and under budget, but one cut splits it'); + assert.ok(!e.n1 && e.weak.length > 0); + build(ev, [['dub', 'nyc', 'havf']]); + assert.equal(evalP(ev).stars, 3); + ev('S.pz.budget=1000'); + assert.equal(evalP(ev).stars, 2, 'over budget loses the second star'); + // Two waves in the same trench are one backhoe away from nothing. + ev("pzBegin(pzDef('shining'))"); + 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'); + // Twists: no subsea, ring, latency, minimum size, cities to avoid. + ev("pzBegin(pzDef('sharks'))");build(ev, REF.sharks.one); + assert.ok(evalP(ev).goal); + ev("pzBegin(pzDef('fire'))");build(ev, REF.fire.one);ev("ACT.pzRmLink({id:S.links[3].id})"); + e = evalP(ev); + assert.ok(e.conn && !e.goal, 'a line is not a ring'); + ev('ACT.pzUndo({})'); + assert.ok(evalP(ev).goal, 'undo puts the ring back'); + ev("pzBegin(pzDef('flash'))");build(ev, [['nyc', 'lon', 'grace']]); + e = evalP(ev); + assert.ok(e.conn && !e.goal, 'Grace Hopscotch is too slow for the traders'); + ev("pzBegin(pzDef('fatpipes'))");build(ev, REF.fatpipes.one.map(([a, b, v]) => [a, b, v, 0])); + assert.ok(!evalP(ev).goal, '10G is too thin'); + ev("ACT.pzTier({id:S.links[0].id,tier:1});ACT.pzTier({id:S.links[1].id,tier:1});ACT.pzTier({id:S.links[2].id,tier:1})"); + assert.ok(evalP(ev).goal, 'upgraded in place'); + ev("pzBegin(pzDef('nofra'))"); + ev("ACT.pzPop({city:'fra'})"); + assert.equal(ev("!!S.pops.fra"), false, 'no POP in a city to avoid'); + assert.equal(ev("pzKind('lon')"), null, 'cities outside the puzzle are inert'); + ev("ACT.pzPop({city:'lon'})"); + assert.equal(ev("Object.keys(S.pops).length"), 0); + // Subsea is greyed out in the shark tank. + ev("pzBegin(pzDef('sharks'));ACT.pzPop({city:'lis'});ACT.pzLinkTo({a:'lis',b:'bcn'});ACT.pzVia({v:'medusa'});ACT.pzLink({tier:0})"); + assert.equal(ev('S.links.length'), 0); + assert.deepEqual(errors, []); +}); + +test('no clock in a puzzle: days never pass, nothing breaks, no bills', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('hello'))"); + build(ev, REF.hello.three); + ev('ACT.speed({v:8});ACT.phonePlay({});for(let i=0;i<50;i++)frame(performance.now()+i*3000)'); + assert.equal(ev('S.day'), 0); + assert.equal(ev('UI.speed'), 0); + assert.equal(ev('S.inc.length'), 0); + assert.equal(ev('S.cash'), ev('START_CASH'), 'nothing is charged'); + assert.equal(ev("document.getElementById('left').hidden"), true, 'no goals/deals/NOC/networks drawer'); + assert.equal(ev("document.getElementById('pzBox').hidden"), false); + assert.deepEqual(errors, []); +}); + +test('the main save is byte-identical before and after playing and solving 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)"); + const before = ev("localStorage.getItem('sot-save-v1')"); + const name = ev('S.name'), day = ev('S.day'); + ev('ACT.puzzleMenu({})'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Hello, World/); + ev("ACT.pzStart({id:'hello'})"); + assert.equal(ev('S.mode'), 'puzzle'); + build(ev, REF.hello.three); + ev("save(true);for(let i=0;i<5;i++)frame(performance.now()+6000*i);window.dispatchEvent(new Event('pagehide'));ACT.exportSave({})"); + assert.equal(ev("localStorage.getItem('sot-save-v1')"), before, 'untouched while in the puzzle'); + assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).s.hello.st"), 3, 'the stars are kept'); + ev('ACT.pzLeave({})'); + assert.equal(ev('S.mode'), 'normal'); + assert.equal(ev('S.name'), name); + assert.equal(ev('S.day'), day); + assert.ok(ev('!!S.pops.ams')); + assert.equal(ev('UI.started'), true); + assert.equal(ev("localStorage.getItem('sot-save-v1')"), before, 'and after'); + assert.deepEqual(errors, []); +}); + +test('leaving a puzzle with no game goes back to the title screen', () => { + const { ev, errors } = load(); + assert.ok(ev("!!document.querySelector('#modalCard [data-act=puzzleMenu]')"), 'the title screen has a way in'); + ev("document.querySelector('#modalCard [data-act=puzzleMenu]').click()"); + ev("document.querySelector('#modalCard [data-act=pzStart]').click()"); + assert.equal(ev('S.mode'), 'puzzle'); + ev('ACT.pzLeave({})'); + assert.equal(ev('S'), null); + assert.equal(ev("localStorage.getItem('sot-save-v1')"), null, 'no main save appeared'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Series/); + assert.deepEqual(errors, []); +}); + +test('results card pops the stars, offers the next puzzle, a retry and a share line', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('eurotrip'))"); + build(ev, REF.eurotrip.one); + let card = ev("document.getElementById('modalCard').textContent"); + assert.match(card, /Puzzle solved/); + assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')")); + assert.match(ev("document.querySelector('#modalCard [data-act=pzStart]').dataset.args"), /shining/); + build(ev, [['lon', 'ams', 'concerto'], ['ams', 'fra', 'land']]); + card = ev("document.getElementById('modalCard').textContent"); + assert.match(card, /A backhoe walks into your network/); + assert.equal(ev("document.querySelectorAll('#modalCard .pzbig.on').length"), 3); + const line = ev('pzShareText(pzEval())'); + assert.match(line, /^Series of Tubes puzzle Euro Trip ⭐⭐⭐ \$\d+k · seriesoftub\.es$/); + assert.deepEqual(errors, []); +}); + +test('weekly puzzle: stable seed per ISO week, solvable, share string and streak', () => { + const { ev, errors } = load(); + const a = ev("JSON.stringify(pzWeekly(new Date(2026,9,28)))"), b = ev("JSON.stringify(pzWeekly(new Date(2026,10,1)))"), c = ev("JSON.stringify(pzWeekly(new Date(2026,10,2)))"); + assert.equal(a, b, 'same week, same puzzle'); + assert.notEqual(a, c, 'next week, a new one'); + const w = JSON.parse(a); + 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) { + 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); + 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`)]; })); + 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. + ev("const p=pzLoad();pzStreak(p,'2026-W45');pzStreak(p,'2026-W45');pzStreak(p,'2026-W46');window.__p=p"); + assert.equal(ev('__p.streak.n'), 3); + ev("pzStreak(__p,'2026-W49')"); + assert.equal(ev('__p.streak.n'), 1); + assert.equal(ev('__p.streak.best'), 3); + assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53'); + assert.equal(ev("pzPrevKey('2026-W01')"), '2025-W52'); + assert.deepEqual(errors, []); +}); + +test('pack unlocking follows the stars, and bad progress data is ignored', () => { + const { ev, errors } = load(); + ev("localStorage.removeItem('sot-puzzles')"); + assert.equal(ev("pzPackOpen('hello')"), true); + assert.equal(ev("pzPackOpen('fire')"), false); + ev("ACT.pzStart({id:'aloha'})"); + assert.notEqual(ev('S&&S.mode'), 'puzzle', 'a locked puzzle does not start'); + ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:3},eurotrip:{st:3}}}))"); + assert.equal(ev("pzPackOpen('fire')"), true, '6 stars open pack 2'); + ev('ACT.puzzleMenu({})'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Next pack, Speed Runs, unlocks at 14/); + ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:99,sp:'x'},nope:{st:3},__proto__:{st:3}},wk:{bad:{st:3}},streak:{n:-4,last:''}}))"); + const p = JSON.parse(ev('JSON.stringify(pzLoad())')); + assert.deepEqual(p.s, { hello: { st: 3, sp: null } }); + assert.deepEqual(p.wk, {}); + assert.deepEqual(p.streak, { last: null, n: 0, best: 0 }); + ev("localStorage.setItem('sot-puzzles','{nope')"); + assert.equal(ev('pzStarsTotal(pzLoad())'), 0); + assert.deepEqual(errors, []); +}); + +test('puzzle HUD fits a 360 px phone: bottom sheet, no tab bar, panels work', () => { + const { dom, ev, errors } = load(); + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'))"); + ev("pzBegin(pzDef('hello'))"); + assert.equal(ev("document.getElementById('tabbar').hidden"), true); + assert.equal(ev("document.getElementById('pzBox').hidden"), false); + ev("selectCity('lon')"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Open a POP/); + ev("document.querySelector('#panelBody [data-act=pzPop]').click()"); + assert.ok(ev('!!S.pops.lon')); + ev("selectCity('par')"); + assert.equal(ev("document.getElementById('panel').hidden"), true, 'other cities do nothing'); + ev("pzLinkModal('lon','nyc')"); + assert.ok(ev("document.querySelectorAll('#modalCard .tierbtn').length") === 3, 'three sizes'); + assert.deepEqual(errors, []); + void dom; +}); + +test('puzzles in every language', () => { + for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { + const { ev, errors } = load({ lang }); + ev("ACT.puzzleMenu({});pzBegin(pzDef('braces'))"); + build(ev, REF.braces.three); + const seen = ev("['pzBox','modalCard','hud'].map(id=>document.getElementById(id).textContent).join(' ')"); + assert.ok(!/puzzles\./.test(seen), `${lang}: no raw labels`); + assert.match(seen, /⭐/); + assert.deepEqual(errors, [], lang); + } +}); From 78100bd158caa64f834a06ac0dd16ce09eb43300 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 16:24:06 +0100 Subject: [PATCH 018/181] Puzzles: landscape framing, toasts beside the card, CHANGELOG (#190) --- CHANGELOG.md | 1 + src/game/60-features/92-puzzles.js | 4 ++-- src/styles/70-puzzles.css | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aa39a98..8bb6014 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- 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. - 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/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index bcb34db..05abb4c 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -86,10 +86,10 @@ function pzLeave(){const from=UI.pzFrom;document.body.classList.remove('pz');UI. 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();} -// The camera frames the puzzle's cities, leaving room for the puzzle card (left on wide screens, a bottom sheet on phones). +// The camera frames the puzzle's cities beside the puzzle card: left on wide screens, right on phones on their side, a bottom sheet on phones. function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity; for(const C of cs){const x=x0+wrapDx(x0,C.x);a=Math.min(a,x);b=Math.max(b,x);c=Math.min(c,C.y);d=Math.max(d,C.y);} - const ph=isPhone(),pl=ph?0:330,pb=ph?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-pl-90),ah=Math.max(120,CH-pb-150); + const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();} // ---------- building ---------- function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links}));if(h.length>60)h.shift();} diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index 2b152d7..20fa6b1 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -36,4 +36,5 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB @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} body.pz #hint{bottom:12px !important;left:30% !important} + body.pz #toasts{left:8px !important;transform:none !important;width:calc(48% - 16px) !important} } From 6489db146eeda45dae0410453b06cbc8a172dd1b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 16:54:19 +0100 Subject: [PATCH 019/181] Tier 1 by customer cone (#85), and badge variants per ruleset preset Cones: a PNI or IX session reaches the peer and its transitive customer cone, precomputed once at load (CONE/CONE_S/DOWN/ANC). Cone routes rank after direct peering and before transit (CONE_RANK 2.5), so peering widely still pays. The long tail and several real eyeballs get real-world upstreams. Cones only add reach, so the rule is easier for every save and needs no version flag. Badges: S.achP[id] records the preset variant (freeze/oncall/bgp), sanitized, default 'oncall' for old saves; the device hall of fame records every variant earned. Harder presets upgrade a badge; toast, list, collection shelf and the share card show it. Sandbox and puzzles earn none. --- CHANGELOG.md | 2 + site/i18n/de.js | 18 ++- site/i18n/es.js | 18 ++- site/i18n/fr.js | 18 ++- site/i18n/it.js | 18 ++- site/i18n/pt.js | 18 ++- src/game/30-networks/10-networks.js | 14 +- src/game/30-networks/30-long-tail.js | 15 ++- src/game/30-networks/40-traffic-shares.js | 20 ++- src/game/40-progress/20-goals.js | 2 +- src/game/50-state.js | 2 +- src/game/60-features/50-traceroute.js | 10 +- src/game/60-features/60-share-card.js | 5 +- src/game/60-features/80-new-game.js | 2 +- src/game/70-rules/80-hot-ports-and-rank.js | 5 +- src/game/80-simulation/30-compute.js | 24 ++-- src/game/80-simulation/50-sanitize.js | 3 + src/game/88-days/20-badges.js | 35 +++-- src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/70-link-panels.js | 2 + src/game/94-dashboard/20-meet-a-network.js | 2 + src/game/95-modals/60-help.js | 2 +- src/i18n/en.js | 18 ++- src/styles/40-modal.css | 11 ++ tests/badges-variants.test.js | 137 +++++++++++++++++++ tests/helpers/reference-allocation.js | 2 +- tests/tier1-cone.test.js | 148 +++++++++++++++++++++ 27 files changed, 493 insertions(+), 60 deletions(-) create mode 100644 tests/badges-variants.test.js create mode 100644 tests/tier1-cone.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index aa39a98..1f7477c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- 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. - 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/site/i18n/de.js b/site/i18n/de.js index 0b751b2..cb85986 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -19,6 +19,7 @@ "badges.attend_a_conference":"Besuche eine Konferenz.", "badges.attend_six_conferences_in_one_game":"Besuche sechs Konferenzen in einem Spiel.", "badges.badge_unlocked_name":"Abzeichen freigeschaltet: {name}", +"badges.badge_upgraded_name":"Abzeichen aufgewertet: {name}", "badges.blackhole_one_of_your_own_cities":"Blackhole eine deiner eigenen Städte, um einen DDoS zu stoppen.", "badges.bring_up_your_first_peering_session":"Bring deine erste Peering-Session hoch.", "badges.build_fiber_across_the_andes":"Verlege Glasfaser über die Anden.", @@ -100,9 +101,14 @@ "badges.take_a_de_kicks_retention_offer":"Nimm ein Halteangebot von DE-KICKS an.", "badges.take_out_a_loan":"Nimm einen Kredit auf.", "badges.the_long_way_round":"Der lange Weg außenrum", +"badges.this_game_earns_fiery_badges":"Dieses Spiel läuft auf BGP um 3 Uhr nachts: Jedes Abzeichen hier wird im Feuer geschmiedet und wertet eins auf, das du schon hast.", +"badges.this_game_earns_frosted_badges":"Dieses Spiel läuft im Change Freeze: Abzeichen von hier gibt es gefriergetrocknet.", "badges.through_the_wall":"Durch die Mauer", "badges.turn_on_a_transit_clean_pipe":"Schalte bei einem Transit eine Clean-Pipe-Option dazu.", "badges.two_buildings_three_cities":"Zwei Gebäude, drei Städte", +"badges.variant_forged_at_3_a_m":"Um 3 Uhr geschmiedet", +"badges.variant_freeze_dried":"Gefriergetrocknet", +"badges.variant_on_call":"Rufbereitschaft", "badges.weather_a_ddos_with_your_defences":"Überstehe einen DDoS mit einsatzbereiter Abwehr.", "badges.weather_a_multi_terabit_ddos":"Überstehe einen DDoS im Multi-Terabit-Bereich.", "badges.win_without_ever_taking_a_loan":"Gewinne, ohne je einen Kredit aufzunehmen.", @@ -1829,7 +1835,7 @@ "goals.make_5_peering_friends":"Finde 5 Peering-Freunde", "goals.on_the_peering_tab_request_sessions":"Frag im Tab Peering Sessions an oder tritt dem Route Server bei, um mit jedem offenen Netz auf einmal zu peeren.", "goals.open_your_home_city_and_press":"Öffne deine Heimatstadt und drück auf „Breitband starten“. Privatkunden sind Leute zu Hause, die Katzenvideos schauen. Sie zahlen dir jeden Monat.", -"goals.peer_with_every_tier_1_over":"Peere mit jedem Tier 1 über PNIs und kündige jeden Transit-Port. Dann verlangt niemand mehr Geld dafür, dass du das Internet erreichst.", +"goals.peer_with_every_tier_1_their_customers":"Peere mit jedem Tier 1 über PNIs und kündige jeden Transit-Port. Ihre Kunden kommen gratis mit, du jagst also nur Netze, denen niemand Transit verkauft.", "goals.pops_in_five_of_the_six":"POPs in fünf der sechs Regionen der Karte.", "goals.reach_the_whole_internet":"Erreiche das ganze Internet", "goals.serve_10_tbps":"Liefere 10 Tbps aus", @@ -1891,7 +1897,7 @@ "help.the_chart_button_at_the_top":"Der Diagramm-Knopf oben öffnet Traffic-Graphen nach Ausgang (Caches, PNIs, IX, Transit), Geld über die Zeit, Traffic pro ASN, wie er dich erreicht und was sein Transit kostet, sowie deine meistgenutzten Links und Router.", "help.the_group_behind_several_big":"Die Gruppe hinter mehreren großen Exchanges (Frankfurt, Madrid, Marseille, Dubai, Mumbai, New York) behandelt Preislisten wie ein Staatsgeheimnis. Ports werden pro Kunde angeboten und werden teurer, je größer du aussiehst. Feilschen kann klappen, nach hinten losgehen oder eine Woche hängen. Einmal im Jahr werden die Preise nach oben „harmonisiert“, Zusatzleistungen landen auf deiner Rechnung, bis du sie abbestellst, und wer gehen will, bekommt einen Halterabatt, der mit einer Gebühr endet.", "help.things_break_all_the_time_fiber":"Ständig geht was kaputt: Faserbrüche, Router-Abstürze, Stromausfälle, IX-Schleifen, Fabric-Ausfälle, Route Leaks, DDoS, Vertipper, Kühlungsausfälle und Geopolitik: Sanktionen, Zölle, BGP-Hijacks, Streit um Anlandegenehmigungen, Shutdowns an Prüfungstagen und Kabelschnitte im Roten Meer. Traffic wird automatisch über andere Pfade und Upstreams umgeleitet. Parallele Links auf redundanten Routen, ein zweiter Router und ein Notstromgenerator helfen alle. Oder bezahl für Express-Reparaturen.", -"help.tier_1s_reach_the_whole_internet":"Tier 1s erreichen das ganze Internet, ohne jemanden zu bezahlen, weil sie alle miteinander peeren. Tier 2s peeren viel, kaufen aber noch etwas Transit.", +"help.tier_1s_reach_the_whole_internet_cones":"Tier 1s erreichen das ganze Internet, ohne jemanden zu bezahlen: Sie peeren alle miteinander, und jeder bringt seinen Customer Cone mit, alle, die bei ihm Transit kaufen. Tier 2s peeren viel, kaufen aber noch etwas Transit.", "help.traffic_follows_the_shortest_path_by":"Traffic folgt dem kürzesten Pfad nach Entfernung und Link-Metrik und wird von selbst umgeleitet, wenn Links ausfallen. Ist ein Pfad nur voll, wird der Überlauf verworfen, genau wie bei einem echten IGP. Ab Kundenlevel 3 kannst du im Tab NOC Auto-TE installieren: Es leitet den Überlauf auf bis zu zwei Ausweichpfade mit freier Kapazität um, solange sie höchstens doppelt so lang sind.", "help.transit_bills_sample_your_usage":"Transit-Rechnungen messen deine Nutzung jeden Tag und berechnen das 95. Perzentil der letzten 30 Tage, also werden kurze Spitzen verziehen, lange aber nicht.", "help.users_feel_the_round_trip_to":"Nutzer spüren die Round-Trip-Zeit bis dorthin, wo ihr Traffic dein Netz in Richtung Transit verlässt. Bis 20 ms (etwa 1.500 km) ist okay; über 50 ms zählen Breitband und Internetdienste als schlechter Service, was Umsatz und Kunden kostet. Traffic über dein eigenes Peering, PNIs und Caches wird nicht bestraft.", @@ -1916,12 +1922,13 @@ "hot_ports_and_rank.upgrade_the_ix_port_or_add":"Rüste den IX-Port auf oder füg ein LAG-Mitglied hinzu.", "hot_ports_and_rank.upgrade_the_router_or_add_a":"Rüste den Router auf oder füg im Tab Infra einen zweiten hinzu.", "hot_ports_and_rank.you_buy_transit_again":"du kaufst wieder Transit", -"hot_ports_and_rank.you_cannot_reach_list":"du erreichst {list} nicht", +"hot_ports_and_rank.you_cannot_reach_list_outside_cones":"du erreichst {list} nicht, und keiner deiner Peers verkauft dorthin Transit", "hot_ports_and_rank.your_reach_is_p_not_100":"deine Erreichbarkeit ist {p}, nicht 100 %", "hud_and_panels.all_connections_n":"Alle Verbindungen {n}", "hud_and_panels.all_systems_green_enjoy_it_while":"Alle Systeme grün. Genieß es, solange es anhält.", "hud_and_panels.auto_fix_in_n_day":{"one":"Auto-Fix in {n} Tag","other":"Auto-Fix in {n} Tagen"}, "hud_and_panels.blackholing_g":"Blackholing {g}", +"hud_and_panels.buys_transit_from_net_peer_with":"Kauft Transit bei {net}. Peere mit {net}, dann kommt es mit.", "hud_and_panels.customer_level_lv_name":"Kundenlevel {lv}: {name}", "hud_and_panels.dropping_or_overflowing":"verwirft oder läuft über", "hud_and_panels.every_network_on_the_map_traffic":"Jedes Netz auf der Karte. Der Traffic-Anteil ist, wie viel vom Traffic deiner Nutzer zu ihnen geht. Tippe auf eine Verbindung, um zu ihrem POP zu springen.", @@ -1958,6 +1965,7 @@ "hud_and_panels.p_of_traffic_between_them_scattered":"{p} % des Traffics zusammen, verstreut über die Exchanges. Du peerst mit {n}.", "hud_and_panels.ports_caches_and_routers_running_hot":"Ports, Caches und Router, die heißlaufen", "hud_and_panels.raise_a_full_link_s_metric":"Erhöhe die Metrik eines vollen Links, damit der Traffic einen anderen Pfad bevorzugt, rüste ihn auf oder installiere Auto-TE.", +"hud_and_panels.reached_through_the_customer_cone_of":"Erreicht über den Customer Cone von {net}: Es kauft dort Transit.", "hud_and_panels.reaches_networks_from_the_last":"Erreicht kostenlos Netze aus dem letzten Update, zu denen du keinen anderen Pfad hast. Verbinde dich mit ihnen, bevor es endet.", "hud_and_panels.reward_cash":"Belohnung {cash}", "hud_and_panels.survived_with_no_impact":"Ohne Auswirkungen überstanden", @@ -2349,6 +2357,8 @@ "loop.welcome_back_name_your_network_is":"Willkommen zurück, {name}.
Dein Netz ist genau da, wo du es gelassen hast: {date}.", "loop.your_saved_game_could_not_be":"Dein Spielstand konnte nicht geladen werden.
Er war beschädigt, also wurde ein Backup aufbewahrt, und du kannst neu anfangen.", "meet_a_network.all_n_out_of_reach":{"one":"Alle {n} außer Reichweite","other":"Alle {n} außer Reichweite"}, +"meet_a_network.peer_with_the_tier_1_club":"Peere mit dem Tier-1-Club: Ihre Kunden kommen gratis mit. Nur Netze, die in niemandes Customer Cone sind, brauchen eigenes Peering.", +"meet_a_network.peer_with_the_tier_1_club_n":{"one":"Peere mit dem Tier-1-Club: Ihre Kunden kommen gratis mit. {n} Netz kommt schon mit einem Peer mit.","other":"Peere mit dem Tier-1-Club: Ihre Kunden kommen gratis mit. {n} Netze kommen schon mit einem Peer mit."}, "meet_a_network.pnis_with_every_tier_1":"PNIs mit jedem Tier 1", "meet_a_network.reach_without_transit":"Erreichbarkeit ohne Transit", "meet_a_network.road_to_tier_1":"Weg zu Tier 1", @@ -3036,6 +3046,7 @@ "title.scenarios_amp_weekly_challenge":"Szenarien & Wochen-Challenge →", "title.source_on_github":"Quellcode auf GitHub", "title.your_network_name_was_saved_and":"Dein Netz {name} wurde gespeichert und wartet auf dich.", +"traceroute.a_peer_s_customers_come_after":"die Kunden eines Peers kommen nach direkten Peers und vor Transit", "traceroute.across_the_ix_switch":"über den Switch des {ix}", "traceroute.as_path_path":"AS-Pfad: {path}", "traceroute.caches_beat_pnis":"Caches schlagen PNIs", @@ -3051,6 +3062,7 @@ "traceroute.n_network_unreachable":"!N Netz nicht erreichbar", "traceroute.name_transit":"Transit von {name}", "traceroute.net_carries_it_to_city":"{net} bringt es nach {city}", +"traceroute.net_hands_it_to_its_customer":"{net} übergibt es an seinen Kunden {to}", "traceroute.net_hands_it_to_to":"{net} übergibt es an {to}", "traceroute.no_path_every_route_between_these":"Kein Pfad: Jede Route zwischen diesen Städten ist ausgefallen oder fehlt.", "traceroute.no_working_path_between_these_pops":"kein funktionierender Pfad zwischen diesen POPs", diff --git a/site/i18n/es.js b/site/i18n/es.js index 2f2a645..3ff25a9 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -17,6 +17,7 @@ "badges.attend_a_conference":"Asiste a una conferencia.", "badges.attend_six_conferences_in_one_game":"Asiste a seis conferencias en una partida.", "badges.badge_unlocked_name":"Insignia desbloqueada: {name}", +"badges.badge_upgraded_name":"Insignia mejorada: {name}", "badges.blackhole_one_of_your_own_cities":"Haz un blackhole a una de tus propias ciudades para frenar un DDoS.", "badges.bring_up_your_first_peering_session":"Levanta tu primera sesión de peering.", "badges.build_fiber_across_the_andes":"Tiende fibra a través de los Andes.", @@ -98,9 +99,14 @@ "badges.take_a_de_kicks_retention_offer":"Acepta una oferta de retención de DE-KICKS.", "badges.take_out_a_loan":"Pide un préstamo.", "badges.the_long_way_round":"El camino largo", +"badges.this_game_earns_fiery_badges":"Esta partida va de BGP a las 3 de la mañana: cada insignia que ganes aquí sale forjada en fuego y mejora la que ya tengas.", +"badges.this_game_earns_frosted_badges":"Esta partida está en Change Freeze: las insignias de aquí salen liofilizadas.", "badges.through_the_wall":"A través del muro", "badges.turn_on_a_transit_clean_pipe":"Activa un complemento de tubería limpia de tránsito.", "badges.two_buildings_three_cities":"Dos edificios, tres ciudades", +"badges.variant_forged_at_3_a_m":"Forjada a las 3 a. m.", +"badges.variant_freeze_dried":"Liofilizada", +"badges.variant_on_call":"De guardia", "badges.weather_a_ddos_with_your_defences":"Aguanta un DDoS con tus defensas listas.", "badges.weather_a_multi_terabit_ddos":"Aguanta un DDoS de varios terabits.", "badges.win_without_ever_taking_a_loan":"Gana sin pedir nunca un préstamo.", @@ -1827,7 +1833,7 @@ "goals.make_5_peering_friends":"Haz 5 amigos de peering", "goals.on_the_peering_tab_request_sessions":"En la pestaña Peering, solicita sesiones, o únete al route server para hacer peering con todas las redes abiertas a la vez.", "goals.open_your_home_city_and_press":"Abre tu ciudad natal y pulsa «Lanzar banda ancha». Los eyeballs son personas en casa viendo vídeos de gatos. Te pagan cada mes.", -"goals.peer_with_every_tier_1_over":"Haz peering con todos los Tier 1 por PNI y cancela todos los puertos de tránsito. Así nadie te cobra por llegar a internet.", +"goals.peer_with_every_tier_1_their_customers":"Haz peering con todos los Tier 1 por PNI y cancela todos los puertos de tránsito. Sus clientes vienen gratis, así que solo persigues las redes a las que nadie vende tránsito.", "goals.pops_in_five_of_the_six":"POPs en cinco de las seis regiones del mapa.", "goals.reach_the_whole_internet":"Llega a todo internet", "goals.serve_10_tbps":"Sirve 10 Tbps", @@ -1889,7 +1895,7 @@ "help.the_chart_button_at_the_top":"El botón de gráficas de arriba abre gráficas de tráfico por salida (cachés, PNIs, IX, tránsito), dinero en el tiempo, tráfico por ASN con cómo te llega y cuánto cuesta su tránsito, además de tus enlaces y routers más ocupados.", "help.the_group_behind_several_big":"El grupo detrás de varios grandes intercambios (Fráncfort, Madrid, Marsella, Dubái, Bombay, Nueva York) trata las listas de precios como secreto de Estado. Los puertos se cotizan por cliente y suben cuanto más grande pareces. Regatear puede funcionar, salir mal o quedarse parado una semana. Los precios se «armonizan» al alza una vez al año, los complementos aparecen en tu factura hasta que te das de baja, y intentar irte te gana un descuento de retención que acaba con una tarifa.", "help.things_break_all_the_time_fiber":"Las cosas se rompen todo el tiempo: cortes de fibra, caídas de router, cortes de luz, bucles en IX, caídas de fabric, fugas de rutas, DDoS, dedazos, fallos de refrigeración y geopolítica: sanciones, aranceles, secuestros de BGP, disputas de permisos de aterrizaje, apagones por exámenes y cortes de cables del Mar Rojo. El tráfico se reencamina solo por otras rutas y upstreams. Los enlaces paralelos por rutas diversas, un segundo router y un generador de respaldo ayudan. O paga por reparaciones urgentes.", -"help.tier_1s_reach_the_whole_internet":"Los Tier 1 llegan a todo internet sin pagar a nadie, porque todos hacen peering entre sí. Los Tier 2 hacen mucho peering pero aún compran algo de tránsito.", +"help.tier_1s_reach_the_whole_internet_cones":"Los Tier 1 llegan a todo internet sin pagar a nadie: todos hacen peering entre sí y cada uno trae su cono de clientes, todos los que le compran tránsito. Los Tier 2 hacen mucho peering pero aún compran algo de tránsito.", "help.traffic_follows_the_shortest_path_by":"El tráfico sigue la ruta más corta por distancia y métrica de enlace, y se reencamina solo cuando fallan enlaces. Cuando una ruta simplemente está llena, el exceso se descarta, igual que en un IGP real. Desde el nivel de cliente 3 puedes instalar Auto-TE en la pestaña NOC: desborda el exceso hacia hasta dos rutas alternativas con capacidad libre, siempre que no sean más del doble de largas.", "help.transit_bills_sample_your_usage":"Las facturas de tránsito muestrean tu uso cada día y cobran el percentil 95 de los últimos 30 días, así que los picos cortos se perdonan pero los largos no.", "help.users_feel_the_round_trip_to":"Los usuarios sienten el viaje de ida y vuelta hasta donde su tráfico sale de tu red hacia el tránsito. Hasta 20 ms (unos 1500 km) está bien; pasados 50 ms la banda ancha y los servicios de internet cuentan como mal servicio, lo que cuesta ingresos y clientes. El tráfico por tu propio peering, PNIs y cachés no se penaliza.", @@ -1914,12 +1920,13 @@ "hot_ports_and_rank.upgrade_the_ix_port_or_add":"Mejora el puerto IX o añade un miembro LAG.", "hot_ports_and_rank.upgrade_the_router_or_add_a":"Mejora el router o añade uno segundo en la pestaña Infra.", "hot_ports_and_rank.you_buy_transit_again":"vuelves a comprar tránsito", -"hot_ports_and_rank.you_cannot_reach_list":"no llegas a {list}", +"hot_ports_and_rank.you_cannot_reach_list_outside_cones":"no llegas a {list}, y ninguno de tus peers les vende tránsito", "hot_ports_and_rank.your_reach_is_p_not_100":"tu alcance es del {p}, no del 100 %", "hud_and_panels.all_connections_n":"Todas las conexiones {n}", "hud_and_panels.all_systems_green_enjoy_it_while":"Todos los sistemas en verde. Disfrútalo mientras dure.", "hud_and_panels.auto_fix_in_n_day":{"one":"Autorreparación en {n} día","other":"Autorreparación en {n} días"}, "hud_and_panels.blackholing_g":"blackhole de {g}", +"hud_and_panels.buys_transit_from_net_peer_with":"Compra tránsito a {net}. Haz peering con {net} y viene con ella.", "hud_and_panels.customer_level_lv_name":"Nivel de cliente {lv}: {name}", "hud_and_panels.dropping_or_overflowing":"descartando o desbordando", "hud_and_panels.every_network_on_the_map_traffic":"Todas las redes del mapa. La cuota de tráfico es cuánto del tráfico de tus usuarios va hacia ellas. Toca una conexión para saltar a su POP.", @@ -1956,6 +1963,7 @@ "hud_and_panels.p_of_traffic_between_them_scattered":"{p} % del tráfico entre ellas, repartido entre intercambios. Haces peering con {n}.", "hud_and_panels.ports_caches_and_routers_running_hot":"Puertos, cachés y routers al rojo vivo", "hud_and_panels.raise_a_full_link_s_metric":"Sube la métrica de un enlace lleno para que el tráfico prefiera otra ruta, mejóralo o instala Auto-TE.", +"hud_and_panels.reached_through_the_customer_cone_of":"Alcanzada por el cono de clientes de {net}: le compra tránsito.", "hud_and_panels.reaches_networks_from_the_last":"Llega gratis a redes de la última actualización a las que no tienes otra ruta. Conéctate a ellas antes de que termine.", "hud_and_panels.reward_cash":"Recompensa {cash}", "hud_and_panels.survived_with_no_impact":"Superado sin impacto", @@ -2347,6 +2355,8 @@ "loop.welcome_back_name_your_network_is":"Bienvenido de nuevo, {name}.
Tu red está justo donde la dejaste: {date}.", "loop.your_saved_game_could_not_be":"No se pudo cargar tu partida guardada.
Estaba dañada, así que se guardó una copia y puedes empezar de cero.", "meet_a_network.all_n_out_of_reach":{"one":"{n} fuera de alcance","other":"Las {n} fuera de alcance"}, +"meet_a_network.peer_with_the_tier_1_club":"Haz peering con el club de los Tier 1: sus clientes vienen gratis. Solo las redes que no están en el cono de nadie necesitan peering propio.", +"meet_a_network.peer_with_the_tier_1_club_n":{"one":"Haz peering con el club de los Tier 1: sus clientes vienen gratis. {n} red ya viene con un peer.","other":"Haz peering con el club de los Tier 1: sus clientes vienen gratis. {n} redes ya vienen con un peer."}, "meet_a_network.pnis_with_every_tier_1":"PNIs con todos los Tier 1", "meet_a_network.reach_without_transit":"Alcance sin tránsito", "meet_a_network.road_to_tier_1":"Camino al Tier 1", @@ -3034,6 +3044,7 @@ "title.scenarios_amp_weekly_challenge":"Escenarios y desafío semanal →", "title.source_on_github":"Código en GitHub", "title.your_network_name_was_saved_and":"Tu red {name} se guardó y te está esperando.", +"traceroute.a_peer_s_customers_come_after":"los clientes de un peer van después de los peers directos y antes del tránsito", "traceroute.across_the_ix_switch":"a través del switch de {ix}", "traceroute.as_path_path":"AS path: {path}", "traceroute.caches_beat_pnis":"las cachés ganan a los PNIs", @@ -3049,6 +3060,7 @@ "traceroute.n_network_unreachable":"!N red inalcanzable", "traceroute.name_transit":"Tránsito de {name}", "traceroute.net_carries_it_to_city":"{net} lo lleva hasta {city}", +"traceroute.net_hands_it_to_its_customer":"{net} lo entrega a su cliente {to}", "traceroute.net_hands_it_to_to":"{net} lo entrega a {to}", "traceroute.no_path_every_route_between_these":"Sin ruta: todas las rutas entre estas ciudades están caídas o no existen.", "traceroute.no_working_path_between_these_pops":"sin ruta operativa entre estos POPs", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 413ae5f..1c09ae3 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -17,6 +17,7 @@ "badges.attend_a_conference":"Participe à une conférence.", "badges.attend_six_conferences_in_one_game":"Participe à six conférences dans une même partie.", "badges.badge_unlocked_name":"Badge débloqué : {name}", +"badges.badge_upgraded_name":"Badge amélioré : {name}", "badges.blackhole_one_of_your_own_cities":"Blackhole une de tes propres villes pour stopper un DDoS.", "badges.bring_up_your_first_peering_session":"Monte ta première session de peering.", "badges.build_fiber_across_the_andes":"Pose de la fibre à travers les Andes.", @@ -98,9 +99,14 @@ "badges.take_a_de_kicks_retention_offer":"Accepte une offre de fidélisation DE-KICKS.", "badges.take_out_a_loan":"Contracte un prêt.", "badges.the_long_way_round":"Le grand détour", +"badges.this_game_earns_fiery_badges":"Cette partie tourne en BGP à 3 h du matin : chaque badge gagné ici est forgé dans le feu et améliore celui que tu as déjà.", +"badges.this_game_earns_frosted_badges":"Cette partie est en Change Freeze : les badges gagnés ici sont lyophilisés.", "badges.through_the_wall":"Derrière la Muraille", "badges.turn_on_a_transit_clean_pipe":"Active une option clean-pipe sur un transit.", "badges.two_buildings_three_cities":"Deux bâtiments, trois villes", +"badges.variant_forged_at_3_a_m":"Forgé à 3 h du matin", +"badges.variant_freeze_dried":"Lyophilisé", +"badges.variant_on_call":"D’astreinte", "badges.weather_a_ddos_with_your_defences":"Encaisse un DDoS avec tes défenses prêtes.", "badges.weather_a_multi_terabit_ddos":"Encaisse un DDoS de plusieurs térabits.", "badges.win_without_ever_taking_a_loan":"Gagne sans jamais contracter de prêt.", @@ -1827,7 +1833,7 @@ "goals.make_5_peering_friends":"Fais-toi 5 amis de peering", "goals.on_the_peering_tab_request_sessions":"Dans l’onglet Peering, demande des sessions, ou rejoins le route server pour peerer d’un coup avec tous les réseaux à politique ouverte.", "goals.open_your_home_city_and_press":"Ouvre ta ville de départ et appuie sur « Lancer le haut débit ». Les eyeballs, ce sont les gens chez eux qui regardent des vidéos de chats. Ils te paient tous les mois.", -"goals.peer_with_every_tier_1_over":"Peere avec chaque Tier 1 via des PNI et résilie tous tes ports de transit. Plus personne ne te fait alors payer pour atteindre Internet.", +"goals.peer_with_every_tier_1_their_customers":"Peere avec chaque Tier 1 via des PNI et résilie tous tes ports de transit. Leurs clients viennent gratuitement avec, tu ne cours donc qu’après les réseaux à qui personne ne vend de transit.", "goals.pops_in_five_of_the_six":"Des POP dans cinq des six régions de la carte.", "goals.reach_the_whole_internet":"Atteins tout Internet", "goals.serve_10_tbps":"Sers 10 Tbps", @@ -1889,7 +1895,7 @@ "help.the_chart_button_at_the_top":"Le bouton graphique en haut ouvre les courbes de trafic par sortie (caches, PNI, IX, transit), l’argent dans le temps, le trafic par ASN avec son mode d’arrivée et son coût en transit, plus tes liens et routeurs les plus chargés.", "help.the_group_behind_several_big":"Le groupe derrière plusieurs grands IX (Frankfurt, Madrid, Marseille, Dubai, Mumbai, New York) traite ses grilles tarifaires comme un secret d’État. Les ports sont chiffrés client par client et grimpent d’autant plus que tu as l’air gros. Négocier peut marcher, se retourner contre toi ou s’enliser une semaine. Une fois par an, les prix sont « harmonisés » à la hausse, des options apparaissent sur ta facture tant que tu ne les refuses pas, et tenter de partir te vaut une remise de fidélité qui se termine par des frais.", "help.things_break_all_the_time_fiber":"Ça casse tout le temps : coupures de fibre, crashs de routeurs, coupures de courant, boucles sur les IX, pannes de fabric, fuites de routes, DDoS, erreurs de manip, pannes de refroidissement, et géopolitique : sanctions, droits de douane, détournements BGP, litiges sur les permis d’atterrissement, coupures les jours d’examen et câbles sectionnés en mer Rouge. Le trafic se reroute automatiquement via d’autres chemins et upstreams. Des liens parallèles sur des chemins diversifiés, un second routeur et un groupe électrogène de secours aident tous. Ou paie pour accélérer les réparations.", -"help.tier_1s_reach_the_whole_internet":"Les Tier 1 atteignent tout Internet sans payer personne, parce qu’ils font tous du peering entre eux. Les Tier 2 font beaucoup de peering mais achètent encore un peu de transit.", +"help.tier_1s_reach_the_whole_internet_cones":"Les Tier 1 atteignent tout Internet sans payer personne : ils font tous du peering entre eux, et chacun apporte son cône de clients, tous ceux qui lui achètent du transit. Les Tier 2 font beaucoup de peering mais achètent encore un peu de transit.", "help.traffic_follows_the_shortest_path_by":"Le trafic suit le chemin le plus court selon la distance et la métrique des liens, et se reroute tout seul quand des liens tombent. Quand un chemin est simplement plein, l’excédent est jeté, comme dans un vrai IGP. Dès le niveau clients 3, tu peux installer Auto-TE dans l’onglet NOC : il déverse l’excédent sur jusqu’à deux chemins alternatifs avec de la capacité libre, tant qu’ils ne sont pas plus de deux fois plus longs.", "help.transit_bills_sample_your_usage":"Les factures de transit échantillonnent ta conso chaque jour et facturent le 95e percentile des 30 derniers jours : les pics courts sont pardonnés, les longs non.", "help.users_feel_the_round_trip_to":"Les utilisateurs sentent l’aller-retour jusqu’à l’endroit où leur trafic quitte votre réseau pour le transit. Jusqu’à 20 ms (environ 1 500 km), ça va ; au-delà de 50 ms, le haut débit et les services internet comptent comme un mauvais service, ce qui coûte revenus et clients. Le trafic qui passe par votre peering, vos PNI et vos caches n’est pas pénalisé.", @@ -1914,12 +1920,13 @@ "hot_ports_and_rank.upgrade_the_ix_port_or_add":"Mets à niveau le port IX ou ajoute un membre au LAG.", "hot_ports_and_rank.upgrade_the_router_or_add_a":"Mets à niveau le routeur ou ajoutes-en un second dans l’onglet Infra.", "hot_ports_and_rank.you_buy_transit_again":"tu rachètes du transit", -"hot_ports_and_rank.you_cannot_reach_list":"tu n’atteins pas {list}", +"hot_ports_and_rank.you_cannot_reach_list_outside_cones":"tu n’atteins pas {list}, et aucun de tes peers ne leur vend de transit", "hot_ports_and_rank.your_reach_is_p_not_100":"ta couverture est de {p}, pas 100 %", "hud_and_panels.all_connections_n":"Toutes les connexions {n}", "hud_and_panels.all_systems_green_enjoy_it_while":"Tout est au vert. Profites-en, ça ne durera pas.", "hud_and_panels.auto_fix_in_n_day":{"one":"Réparation auto dans {n} jour","other":"Réparation auto dans {n} jours"}, "hud_and_panels.blackholing_g":"{g} en blackhole", +"hud_and_panels.buys_transit_from_net_peer_with":"Achète du transit à {net}. Peere avec {net} et il vient avec.", "hud_and_panels.customer_level_lv_name":"Niveau client {lv} : {name}", "hud_and_panels.dropping_or_overflowing":"pertes ou débordement", "hud_and_panels.every_network_on_the_map_traffic":"Tous les réseaux de la carte. La part de trafic, c’est la portion du trafic de tes utilisateurs qui va vers eux. Touche une connexion pour sauter à son POP.", @@ -1956,6 +1963,7 @@ "hud_and_panels.p_of_traffic_between_them_scattered":"{p} % du trafic à eux tous, éparpillé sur les IX. Tu es en peering avec {n}.", "hud_and_panels.ports_caches_and_routers_running_hot":"Ports, caches et routeurs en surchauffe", "hud_and_panels.raise_a_full_link_s_metric":"Augmente la métrique d’un lien plein pour que le trafic préfère un autre chemin, mets-le à niveau ou installe Auto-TE.", +"hud_and_panels.reached_through_the_customer_cone_of":"Atteint via le cône de clients de {net} : il lui achète du transit.", "hud_and_panels.reaches_networks_from_the_last":"Atteint gratuitement les réseaux de la dernière mise à jour vers lesquels tu n’as aucun autre chemin. Connecte-toi à eux avant la fin.", "hud_and_panels.reward_cash":"Récompense {cash}", "hud_and_panels.survived_with_no_impact":"Encaissés sans impact", @@ -2347,6 +2355,8 @@ "loop.welcome_back_name_your_network_is":"Re-bonjour, {name}.
Ton réseau est exactement là où tu l’as laissé : {date}.", "loop.your_saved_game_could_not_be":"Impossible de charger ta sauvegarde.
Elle était endommagée : une copie a été conservée et tu peux repartir de zéro.", "meet_a_network.all_n_out_of_reach":{"one":"Les {n} hors couverture","other":"Les {n} hors couverture"}, +"meet_a_network.peer_with_the_tier_1_club":"Peere avec le club des Tier 1 : leurs clients viennent gratuitement avec. Seuls les réseaux qui ne sont dans le cône de personne demandent leur propre peering.", +"meet_a_network.peer_with_the_tier_1_club_n":{"one":"Peere avec le club des Tier 1 : leurs clients viennent gratuitement avec. {n} réseau vient déjà avec un peer.","other":"Peere avec le club des Tier 1 : leurs clients viennent gratuitement avec. {n} réseaux viennent déjà avec un peer."}, "meet_a_network.pnis_with_every_tier_1":"PNI avec chaque Tier 1", "meet_a_network.reach_without_transit":"Couverture sans transit", "meet_a_network.road_to_tier_1":"En route vers le Tier 1", @@ -3034,6 +3044,7 @@ "title.scenarios_amp_weekly_challenge":"Scénarios et défi de la semaine →", "title.source_on_github":"Code source sur GitHub", "title.your_network_name_was_saved_and":"Ton réseau {name} a été sauvegardé et t’attend.", +"traceroute.a_peer_s_customers_come_after":"les clients d’un peer passent après les peers directs, avant le transit", "traceroute.across_the_ix_switch":"via le switch de {ix}", "traceroute.as_path_path":"AS path : {path}", "traceroute.caches_beat_pnis":"les caches battent les PNI", @@ -3049,6 +3060,7 @@ "traceroute.n_network_unreachable":"!N réseau injoignable", "traceroute.name_transit":"Transit {name}", "traceroute.net_carries_it_to_city":"{net} l’achemine jusqu’à {city}", +"traceroute.net_hands_it_to_its_customer":"{net} le passe à son client {to}", "traceroute.net_hands_it_to_to":"{net} le passe à {to}", "traceroute.no_path_every_route_between_these":"Aucun chemin : toutes les routes entre ces villes sont coupées ou inexistantes.", "traceroute.no_working_path_between_these_pops":"aucun chemin fonctionnel entre ces POP", diff --git a/site/i18n/it.js b/site/i18n/it.js index 103bc61..34ebe16 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -17,6 +17,7 @@ "badges.attend_a_conference":"Partecipa a una conferenza.", "badges.attend_six_conferences_in_one_game":"Partecipa a sei conferenze in una partita.", "badges.badge_unlocked_name":"Badge sbloccato: {name}", +"badges.badge_upgraded_name":"Badge migliorato: {name}", "badges.blackhole_one_of_your_own_cities":"Metti in buco nero una tua città per fermare un DDoS.", "badges.bring_up_your_first_peering_session":"Attiva la tua prima sessione di peering.", "badges.build_fiber_across_the_andes":"Posa fibra attraverso le Ande.", @@ -98,9 +99,14 @@ "badges.take_a_de_kicks_retention_offer":"Accetta un’offerta di fidelizzazione DE-KICKS.", "badges.take_out_a_loan":"Chiedi un prestito.", "badges.the_long_way_round":"Il giro lungo", +"badges.this_game_earns_fiery_badges":"Questa partita gira con BGP alle 3 di notte: ogni badge che guadagni qui è forgiato nel fuoco e migliora quello che hai già.", +"badges.this_game_earns_frosted_badges":"Questa partita è in Change Freeze: i badge che guadagni qui arrivano liofilizzati.", "badges.through_the_wall":"Oltre la Muraglia", "badges.turn_on_a_transit_clean_pipe":"Attiva un add-on clean-pipe su un transit.", "badges.two_buildings_three_cities":"Due edifici, tre città", +"badges.variant_forged_at_3_a_m":"Forgiato alle 3 di notte", +"badges.variant_freeze_dried":"Liofilizzato", +"badges.variant_on_call":"Reperibile", "badges.weather_a_ddos_with_your_defences":"Reggi un DDoS con le difese pronte.", "badges.weather_a_multi_terabit_ddos":"Reggi un DDoS da più terabit.", "badges.win_without_ever_taking_a_loan":"Vinci senza mai chiedere un prestito.", @@ -1827,7 +1833,7 @@ "goals.make_5_peering_friends":"Fatti 5 amici di peering", "goals.on_the_peering_tab_request_sessions":"Nella scheda Peering richiedi delle sessioni, oppure entra nel route server per fare peering con tutte le reti open in un colpo solo.", "goals.open_your_home_city_and_press":"Apri la tua città di partenza e premi “Lancia la banda larga”. Gli eyeball sono persone a casa che guardano video di gatti. Ti pagano ogni mese.", -"goals.peer_with_every_tier_1_over":"Fai peering con ogni Tier 1 via PNI e disdici ogni porta di transit. Così nessuno ti fa pagare per raggiungere internet.", +"goals.peer_with_every_tier_1_their_customers":"Fai peering con ogni Tier 1 via PNI e disdici ogni porta di transit. I loro clienti arrivano gratis, quindi rincorri solo le reti a cui nessuno vende transit.", "goals.pops_in_five_of_the_six":"POP in cinque delle sei regioni della mappa.", "goals.reach_the_whole_internet":"Raggiungi tutta internet", "goals.serve_10_tbps":"Servi 10 Tbps", @@ -1889,7 +1895,7 @@ "help.the_chart_button_at_the_top":"Il pulsante del grafico in alto apre i grafici del traffico per uscita (cache, PNI, IX, transit), i soldi nel tempo, il traffico per ASN con come ti raggiunge e quanto costa in transit, più i tuoi link e router più carichi.", "help.the_group_behind_several_big":"Il gruppo dietro diversi grandi exchange (Frankfurt, Madrid, Marseille, Dubai, Mumbai, New York) tratta i listini come un segreto di Stato. Le porte vengono quotate cliente per cliente e salgono quanto più sembri grande. Contrattare può funzionare, ritorcertisi contro o arenarsi per una settimana. Una volta l’anno i prezzi vengono “armonizzati” verso l’alto, in fattura spuntano servizi aggiuntivi finché non li disdici, e provare ad andartene ti frutta uno sconto fedeltà che finisce con una penale.", "help.things_break_all_the_time_fiber":"Le cose si rompono di continuo: tagli di fibra, crash dei router, blackout, loop sugli IX, disservizi dei fabric, route leak, DDoS, dita grosse, guasti al raffreddamento, e poi la geopolitica: sanzioni, dazi, hijack BGP, dispute sui permessi di approdo, shutdown nei giorni d’esame e cavi tranciati nel Mar Rosso. Il traffico si reinstrada da solo su altri percorsi e upstream. Link paralleli su percorsi diversi, un secondo router e un generatore di backup aiutano tutti. Oppure paga per accelerare le riparazioni.", -"help.tier_1s_reach_the_whole_internet":"I Tier 1 raggiungono tutto internet senza pagare nessuno, perché fanno tutti peering tra loro. I Tier 2 fanno molto peering ma comprano ancora un po’ di transit.", +"help.tier_1s_reach_the_whole_internet_cones":"I Tier 1 raggiungono tutto internet senza pagare nessuno: fanno tutti peering tra loro e ognuno si porta dietro il suo cono di clienti, tutti quelli che gli comprano transit. I Tier 2 fanno molto peering ma comprano ancora un po’ di transit.", "help.traffic_follows_the_shortest_path_by":"Il traffico segue il percorso più corto per distanza e metrica dei link, e si reinstrada da solo quando i link si guastano. Quando un percorso è semplicemente pieno, l’eccesso viene scartato, proprio come in un vero IGP. Dal livello clienti 3 puoi installare Auto-TE nella scheda NOC: riversa l’eccesso su un massimo di due percorsi alternativi con capacità libera, purché non siano lunghi più del doppio.", "help.transit_bills_sample_your_usage":"Le bollette del transit campionano il tuo consumo ogni giorno e addebitano il 95° percentile degli ultimi 30 giorni: i picchi brevi vengono perdonati, quelli lunghi no.", "help.users_feel_the_round_trip_to":"Gli utenti sentono l’andata e ritorno fino al punto in cui il loro traffico lascia la tua rete per il transito. Fino a 20 ms (circa 1.500 km) va bene; oltre i 50 ms banda larga e servizi internet contano come servizio scadente, e costa ricavi e clienti. Il traffico sul tuo peering, sulle PNI e sulle cache non viene penalizzato.", @@ -1914,12 +1920,13 @@ "hot_ports_and_rank.upgrade_the_ix_port_or_add":"Fai l’upgrade della porta IX o aggiungi un membro al LAG.", "hot_ports_and_rank.upgrade_the_router_or_add_a":"Fai l’upgrade del router o aggiungine un secondo nella scheda Infra.", "hot_ports_and_rank.you_buy_transit_again":"compri di nuovo transit", -"hot_ports_and_rank.you_cannot_reach_list":"non raggiungi {list}", +"hot_ports_and_rank.you_cannot_reach_list_outside_cones":"non raggiungi {list}, e nessuno dei tuoi peer gli vende transit", "hot_ports_and_rank.your_reach_is_p_not_100":"la tua raggiungibilità è {p}, non 100%", "hud_and_panels.all_connections_n":"Tutte le connessioni {n}", "hud_and_panels.all_systems_green_enjoy_it_while":"Tutto verde. Goditela finché dura.", "hud_and_panels.auto_fix_in_n_day":{"one":"Si risolve da solo tra {n} giorno","other":"Si risolve da solo tra {n} giorni"}, "hud_and_panels.blackholing_g":"{g} in blackhole", +"hud_and_panels.buys_transit_from_net_peer_with":"Compra transit da {net}. Fai peering con {net} e arriva con lei.", "hud_and_panels.customer_level_lv_name":"Livello cliente {lv}: {name}", "hud_and_panels.dropping_or_overflowing":"scarta o trabocca", "hud_and_panels.every_network_on_the_map_traffic":"Tutte le reti sulla mappa. La quota di traffico è quanto del traffico dei tuoi utenti va verso di loro. Tocca una connessione per andare al suo POP.", @@ -1956,6 +1963,7 @@ "hud_and_panels.p_of_traffic_between_them_scattered":"{p}% del traffico in tutto, sparse tra vari exchange. Sei in peering con {n}.", "hud_and_panels.ports_caches_and_routers_running_hot":"Porte, cache e router sotto sforzo", "hud_and_panels.raise_a_full_link_s_metric":"Alza la metrica di un link pieno così il traffico preferisce un altro percorso, potenzialo, oppure installa Auto-TE.", +"hud_and_panels.reached_through_the_customer_cone_of":"Raggiunta tramite il cono di clienti di {net}: compra transit lì.", "hud_and_panels.reaches_networks_from_the_last":"Raggiunge gratis le reti dell’ultimo aggiornamento che non hai altro modo di raggiungere. Collegati a loro prima che finisca.", "hud_and_panels.reward_cash":"Premio {cash}", "hud_and_panels.survived_with_no_impact":"Superati senza danni", @@ -2347,6 +2355,8 @@ "loop.welcome_back_name_your_network_is":"Bentornato, {name}.
La tua rete è proprio dove l’avevi lasciata: {date}.", "loop.your_saved_game_could_not_be":"Impossibile caricare la partita salvata.
Era danneggiata: ne abbiamo tenuto una copia di backup e puoi ricominciare da zero.", "meet_a_network.all_n_out_of_reach":{"one":"Tutte le {n} fuori copertura","other":"Tutte le {n} fuori copertura"}, +"meet_a_network.peer_with_the_tier_1_club":"Fai peering con il club dei Tier 1: i loro clienti arrivano gratis. Solo le reti che non stanno nel cono di nessuno vogliono un peering tutto loro.", +"meet_a_network.peer_with_the_tier_1_club_n":{"one":"Fai peering con il club dei Tier 1: i loro clienti arrivano gratis. {n} rete arriva già con un peer.","other":"Fai peering con il club dei Tier 1: i loro clienti arrivano gratis. {n} reti arrivano già con un peer."}, "meet_a_network.pnis_with_every_tier_1":"PNI con ogni Tier 1", "meet_a_network.reach_without_transit":"Copertura senza transit", "meet_a_network.road_to_tier_1":"Verso il Tier 1", @@ -3034,6 +3044,7 @@ "title.scenarios_amp_weekly_challenge":"Scenari e sfida settimanale →", "title.source_on_github":"Codice su GitHub", "title.your_network_name_was_saved_and":"La tua rete {name} è stata salvata e ti sta aspettando.", +"traceroute.a_peer_s_customers_come_after":"i clienti di un peer vengono dopo i peer diretti e prima del transit", "traceroute.across_the_ix_switch":"attraverso lo switch di {ix}", "traceroute.as_path_path":"AS path: {path}", "traceroute.caches_beat_pnis":"le cache battono i PNI", @@ -3049,6 +3060,7 @@ "traceroute.n_network_unreachable":"!N rete irraggiungibile", "traceroute.name_transit":"Transit {name}", "traceroute.net_carries_it_to_city":"{net} lo porta fino a {city}", +"traceroute.net_hands_it_to_its_customer":"{net} lo passa al suo cliente {to}", "traceroute.net_hands_it_to_to":"{net} lo passa a {to}", "traceroute.no_path_every_route_between_these":"Nessun percorso: ogni strada tra queste città è giù o non esiste.", "traceroute.no_working_path_between_these_pops":"nessun percorso funzionante tra questi POP", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 046f9a8..1d42107 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -17,6 +17,7 @@ "badges.attend_a_conference":"Participe de uma conferência.", "badges.attend_six_conferences_in_one_game":"Participe de seis conferências numa partida.", "badges.badge_unlocked_name":"Badge desbloqueado: {name}", +"badges.badge_upgraded_name":"Badge melhorado: {name}", "badges.blackhole_one_of_your_own_cities":"Mande uma das suas próprias cidades para o blackhole para parar um DDoS.", "badges.bring_up_your_first_peering_session":"Suba sua primeira sessão de peering.", "badges.build_fiber_across_the_andes":"Construa fibra cruzando os Andes.", @@ -98,9 +99,14 @@ "badges.take_a_de_kicks_retention_offer":"Aceite uma oferta de retenção da DE-KICKS.", "badges.take_out_a_loan":"Pegue um empréstimo.", "badges.the_long_way_round":"A volta longa", +"badges.this_game_earns_fiery_badges":"Este jogo roda BGP às 3 da manhã: cada badge que você ganha aqui é forjado no fogo e melhora o que você já tem.", +"badges.this_game_earns_frosted_badges":"Este jogo está em Change Freeze: os badges daqui vêm liofilizados.", "badges.through_the_wall":"Através da Muralha", "badges.turn_on_a_transit_clean_pipe":"Ative um add-on clean-pipe num transit.", "badges.two_buildings_three_cities":"Dois prédios, três cidades", +"badges.variant_forged_at_3_a_m":"Forjado às 3 da manhã", +"badges.variant_freeze_dried":"Liofilizado", +"badges.variant_on_call":"De plantão", "badges.weather_a_ddos_with_your_defences":"Aguente um DDoS com as defesas prontas.", "badges.weather_a_multi_terabit_ddos":"Aguente um DDoS de vários terabits.", "badges.win_without_ever_taking_a_loan":"Vença sem nunca pegar um empréstimo.", @@ -1827,7 +1833,7 @@ "goals.make_5_peering_friends":"Faça 5 amigos de peering", "goals.on_the_peering_tab_request_sessions":"Na aba Peering, peça sessões ou entre no route server para fazer peering com todas as redes abertas de uma vez.", "goals.open_your_home_city_and_press":"Abra sua cidade natal e aperte “Lançar banda larga”. Eyeballs são pessoas em casa vendo vídeo de gatinho. Elas te pagam todo mês.", -"goals.peer_with_every_tier_1_over":"Faça peering com todas as Tier 1 via PNI e cancele todas as portas de transit. Aí ninguém te cobra para chegar à internet.", +"goals.peer_with_every_tier_1_their_customers":"Faça peering com todas as Tier 1 via PNI e cancele todas as portas de transit. Os clientes delas vêm de graça, então você só corre atrás das redes a quem ninguém vende transit.", "goals.pops_in_five_of_the_six":"POPs em cinco das seis regiões do mapa.", "goals.reach_the_whole_internet":"Alcance a internet inteira", "goals.serve_10_tbps":"Sirva 10 Tbps", @@ -1889,7 +1895,7 @@ "help.the_chart_button_at_the_top":"O botão de gráfico no topo abre gráficos de tráfego por saída (caches, PNIs, IX, transit), dinheiro ao longo do tempo, tráfego por ASN com como ele chega até você e quanto custa o transit dele, além dos seus links e routers mais ocupados.", "help.the_group_behind_several_big":"O grupo por trás de vários grandes exchanges (Frankfurt, Madrid, Marseille, Dubai, Mumbai, New York) trata tabela de preços como segredo de Estado. As portas são cotadas cliente a cliente e sobem quanto maior você parece. Pechinchar pode funcionar, sair pela culatra ou travar por uma semana. Uma vez por ano os preços são \"harmonizados\" para cima, serviços extras aparecem na sua fatura até você cancelar, e tentar sair te rende um desconto de retenção que termina em multa.", "help.things_break_all_the_time_fiber":"As coisas quebram o tempo todo: cortes de fibra, crashes de router, quedas de energia, loops no IX, quedas de fabric, route leaks, DDoS, dedo gordo, falhas de refrigeração e geopolítica: sanções, tarifas, sequestros de BGP, disputas de licença de desembarque, apagões em dia de prova e cortes de cabo no Mar Vermelho. O tráfego se reroteia sozinho por outros caminhos e upstreams. Links paralelos em rotas diversas, um segundo router e um gerador de backup, tudo ajuda. Ou pague para acelerar os reparos.", -"help.tier_1s_reach_the_whole_internet":"Os Tier 1 alcançam a internet toda sem pagar ninguém, porque todos fazem peering entre si. Os Tier 2 fazem muito peering, mas ainda compram algum transit.", +"help.tier_1s_reach_the_whole_internet_cones":"Os Tier 1 alcançam a internet toda sem pagar ninguém: todos fazem peering entre si, e cada um traz o seu cone de clientes, todos que compram transit dele. Os Tier 2 fazem muito peering, mas ainda compram algum transit.", "help.traffic_follows_the_shortest_path_by":"O tráfego segue o caminho mais curto por distância e métrica de link, e se reroteia sozinho quando links caem. Quando um caminho só está cheio, o excesso é descartado, igualzinho a um IGP de verdade. A partir do nível de clientes 3 você pode instalar o Auto-TE na aba NOC: ele joga o excesso em até dois caminhos alternativos com capacidade livre, desde que não sejam mais que o dobro do comprimento.", "help.transit_bills_sample_your_usage":"A conta do transit mede seu uso todo dia e cobra o percentil 95 dos últimos 30 dias, então picos curtos são perdoados, mas os longos não.", "help.users_feel_the_round_trip_to":"Os usuários sentem a ida e volta até onde o tráfego deles sai da sua rede para o trânsito. Até 20 ms (cerca de 1.500 km) está tudo bem; acima de 50 ms banda larga e serviços de internet contam como serviço ruim, o que custa receita e clientes. O tráfego pelo seu próprio peering, PNIs e caches não é penalizado.", @@ -1914,12 +1920,13 @@ "hot_ports_and_rank.upgrade_the_ix_port_or_add":"Faça upgrade da porta do IX ou adicione um membro ao LAG.", "hot_ports_and_rank.upgrade_the_router_or_add_a":"Faça upgrade do router ou adicione um segundo na aba Infra.", "hot_ports_and_rank.you_buy_transit_again":"você volta a comprar transit", -"hot_ports_and_rank.you_cannot_reach_list":"você não alcança {list}", +"hot_ports_and_rank.you_cannot_reach_list_outside_cones":"você não alcança {list}, e nenhum dos seus peers vende transit para eles", "hot_ports_and_rank.your_reach_is_p_not_100":"seu alcance é {p}, não 100%", "hud_and_panels.all_connections_n":"Todas as conexões {n}", "hud_and_panels.all_systems_green_enjoy_it_while":"Tudo verde. Aproveite enquanto dura.", "hud_and_panels.auto_fix_in_n_day":{"one":"Se resolve sozinho em {n} dia","other":"Se resolve sozinho em {n} dias"}, "hud_and_panels.blackholing_g":"{g} em blackhole", +"hud_and_panels.buys_transit_from_net_peer_with":"Compra transit de {net}. Faça peering com {net} e ela vem junto.", "hud_and_panels.customer_level_lv_name":"Nível de cliente {lv}: {name}", "hud_and_panels.dropping_or_overflowing":"descartando ou transbordando", "hud_and_panels.every_network_on_the_map_traffic":"Todas as redes do mapa. A fatia de tráfego é quanto do tráfego dos seus usuários vai para elas. Toque numa conexão para ir ao POP dela.", @@ -1956,6 +1963,7 @@ "hud_and_panels.p_of_traffic_between_them_scattered":"{p}% do tráfego somadas, espalhadas pelos exchanges. Você faz peering com {n}.", "hud_and_panels.ports_caches_and_routers_running_hot":"Portas, caches e routers no talo", "hud_and_panels.raise_a_full_link_s_metric":"Aumente a métrica de um link cheio para o tráfego preferir outra rota, faça upgrade nele ou instale o Auto-TE.", +"hud_and_panels.reached_through_the_customer_cone_of":"Alcançada pelo cone de clientes de {net}: compra transit dela.", "hud_and_panels.reaches_networks_from_the_last":"Alcança de graça as redes da última atualização que você não tem outro caminho para alcançar. Conecte-se a elas antes que acabe.", "hud_and_panels.reward_cash":"Prêmio {cash}", "hud_and_panels.survived_with_no_impact":"Sobreviveu sem impacto", @@ -2347,6 +2355,8 @@ "loop.welcome_back_name_your_network_is":"Bem-vindo de volta, {name}.
Sua rede está do jeitinho que você deixou: {date}.", "loop.your_saved_game_could_not_be":"Não deu para carregar seu jogo salvo.
Ele estava corrompido, então guardamos um backup e você pode começar do zero.", "meet_a_network.all_n_out_of_reach":{"one":"Todas as {n} fora de alcance","other":"Todas as {n} fora de alcance"}, +"meet_a_network.peer_with_the_tier_1_club":"Faça peering com o clube dos Tier 1: os clientes deles vêm de graça. Só as redes que não estão no cone de ninguém precisam de peering próprio.", +"meet_a_network.peer_with_the_tier_1_club_n":{"one":"Faça peering com o clube dos Tier 1: os clientes deles vêm de graça. {n} rede já vem junto com um peer.","other":"Faça peering com o clube dos Tier 1: os clientes deles vêm de graça. {n} redes já vêm junto com um peer."}, "meet_a_network.pnis_with_every_tier_1":"PNIs com cada Tier 1", "meet_a_network.reach_without_transit":"Alcance sem transit", "meet_a_network.road_to_tier_1":"Rumo ao Tier 1", @@ -3034,6 +3044,7 @@ "title.scenarios_amp_weekly_challenge":"Cenários e desafio semanal →", "title.source_on_github":"Código no GitHub", "title.your_network_name_was_saved_and":"Sua rede {name} foi salva e está te esperando.", +"traceroute.a_peer_s_customers_come_after":"os clientes de um peer vêm depois dos peers diretos e antes do transit", "traceroute.across_the_ix_switch":"pelo switch do {ix}", "traceroute.as_path_path":"AS path: {path}", "traceroute.caches_beat_pnis":"caches vencem PNIs", @@ -3049,6 +3060,7 @@ "traceroute.n_network_unreachable":"!N rede inalcançável", "traceroute.name_transit":"Transit {name}", "traceroute.net_carries_it_to_city":"{net} leva até {city}", +"traceroute.net_hands_it_to_its_customer":"{net} passa para o seu cliente {to}", "traceroute.net_hands_it_to_to":"{net} passa para {to}", "traceroute.no_path_every_route_between_these":"Sem caminho: todas as rotas entre essas cidades estão fora do ar ou não existem.", "traceroute.no_working_path_between_these_pops":"nenhum caminho funcionando entre esses POPs", diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index d7cad9b..722e735 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -37,7 +37,7 @@ NETS.push( {id:'bcd',name:'Bell Canad-eh',asn:577,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#00549A',pops:['hfx','tor','mtl','nyc','chi','ott','cal','van'],ix:['tor','mtl','ott'],blurb:tr('networks.polite_enormous_and_sorry_about_the')}); NETS.push( {id:'tsf',name:'Telkom-selfie',asn:7713,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#E4002B',pops:['jkt','sin'],ix:['jkt','sin'],blurb:tr('networks.indonesia_s_mobile_giant_every')}, - {id:'pld',name:'PLDTea Time',asn:9299,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,col:'#D62027',pops:['mnl','hkg','sin'],ix:['hkg'],blurb:tr('networks.philippine_giant_peering_requests')}, + {id:'pld',name:'PLDTea Time',asn:9299,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,up:['ntt','tat'],col:'#D62027',pops:['mnl','hkg','sin'],ix:['hkg'],blurb:tr('networks.philippine_giant_peering_requests')}, {id:'spk',name:'Spark-le',asn:4771,type:'eye',pol:'open',share:.005,col:'#6A2C91',pops:['akl','syd','chc','ivc'],ix:['akl','syd','chc'],blurb:tr('networks.new_zealand_s_shiniest_isp')}, {id:'tsy',name:'Telstraya',asn:1221,type:'t2',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['hnl','gum','suv','pom','nou','hir','syd','per','sin','hkg','lax','tpe','mel','bne','drw','adl','cbr','hba'],ix:['gum','sin','hkg'],blurb:tr('networks.australia_s_big_one_g_day')}); NETS.push( @@ -49,7 +49,7 @@ NETS.push( {id:'art',name:'Air-Tell Africa',asn:36928,type:'eye',pol:'selective',up:['tat','tly'],minIx:4,minPni:18,share:.006,col:'#ED1C24',pops:['lag','kla','kgl','dar','lun','fih','nbo','tnr','sez'],ix:['lag','kla','kgl','dar','lun','fih','nbo'],blurb:tr('networks.mobile_money_and_prepaid_data_in')}, {id:'eth',name:'Ethio-Tele-Calm',asn:24759,type:'eye',pol:'selective',up:['tat'],minIx:2,minPni:12,share:.005,col:'#8DC63F',pops:['add'],ix:['add'],blurb:tr('networks.ethiopia_s_state_telco_a_hundred')}, {id:'mrc',name:'Atlas Shrugged Telecom',asn:36905,type:'eye',pol:'selective',up:['lvl','tly'],minIx:3,minPni:15,share:.004,col:'#F28C00',pops:['cas','abj','dkr'],ix:['cas'],blurb:tr('networks.morocco_s_incumbent_with_sister')}, - {id:'sfc',name:'Safari-Comic',asn:33771,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#4CB848',pops:['nbo','mba','add'],ix:['nbo','mba','add'],blurb:tr('networks.kenya_s_mobile_giant_pays_you')}, + {id:'sfc',name:'Safari-Comic',asn:33771,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,up:['cog','lvl','scm'],col:'#4CB848',pops:['nbo','mba','add'],ix:['nbo','mba','add'],blurb:tr('networks.kenya_s_mobile_giant_pays_you')}, {id:'teg',name:'Tele-Comet Egypt',asn:8452,type:'t2',pol:'selective',minIx:15,minPni:40,share:.006,price:8,col:'#5B2D8E',pops:['cai','mrs','fra','lon'],ix:['cai','mrs'],blurb:tr('networks.owns_the_land_crossing_every_red')}); NETS.push( {id:'clr',name:'Clarovision',asn:28537,type:'t2',pol:'selective',minIx:10,minPni:30,share:.012,price:5,col:'#DA291C',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog','pan','mex','mia','sju','sdq'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog'],blurb:tr('networks.the_big_regional_carrier_sees')}, @@ -65,10 +65,10 @@ NETS.push( {id:'jio',name:'Jio-graphy',asn:55863,type:'eye',pol:'selective',minIx:10,minPni:30,share:.02,col:'#0F3CC9',pops:['bom','del','maa','blr','hyd'],ix:['bom','del','maa','blr','hyd'],blurb:tr('networks.gave_a_billion_people_cheap_data')}, {id:'atl',name:'Airtel-tale',asn:9849,type:'t2',pol:'selective',minIx:15,minPni:40,share:.01,price:7,col:'#E40000',pops:['bom','del','maa','blr','hyd','sin','lon','dxb','dac','cbo'],ix:['bom','del','maa','blr'],blurb:tr('networks.india_s_other_giant_every_outage')}, {id:'cht',name:'Chunghwa Tele-calm',asn:3426,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#00A0E9',pops:['tpe','hkg','tok','lax','sin'],ix:['tpe','hkg'],blurb:tr('networks.taiwan_s_incumbent_stays_calm_while')}, - {id:'duu',name:'Du-opoly',asn:15820,type:'eye',pol:'paid',freeLv:11,paidFee:6000,share:.004,col:'#00A9CE',pops:['dxb','auh','fuj'],ix:[],blurb:tr('networks.the_other_half_of_the_uae')}); + {id:'duu',name:'Du-opoly',asn:15820,type:'eye',pol:'paid',freeLv:11,paidFee:6000,share:.004,up:['tat','tly'],col:'#00A9CE',pops:['dxb','auh','fuj'],ix:[],blurb:tr('networks.the_other_half_of_the_uae')}); NETS.push( {id:'kdi',name:'KD-DIY',asn:2561,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#E85D04',pops:['tok','osa','lax','sin','hkg','fuk'],ix:['tok','osa','fuk'],blurb:tr('networks.japanese_carrier_that_builds')}, - {id:'opt',name:'Floptus',asn:4804,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,col:'#00837E',pops:['syd','mel','bne','per'],ix:[],blurb:tr('networks.australia_s_number_two_once_took')}, + {id:'opt',name:'Floptus',asn:4804,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,up:['sgt'],col:'#00837E',pops:['syd','mel','bne','per'],ix:[],blurb:tr('networks.australia_s_number_two_once_took')}, {id:'tpr',name:'Toilet Paper Group',asn:7545,type:'eye',pol:'selective',minIx:8,minPni:25,share:.0035,col:'#4E2A84',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.stockpiled_bandwidth_in_2020_and')}, {id:'abb',name:'Aussie Boyband',asn:4764,type:'eye',pol:'open',share:.002,col:'#00B140',pops:['syd','mel','bne','per','adl','cbr','drw','hba'],ix:['syd','mel','bne','per','adl','drw'],blurb:tr('networks.matching_outfits_perfect_harmonies')}, {id:'voc',name:'Hocus Pocus',asn:4826,type:'t2',pol:'open',up:['ntt','tly'],share:.002,price:7,col:'#E4002B',pops:['syd','mel','bne','per','adl','cbr','drw','hba','sin'],ix:['syd','mel','bne','per','adl','hba','drw','sin'],blurb:tr('networks.now_you_see_the_fibre_now')}, @@ -96,11 +96,11 @@ NETS.push( {id:'cit',name:'Citrus Belgium',asn:47377,type:'eye',pol:'selective',minIx:10,minPni:30,share:.005,up:['lvl'],col:'#FF7900',pops:['bru','par'],ix:['bru'],blurb:tr('networks.tangerine_s_belgian_daughter_mobile')}, {id:'pst',name:'Poste Restante',asn:6663,type:'eye',pol:'selective',minIx:4,minPni:15,share:.001,up:['lvl','tly'],col:'#FFCC00',pops:['bet','fra','ams'],ix:['bet','fra'],blurb:tr('networks.luxembourg_s_post_office_which_also')}, {id:'cms',name:'CityMess',asn:199095,type:'eye',pol:'open',share:.002,up:['cog'],col:'#00B2A9',pops:['oos','bru'],ix:['bru'],blurb:tr('networks.private_5g_and_business_fiber_from')}); -NETS.push({id:'kys',name:'Kyiv Superstar',asn:15859,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#0055B8',pops:['kyv','waw','fra'],ix:['kyv'],blurb:tr('networks.ukraine_s_biggest_mobile_network_has')}); +NETS.push({id:'kys',name:'Kyiv Superstar',asn:15859,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,up:['cog','tly'],col:'#0055B8',pops:['kyv','waw','fra'],ix:['kyv'],blurb:tr('networks.ukraine_s_biggest_mobile_network_has')}); NETS.push({id:'stc',name:'Sticky Telecom',asn:39368,type:'t2',pol:'selective',minIx:10,minPni:30,share:.01,price:8,col:'#4F008C',pops:['ruh','jed','dxb','fra','lon','cai'],ix:['ruh'],blurb:tr('networks.the_kingdom_s_incumbent_once_you')}, - {id:'ord',name:'Ooh-redoo',asn:8871,type:'eye',pol:'paid',freeLv:11,paidFee:5000,share:.004,col:'#ED1C24',pops:['doh','dxb','jkt','mct'],ix:[],blurb:tr('networks.qatar_s_big_operator_paid_peering')}); + {id:'ord',name:'Ooh-redoo',asn:8871,type:'eye',pol:'paid',freeLv:11,paidFee:5000,share:.004,up:['tat','tly'],col:'#ED1C24',pops:['doh','dxb','jkt','mct'],ix:[],blurb:tr('networks.qatar_s_big_operator_paid_peering')}); NETS.push( - {id:'tim',name:'TIM-Tam Italia',asn:3269,type:'eye',pol:'selective',minIx:8,minPni:25,share:.008,col:'#004691',pops:['mil','rom','pmo'],ix:['mil','rom'],blurb:tr('networks.italy_s_incumbent_sweet_on_the')}, + {id:'tim',name:'TIM-Tam Italia',asn:3269,type:'eye',pol:'selective',minIx:8,minPni:25,share:.008,up:['skl'],col:'#004691',pops:['mil','rom','pmo'],ix:['mil','rom'],blurb:tr('networks.italy_s_incumbent_sweet_on_the')}, {id:'skl',name:'Sparkly Seabone',asn:6762,type:'t1',pol:'restrictive',share:.04,price:6,col:'#5B2C83',pops:['pmo','mil','rom','ath','mrs','bcn','mad','lis','par','lon','ams','fra','zrh','vie','bud','prg','waw','buh','sof','ist','ber','sto','nyc','ash','mia','atn','dal','chi','lax','sjc','tor','mex','pan','bog','lim','scl','bue','sao','rio','for','cai','jed','dxb','bom','sin','hkg','tok','hav'],ix:[],blurb:tr('networks.the_tier_1_that_grew_up')}, {id:'fwb',name:'Fast-Webby',asn:12874,type:'eye',pol:'open',share:.004,col:'#FDC300',pops:['mil','rom'],ix:['mil','rom'],blurb:tr('networks.fiber_to_the_italian_home_with')}, {id:'meo',name:'MEO-w Portugal',asn:3243,type:'eye',pol:'selective',minIx:5,minPni:20,share:.004,col:'#00A3E0',pops:['pdl','lis','mad'],ix:['lis'],blurb:tr('networks.portugal_s_incumbent_purrs_when_you')}, diff --git a/src/game/30-networks/30-long-tail.js b/src/game/30-networks/30-long-tail.js index e47a68c..321f35f 100644 --- a/src/game/30-networks/30-long-tail.js +++ b/src/game/30-networks/30-long-tail.js @@ -61,20 +61,27 @@ const TAIL=[ ['Peach State Hosting','cdn',['atn'],tr('long_tail.sweet_fuzzy_and_surprisingly')], ['Chowder Hosting','cdn',['bos'],tr('long_tail.thick_comforting_and_very_new')], ]; +/* Who the long tail buys transit from (#85): small networks almost always buy it from a big carrier where they sit, + usually the cheapest Tier 1 in town or two of them. One or two of the founding five Tier 1s with a PoP in their home + cities, picked by name so it never changes; where none sits (Auckland), a carrier there that buys from them. */ +const TAIL_UP=['cog','lvl','tly','ntt','tat']; +function tailUp(name,home){const h=hstr(name+'|up'),t1=TAIL_UP.filter(id=>{const n=NETS.find(x=>x.id===id);return home.some(c=>n.pops.includes(c));}); + if(!t1.length)return NETS.filter(n=>n.price&&n.up&&n.up.some(u=>TAIL_UP.includes(u))&&home.some(c=>n.pops.includes(c))).map(n=>n.id).slice(0,1); + const a=t1[h%t1.length],b=t1[(h>>>8)%t1.length];return t1.length>1&&(h>>>16)%100<50&&b!==a?[a,b]:[a];} function ixStatic(c){const o=[];if(CITY[c]&&CITY[c].ix)o.push(c);for(const x of XIX)if(x.c===c)o.push(x.id);return o;} TAIL.forEach(([name,type,home,blurb,sh],i)=>{const h=hstr(name),cand=home.flatMap(ixStatic),ix=[]; if(cand.length){ix.push(cand[h%cand.length]);if(cand.length>1&&(h>>>8)%100<40){const o=cand[(h>>>12)%cand.length];if(!ix.includes(o))ix.push(o);}} const sel=(h>>>4)%10>=8; - NETS.push({id:'tail'+i,name,asn:200000+(h%190000),type,tail:true,pol:sel?'selective':'open',...(sel?{minIx:1+(h>>>16)%3,minPni:6+(h>>>18)%8}:{}),share:sh||+(0.0006+((h>>>20)%15)*0.0001).toFixed(4),col:`hsl(${h%360} 55% 46%)`,pops:home.slice(),ix,blurb});}); + NETS.push({id:'tail'+i,name,asn:200000+(h%190000),type,tail:true,up:tailUp(name,home),pol:sel?'selective':'open',...(sel?{minIx:1+(h>>>16)%3,minPni:6+(h>>>18)%8}:{}),share:sh||+(0.0006+((h>>>20)%15)*0.0001).toFixed(4),col:`hsl(${h%360} 55% 46%)`,pops:home.slice(),ix,blurb});}); NETS.push( {id:'ktt',name:'Kay-Tea',asn:4766,type:'eye',pol:'paid',paidFee:5000,perG:90,kr:true,share:.012,col:'#E4002B',pops:['icn','hkg','tok','lax'],ix:[],blurb:tr('long_tail.korea_s_incumbent_sender_pays_every')}, {id:'skb',name:'SK Broadbandit',asn:9318,type:'eye',pol:'paid',paidFee:4000,perG:110,kr:true,share:.01,col:'#EA002C',pops:['icn','hkg','sjc'],ix:[],blurb:tr('long_tail.took_a_streaming_giant_to_court')}, {id:'lgu',name:'LG You-Pay-Plus',asn:3786,type:'eye',pol:'paid',paidFee:3000,perG:80,kr:true,share:.008,col:'#E6007E',pops:['icn','tok'],ix:[],blurb:tr('long_tail.the_plus_is_a_usage_fee')}); NETS.push( {id:'btt',name:'Bee-Tee',asn:2856,type:'eye',pol:'selective',minIx:10,minPni:30,share:.012,col:'#5514B4',pops:['lon','man','edi','bde'],ix:['lon','man'],blurb:tr('long_tail.the_uk_s_incumbent_buzzes_politely')}, - {id:'sky',name:'Sky-High Broadband',asn:5607,type:'eye',pol:'selective',minIx:6,minPni:25,share:.008,col:'#0072C9',pops:['lon','man','edi','dub'],ix:['lon','man','edi'],blurb:tr('long_tail.football_films_and_a_router_that')}, - {id:'vmo',name:'Virgin Mediocre',asn:5089,type:'eye',pol:'selective',minIx:6,minPni:25,share:.007,col:'#E10A0A',pops:['lon','man','edi'],ix:['lon','man'],blurb:tr('long_tail.cable_broadband_for_half_of_britain')}, - {id:'tnr',name:'Tele-Nor-Way',asn:2119,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#00A9E0',pops:['osl','svg','sto','cph','krs'],ix:['osl','svg'],blurb:tr('long_tail.norway_s_incumbent_neither_yes_nor')}); + {id:'sky',name:'Sky-High Broadband',asn:5607,type:'eye',pol:'selective',minIx:6,minPni:25,share:.008,up:['tly','lvl'],col:'#0072C9',pops:['lon','man','edi','dub'],ix:['lon','man','edi'],blurb:tr('long_tail.football_films_and_a_router_that')}, + {id:'vmo',name:'Virgin Mediocre',asn:5089,type:'eye',pol:'selective',minIx:6,minPni:25,share:.007,up:['lvl','ntt'],col:'#E10A0A',pops:['lon','man','edi'],ix:['lon','man'],blurb:tr('long_tail.cable_broadband_for_half_of_britain')}, + {id:'tnr',name:'Tele-Nor-Way',asn:2119,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,up:['tly','lvl'],col:'#00A9E0',pops:['osl','svg','sto','cph','krs'],ix:['osl','svg'],blurb:tr('long_tail.norway_s_incumbent_neither_yes_nor')}); NETS.push( {id:'hwt',name:'Hawaiian Telecombo',asn:36149,type:'eye',pol:'selective',minIx:3,minPni:15,share:.004,up:['ntt','lvl'],col:'#5B2A86',pops:['hnl'],ix:['hnl'],blurb:tr('long_tail.hawaii_s_incumbent_every_plan_comes')}, {id:'gtg',name:'Grand Theft Teleguam',asn:9246,type:'t2',pol:'open',share:.002,price:8,up:['ntt','tat'],col:'#0072CE',pops:['gum','ror','maj','hnl','tok'],ix:['gum','hnl'],blurb:tr('long_tail.guam_s_incumbent_and_the_way')}, diff --git a/src/game/30-networks/40-traffic-shares.js b/src/game/30-networks/40-traffic-shares.js index 539bf5e..67a0c3b 100644 --- a/src/game/30-networks/40-traffic-shares.js +++ b/src/game/30-networks/40-traffic-shares.js @@ -1,6 +1,22 @@ const NET=Object.fromEntries(NETS.map(n=>[n.id,n])),NET_IDS=NETS.map(n=>n.id); -// The networks a PNI with each upstream reaches: the upstream itself plus everyone who buys transit from it. -const PNI_NETS={};for(const n of NETS)PNI_NETS[n.id]=[n.id].concat(NETS.filter(x=>x.up&&x.up.includes(n.id)).map(x=>x.id)); +/* Customer cones (#85): a network announces to its peers itself and everyone who buys transit from it, and their + customers in turn. So a PNI or a session with a network reaches its whole cone, and peering with every Tier 1 brings + their customers along. Built once at load: CONE[id] lists the network first, then its cone; CONE_S is the same as a + Set, and DOWN[id] holds the cone without the network itself (empty for most). */ +/* Who buys from whom follows the real networks' upstreams (bgp.he.net, CAIDA AS Rank, Oct 2026). Added in 2.0: Kyiv + Superstar (Cogentle, Tell-Ya), Ooh-redoo and Du-opoly (Ta-Ta, Tell-Ya), Safari-Comic (Cogentle, Level Tree, Sea-Comedy), + 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. */ +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);}} + CONE[n.id]=[...s];CONE_S[n.id]=s;DOWN[n.id]=CONE[n.id].slice(1);}} +// ANC[id]: every network whose cone holds it, nearest upstream first (who brings it along, for the panels). +const ANC={};for(const n of NETS){const o=[],q=(n.up||[]).slice();while(q.length){const u=q.shift();if(o.includes(u)||!NETS.some(x=>x.id===u))continue;o.push(u);q.push(...(NETS.find(x=>x.id===u).up||[]));}ANC[n.id]=o;} +// The networks a PNI with each network reaches: its customer cone. CONE_RANK: where routing tries a peer's cone. +const PNI_NETS=CONE,CONE_RANK=2.5; for(const X of XIX){X.members=NETS.filter(n=>Array.isArray(n.ix)&&n.ix.includes(X.id)||!n.tail&&(X.core?X.core.includes(n.id):(n.ix==='ALL'||Array.isArray(n.ix)&&n.ix.includes(X.c))&&hstr(n.id+'|'+X.id)%100<(n.ix==='ALL'?72:X.take*100))).map(n=>n.id);} const NSH={}; {const t=NETS.reduce((a,n)=>a+n.share,0); NETS.forEach(n=>NSH[n.id]=n.share/t);} // After Glitch leaves Korea, Seoul viewers watch half as much of it and the rest moves to everyone else. diff --git a/src/game/40-progress/20-goals.js b/src/game/40-progress/20-goals.js index 1d37014..9e4eaf3 100644 --- a/src/game/40-progress/20-goals.js +++ b/src/game/40-progress/20-goals.js @@ -18,6 +18,6 @@ const GOALS=[ {id:'c5',t:tr('common.five_continents'),d:tr('goals.pops_in_five_of_the_six'),r:100000,ok:()=>regionsCount()>=5}, {id:'gi',t:tr('goals.sign_a_giant'),d:tr('goals.land_an_ai_wan_a_multi'),r:150000,ok:()=>S.biz.some(b=>BIZ_T[b.type]&&BIZ_T[b.type].mega&&!BIZ_T[b.type].event)}, {id:'t10',t:tr('goals.serve_10_tbps'),d:tr('goals.ten_terabits_per_second_of_happy'),r:250000,ok:()=>R.served>=10000}, - {id:'t1',t:tr('common.go_transit_free_tier_1'),d:tr('goals.peer_with_every_tier_1_over'),r:0,win:true,ok:()=>isTier1()}, + {id:'t1',t:tr('common.go_transit_free_tier_1'),d:tr('goals.peer_with_every_tier_1_their_customers'),r:0,win:true,ok:()=>isTier1()}, ]; diff --git a/src/game/50-state.js b/src/game/50-state.js index 41e2b01..35dd8f6 100644 --- a/src/game/50-state.js +++ b/src/game/50-state.js @@ -2,4 +2,4 @@ let S=null, R=emptyR(); const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false}; let uidN=1; const uid=()=>'i'+(Date.now()%1e7).toString(36)+(uidN++); -function emptyR(){return {nt:{},reachNT:0,teBlack:0,tNet:{},egT:{},netEg:{},l2lat:{},nodeLoad:{},nodeCap:{},div:{},l2:{},gfwLost:0,gfwCross:0,ef:{},egDesc:{},p95:{},peered:0,peerShare:0,load:{},useT:{},useIx:{},usePni:{},useCache:{},cityDem:{},citySrv:{},cityEye:{},latF:{},latFar:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{}};} +function emptyR(){return {nt:{},cone:{},reachNT:0,teBlack:0,tNet:{},egT:{},netEg:{},l2lat:{},nodeLoad:{},nodeCap:{},div:{},l2:{},gfwLost:0,gfwCross:0,ef:{},egDesc:{},p95:{},peered:0,peerShare:0,load:{},useT:{},useIx:{},usePni:{},useCache:{},cityDem:{},citySrv:{},cityEye:{},latF:{},latFar:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{}};} diff --git a/src/game/60-features/50-traceroute.js b/src/game/60-features/50-traceroute.js index dd7ad77..c29ba72 100644 --- a/src/game/60-features/50-traceroute.js +++ b/src/game/60-features/50-traceroute.js @@ -8,8 +8,9 @@ function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCitie const path=dst=>{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=[]; 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}); - for(const p of S.pni)if(p.net===net&&pniOn(p)&&popUp(p.city)&&liveN(p.city,p.site,p.n))out.push({k:'p',rank:1,city:p.city,pref:p.pref||'normal',lab:tr('common.pni_with_net',{net:NET[net].name}),used:R.usePni[p.id]||0,cap:liveCap(pniG(p),p.city,p.site,p.n)}); - for(const c in S.ixp)if(ixSessions(c).has(net)&&(popUp(ixCity(c))||remoteCities().includes(ixCity(c)))&&!(ev.ixdown&&ev.ixdown[c]>day))out.push({k:'ix',rank:2,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)}); + // 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 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;} 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; @@ -28,10 +29,11 @@ function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[] hop(`ae-2.core.${far}.${slug(T.name)}.net`,`203.0.113.${(hstr(far)+7)%250}`,km*1.3/100+0.3,CITY[far]?tr('traceroute.net_carries_it_to_city',{net:T.name,city:CITY[far].name}):''); 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(N.name)}.${e.city}.${me}`,ip(hstr(N.id),3),0.2,tr('traceroute.private_cross_connect'));} + 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}));} else{hop(`cache-${slug(N.name)}.${e.city}.${me}`,ip(hstr(N.id),4),0.1,tr('traceroute.embedded_cache_in_your_rack'));} asPath.push(N.asn);if(e.k!=='c')hop(`www.${slug(N.name)}.example`,`198.51.100.${(hstr(N.id)+1)%250}`,0.5+(e.k==='t'?1:0.2),`${N.name}`); - const order={c:tr('traceroute.caches_beat_pnis'),p:tr('traceroute.pnis_beat_ix_peering'),ix:tr('traceroute.ix_peering_beats_transit'),t:tr('traceroute.transit_is_the_last_resort')}[e.k]; + const order=e.via?tr('traceroute.a_peer_s_customers_come_after'):{c:tr('traceroute.caches_beat_pnis'),p:tr('traceroute.pnis_beat_ix_peering'),ix:tr('traceroute.ix_peering_beats_transit'),t:tr('traceroute.transit_is_the_last_resort')}[e.k]; const cn=cnCity(src)!==!!N.cn?' '+tr('traceroute.crossing_the_great_firewall_here',{p:S.ev.gfw>S.day?35:20}):''; return {text:lines.join('\n'),why:`${tr('traceroute.exit_exit_in_city',{exit:e.lab,city:CITY[e.city].name})} ${tr('traceroute.rule_and_closer_exits_win_ties',{rule:order[0].toUpperCase()+order.slice(1)})}${e.pref!=='normal'?tr('traceroute.this_one_is_set_to_mode',{mode:e.pref==='high'?tr('common.prefer'):tr('common.backup_only')}):''}.${e.used>=e.cap*0.999?' '+tr('traceroute.it_is_full_so_some_traffic'):''}${cn}`,asPath};} function traceModal(src,to){const pops=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));src=src&&S.pops[src]?src:UI.trFrom&&S.pops[UI.trFrom]?UI.trFrom:S.home&&S.pops[S.home]?S.home:pops[0]; diff --git a/src/game/60-features/60-share-card.js b/src/game/60-features/60-share-card.js index 2178751..dcb0266 100644 --- a/src/game/60-features/60-share-card.js +++ b/src/game/60-features/60-share-card.js @@ -15,11 +15,14 @@ function shareCanvas(){const Wc=1200,Hc=630,cv=document.createElement('canvas'); g.fillStyle='#1E2640';g.font='900 54px "Baloo 2", sans-serif';g.textBaseline='top';g.fillText(S.name,40,28); g.font='800 26px Nunito, sans-serif';g.fillText(`AS${S.asn} · ${tierLabel()} · ${dateStr(S.day)}${S.mode==='sandbox'?' · '+tr('common.sandbox'):''}`,42,92); // stats - const got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined),rk={l:0,e:1,r:2,c:3},top=got.slice().sort((a,b)=>rk[a.r]-rk[b.r]).slice(0,8); + const got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined),rk={l:0,e:1,r:2,c:3},lv=b=>bvar(S.achP&&S.achP[b.id]).lv,top=got.slice().sort((a,b)=>rk[a.r]-rk[b.r]||lv(b)-lv(a)).slice(0,8); const rows=[[tr('common.peak_traffic'),fmtG(S.stats.peak||0)],[tr('common.peered'),pct(R.peerShare||0)],[tr('common.pops'),tr('share_card.n_in_r_regions',{n:Object.keys(S.pops).length,r:regionsCount()})],[tr('common.links'),String(S.links.length)],[tr('common.customers'),String(S.biz.length)],[tr('common.incidents_survived'),String(S.stats.survived||0)],[tr('common.shark_bites'),String(S.stats.sharks||0)],[tr('common.badges'),`${got.length}/${BADGES.length}`]]; 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();}}); 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); return cv;} function shareModal(){const cv=shareCanvas();if(!cv){toast(tr('share_card.your_browser_cannot_draw_the_card'),'bad');return;}let url='';try{url=cv.toDataURL('image/png');}catch(e){} diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 6a368e3..58c2d53 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:{},pairMet:{}, + ltv:2,t1v:3,auV:1,achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, done:{},inc:[],ev:{},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/70-rules/80-hot-ports-and-rank.js b/src/game/70-rules/80-hot-ports-and-rank.js index c7f0f16..1d6671a 100644 --- a/src/game/70-rules/80-hot-ports-and-rank.js +++ b/src/game/70-rules/80-hot-ports-and-rank.js @@ -13,8 +13,11 @@ function isTier2(){return Object.keys(S.pops).length>=5&&Object.keys(S.ixp).leng // Sparkly Seabone joined the Tier 1s in 1.12. Older saves keep the five they were playing for. // Tier 1s added later only count for games started after them, so old saves keep their win (#155). const t1Need=()=>NETS.filter(n=>n.type==='t1'&&(n.id!=='skl'||(S&&S.t1v>=2))&&(n.id!=='att'||(S&&S.t1v>=3))); +/* Reach is counted through customer cones (#85): a PNI with a Tier 1 reaches everyone who buys transit from it, and + their customers. That only ever adds reach, so the rule is easier for every save, old ones included, and needs no + version: what was Tier 1 stays Tier 1. Networks in nobody's cone still need peering of their own. */ function isTier1(){return t1Need().every(n=>S.pni.some(p=>p.net===n.id&&pniOn(p)))&&S.transit.length===0&&R.reach>0.999;} // What you are now, not what you once were (#46): buying transit again or losing reach drops the label. function tierLabel(){return S.won&&isTier1()?'Tier 1':isTier2()?'Tier 2':'Tier 3';} -function t1Why(){if(S.transit.length)return tr('hot_ports_and_rank.you_buy_transit_again');const miss=t1Need().filter(n=>!S.pni.some(p=>p.net===n.id&&pniOn(p)));if(miss.length)return tr('hot_ports_and_rank.no_pni_with_list',{list:miss.map(n=>n.name).join(', ')});{const lost=NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id]);if(lost.length)return tr('hot_ports_and_rank.you_cannot_reach_list',{list:lost.slice(0,3).map(n=>n.name).join(', ')+(lost.length>3?' '+tr('hot_ports_and_rank.and_n_more',{n:lost.length-3}):'')});}return tr('hot_ports_and_rank.your_reach_is_p_not_100',{p:reachPct(R.reach)});} +function t1Why(){if(S.transit.length)return tr('hot_ports_and_rank.you_buy_transit_again');const miss=t1Need().filter(n=>!S.pni.some(p=>p.net===n.id&&pniOn(p)));if(miss.length)return tr('hot_ports_and_rank.no_pni_with_list',{list:miss.map(n=>n.name).join(', ')});{const lost=NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id]);if(lost.length)return tr('hot_ports_and_rank.you_cannot_reach_list_outside_cones',{list:lost.slice(0,3).map(n=>n.name).join(', ')+(lost.length>3?' '+tr('hot_ports_and_rank.and_n_more',{n:lost.length-3}):'')});}return tr('hot_ports_and_rank.your_reach_is_p_not_100',{p:reachPct(R.reach)});} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index cbe0fd6..1e3c057 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -23,20 +23,26 @@ function compute(){ E.push(ex);if(pf)E.push({...ex,cap:cap*pf,prep:true});} // `nets`: every network ok() can say yes to, so it need not be asked about the other hundred. for(const c in S.ixp){const ct=ixCity(c);if(!(popUp(ct)||remote.includes(ct))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||!(S.myIx[c]?myIxLive(c):liveN(ct,(S.ixSite||{})[c],(S.ixn||{})[c])))continue;const set=ixSessions(c);R2.sessions+=set.size; - E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:labOf(N_('common.ix_peering'),'ix',ixName(c)),id:c,city:ct,cap:ixCap(c),used:0,rank:2,ok:n=>set.has(n),nets:set});} - for(const p of S.pni){if(!pniOn(p)||!popUp(p.city)||!liveN(p.city,p.site,p.n))continue;R2.sessions++;E.push({k:'p',pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:labOf(N_('common.pni_with_net'),'net',NET[p.net].name),id:p.id,city:p.city,cap:liveCap(pniG(p),p.city,p.site,p.n)*lagF(p)*(p.sacrif?0.5:1),used:0,rank:1,ok:n=>n===p.net||!!(NET[n].up&&NET[n].up.includes(p.net)),nets:PNI_NETS[p.net]});} + // A peer announces its customers too (#85): the session reaches its cone, after the networks peering directly. + let all=set;for(const id of set)if(DOWN[id].length){if(all===set)all=new Set(set);for(const x of DOWN[id])all.add(x);} + E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:labOf(N_('common.ix_peering'),'ix',ixName(c)),id:c,city:ct,cap:ixCap(c),used:0,rank:2,ok:n=>all.has(n),nets:all,dir:all===set?null:set});} + for(const p of S.pni){if(!pniOn(p)||!popUp(p.city)||!liveN(p.city,p.site,p.n))continue;R2.sessions++;E.push({k:'p',pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:labOf(N_('common.pni_with_net'),'net',NET[p.net].name),id:p.id,city:p.city,cap:liveCap(pniG(p),p.city,p.site,p.n)*lagF(p)*(p.sacrif?0.5:1),used:0,rank:1,net:p.net,ok:n=>CONE_S[p.net].has(n),nets:CONE[p.net]});} for(const c of S.caches){if(!popUp(c.city)||siteDown(c.city,c.site==='b'?'b':'a'))continue;E.push({k:'c',pref:'normal',lab:labOf(N_('common.name_cache'),'name',NET[c.net].cache.name),id:c.id,city:c.city,cap:CACHE_CAP,used:0,rank:0,ok:n=>n===c.net,nets:[c.net]});} // After an update adds networks, a free courtesy route reaches the new ones you have no other way to (#46). R2.graceNets=0;if(S.grace&&S.grace.until>day){const gs=new Set(S.grace.nets.filter(n=>NET[n]&&!E.some(e=>e.k!=='c'&&e.ok(n)))),hc=popUp(S.home)?S.home:pops.find(popUp); R2.graceNets=gs.size;if(gs.size&&hc)E.push({k:'ix',pref:'normal',lab:tr('compute.courtesy_route_to_new_networks'),id:'~grace',city:hc,cap:1e9,used:0,rank:2,ok:n=>gs.has(n),nets:gs});} {const rp=ev.rpki&&ev.rpki.until>day?new Set(ev.rpki.nets):null;if(rp)for(const e of E){if(e.k==='c')continue;const o=e.ok;e.ok=n=>!rp.has(n)&&o(n);}} + // coneOf: does exit e reach network n only through a peer's customer cone (#85)? + const coneOf=(e,n)=>e.k==='p'?e.net!==n:!!e.dir&&!e.dir.has(n); // 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;} // 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];}} + 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;}} 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). @@ -147,15 +153,17 @@ function compute(){ 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 base=e=>e.pref==='low'?4:e.rank; + /* A network in a peer's customer cone, reached through that peer (#85): after every network you peer with directly + (its AS path is one hop longer) and before transit. */ + const base=(e,n)=>e.pref==='low'?4:e.rank>0&&e.rank<3&&coneOf(e,n)?CONE_RANK: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;}; - const RANKS=TR?[0,0.5,1,2,2.9,3,3.5,4,4.4,4.5,4.6]:[0,1,2,3,4]; + const eff=(e,n)=>{let r=base(e,n);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;}; + const RANKS=TR?[0,0.5,1,2,CONE_RANK,2.9,3,3.5,4,4.4,4.5,4.6]:[0,1,2,CONE_RANK,3,4]; // With `protect customers`, business flows take every rank first; home users get what is left. 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. - const byRank={};for(const id of NET_IDS){const m=byRank[id]={};for(const e of okBy[id]){const r=TR?eff(e,id):base(e);(m[r]||(m[r]=[])).push(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]);}}} // 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=[]; @@ -200,7 +208,7 @@ function compute(){ // same comparison, so the order is the same either way. const sortD=a=>{const n=a.length;if(n>24){a.sort(byDist);return;}for(let i=1;i=0&&byDist(a[j],x)>0){a[j+1]=a[j];j--;}a[j+1]=x;}}; for(const pass of PASSES||[null])for(const rank of RANKS){ - if(TR?!E.length:!E.some(e=>base(e)===rank))continue; + if(!RSET.has(rank))continue; // Index loops in here: plain for…of allocates an iterator per loop until V8 has optimised compute(). for(let fi=0,FN=flows.length;fi(st().hackWin||0)>=1}, {id:'zero',i:'🕳️',t:tr('badges.zero_peers_given'),d:tr('badges.reach_tier_2_with_every_single'),r:'l',secret:true,ok:()=>isTier2()&&!Object.keys(S.peers).length&&!S.pni.length}, ]; -function hof(){try{return JSON.parse(localStorage.getItem('sot-badges')||'{}')||{};}catch(e){return {};}} -function checkBadges(){S.ach=S.ach||{};if(S.mode==='sandbox')return;let h=null; - for(const b of BADGES){if(S.ach[b.id]!==undefined)continue;let ok=false;try{ok=b.ok();}catch(e){} - if(!ok)continue;S.ach[b.id]=S.day;const R0=RARITY[b.r]; - if(!h)h=hof();if(!h[b.id])h[b.id]={d:new Date().toISOString().slice(0,10),n:S.name}; - toast(`${b.i} ${tr('badges.badge_unlocked_name',{name:esc(b.t)})}
${R0.n} · ${esc(b.d)}`,'goal',[],{a:'tab',v:'goals'});sfx('coin');track('badge_'+b.id);} +/* Badge variants by ruleset (2.0): On-call earns the standard badge, Change Freeze a frosted one and BGP at 3 a.m. a + 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; +// 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';} +// 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:{}; + x.vs={};for(const v of BVAR_IDS)if(typeof vs[v]==='string')x.vs[v]=vs[v];if(!Object.keys(x.vs).length)x.vs.oncall=typeof x.d==='string'?x.d:''; + x.v=BVAR_IDS.filter(v=>x.vs[v]!==undefined).pop();} + return h;} +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));} if(h)try{localStorage.setItem('sot-badges',JSON.stringify(h));}catch(e){}} -function badgeGrid(){const h=hof(),got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined).length; - return `

${tr('common.badges')} ${tr('badges.got_total_this_game_ever_ever',{got,total:BADGES.length,ever:Object.keys(h).filter(k=>BADGES.some(b=>b.id===k)).length})}

${BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!h[b.id],R0=RARITY[b.r],hide=b.secret&&!on&&!ever; - return `
${hide?'❔':b.i}${esc(hide?'???':b.t)}${R0.n}${ever&&!on?' · '+tr('common.earned_before'):''}${hide?'':`${esc(b.d)}`}
`;}).join('')}
`;} +// 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;} +function badgeGrid(){const h=hof(),got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined).length,sh=badgeShelf(h),V=badgeVar(); + return `

${tr('common.badges')} ${tr('badges.got_total_this_game_ever_ever',{got,total:BADGES.length,ever:Object.keys(h).filter(k=>BADGES.some(b=>b.id===k)).length})}

+
${BVAR_IDS.map(v=>`${BVAR[v].i} ${esc(tr(BVAR[v].n))} ${sh[v]}/${BADGES.length}`).join('')}
${V&&V!=='oncall'?`

${V==='bgp'?tr('badges.this_game_earns_fiery_badges'):tr('badges.this_game_earns_frosted_badges')}

`:''} +
${BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!h[b.id],R0=RARITY[b.r],hide=b.secret&&!on&&!ever,vk=on?bvar(S.achP&&S.achP[b.id]).k:ever?h[b.id].v:'',vn=vk&&vk!=='oncall'?' · '+BVAR[vk].i+' '+tr(BVAR[vk].n):''; + return `
${hide?'❔':b.i}${esc(hide?'???':b.t)}${R0.n}${ever&&!on?' · '+tr('common.earned_before'):''}${vk&&vk!=='oncall'?`${BVAR[vk].i} ${esc(tr(BVAR[vk].n))}`:''}${hide?'':`${esc(b.d)}`}
`;}).join('')}
`;} function checkGoals(){checkBadges(); for(const g of GOALS){if(S.done[g.id]!==undefined)continue;let ok=false;try{ok=g.ok();}catch(e){} if(ok){S.done[g.id]=S.day;if(g.r&&S.mode!=='sandbox'){S.cash+=g.r;} diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 2a98394..9248b98 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -76,7 +76,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&&!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(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/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 0378b3f..e89b6e4 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -132,6 +132,8 @@ function svgChart(rows,stackKeys,lines,fmtY){ // For a network you currently reach over transit: the cheapest way to move it to peering. // Exchange members as sets, rebuilt once per routing pass: hints are asked for many networks at a time. let IXMR=null,IXMC={};const ixHas=(x,id)=>{if(IXMR!==R){IXMR=R;IXMC={};}return (IXMC[x]||(IXMC[x]=new Set(ixMembers(x)))).has(id);}; +// Who brings a network along (#85): the nearest of its upstreams, then theirs; null if it sits in nobody's cone. +function coneVia(id){const a=ANC[id];if(!a||!a.length)return null;const t1=a.find(u=>NET[u].type==='t1');return NET[t1||a[0]];} function offTransitHint(id,city){const n=NET[id];if(n.type==='t1')return tr('link_panels.tier_1_only_a_pni_and'); const ixc=Object.keys(S.pops).flatMap(ixIdsIn).filter(x=>ixHas(x,id)),here=city&&ixIdsIn(city).find(x=>ixHas(x,id))||null,pick1=here||ixc.find(x=>S.ixp[x]!==undefined)||ixc[0]; if(n.pol==='open'){if(pick1)return here||ixNamesCity(pick1)?tr('link_panels.open_peer_join_the_route_server',{ix:ixName(pick1)}):tr('link_panels.open_peer_join_the_route_server_01a1',{ix:ixName(pick1),city:CITY[ixCity(pick1)].name});const x=nearestSpot(id);return x?tr('link_panels.open_peer_but_not_on_any',{city:CITY[x.c].name}):tr('link_panels.open_peer_but_not_on_any_bfbb');} diff --git a/src/game/94-dashboard/20-meet-a-network.js b/src/game/94-dashboard/20-meet-a-network.js index 344f305..736005a 100644 --- a/src/game/94-dashboard/20-meet-a-network.js +++ b/src/game/94-dashboard/20-meet-a-network.js @@ -27,5 +27,7 @@ function t1Card(){const cur=GOALS.find(g=>S.done[g.id]===undefined);if(!((cur&&c h+=pRow({l:tr('meet_a_network.pnis_with_every_tier_1'),v:need.length-miss.length,max:need.length,txt:`${need.length-miss.length} / ${need.length}`}); if(miss.length)h+=`
${miss.map(nb).join('')}
`+(club.ok?'':`

${tr('meet_a_network.tier_1s_only_take_a_pni',{list:club.missing.join(', ')})}

`); h+=pRow({l:tr('meet_a_network.reach_without_transit'),v:Math.min(R.reachNT,0.999),max:0.999,txt:`${reachPct(R.reachNT)} / 99.9%`}); + // Their customers come along for free (#85): say how many, so the long tail does not look like homework. + {const nc=Object.keys(R.cone||{}).length;h+=`

${nc?trn('meet_a_network.peer_with_the_tier_1_club_n',nc):tr('meet_a_network.peer_with_the_tier_1_club')}

`;} if(lost.length)h+=`
${lost.slice(0,3).map(nb).join('')}${btn(trn('meet_a_network.all_n_out_of_reach',lost.length),'netFilter',{f:'out'},'pink sm')}
`; return h+'
';} diff --git a/src/game/95-modals/60-help.js b/src/game/95-modals/60-help.js index e8e5e51..e632c99 100644 --- a/src/game/95-modals/60-help.js +++ b/src/game/95-modals/60-help.js @@ -5,7 +5,7 @@ function showHelp(){
${tr('common.eyeballs')}
${tr('help.home_broadband_users_they_mostly')}
POP
${tr('help.point_of_presence_your_router_in')}
${tr('common.ip_transit')}
${tr('help.you_pay_a_bigger_network_per')}
-
Tier 1 / Tier 2
${tr('help.tier_1s_reach_the_whole_internet')}
+
Tier 1 / Tier 2
${tr('help.tier_1s_reach_the_whole_internet_cones')}
CDN
${tr('help.content_networks_like_netchill_and')}
${tr('help.ix_internet_exchange')}
${tr('help.a_shared_switch_in_a_city')}
PNI
${tr('help.private_network_interconnect_a_cable')}
diff --git a/src/i18n/en.js b/src/i18n/en.js index 008cdfd..2a4aa4f 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -18,6 +18,7 @@ "badges.attend_a_conference":"Attend a conference.", "badges.attend_six_conferences_in_one_game":"Attend six conferences in one game.", "badges.badge_unlocked_name":"Badge unlocked: {name}", +"badges.badge_upgraded_name":"Badge upgraded: {name}", "badges.blackhole_one_of_your_own_cities":"Blackhole one of your own cities to stop a DDoS.", "badges.bring_up_your_first_peering_session":"Bring up your first peering session.", "badges.build_fiber_across_the_andes":"Build fiber across the Andes.", @@ -99,9 +100,14 @@ "badges.take_a_de_kicks_retention_offer":"Take a DE-KICKS retention offer.", "badges.take_out_a_loan":"Take out a loan.", "badges.the_long_way_round":"The Long Way Round", +"badges.this_game_earns_fiery_badges":"This game runs BGP at 3 a.m.: every badge you earn here is forged in fire, and upgrades one you already have.", +"badges.this_game_earns_frosted_badges":"This game runs a Change Freeze: badges you earn here come freeze-dried.", "badges.through_the_wall":"Through the Wall", "badges.turn_on_a_transit_clean_pipe":"Turn on a transit clean-pipe add-on.", "badges.two_buildings_three_cities":"Two Buildings, Three Cities", +"badges.variant_forged_at_3_a_m":"Forged at 3 a.m.", +"badges.variant_freeze_dried":"Freeze-dried", +"badges.variant_on_call":"On-call", "badges.weather_a_ddos_with_your_defences":"Weather a DDoS with your defences ready.", "badges.weather_a_multi_terabit_ddos":"Weather a multi-terabit DDoS.", "badges.win_without_ever_taking_a_loan":"Win without ever taking a loan.", @@ -1828,7 +1834,7 @@ "goals.make_5_peering_friends":"Make 5 peering friends", "goals.on_the_peering_tab_request_sessions":"On the Peering tab, request sessions, or join the route server to peer with every open network at once.", "goals.open_your_home_city_and_press":"Open your home city and press “Launch broadband”. Eyeballs are people at home watching cat videos. They pay you every month.", -"goals.peer_with_every_tier_1_over":"Peer with every Tier 1 over PNIs and cancel every transit port. Then nobody charges you to reach the internet.", +"goals.peer_with_every_tier_1_their_customers":"Peer with every Tier 1 over PNIs and cancel every transit port. Their customers come along for free, so you only chase the networks nobody sells transit to.", "goals.pops_in_five_of_the_six":"POPs in five of the six regions on the map.", "goals.reach_the_whole_internet":"Reach the whole internet", "goals.serve_10_tbps":"Serve 10 Tbps", @@ -1890,7 +1896,7 @@ "help.the_chart_button_at_the_top":"The chart button at the top opens traffic graphs by exit (caches, PNIs, IX, transit), money over time, per-ASN traffic with how it reaches you and what its transit costs, plus your busiest links and routers.", "help.the_group_behind_several_big":"The group behind several big exchanges (Frankfurt, Madrid, Marseille, Dubai, Mumbai, New York) treats price lists as a state secret. Ports are quoted per customer and go up the bigger you look. Haggling can work, backfire or stall for a week. Prices get \"harmonised\" upwards once a year, add-ons appear on your invoice until you opt out, and trying to leave earns you a retention discount that ends with a fee.", "help.things_break_all_the_time_fiber":"Things break all the time: fiber cuts, router crashes, power cuts, IX loops, fabric outages, route leaks, DDoS, fat fingers, cooling failures, and geopolitics: sanctions, tariffs, BGP hijacks, landing permit disputes, exam-day shutdowns and Red Sea cable cuts. Traffic reroutes automatically over other paths and upstreams. Parallel links on diverse routes, a second router and a backup generator all help. Or pay to rush repairs.", -"help.tier_1s_reach_the_whole_internet":"Tier 1s reach the whole internet without paying anyone, because they all peer with each other. Tier 2s peer a lot but still buy some transit.", +"help.tier_1s_reach_the_whole_internet_cones":"Tier 1s reach the whole internet without paying anyone: they all peer with each other, and each brings along its customer cone, everyone who buys transit from it. Tier 2s peer a lot but still buy some transit.", "help.traffic_follows_the_shortest_path_by":"Traffic follows the shortest path by distance and link metric, and reroutes by itself when links fail. When a path is merely full, the overflow is dropped, just like a real IGP. From customer level 3 you can install Auto-TE in the NOC tab: it spills overflow onto up to two alternate paths with free capacity, as long as they are no more than twice as long.", "help.transit_bills_sample_your_usage":"Transit bills sample your usage every day and charge the 95th percentile of the last 30 days, so short spikes are forgiven but long ones are not.", "help.users_feel_the_round_trip_to":"Users feel the round trip to wherever their traffic leaves your network for transit. Up to 20 ms (about 1,500 km) is fine; past 50 ms broadband and internet services count as bad service, which costs revenue and customers. Traffic over your own peering, PNIs and caches is not penalised.", @@ -1915,12 +1921,13 @@ "hot_ports_and_rank.upgrade_the_ix_port_or_add":"Upgrade the IX port or add a LAG member.", "hot_ports_and_rank.upgrade_the_router_or_add_a":"Upgrade the router or add a second one in the Infra tab.", "hot_ports_and_rank.you_buy_transit_again":"you buy transit again", -"hot_ports_and_rank.you_cannot_reach_list":"you cannot reach {list}", +"hot_ports_and_rank.you_cannot_reach_list_outside_cones":"you cannot reach {list}, which nobody you peer with sells transit to", "hot_ports_and_rank.your_reach_is_p_not_100":"your reach is {p}, not 100%", "hud_and_panels.all_connections_n":"All connections {n}", "hud_and_panels.all_systems_green_enjoy_it_while":"All systems green. Enjoy it while it lasts.", "hud_and_panels.auto_fix_in_n_day":{"one":"Auto-fix in {n} day","other":"Auto-fix in {n} days"}, "hud_and_panels.blackholing_g":"blackholing {g}", +"hud_and_panels.buys_transit_from_net_peer_with":"Buys transit from {net}. Peer with {net} and it comes along.", "hud_and_panels.customer_level_lv_name":"Customer level {lv}: {name}", "hud_and_panels.dropping_or_overflowing":"dropping or overflowing", "hud_and_panels.every_network_on_the_map_traffic":"Every network on the map. Traffic share is how much of your users' traffic goes to them. Tap a connection to jump to its POP.", @@ -1957,6 +1964,7 @@ "hud_and_panels.p_of_traffic_between_them_scattered":"{p}% of traffic between them, scattered across exchanges. You peer with {n}.", "hud_and_panels.ports_caches_and_routers_running_hot":"Ports, caches and routers running hot", "hud_and_panels.raise_a_full_link_s_metric":"Raise a full link’s metric so traffic prefers another path, upgrade it, or install Auto-TE.", +"hud_and_panels.reached_through_the_customer_cone_of":"Reached through the customer cone of {net}: it buys transit there.", "hud_and_panels.reaches_networks_from_the_last":"Reaches networks from the last update that you have no other path to, for free. Connect to them before it ends.", "hud_and_panels.reward_cash":"Reward {cash}", "hud_and_panels.survived_with_no_impact":"Survived with no impact", @@ -2348,6 +2356,8 @@ "loop.welcome_back_name_your_network_is":"Welcome back, {name}.
Your network is right where you left it: {date}.", "loop.your_saved_game_could_not_be":"Your saved game could not be loaded.
It was damaged, so a backup was kept and you can start fresh.", "meet_a_network.all_n_out_of_reach":{"one":"All {n} out of reach","other":"All {n} out of reach"}, +"meet_a_network.peer_with_the_tier_1_club":"Peer with the Tier 1 club: their customers come along for free. Only networks in nobody’s customer cone need peering of their own.", +"meet_a_network.peer_with_the_tier_1_club_n":{"one":"Peer with the Tier 1 club: their customers come along for free. {n} network already comes along with a peer.","other":"Peer with the Tier 1 club: their customers come along for free. {n} networks already come along with a peer."}, "meet_a_network.pnis_with_every_tier_1":"PNIs with every Tier 1", "meet_a_network.reach_without_transit":"Reach without transit", "meet_a_network.road_to_tier_1":"Road to Tier 1", @@ -3035,6 +3045,7 @@ "title.scenarios_amp_weekly_challenge":"Scenarios & weekly challenge →", "title.source_on_github":"Source on GitHub", "title.your_network_name_was_saved_and":"Your network {name} was saved and is waiting for you.", +"traceroute.a_peer_s_customers_come_after":"a peer’s customers come after direct peers, before transit", "traceroute.across_the_ix_switch":"across the {ix} switch", "traceroute.as_path_path":"AS path: {path}", "traceroute.caches_beat_pnis":"caches beat PNIs", @@ -3050,6 +3061,7 @@ "traceroute.n_network_unreachable":"!N network unreachable", "traceroute.name_transit":"{name} transit", "traceroute.net_carries_it_to_city":"{net} carries it to {city}", +"traceroute.net_hands_it_to_its_customer":"{net} hands it to its customer {to}", "traceroute.net_hands_it_to_to":"{net} hands it to {to}", "traceroute.no_path_every_route_between_these":"No path: every route between these cities is down or missing.", "traceroute.no_working_path_between_these_pops":"no working path between these POPs", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 4e1845f..ed4b79c 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -10,6 +10,17 @@ .bdg.ever{opacity:.85;border-style:dashed;border-color:var(--rc)} .bdg.on{opacity:1;border-color:var(--rc);background:#fff;box-shadow:0 2px 0 var(--rc)} .bdg.on .bi,.bdg.ever .bi{filter:none} +.bdg .bv{font:900 10px Nunito,sans-serif;letter-spacing:.02em} +.bdg.on.v-freeze{background:linear-gradient(160deg,#F2FBFF,#D6F1FC);border-color:#5BC0EB;box-shadow:0 2px 0 #5BC0EB,inset 0 0 0 2px #fff} +.bdg.v-freeze .bv{color:#2A8DB8} +.bdg.on.v-bgp{background:linear-gradient(160deg,#FFF6E8,#FFD9B8);border-color:#FF5A1F;box-shadow:0 2px 0 #C8102E,0 0 8px rgba(255,90,31,.45)} +.bdg.v-bgp .bv{color:#C8102E} +.bdg.ever.v-freeze{border-color:#5BC0EB}.bdg.ever.v-bgp{border-color:#FF5A1F} +.bshelf{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 8px} +.bsh{font:800 12px Nunito,sans-serif;border:2px solid #C9CEDD;border-radius:999px;padding:2px 9px;background:#fff;white-space:nowrap} +.bsh.v-freeze{border-color:#5BC0EB}.bsh.v-oncall{border-color:#FFD23F}.bsh.v-bgp{border-color:#FF5A1F} +.bsh.cur{box-shadow:0 2px 0 var(--ink)} +.bvt.v-freeze{color:#2A8DB8;font-weight:900}.bvt.v-bgp{color:#FF5A1F;font-weight:900} .scn{display:flex;gap:10px;align-items:center;border:2px solid #DDE1EC;border-radius:12px;padding:8px 10px;margin-top:8px} .scn.wk{border-color:var(--me);background:#FFF0F6} .scn .nm{font-weight:900} diff --git a/tests/badges-variants.test.js b/tests/badges-variants.test.js new file mode 100644 index 0000000..648aaed --- /dev/null +++ b/tests/badges-variants.test.js @@ -0,0 +1,137 @@ +// Badge variants by ruleset preset (2.0): On-call earns the standard badge, Change Freeze a frosted one and BGP at +// 3 a.m. a fiery one; Sandbox and puzzles earn none. A harder preset upgrades a badge you already have. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// The preset is read from S.rules.preset until the ruleset feature lands with rulePreset(). +const start = (ev, preset) => { + ev("localStorage.removeItem('sot-badges');ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + if (preset) ev(`S.rules={preset:'${preset}'}`); + ev("S.ach={};S.achP={};compute()"); +}; +const earnHello = (ev) => ev("S.pni.push({id:'x',net:'nfx',city:'fra',tier:0});compute();checkBadges()"); +const hof = (ev) => JSON.parse(ev("localStorage.getItem('sot-badges')||'{}'")); + +test('every save without a preset plays On-call and earns the standard badge', () => { + const { ev, errors } = load(); + start(ev); + assert.equal(ev('badgeVar()'), 'oncall'); + earnHello(ev); + assert.ok(ev('S.ach.hello!==undefined')); + assert.equal(ev('S.achP.hello'), 'oncall'); + assert.deepEqual(hof(ev).hello.vs && Object.keys(hof(ev).hello.vs), ['oncall']); + assert.equal(hof(ev).hello.v, 'oncall'); + assert.deepEqual(errors, []); +}); + +test('Change Freeze earns frosted badges and BGP at 3 a.m. fiery ones, shown in the toast and the list', () => { + for (const [p, name, cls] of [['freeze', /Freeze-dried/, 'v-freeze'], ['bgp', /Forged at 3 a\.m\./, 'v-bgp']]) { + const { ev, dom, errors } = load(); + start(ev, p); + ev("window.__t=[];const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);}"); + earnHello(ev); + assert.equal(ev('S.achP.hello'), p); + assert.match(ev("window.__t.join(' ')"), name, `${p}: the toast names the variant`); + ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()"); + const card = dom.window.document.querySelector(`#leftBody .bdg.on.${cls}`); + assert.ok(card, `${p}: the badge list shows the variant`); + assert.match(card.textContent, name); + assert.equal(hof(ev).hello.v, p, 'remembered on this device'); + assert.deepEqual(errors, []); + } +}); + +test('Sandbox and puzzles earn no badges', () => { + for (const p of ['sandbox', 'puzzle']) { + const { ev, errors } = load(); + start(ev, p); + earnHello(ev); + assert.equal(ev('badgeVar()'), null); + assert.equal(ev('Object.keys(S.ach).length'), 0, p); + assert.deepEqual(errors, []); + } + const { ev, errors } = load(); + start(ev); + ev("S.mode='sandbox'"); + earnHello(ev); + assert.equal(ev('Object.keys(S.ach).length'), 0, 'the old sandbox mode too'); + assert.deepEqual(errors, []); +}); + +test('a harder preset upgrades a badge, an easier one never downgrades it', () => { + const { ev, errors } = load(); + start(ev, 'freeze'); + earnHello(ev); + const day = ev('S.ach.hello'); + ev("window.__t=[];const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);}"); + ev("S.rules.preset='oncall';checkBadges()"); + assert.equal(ev('S.achP.hello'), 'oncall', 'On-call beats Change Freeze'); + assert.match(ev("window.__t.join(' ')"), /Badge upgraded/); + ev("S.day+=10;S.rules.preset='bgp';checkBadges()"); + assert.equal(ev('S.achP.hello'), 'bgp'); + assert.equal(ev('S.ach.hello'), day, 'the day it was first earned stays'); + ev("window.__t=[];S.rules.preset='freeze';checkBadges()"); + assert.equal(ev('S.achP.hello'), 'bgp', 'never downgraded'); + assert.equal(ev("window.__t.length"), 0, 'and no toast'); + const h = hof(ev).hello; + assert.deepEqual(Object.keys(h.vs).sort(), ['bgp', 'freeze', 'oncall'], 'the collection holds every variant earned'); + assert.equal(h.v, 'bgp', 'the shelf shows the best one'); + assert.deepEqual(errors, []); +}); + +test('the collection counts badges per variant on this device, and fits a phone', () => { + const { ev, dom, errors } = load(); + ev('window.innerWidth=360'); + start(ev, 'bgp'); + earnHello(ev); + ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()"); + const shelf = dom.window.document.querySelector('#leftBody .bshelf'); + assert.ok(shelf); + const total = ev('BADGES.length'); + assert.match(shelf.textContent, new RegExp(`Forged at 3 a\\.m\\. 1/${total}`)); + assert.match(shelf.textContent, new RegExp(`Freeze-dried 0/${total}`)); + assert.ok(dom.window.document.querySelector('#leftBody .bsh.v-bgp.cur'), 'the variant this game earns is marked'); + assert.match(dom.window.document.getElementById('leftBody').textContent, /forged in fire/); + assert.deepEqual(JSON.parse(ev('JSON.stringify(badgeShelf(hof()))')), { freeze: 0, oncall: 0, bgp: 1 }); + assert.deepEqual(errors, []); +}); + +test('old saves and old halls of fame keep loading, as standard badges', () => { + const { ev, errors } = load(); + start(ev); + // a 1.x save: S.ach holds days, no S.achP; a 1.x hall of fame: {d, n} per badge + ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2025-01-02',n:'Old'},t1:{d:'2025-03-04',n:'Old'},junk:5}))"); + ev("const o=JSON.parse(JSON.stringify(S));o.ach={hello:12,t1:'400'};delete o.achP;S=migrate(o)"); + assert.equal(ev('S.achP.hello'), 'oncall'); + assert.equal(ev('S.ach.t1'), 400, 'days are numbers'); + assert.deepEqual(JSON.parse(ev("JSON.stringify(Object.keys(S.achP).sort())")), ['hello', 't1']); + const h = JSON.parse(ev('JSON.stringify(hof())')); + assert.equal(h.hello.v, 'oncall'); + assert.equal(h.hello.vs.oncall, '2025-01-02'); + assert.equal(h.junk, undefined, 'broken entries are dropped'); + // a hand-edited variant is not trusted + ev("const o=JSON.parse(JSON.stringify(S));o.achP={hello:'lava',t1:'bgp'};S=migrate(o)"); + assert.equal(ev('S.achP.hello'), 'oncall'); + assert.equal(ev('S.achP.t1'), 'bgp'); + ev("localStorage.setItem('sot-badges','[1,2]')"); + assert.equal(ev('JSON.stringify(hof())'), '{}'); + ev("UI.left='goals';UI.leftOpen=true;renderLeft()"); + // new games start with an empty variant map + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('JSON.stringify(S.achP)'), '{}'); + assert.deepEqual(errors, []); +}); + +test('the share card rings the variant badges', () => { + const { ev, errors } = load(); + start(ev, 'bgp'); + earnHello(ev); + // count the strokes the card draws with a variant badge and with the same badge in its standard look + const calls = () => ev("(()=>{const cv=shareCanvas();return cv.getContext('2d').calls.n;})()"); + const fiery = calls(); + ev("S.achP.hello='oncall'"); + const plain = calls(); + assert.ok(fiery > plain, `the ring and the tally are drawn (${fiery} > ${plain} calls)`); + assert.deepEqual(errors, []); +}); diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index a5c557c..a69d199 100644 --- a/tests/helpers/reference-allocation.js +++ b/tests/helpers/reference-allocation.js @@ -6,7 +6,7 @@ module.exports = ` 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.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 { + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;delete S.done.t1;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=500"); + ev("S.transit=[];S.ixp={};S.peers={};S.pni=[];S.grace=null;for(const n of t1Need())S.pni.push({id:'p'+n.id,net:n.id,city:'fra',tier:2});compute()"); +}; + +test('cones are built once at load and hold customers of customers', () => { + const { ev, errors } = load(); + assert.equal(ev("CONE.voc.includes('ddo')&&CONE.voc.includes('spn')"), true, 'Hocus Pocus brings its own customers'); + // Doodoo buys from Hocus Pocus, which buys from Not That Telecom: two levels down + assert.equal(ev("NET.ddo.up.includes('voc')&&NET.voc.up.includes('ntt')"), true); + assert.equal(ev("CONE_S.ntt.has('ddo')"), true, 'the Tier 1 cone is transitive'); + assert.equal(ev("CONE.ntt[0]"), 'ntt', 'a network is first in its own cone'); + assert.equal(ev("PNI_NETS===CONE"), true); + assert.equal(ev("ANC.ddo[0]"), 'voc', 'nearest upstream first'); + assert.equal(ev("NETS.filter(n=>n.tail).every(n=>n.up&&n.up.length&&n.up.every(u=>NET[u]))"), true, 'the long tail buys transit'); + 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); + assert.deepEqual(errors, []); +}); + +test('a transit-free network with PNIs to every Tier 1 reaches the long tail through their cones', () => { + const { ev, errors } = load(); + t1Club(ev); + const tail = ev("NETS.find(n=>n.tail&&n.pops.includes('akl')).id"); + for (const id of ['tail0', 'tail38', tail, 'sky', 'kys', 'tim']) { + assert.equal(ev(`!!R.reachable.${id}`), true, `${id} is reachable`); + assert.equal(ev(`!!R.nt.${id}`), true, `${id} without transit`); + assert.equal(ev(`!!R.cone.${id}`), true, `${id} through a peer's cone`); + } + // the traffic really goes over the PNI with the upstream, not some made-up exit + const up = ev("NET.tail0.up[0]"); + assert.ok(ev("(R.netEg.tail0||{}).p") > 0, 'over a PNI'); + assert.ok(ev(`R.usePni['p${up}']`) > 0, 'the PNI with its upstream carries it'); + // the traceroute shows the hand-off to the customer and an AS path one hop longer + const tr = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'tail0'}))")); + assert.match(tr.text, /hands it to its customer/); + assert.equal(tr.asPath.length, 3, 'you, the Tier 1, the customer'); + assert.equal(tr.asPath[1], ev(`NET.${up}.asn`), 'through the upstream it buys transit from'); + assert.match(tr.why, /customers come after direct peers/); + assert.deepEqual(errors, []); +}); + +test('a network in nobody\'s cone still needs reaching directly', () => { + const { ev, errors } = load(); + t1Club(ev); + // Doitsche Telekomm buys from no one: no Tier 1 PNI reaches it + assert.equal(ev("(NET.dtk.up||[]).length"), 0); + assert.equal(ev("R.reachable.dtk"), false); + assert.equal(ev("isTier1()"), false); + assert.match(ev('t1Why()'), /nobody you peer with sells transit to/); + // peer with every island directly and the win comes + ev("for(const n of NETS)if(!R.reachable[n.id])S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});for(const n of NETS)if(n.pops.length&&!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};compute()"); + assert.ok(ev("R.reach") > 0.999, `reach ${ev('R.reach')}`); + assert.equal(ev("isTier1()"), true); + assert.deepEqual(errors, []); +}); + +test('the long tail no longer stands between you and Tier 1', () => { + const { ev, errors } = load(); + t1Club(ev); + // peer directly only with the networks in nobody's cone, never with the long tail itself + ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute()"); + assert.equal(ev("S.pni.some(p=>NET[p.net].tail)"), false, 'no session with any long-tail network'); + assert.equal(ev("NETS.filter(n=>n.tail).every(n=>R.reachable[n.id])"), true); + assert.equal(ev("isTier1()"), true); + // the peers you need directly are all real networks of some size, and fewer than before + const islands = ev("S.pni.filter(p=>p.id[0]==='i').length"); + assert.ok(islands < 70, `${islands} networks to peer with directly`); + assert.deepEqual(errors, []); +}); + +test('a peer\'s cone comes after direct peering and before transit, so peering widely still pays', () => { + const { ev, errors } = load(); + t1Club(ev); + ev("ACT.buyTransit({city:'fra',net:'cog',tier:2});S.pni=S.pni.filter(p=>p.net!=='cog');compute()"); + // a Cogentle customer is reached through another Tier 1's cone only if it buys from one; transit is the fallback + const id = ev("NETS.find(n=>n.tail&&n.up.length===1&&n.up[0]==='tly').id"); + assert.ok(ev(`(R.netEg.${id}||{}).p`) > 0, 'over the PNI with its upstream, not over transit'); + assert.equal(ev(`(R.netEg.${id}||{}).t||0`), 0); + // a direct session beats the cone: peer with it at the exchange and its traffic moves there + ev(`S.pops.fra.bb.d=500;ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'});compute()`); + if (ev(`ixSessions('fra').has('${id}')`)) { + assert.ok(ev(`(R.netEg.${id}||{}).ix`) > 0, 'direct peering wins over the cone'); + assert.equal(ev(`(R.netEg.${id}||{}).p||0`), 0); + } + // an IX session also brings the member's customers along + assert.equal(ev("ixSessions('fra').has('gsl')"), true); + const down = ev("DOWN.gsl.find(id=>!t1Need().some(t=>CONE_S[t.id].has(id))&&!ixSessions('fra').has(id))||''"); + if (down) assert.equal(ev(`R.reachable.${down}`), true, `${down} comes along with Glowball Sakura Lager's session`); + assert.deepEqual(errors, []); +}); + +test('old saves keep their win: cones only ever add reach', () => { + const { ev, errors } = load(); + t1Club(ev); + ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute()"); + ev("S.won=true;S.done.t1=S.day;S.t1Now=true"); + // a save from before 2.0, with an older Tier 1 set and no record of cones, loads and is still Tier 1 + ev("const o=JSON.parse(JSON.stringify(S));o.t1v=2;S=migrate(o);compute()"); + assert.equal(ev("S.won"), true); + assert.equal(ev("isTier1()"), true); + assert.equal(ev("tierLabel()"), 'Tier 1'); + // and reach with cones is never lower than reach without: every exit still reaches what it did + const before = ev("R.reach"); + ev("for(const id of NET_IDS){CONE_S[id]=new Set([id]);DOWN[id]=[];}compute()"); + assert.ok(ev("R.reach") <= before + 1e-9, 'switching cones off can only lose reach'); + assert.deepEqual(errors, []); +}); + +test('the Road to Tier 1 card and the network list explain the cone, on a phone too', () => { + for (const w of [1280, 360]) { + const { ev, dom, errors } = load(); + ev(`window.innerWidth=${w}`); + t1Club(ev); + ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()"); + const txt = dom.window.document.getElementById('leftBody').textContent; + assert.match(txt, /Road to Tier 1/); + assert.match(txt, /their customers come along for free/); + assert.match(txt, /\d+ networks already come along with a peer/); + ev("ACT.netFocus({id:'tail0'})"); + assert.match(dom.window.document.getElementById('leftBody').textContent, /Reached through the customer cone of/); + ev("S.pni=[];compute();ACT.netFocus({id:'tail0'})"); + assert.match(dom.window.document.getElementById('leftBody').textContent, /Buys transit from .*Peer with/); + assert.match(ev("GOALS.find(g=>g.id==='t1').d"), /customers come along for free/); + assert.deepEqual(errors, [], `${w}px`); + } +}); + +test('routing with cones costs about what it did: exits are asked once, cones are built at load', () => { + const { ev, errors } = load(); + t1Club(ev); + ev("for(const n of NETS.filter(n=>!n.tail&&!n.cn).slice(0,40))for(const c of ['fra','ams','lon']){if(!S.pops[c])S.pops[c]={day:0,bb:{d:400},boost:0,down:0,routers:4,gen:true};S.pni.push({id:n.id+c,net:n.id,city:c,tier:2});}compute()"); + const t = ev("(()=>{for(let i=0;i<3;i++)compute();const a=performance.now();for(let i=0;i<10;i++)compute();return (performance.now()-a)/10;})()"); + const plain = ev(`(()=>{const keep={};for(const id of NET_IDS){keep[id]=[CONE_S[id],DOWN[id]];CONE_S[id]=new Set([id]);DOWN[id]=[];} + for(let i=0;i<3;i++)compute();const a=performance.now();for(let i=0;i<10;i++)compute();const r=(performance.now()-a)/10;for(const id of NET_IDS){CONE_S[id]=keep[id][0];DOWN[id]=keep[id][1];}return r;})()`); + assert.ok(t < plain * 2 + 20, `compute() with cones ${t.toFixed(1)} ms vs without ${plain.toFixed(1)} ms`); + assert.deepEqual(errors, []); +}); From 7c8fa68659ad53cb52701684c0de9733e45bee53 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 17:40:22 +0100 Subject: [PATCH 020/181] 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 021/181] 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 022/181] 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 023/181] 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 024/181] 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 025/181] 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 026/181] 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 027/181] 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 028/181] 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:00:58 +0100 Subject: [PATCH 029/181] Every city has its country code; the 2x border toll stays an African thing --- src/game/20-world/50-cities.js | 336 +++++++++--------- .../80-simulation/80-geography-and-latency.js | 3 +- 2 files changed, 170 insertions(+), 169 deletions(-) diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index b6410df..1c07a87 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -1,125 +1,125 @@ const CITIES=[ - {id:'sea',name:'Seattle',x:205,y:245,land:'am',reg:'AM',P:300,ix:'Sea-IX',dc:'Westerly Carrier Hotel'}, - {id:'sjc',name:'San Jose',x:240,y:345,land:'am',reg:'AM',P:500,ix:'Silly-Con Valley IX',dc:'Equinox SV'}, - {id:'dal',name:'Dallas',x:385,y:415,land:'am',reg:'AM',P:450,ix:'Yee-Haw-IX',dc:'Infomaniac Building'}, - {id:'chi',name:'Chicago',x:470,y:270,land:'am',reg:'AM',P:600,ix:'Windy-IX',dc:'350 Cermak'}, - {id:'ash',name:'Ashburn',x:572,y:332,land:'am',reg:'AM',P:250,ix:'Equinox Ashburn IX',dc:'Data Center Alley',note:tr('cities.the_data_center_capital_rumor_says')}, - {id:'nyc',name:'New York',x:615,y:283,land:'am',reg:'AM',P:1200,ix:'NY-Yikes',dc:'60 Hudson'}, - {id:'mia',name:'Miami',x:530,y:482,land:'am',reg:'AM',P:400,ix:'Miam-IX',dc:'Nap of the Americas',note:tr('cities.cable_landing_hub_for_south_america')}, - {id:'sao',name:'São Paulo',x:640,y:730,land:'sa',reg:'SA',P:900,br:true,andes:'e',ix:'IX.brrr São Paulo',ixCheap:0.3,dc:'Digital Reality SP',note:tr('cities.south_america_s_biggest_market_and')}, - {id:'lon',name:'London',x:935,y:275,land:'uk',reg:'EU',P:1000,ix:'LYNX',dc:'Telly-House Docklands',note:tr('cities.on_an_island_so_every_link')}, - {id:'ams',name:'Amsterdam',x:1015,y:245,land:'eu',reg:'EU',P:350,ix:'HAMS-IX',dc:'Science Park'}, - {id:'fra',name:'Frankfurt',x:1075,y:295,land:'eu',reg:'EU',P:600,ix:'DE-KICKS',dc:'Kleyerstraße Campus',note:tr('cities.europe_s_crossroads_lots_of_networks')}, - {id:'par',name:'Paris',x:990,y:320,land:'eu',reg:'EU',P:900,ix:'Fromage-IX',dc:'Interaction PAR'}, - {id:'mrs',name:'Marseille',x:1045,y:378,land:'eu',reg:'EU',P:250,ix:'Bouilla-IX',dc:'Cable Landing Station',note:tr('cities.subsea_cables_to_africa_and_asia')}, - {id:'tor',name:'Toronto',ca:true,x:548,y:252,land:'am',reg:'AM',P:500,ix:'Sorry-IX',dc:'151 Front Street',note:tr('cities.canada_s_hub_polite_packets_long')}, - {id:'bru',name:'Brussels',x:0,y:0,land:'eu',reg:'EU',P:150,be:true,tape:true,ix:'Frites-IX',dc:'Digital Unreality BRU1',note:tr('cities.right_between_london_amsterdam_paris')}, - {id:'oos',name:'Oostkamp',x:0,y:0,land:'eu',reg:'EU',P:30,be:true,tape:true,ix:'',dc:'DC-Starfish Oostkamp',note:tr('cities.inland_from_ostend_where_the_cables')}, - {id:'bet',name:'Bettembourg',x:0,y:0,land:'eu',reg:'EU',P:60,arpu:1.4,lux:true,ix:'LU-SICK',dc:'LuxDisconnect DC1.2',note:tr('cities.luxembourg_s_data_centers_are_not')}, - {id:'mtl',name:'Montreal',ca:true,x:598,y:238,land:'am',reg:'AM',P:300,ix:'Poutine-IX',dc:'Hydro-powered Hangar',note:tr('cities.cheap_hydro_power_makes_it_a')}, - {id:'kcy',name:'Kansas City',x:0,y:0,land:'am',reg:'AM',P:200,ix:'Toto-IX',dc:'The Limestone Cave',note:tr('cities.the_geographic_middle_of_the_us')}, - {id:'cal',name:'Calgary',x:0,y:0,land:'am',reg:'AM',P:150,ca:true,ix:'Stampede-IX',dc:'Bow & Arrow DC',note:tr('cities.the_prairie_gateway_between')}, - {id:'van',name:'Vancouver',x:0,y:0,land:'am',reg:'AM',P:250,ca:true,ix:'Raincouver-IX',dc:'Colo-Logics VAN3',note:tr('cities.canada_s_pacific_door_it_rains')}, - {id:'ott',name:'Ottawa',x:0,y:0,land:'am',reg:'AM',P:120,ca:true,blackout:true,ix:'Bytown-IX',dc:'Purely Colo (Mostly)',note:tr('cities.canada_s_capital_once_called_bytown')}, - {id:'lax',name:'Los Angeles',x:270,y:395,land:'am',reg:'AM',P:900,ix:'Any2-Anywhere',dc:'One Wilshire',note:tr('cities.pacific_cables_land_nearby_and')}, - {id:'mex',name:'Mexico City',x:368,y:470,land:'am',reg:'AM',P:700,ix:'',dc:'Querétaro Campus',note:tr('cities.huge_mobile_market_most_of_its')}, - {id:'rek',name:'Reykjavik',x:850,y:170,land:'is',reg:'EU',P:60,ix:'',dc:'Geothermal Bitcoin Barn',note:tr('cities.free_cooling_and_geothermal_power')}, - {id:'dub',name:'Dublin',x:876,y:268,land:'ie',reg:'EU',P:250,ix:'Craic-IX',dc:'Clonsilla Hyperscale Campus',note:tr('cities.every_hyperscaler_s_european_hq')}, - {id:'osl',name:'Oslo',x:1062,y:172,land:'eu',reg:'EU',P:200,ix:'NIX-NIX',dc:'Fjord-cooled Mountain Hall'}, - {id:'cph',name:'Copenhagen',x:1085,y:215,land:'eu',reg:'EU',P:250,ix:'Hygge-IX',dc:'Danish Design DC',note:tr('cities.landing_point_for_cables_from_the')}, - {id:'hel',name:'Helsinki',x:1168,y:140,land:'eu',reg:'EU',P:200,ix:'Sauna-IX',dc:'Underground Sauna Bunker',note:tr('cities.fast_fiber_east_and_west_and')}, - {id:'beg',name:'Belgrade',x:1122,y:338,land:'eu',reg:'EU',P:250,ix:'',dc:'Danube Docks DC'}, - {id:'sof',name:'Sofia',x:1165,y:358,land:'eu',reg:'EU',P:250,ix:'Rakija-IX',dc:'Vitosha DC',note:tr('cities.balkan_peering_hub_with_famously')}, - {id:'dxb',name:'Dubai',x:1292,y:428,land:'eu',reg:'AS',P:400,uae:true,ix:'Sand-IX',dc:'Air-conditioned Mirage DC',note:tr('cities.crossroads_for_cables_between_europe')}, - {id:'mos',name:'Moscow',x:1235,y:192,land:'eu',reg:'EU',P:900,ru:true,arpu:0.5,ix:'Borscht-IX',dc:'Very Secure Bunker',note:tr('cities.sovereign_internet_rules_every_pop')}, - {id:'akl',name:'Auckland',x:1964,y:826,land:'nz',reg:'OC',P:250,ix:'Kiwi-IX',dc:'Sheep-cooled Shed',note:tr('cities.far_from_everything_every_packet')}, - {id:'per',name:'Perth',x:1712,y:785,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:200,ix:'Beard-IX',dc:'Very Remote DC',dc2:'Next-Door-DC P#',dc2N:2,note:tr('cities.the_most_isolated_big_city_on')}, - {id:'jkt',name:'Jakarta',x:1614,y:624,land:'idn',reg:'AS',P:900,ix:'Nasi-IX',dc:'Monsoon-proof DC',note:tr('cities.270_million_people_on_17_000')}, - {id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',P:600,ix:'',dc:'Typhoon-rated DC',note:tr('cities.typhoons_earthquakes_and_a_lot_of')}, - {id:'ber',name:'Berlin',x:0,y:0,land:'eu',reg:'EU',P:450,ix:'Currywurst-IX',dc:'Former Brewery DC',note:tr('cities.startups_techno_and_a_surprising')}, - {id:'ham',name:'Hamburg',x:0,y:0,land:'eu',reg:'EU',P:250,ix:'Moin-IX',dc:'Speicherstadt Colo',note:tr('cities.germany_s_port_city_everyone_says')}, - {id:'dus',name:'Düsseldorf',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Altbier-IX',dc:'Königsallee Cage',note:tr('cities.the_rhine_ruhr_hub_more_carrier')}, - {id:'muc',name:'Munich',x:0,y:0,land:'eu',reg:'EU',P:250,ix:'Brezn-IX',dc:'Weißwurst Works',note:tr('cities.bavaria_s_capital_cars_insurers_and')}, - {id:'zrh',name:'Zurich',x:0,y:0,land:'eu',reg:'EU',P:250,ix:'Cuckoo-IX',dc:'Bank Vault DC',note:tr('cities.banks_very_punctual_packets_and')}, + {id:'sea',name:'Seattle',x:205,y:245,land:'am',reg:'AM',cc:'US',P:300,ix:'Sea-IX',dc:'Westerly Carrier Hotel'}, + {id:'sjc',name:'San Jose',x:240,y:345,land:'am',reg:'AM',cc:'US',P:500,ix:'Silly-Con Valley IX',dc:'Equinox SV'}, + {id:'dal',name:'Dallas',x:385,y:415,land:'am',reg:'AM',cc:'US',P:450,ix:'Yee-Haw-IX',dc:'Infomaniac Building'}, + {id:'chi',name:'Chicago',x:470,y:270,land:'am',reg:'AM',cc:'US',P:600,ix:'Windy-IX',dc:'350 Cermak'}, + {id:'ash',name:'Ashburn',x:572,y:332,land:'am',reg:'AM',cc:'US',P:250,ix:'Equinox Ashburn IX',dc:'Data Center Alley',note:tr('cities.the_data_center_capital_rumor_says')}, + {id:'nyc',name:'New York',x:615,y:283,land:'am',reg:'AM',cc:'US',P:1200,ix:'NY-Yikes',dc:'60 Hudson'}, + {id:'mia',name:'Miami',x:530,y:482,land:'am',reg:'AM',cc:'US',P:400,ix:'Miam-IX',dc:'Nap of the Americas',note:tr('cities.cable_landing_hub_for_south_america')}, + {id:'sao',name:'São Paulo',x:640,y:730,land:'sa',reg:'SA',cc:'BR',P:900,br:true,andes:'e',ix:'IX.brrr São Paulo',ixCheap:0.3,dc:'Digital Reality SP',note:tr('cities.south_america_s_biggest_market_and')}, + {id:'lon',name:'London',x:935,y:275,land:'uk',reg:'EU',cc:'GB',P:1000,ix:'LYNX',dc:'Telly-House Docklands',note:tr('cities.on_an_island_so_every_link')}, + {id:'ams',name:'Amsterdam',x:1015,y:245,land:'eu',reg:'EU',cc:'NL',P:350,ix:'HAMS-IX',dc:'Science Park'}, + {id:'fra',name:'Frankfurt',x:1075,y:295,land:'eu',reg:'EU',cc:'DE',P:600,ix:'DE-KICKS',dc:'Kleyerstraße Campus',note:tr('cities.europe_s_crossroads_lots_of_networks')}, + {id:'par',name:'Paris',x:990,y:320,land:'eu',reg:'EU',cc:'FR',P:900,ix:'Fromage-IX',dc:'Interaction PAR'}, + {id:'mrs',name:'Marseille',x:1045,y:378,land:'eu',reg:'EU',cc:'FR',P:250,ix:'Bouilla-IX',dc:'Cable Landing Station',note:tr('cities.subsea_cables_to_africa_and_asia')}, + {id:'tor',name:'Toronto',ca:true,x:548,y:252,land:'am',reg:'AM',cc:'CA',P:500,ix:'Sorry-IX',dc:'151 Front Street',note:tr('cities.canada_s_hub_polite_packets_long')}, + {id:'bru',name:'Brussels',x:0,y:0,land:'eu',reg:'EU',cc:'BE',P:150,be:true,tape:true,ix:'Frites-IX',dc:'Digital Unreality BRU1',note:tr('cities.right_between_london_amsterdam_paris')}, + {id:'oos',name:'Oostkamp',x:0,y:0,land:'eu',reg:'EU',cc:'BE',P:30,be:true,tape:true,ix:'',dc:'DC-Starfish Oostkamp',note:tr('cities.inland_from_ostend_where_the_cables')}, + {id:'bet',name:'Bettembourg',x:0,y:0,land:'eu',reg:'EU',cc:'LU',P:60,arpu:1.4,lux:true,ix:'LU-SICK',dc:'LuxDisconnect DC1.2',note:tr('cities.luxembourg_s_data_centers_are_not')}, + {id:'mtl',name:'Montreal',ca:true,x:598,y:238,land:'am',reg:'AM',cc:'CA',P:300,ix:'Poutine-IX',dc:'Hydro-powered Hangar',note:tr('cities.cheap_hydro_power_makes_it_a')}, + {id:'kcy',name:'Kansas City',x:0,y:0,land:'am',reg:'AM',cc:'US',P:200,ix:'Toto-IX',dc:'The Limestone Cave',note:tr('cities.the_geographic_middle_of_the_us')}, + {id:'cal',name:'Calgary',x:0,y:0,land:'am',reg:'AM',cc:'CA',P:150,ca:true,ix:'Stampede-IX',dc:'Bow & Arrow DC',note:tr('cities.the_prairie_gateway_between')}, + {id:'van',name:'Vancouver',x:0,y:0,land:'am',reg:'AM',cc:'CA',P:250,ca:true,ix:'Raincouver-IX',dc:'Colo-Logics VAN3',note:tr('cities.canada_s_pacific_door_it_rains')}, + {id:'ott',name:'Ottawa',x:0,y:0,land:'am',reg:'AM',cc:'CA',P:120,ca:true,blackout:true,ix:'Bytown-IX',dc:'Purely Colo (Mostly)',note:tr('cities.canada_s_capital_once_called_bytown')}, + {id:'lax',name:'Los Angeles',x:270,y:395,land:'am',reg:'AM',cc:'US',P:900,ix:'Any2-Anywhere',dc:'One Wilshire',note:tr('cities.pacific_cables_land_nearby_and')}, + {id:'mex',name:'Mexico City',x:368,y:470,land:'am',reg:'AM',cc:'MX',P:700,ix:'',dc:'Querétaro Campus',note:tr('cities.huge_mobile_market_most_of_its')}, + {id:'rek',name:'Reykjavik',x:850,y:170,land:'is',reg:'EU',cc:'IS',P:60,ix:'',dc:'Geothermal Bitcoin Barn',note:tr('cities.free_cooling_and_geothermal_power')}, + {id:'dub',name:'Dublin',x:876,y:268,land:'ie',reg:'EU',cc:'IE',P:250,ix:'Craic-IX',dc:'Clonsilla Hyperscale Campus',note:tr('cities.every_hyperscaler_s_european_hq')}, + {id:'osl',name:'Oslo',x:1062,y:172,land:'eu',reg:'EU',cc:'NO',P:200,ix:'NIX-NIX',dc:'Fjord-cooled Mountain Hall'}, + {id:'cph',name:'Copenhagen',x:1085,y:215,land:'eu',reg:'EU',cc:'DK',P:250,ix:'Hygge-IX',dc:'Danish Design DC',note:tr('cities.landing_point_for_cables_from_the')}, + {id:'hel',name:'Helsinki',x:1168,y:140,land:'eu',reg:'EU',cc:'FI',P:200,ix:'Sauna-IX',dc:'Underground Sauna Bunker',note:tr('cities.fast_fiber_east_and_west_and')}, + {id:'beg',name:'Belgrade',x:1122,y:338,land:'eu',reg:'EU',cc:'RS',P:250,ix:'',dc:'Danube Docks DC'}, + {id:'sof',name:'Sofia',x:1165,y:358,land:'eu',reg:'EU',cc:'BG',P:250,ix:'Rakija-IX',dc:'Vitosha DC',note:tr('cities.balkan_peering_hub_with_famously')}, + {id:'dxb',name:'Dubai',x:1292,y:428,land:'eu',reg:'AS',cc:'AE',P:400,uae:true,ix:'Sand-IX',dc:'Air-conditioned Mirage DC',note:tr('cities.crossroads_for_cables_between_europe')}, + {id:'mos',name:'Moscow',x:1235,y:192,land:'eu',reg:'EU',cc:'RU',P:900,ru:true,arpu:0.5,ix:'Borscht-IX',dc:'Very Secure Bunker',note:tr('cities.sovereign_internet_rules_every_pop')}, + {id:'akl',name:'Auckland',x:1964,y:826,land:'nz',reg:'OC',cc:'NZ',P:250,ix:'Kiwi-IX',dc:'Sheep-cooled Shed',note:tr('cities.far_from_everything_every_packet')}, + {id:'per',name:'Perth',x:1712,y:785,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:200,ix:'Beard-IX',dc:'Very Remote DC',dc2:'Next-Door-DC P#',dc2N:2,note:tr('cities.the_most_isolated_big_city_on')}, + {id:'jkt',name:'Jakarta',x:1614,y:624,land:'idn',reg:'AS',cc:'ID',P:900,ix:'Nasi-IX',dc:'Monsoon-proof DC',note:tr('cities.270_million_people_on_17_000')}, + {id:'mnl',name:'Manila',x:1714,y:494,land:'ph',reg:'AS',cc:'PH',P:600,ix:'',dc:'Typhoon-rated DC',note:tr('cities.typhoons_earthquakes_and_a_lot_of')}, + {id:'ber',name:'Berlin',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:450,ix:'Currywurst-IX',dc:'Former Brewery DC',note:tr('cities.startups_techno_and_a_surprising')}, + {id:'ham',name:'Hamburg',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:250,ix:'Moin-IX',dc:'Speicherstadt Colo',note:tr('cities.germany_s_port_city_everyone_says')}, + {id:'dus',name:'Düsseldorf',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:300,ix:'Altbier-IX',dc:'Königsallee Cage',note:tr('cities.the_rhine_ruhr_hub_more_carrier')}, + {id:'muc',name:'Munich',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:250,ix:'Brezn-IX',dc:'Weißwurst Works',note:tr('cities.bavaria_s_capital_cars_insurers_and')}, + {id:'zrh',name:'Zurich',x:0,y:0,land:'eu',reg:'EU',cc:'CH',P:250,ix:'Cuckoo-IX',dc:'Bank Vault DC',note:tr('cities.banks_very_punctual_packets_and')}, {id:'nbo',name:'Nairobi',x:0,y:0,land:'af',reg:'AF',cc:'KE',P:350,ix:'Safari-IX',dc:'Silicon Savannah Campus',note:tr('cities.east_africa_s_hub_cables_land')}, {id:'cai',name:'Cairo',x:0,y:0,land:'af',land2:'eu',reg:'AF',cc:'EG',P:600,ix:'Pharaoh-IX',dc:'Pyramid-adjacent DC',note:tr('cities.almost_every_europe_asia_cable')}, - {id:'stg',name:'Stuttgart',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Spätzle-IX',dc:'Kehrwoche-certified DC',ixOnly:true,note:tr('cities.cars_engineers_and_kehrwoche_every')}, - {id:'sto',name:'Stockholm',x:1110,y:160,land:'eu',reg:'EU',P:300,ix:'NodNod',dc:'Nuclear Bunker DC'}, - {id:'bcn',name:'Barcelona',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Catnip-IX',dc:'Poblenou DC',note:tr('cities.catalonia_s_own_exchange_small_and')}, - {id:'mad',name:'Madrid',x:935,y:392,land:'eu',reg:'EU',P:600,ix:'Siesta-IX',dc:'Interaction MAD'}, + {id:'stg',name:'Stuttgart',x:0,y:0,land:'eu',reg:'EU',cc:'DE',P:300,ix:'Spätzle-IX',dc:'Kehrwoche-certified DC',ixOnly:true,note:tr('cities.cars_engineers_and_kehrwoche_every')}, + {id:'sto',name:'Stockholm',x:1110,y:160,land:'eu',reg:'EU',cc:'SE',P:300,ix:'NodNod',dc:'Nuclear Bunker DC'}, + {id:'bcn',name:'Barcelona',x:0,y:0,land:'eu',reg:'EU',cc:'ES',P:300,ix:'Catnip-IX',dc:'Poblenou DC',note:tr('cities.catalonia_s_own_exchange_small_and')}, + {id:'mad',name:'Madrid',x:935,y:392,land:'eu',reg:'EU',cc:'ES',P:600,ix:'Siesta-IX',dc:'Interaction MAD'}, {id:'lag',name:'Lagos',x:1010,y:565,land:'af',reg:'AF',cc:'NG',P:500,ix:'Jollof-IX',dc:'Rack-n-Roll Centre'}, {id:'jnb',name:'Johannesburg',x:1130,y:730,land:'af',reg:'AF',cc:'ZA',P:400,za:true,ix:'Braai-IX',dc:'Tera-Cotta Campus'}, - {id:'bom',name:'Mumbai',x:1385,y:488,land:'eu',reg:'AS',P:1100,india:true,ix:'Mumb-IX',dc:'Goregaon Tech Park'}, - {id:'sin',name:'Singapore',x:1556,y:568,land:'eu',reg:'AS',P:450,ix:'Lah-IX',dc:'Equinox SG',note:tr('cities.asia_s_hub_expensive_humid_very')}, - {id:'hkg',name:'Hong Kong',x:1645,y:440,land:'eu',reg:'AS',P:600,ix:'HK-Kicks',dc:'Mega-Eye Plus'}, - {id:'icn',name:'Seoul',x:1722,y:302,land:'eu',reg:'AS',P:900,kr:true,ix:'Kimch-IX',dc:'Gasan Digital Complex',note:tr('cities.some_of_the_fastest_home_broadband')}, - {id:'pek',name:'Beijing',x:1652,y:318,land:'eu',reg:'AS',P:1800,cn:true,arpu:0.6,ix:'',dc:'Zhongguancun DC',note:tr('cities.mainland_china_behind_the_great')}, - {id:'sha',name:'Shanghai',x:1680,y:388,land:'eu',reg:'AS',P:2200,cn:true,arpu:0.6,ix:'',dc:'Lujiazui Data Center',note:tr('cities.mainland_china_enormous_market')}, - {id:'tok',name:'Tokyo',x:1795,y:320,land:'jp',reg:'AS',P:1400,ix:'JP-Naptime',dc:'Otemachi Tower'}, - {id:'syd',name:'Sydney',x:1860,y:790,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:500,ix:'IX Straya',dc:'Next-Door-DC S#',dcN:3,dc2:'Equinox SY#',dc2N:7,note:tr('cities.the_harbour_the_bridge_and_most')}, -{id:'for',name:'Fortaleza',x:0,y:0,land:'sa',reg:'SA',P:250,br:true,andes:'e',ix:'IX.brrr Fortaleza',ixCheap:0.3,dc:'Praia Landing Station',note:tr('cities.where_south_america_s_cables')}, - {id:'rio',name:'Rio de Janeiro',x:0,y:0,land:'sa',reg:'SA',P:600,br:true,andes:'e',ix:'IX.brrr Rio',ixCheap:0.3,dc:'Copacabana Colo',note:tr('cities.beaches_cable_landings_and_a')}, - {id:'bsb',name:'Brasília',x:0,y:0,land:'sa',reg:'SA',P:200,br:true,andes:'e',ix:'IX.brrr Brasília',ixCheap:0.3,dc:'Modernist Concrete Colo',note:tr('cities.brazil_s_planned_capital_shaped_like')}, - {id:'bhz',name:'Belo Horizonte',x:0,y:0,land:'sa',reg:'SA',P:250,br:true,andes:'e',ix:'IX.brrr BH',ixCheap:0.3,dc:'Pão de Queijo Point',note:tr('cities.mountains_mines_and_more_bars_per')}, - {id:'cwb',name:'Curitiba',x:0,y:0,land:'sa',reg:'SA',P:200,br:true,andes:'e',ix:'IX.brrr Curitiba',ixCheap:0.3,dc:'Pine Nut Park DC',note:tr('cities.brazil_s_coldest_big_city_and')}, - {id:'poa',name:'Porto Alegre',x:0,y:0,land:'sa',reg:'SA',P:200,br:true,andes:'e',ix:'IX.brrr Porto Alegre',ixCheap:0.3,dc:'Chimarrão Colo',note:tr('cities.the_deep_south_halfway_to_buenos')}, - {id:'aju',off:true,name:'Aracaju',x:0,y:0,land:'sa',reg:'SA',P:40,br:true,andes:'e',ix:'IX.brrr Aracaju',ixCheap:0.3,dc:'Crab Walk Colo'}, - {id:'bel',name:'Belém',x:0,y:0,land:'sa',reg:'SA',P:100,br:true,andes:'e',rain:true,ix:'IX.brrr Belém',ixCheap:0.3,dc:'Açaí Bowl DC',note:tr('cities.gateway_to_the_amazon_at_the')}, - {id:'bvb',name:'Boa Vista',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',rain:true,ix:'IX.brrr Boa Vista',ixCheap:0.3,dc:'Northern Lights Racks',note:tr('cities.brazil_s_northernmost_capital_the')}, - {id:'cac',off:true,name:'Cascavel',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',ix:'IX.brrr Cascavel',ixCheap:0.3,dc:'Soybean Silo DC'}, - {id:'cpv',off:true,name:'Campina Grande',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',ix:'IX.brrr Campina Grande',ixCheap:0.3,dc:'Forró Forum DC',note:tr('cities.throws_the_biggest_sao_joao_festival')}, - {id:'cpq',name:'Campinas',x:0,y:0,land:'sa',reg:'SA',P:130,br:true,andes:'e',ix:'IX.brrr Campinas',ixCheap:0.3,dc:'Silicon Sugarcane Park',note:tr('cities.brazil_s_tech_hub_an_hour')}, - {id:'cgr',name:'Campo Grande',x:0,y:0,land:'sa',reg:'SA',P:40,br:true,andes:'e',ix:'IX.brrr Campo Grande',ixCheap:0.3,dc:'Pantanal Edge Colo'}, - {id:'cau',off:true,name:'Caruaru',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',ix:'IX.brrr Caruaru',ixCheap:0.3,dc:'Clay Doll Datacenter'}, - {id:'cgb',name:'Cuiabá',x:0,y:0,land:'sa',reg:'SA',P:40,br:true,andes:'e',ix:'IX.brrr Cuiabá',ixCheap:0.3,dc:'Forty Degrees DC',note:tr('cities.the_geographic_center_of_south')}, - {id:'cxj',off:true,name:'Caxias do Sul',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',ix:'IX.brrr Caxias do Sul',ixCheap:0.3,dc:'Wine Cellar Racks',note:tr('cities.italian_immigrants_vineyards_and')}, - {id:'fec',off:true,name:'Feira de Santana',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',ix:'IX.brrr Feira de Santana',ixCheap:0.3,dc:'Crossroads Colo'}, - {id:'fln',off:true,name:'Florianópolis',x:0,y:0,land:'sa',reg:'SA',P:50,br:true,andes:'e',ix:'IX.brrr Florianópolis',ixCheap:0.3,dc:'Island Uplink DC',note:tr('cities.an_island_capital_of_beaches_and')}, - {id:'igu',off:true,name:'Foz do Iguaçu',x:0,y:0,land:'sa',reg:'SA',P:15,br:true,andes:'e',ix:'IX.brrr Foz do Iguaçu',ixCheap:0.3,dc:'Triple Border Racks',note:tr('cities.where_brazil_argentina_and_paraguay')}, - {id:'gyn',name:'Goiânia',x:0,y:0,land:'sa',reg:'SA',P:100,br:true,andes:'e',ix:'IX.brrr Goiânia',ixCheap:0.3,dc:'Pequi Peak DC',note:tr('cities.agribusiness_capital_and_home_of')}, - {id:'jpa',off:true,name:'João Pessoa',x:0,y:0,land:'sa',reg:'SA',P:50,br:true,andes:'e',ix:'IX.brrr João Pessoa',ixCheap:0.3,dc:'Sunrise Point DC',note:tr('cities.the_easternmost_city_of_the_americas')}, - {id:'ljd',off:true,name:'Lajeado',x:0,y:0,land:'sa',reg:'SA',P:10,br:true,andes:'e',ix:'IX.brrr Lajeado',ixCheap:0.3,dc:'Valley Co-op Colo',note:tr('cities.a_small_town_with_its_own')}, - {id:'ldb',name:'Londrina',x:0,y:0,land:'sa',reg:'SA',P:35,br:true,andes:'e',ix:'IX.brrr Londrina',ixCheap:0.3,dc:'Red Soil DC'}, - {id:'mcp',name:'Macapá',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',rain:true,blackout:true,ix:'IX.brrr Macapá',ixCheap:0.3,dc:'Equator Line Colo',note:tr('cities.right_on_the_equator_at_the')}, - {id:'mcz',off:true,name:'Maceió',x:0,y:0,land:'sa',reg:'SA',P:55,br:true,andes:'e',ix:'IX.brrr Maceió',ixCheap:0.3,dc:'Lagoon View Racks'}, - {id:'mao',name:'Manaus',x:0,y:0,land:'sa',reg:'SA',P:90,br:true,andes:'e',rain:true,ix:'IX.brrr Manaus',ixCheap:0.3,dc:'Free Zone Colo',note:tr('cities.two_million_people_in_the_middle')}, - {id:'mgf',off:true,name:'Maringá',x:0,y:0,land:'sa',reg:'SA',P:30,br:true,andes:'e',ix:'IX.brrr Maringá',ixCheap:0.3,dc:'Cathedral Cone DC'}, - {id:'nat',name:'Natal',x:0,y:0,land:'sa',reg:'SA',P:60,br:true,andes:'e',ix:'IX.brrr Natal',ixCheap:0.3,dc:'Dune Buggy DC',note:tr('cities.dunes_buggies_and_the_corner_of')}, - {id:'pmw',name:'Palmas',x:0,y:0,land:'sa',reg:'SA',P:15,br:true,andes:'e',ix:'IX.brrr Palmas',ixCheap:0.3,dc:'Planned Grid DC',note:tr('cities.brazil_s_youngest_state_capital')}, - {id:'pvh',name:'Porto Velho',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',rain:true,ix:'IX.brrr Porto Velho',ixCheap:0.3,dc:'Madeira River Racks'}, - {id:'rao',off:true,name:'Ribeirão Preto',x:0,y:0,land:'sa',reg:'SA',P:50,br:true,andes:'e',ix:'IX.brrr Ribeirão Preto',ixCheap:0.3,dc:'Sugarcane & Servers',note:tr('cities.brazil_s_agribusiness_capital')}, - {id:'rec',name:'Recife',x:0,y:0,land:'sa',reg:'SA',P:160,br:true,andes:'e',ix:'IX.brrr Recife',ixCheap:0.3,dc:'Frevo Colo',note:tr('cities.the_venice_of_brazil_all_bridges')}, - {id:'rbr',name:'Rio Branco',x:0,y:0,land:'sa',reg:'SA',P:20,br:true,andes:'e',rain:true,ix:'IX.brrr Rio Branco',ixCheap:0.3,dc:'Acre-ly Real DC',note:tr('cities.the_capital_of_acre_a_state')}, - {id:'ssa',name:'Salvador',x:0,y:0,land:'sa',reg:'SA',P:160,br:true,andes:'e',ix:'IX.brrr Salvador',ixCheap:0.3,dc:'Axé Uplink DC',note:tr('cities.brazil_s_first_capital_with_cables')}, - {id:'ria',off:true,name:'Santa Maria',x:0,y:0,land:'sa',reg:'SA',P:15,br:true,andes:'e',ix:'IX.brrr Santa Maria',ixCheap:0.3,dc:'Gaúcho Plains Colo'}, - {id:'sjp',off:true,name:'São José do Rio Preto',x:0,y:0,land:'sa',reg:'SA',P:25,br:true,andes:'e',ix:'IX.brrr São José do Rio Preto',ixCheap:0.3,dc:'Rio Preto Racks'}, - {id:'slz',name:'São Luís',x:0,y:0,land:'sa',reg:'SA',P:65,br:true,andes:'e',ix:'IX.brrr São Luís',ixCheap:0.3,dc:'Reggae Island DC',note:tr('cities.an_island_city_of_tiled_colonial')}, - {id:'the',name:'Teresina',x:0,y:0,land:'sa',reg:'SA',P:50,br:true,andes:'e',ix:'IX.brrr Teresina',ixCheap:0.3,dc:'Sunbaked Server Hall',note:tr('cities.the_only_northeastern_capital_away')}, - {id:'vix',name:'Vitória',x:0,y:0,land:'sa',reg:'SA',P:80,br:true,andes:'e',ix:'IX.brrr Vitória',ixCheap:0.3,dc:'Moqueca Colo',note:tr('cities.an_island_capital_with_a_big')}, - {id:'mvd',name:'Montevideo',x:0,y:0,land:'sa',reg:'SA',P:150,andes:'e',ix:'Chivito-IX',dc:'Rambla Racks',note:tr('cities.uruguay_fiber_to_almost_every_home')}, - {id:'asu',name:'Asunción',x:0,y:0,land:'sa',reg:'SA',P:120,andes:'e',ix:'Chipa-IX',dc:'Hydro Surplus DC',note:tr('cities.paraguay_shares_two_giant_dams_with')}, - {id:'cor',name:'Córdoba',x:0,y:0,land:'sa',reg:'SA',P:150,andes:'e',arpu:0.7,ix:'Fernet-IX',dc:'Sierras Server Shed',note:tr('cities.argentina_s_second_city_universities')}, - {id:'lpb',name:'La Paz',x:0,y:0,land:'sa',reg:'SA',P:80,andes:'m',ix:'Salteña-IX',dc:'Cable Car Colo',note:tr('cities.the_highest_seat_of_government_on')}, - {id:'uio',name:'Quito',x:0,y:0,land:'sa',reg:'SA',P:100,andes:'m',ix:'Equator-IX',dc:'Middle of the World DC',note:tr('cities.a_capital_high_in_the_andes')}, - {id:'mde',name:'Medellín',x:0,y:0,land:'sa',reg:'SA',P:150,andes:'m',ix:'Paisa-IX',dc:'Eternal Spring DC',note:tr('cities.the_city_of_eternal_spring_with')}, - {id:'ccs',name:'Caracas',x:0,y:0,land:'sa',reg:'SA',P:120,blackout:true,ix:'Cachapa-IX',dc:'Generator Included DC',note:tr('cities.a_capital_in_a_valley_under')}, - {id:'gua',name:'Guatemala City',x:0,y:0,land:'am',reg:'AM',P:120,ix:'Quetzal-IX',dc:'Volcano View Colo',note:tr('cities.central_america_s_biggest_city')}, - {id:'sjo',name:'San José',x:0,y:0,land:'am',reg:'AM',P:80,ix:'Pura Vida-IX',dc:'Cloud Forest DC',note:tr('cities.costa_rica_runs_almost_entirely_on')}, - {id:'qro',name:'Querétaro',x:0,y:0,land:'am',reg:'AM',P:120,ix:'Gordita-IX',dc:'Bajío Bit Barn',note:tr('cities.mexico_s_data_center_boom_town')}, - {id:'mty',name:'Monterrey',x:0,y:0,land:'am',reg:'AM',P:200,ix:'Cabrito-IX',dc:'Saddle Mountain Colo',note:tr('cities.mexico_s_industrial_capital_a_few')}, - {id:'gdl',name:'Guadalajara',x:0,y:0,land:'am',reg:'AM',P:200,ix:'Tequila-IX',dc:'Mariachi Mainframes',note:tr('cities.mexico_s_silicon_valley_home_of')}, - {id:'bue',name:'Buenos Aires',x:0,y:0,land:'sa',reg:'SA',P:500,andes:'e',arpu:0.7,ix:'Asado-IX',dc:'Puerto Madero DC',note:tr('cities.tango_steak_and_a_currency_that')}, - {id:'scl',name:'Santiago',x:0,y:0,land:'sa',reg:'SA',P:350,andes:'w',ix:'Empanada-IX',dc:'Andes-view Bunker',note:tr('cities.the_pacific_gateway_the_andes_sit')}, - {id:'lim',name:'Lima',x:0,y:0,land:'sa',reg:'SA',P:400,andes:'w',ix:'Ceviche-IX',dc:'Fog-cooled DC',note:tr('cities.it_almost_never_rains_but_the')}, - {id:'bog',name:'Bogotá',x:0,y:0,land:'sa',reg:'SA',P:400,andes:'m',ix:'Arepa-IX',dc:'2,600 m Above Sea Level DC',note:tr('cities.high_up_in_the_andes_no')}, - {id:'pan',name:'Panama City',x:0,y:0,land:'am',reg:'AM',P:80,ix:'Canal-IX',dc:'Isthmus Interconnect',note:tr('cities.every_cable_between_the_americas')}, - {id:'del',name:'Delhi',x:0,y:0,land:'eu',reg:'AS',P:1600,arpu:0.4,india:true,ix:'Butter-Chicken-IX',dc:'Smog-filtered DC',note:tr('cities.an_enormous_very_online_city_a')}, - {id:'maa',name:'Chennai',x:0,y:0,land:'eu',reg:'AS',P:500,arpu:0.5,india:true,ix:'Dosa-IX',dc:'Cyclone-rated Landing Bay',note:tr('cities.india_s_east_coast_landing_hub')}, - {id:'blr',name:'Bengaluru',x:0,y:0,land:'eu',reg:'AS',P:600,arpu:0.6,india:true,ix:'Filter-Kaapi-IX',dc:'Traffic-jam-adjacent Campus',note:tr('cities.india_s_tech_capital_packets_move')}, - {id:'hyd',name:'Hyderabad',x:0,y:0,land:'eu',reg:'AS',P:400,arpu:0.5,india:true,ix:'Biryani-IX',dc:'Hyperscale Hills',note:tr('cities.every_hyperscaler_is_building_a')}, - {id:'tpe',name:'Taipei',x:0,y:0,land:'tw',reg:'AS',P:450,ix:'Bubble-Tea-IX',dc:'Typhoon-proof Tower',note:tr('cities.makes_most_of_the_world_s')}, - {id:'auh',name:'Abu Dhabi',x:0,y:0,land:'eu',reg:'AS',P:200,arpu:1.4,uae:true,ix:'',dc:'Oasis-cooled Campus',note:tr('cities.the_capital_sovereign_ai_money_and')}, - {id:'fuj',name:'Fujairah',x:0,y:0,land:'eu',reg:'AS',P:20,uae:true,ix:'',dc:'Cable Landing Sandcastle',note:tr('cities.most_uae_cables_land_on_this')}, + {id:'bom',name:'Mumbai',x:1385,y:488,land:'eu',reg:'AS',cc:'IN',P:1100,india:true,ix:'Mumb-IX',dc:'Goregaon Tech Park'}, + {id:'sin',name:'Singapore',x:1556,y:568,land:'eu',reg:'AS',cc:'SG',P:450,ix:'Lah-IX',dc:'Equinox SG',note:tr('cities.asia_s_hub_expensive_humid_very')}, + {id:'hkg',name:'Hong Kong',x:1645,y:440,land:'eu',reg:'AS',cc:'HK',P:600,ix:'HK-Kicks',dc:'Mega-Eye Plus'}, + {id:'icn',name:'Seoul',x:1722,y:302,land:'eu',reg:'AS',cc:'KR',P:900,kr:true,ix:'Kimch-IX',dc:'Gasan Digital Complex',note:tr('cities.some_of_the_fastest_home_broadband')}, + {id:'pek',name:'Beijing',x:1652,y:318,land:'eu',reg:'AS',cc:'CN',P:1800,cn:true,arpu:0.6,ix:'',dc:'Zhongguancun DC',note:tr('cities.mainland_china_behind_the_great')}, + {id:'sha',name:'Shanghai',x:1680,y:388,land:'eu',reg:'AS',cc:'CN',P:2200,cn:true,arpu:0.6,ix:'',dc:'Lujiazui Data Center',note:tr('cities.mainland_china_enormous_market')}, + {id:'tok',name:'Tokyo',x:1795,y:320,land:'jp',reg:'AS',cc:'JP',P:1400,ix:'JP-Naptime',dc:'Otemachi Tower'}, + {id:'syd',name:'Sydney',x:1860,y:790,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:500,ix:'IX Straya',dc:'Next-Door-DC S#',dcN:3,dc2:'Equinox SY#',dc2N:7,note:tr('cities.the_harbour_the_bridge_and_most')}, +{id:'for',name:'Fortaleza',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:250,br:true,andes:'e',ix:'IX.brrr Fortaleza',ixCheap:0.3,dc:'Praia Landing Station',note:tr('cities.where_south_america_s_cables')}, + {id:'rio',name:'Rio de Janeiro',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:600,br:true,andes:'e',ix:'IX.brrr Rio',ixCheap:0.3,dc:'Copacabana Colo',note:tr('cities.beaches_cable_landings_and_a')}, + {id:'bsb',name:'Brasília',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:200,br:true,andes:'e',ix:'IX.brrr Brasília',ixCheap:0.3,dc:'Modernist Concrete Colo',note:tr('cities.brazil_s_planned_capital_shaped_like')}, + {id:'bhz',name:'Belo Horizonte',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:250,br:true,andes:'e',ix:'IX.brrr BH',ixCheap:0.3,dc:'Pão de Queijo Point',note:tr('cities.mountains_mines_and_more_bars_per')}, + {id:'cwb',name:'Curitiba',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:200,br:true,andes:'e',ix:'IX.brrr Curitiba',ixCheap:0.3,dc:'Pine Nut Park DC',note:tr('cities.brazil_s_coldest_big_city_and')}, + {id:'poa',name:'Porto Alegre',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:200,br:true,andes:'e',ix:'IX.brrr Porto Alegre',ixCheap:0.3,dc:'Chimarrão Colo',note:tr('cities.the_deep_south_halfway_to_buenos')}, + {id:'aju',off:true,name:'Aracaju',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:40,br:true,andes:'e',ix:'IX.brrr Aracaju',ixCheap:0.3,dc:'Crab Walk Colo'}, + {id:'bel',name:'Belém',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:100,br:true,andes:'e',rain:true,ix:'IX.brrr Belém',ixCheap:0.3,dc:'Açaí Bowl DC',note:tr('cities.gateway_to_the_amazon_at_the')}, + {id:'bvb',name:'Boa Vista',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',rain:true,ix:'IX.brrr Boa Vista',ixCheap:0.3,dc:'Northern Lights Racks',note:tr('cities.brazil_s_northernmost_capital_the')}, + {id:'cac',off:true,name:'Cascavel',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',ix:'IX.brrr Cascavel',ixCheap:0.3,dc:'Soybean Silo DC'}, + {id:'cpv',off:true,name:'Campina Grande',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',ix:'IX.brrr Campina Grande',ixCheap:0.3,dc:'Forró Forum DC',note:tr('cities.throws_the_biggest_sao_joao_festival')}, + {id:'cpq',name:'Campinas',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:130,br:true,andes:'e',ix:'IX.brrr Campinas',ixCheap:0.3,dc:'Silicon Sugarcane Park',note:tr('cities.brazil_s_tech_hub_an_hour')}, + {id:'cgr',name:'Campo Grande',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:40,br:true,andes:'e',ix:'IX.brrr Campo Grande',ixCheap:0.3,dc:'Pantanal Edge Colo'}, + {id:'cau',off:true,name:'Caruaru',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',ix:'IX.brrr Caruaru',ixCheap:0.3,dc:'Clay Doll Datacenter'}, + {id:'cgb',name:'Cuiabá',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:40,br:true,andes:'e',ix:'IX.brrr Cuiabá',ixCheap:0.3,dc:'Forty Degrees DC',note:tr('cities.the_geographic_center_of_south')}, + {id:'cxj',off:true,name:'Caxias do Sul',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',ix:'IX.brrr Caxias do Sul',ixCheap:0.3,dc:'Wine Cellar Racks',note:tr('cities.italian_immigrants_vineyards_and')}, + {id:'fec',off:true,name:'Feira de Santana',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',ix:'IX.brrr Feira de Santana',ixCheap:0.3,dc:'Crossroads Colo'}, + {id:'fln',off:true,name:'Florianópolis',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:50,br:true,andes:'e',ix:'IX.brrr Florianópolis',ixCheap:0.3,dc:'Island Uplink DC',note:tr('cities.an_island_capital_of_beaches_and')}, + {id:'igu',off:true,name:'Foz do Iguaçu',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:15,br:true,andes:'e',ix:'IX.brrr Foz do Iguaçu',ixCheap:0.3,dc:'Triple Border Racks',note:tr('cities.where_brazil_argentina_and_paraguay')}, + {id:'gyn',name:'Goiânia',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:100,br:true,andes:'e',ix:'IX.brrr Goiânia',ixCheap:0.3,dc:'Pequi Peak DC',note:tr('cities.agribusiness_capital_and_home_of')}, + {id:'jpa',off:true,name:'João Pessoa',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:50,br:true,andes:'e',ix:'IX.brrr João Pessoa',ixCheap:0.3,dc:'Sunrise Point DC',note:tr('cities.the_easternmost_city_of_the_americas')}, + {id:'ljd',off:true,name:'Lajeado',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:10,br:true,andes:'e',ix:'IX.brrr Lajeado',ixCheap:0.3,dc:'Valley Co-op Colo',note:tr('cities.a_small_town_with_its_own')}, + {id:'ldb',name:'Londrina',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:35,br:true,andes:'e',ix:'IX.brrr Londrina',ixCheap:0.3,dc:'Red Soil DC'}, + {id:'mcp',name:'Macapá',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',rain:true,blackout:true,ix:'IX.brrr Macapá',ixCheap:0.3,dc:'Equator Line Colo',note:tr('cities.right_on_the_equator_at_the')}, + {id:'mcz',off:true,name:'Maceió',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:55,br:true,andes:'e',ix:'IX.brrr Maceió',ixCheap:0.3,dc:'Lagoon View Racks'}, + {id:'mao',name:'Manaus',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:90,br:true,andes:'e',rain:true,ix:'IX.brrr Manaus',ixCheap:0.3,dc:'Free Zone Colo',note:tr('cities.two_million_people_in_the_middle')}, + {id:'mgf',off:true,name:'Maringá',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:30,br:true,andes:'e',ix:'IX.brrr Maringá',ixCheap:0.3,dc:'Cathedral Cone DC'}, + {id:'nat',name:'Natal',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:60,br:true,andes:'e',ix:'IX.brrr Natal',ixCheap:0.3,dc:'Dune Buggy DC',note:tr('cities.dunes_buggies_and_the_corner_of')}, + {id:'pmw',name:'Palmas',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:15,br:true,andes:'e',ix:'IX.brrr Palmas',ixCheap:0.3,dc:'Planned Grid DC',note:tr('cities.brazil_s_youngest_state_capital')}, + {id:'pvh',name:'Porto Velho',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',rain:true,ix:'IX.brrr Porto Velho',ixCheap:0.3,dc:'Madeira River Racks'}, + {id:'rao',off:true,name:'Ribeirão Preto',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:50,br:true,andes:'e',ix:'IX.brrr Ribeirão Preto',ixCheap:0.3,dc:'Sugarcane & Servers',note:tr('cities.brazil_s_agribusiness_capital')}, + {id:'rec',name:'Recife',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:160,br:true,andes:'e',ix:'IX.brrr Recife',ixCheap:0.3,dc:'Frevo Colo',note:tr('cities.the_venice_of_brazil_all_bridges')}, + {id:'rbr',name:'Rio Branco',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:20,br:true,andes:'e',rain:true,ix:'IX.brrr Rio Branco',ixCheap:0.3,dc:'Acre-ly Real DC',note:tr('cities.the_capital_of_acre_a_state')}, + {id:'ssa',name:'Salvador',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:160,br:true,andes:'e',ix:'IX.brrr Salvador',ixCheap:0.3,dc:'Axé Uplink DC',note:tr('cities.brazil_s_first_capital_with_cables')}, + {id:'ria',off:true,name:'Santa Maria',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:15,br:true,andes:'e',ix:'IX.brrr Santa Maria',ixCheap:0.3,dc:'Gaúcho Plains Colo'}, + {id:'sjp',off:true,name:'São José do Rio Preto',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:25,br:true,andes:'e',ix:'IX.brrr São José do Rio Preto',ixCheap:0.3,dc:'Rio Preto Racks'}, + {id:'slz',name:'São Luís',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:65,br:true,andes:'e',ix:'IX.brrr São Luís',ixCheap:0.3,dc:'Reggae Island DC',note:tr('cities.an_island_city_of_tiled_colonial')}, + {id:'the',name:'Teresina',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:50,br:true,andes:'e',ix:'IX.brrr Teresina',ixCheap:0.3,dc:'Sunbaked Server Hall',note:tr('cities.the_only_northeastern_capital_away')}, + {id:'vix',name:'Vitória',x:0,y:0,land:'sa',reg:'SA',cc:'BR',P:80,br:true,andes:'e',ix:'IX.brrr Vitória',ixCheap:0.3,dc:'Moqueca Colo',note:tr('cities.an_island_capital_with_a_big')}, + {id:'mvd',name:'Montevideo',x:0,y:0,land:'sa',reg:'SA',cc:'UY',P:150,andes:'e',ix:'Chivito-IX',dc:'Rambla Racks',note:tr('cities.uruguay_fiber_to_almost_every_home')}, + {id:'asu',name:'Asunción',x:0,y:0,land:'sa',reg:'SA',cc:'PY',P:120,andes:'e',ix:'Chipa-IX',dc:'Hydro Surplus DC',note:tr('cities.paraguay_shares_two_giant_dams_with')}, + {id:'cor',name:'Córdoba',x:0,y:0,land:'sa',reg:'SA',cc:'AR',P:150,andes:'e',arpu:0.7,ix:'Fernet-IX',dc:'Sierras Server Shed',note:tr('cities.argentina_s_second_city_universities')}, + {id:'lpb',name:'La Paz',x:0,y:0,land:'sa',reg:'SA',cc:'BO',P:80,andes:'m',ix:'Salteña-IX',dc:'Cable Car Colo',note:tr('cities.the_highest_seat_of_government_on')}, + {id:'uio',name:'Quito',x:0,y:0,land:'sa',reg:'SA',cc:'EC',P:100,andes:'m',ix:'Equator-IX',dc:'Middle of the World DC',note:tr('cities.a_capital_high_in_the_andes')}, + {id:'mde',name:'Medellín',x:0,y:0,land:'sa',reg:'SA',cc:'CO',P:150,andes:'m',ix:'Paisa-IX',dc:'Eternal Spring DC',note:tr('cities.the_city_of_eternal_spring_with')}, + {id:'ccs',name:'Caracas',x:0,y:0,land:'sa',reg:'SA',cc:'VE',P:120,blackout:true,ix:'Cachapa-IX',dc:'Generator Included DC',note:tr('cities.a_capital_in_a_valley_under')}, + {id:'gua',name:'Guatemala City',x:0,y:0,land:'am',reg:'AM',cc:'GT',P:120,ix:'Quetzal-IX',dc:'Volcano View Colo',note:tr('cities.central_america_s_biggest_city')}, + {id:'sjo',name:'San José',x:0,y:0,land:'am',reg:'AM',cc:'CR',P:80,ix:'Pura Vida-IX',dc:'Cloud Forest DC',note:tr('cities.costa_rica_runs_almost_entirely_on')}, + {id:'qro',name:'Querétaro',x:0,y:0,land:'am',reg:'AM',cc:'MX',P:120,ix:'Gordita-IX',dc:'Bajío Bit Barn',note:tr('cities.mexico_s_data_center_boom_town')}, + {id:'mty',name:'Monterrey',x:0,y:0,land:'am',reg:'AM',cc:'MX',P:200,ix:'Cabrito-IX',dc:'Saddle Mountain Colo',note:tr('cities.mexico_s_industrial_capital_a_few')}, + {id:'gdl',name:'Guadalajara',x:0,y:0,land:'am',reg:'AM',cc:'MX',P:200,ix:'Tequila-IX',dc:'Mariachi Mainframes',note:tr('cities.mexico_s_silicon_valley_home_of')}, + {id:'bue',name:'Buenos Aires',x:0,y:0,land:'sa',reg:'SA',cc:'AR',P:500,andes:'e',arpu:0.7,ix:'Asado-IX',dc:'Puerto Madero DC',note:tr('cities.tango_steak_and_a_currency_that')}, + {id:'scl',name:'Santiago',x:0,y:0,land:'sa',reg:'SA',cc:'CL',P:350,andes:'w',ix:'Empanada-IX',dc:'Andes-view Bunker',note:tr('cities.the_pacific_gateway_the_andes_sit')}, + {id:'lim',name:'Lima',x:0,y:0,land:'sa',reg:'SA',cc:'PE',P:400,andes:'w',ix:'Ceviche-IX',dc:'Fog-cooled DC',note:tr('cities.it_almost_never_rains_but_the')}, + {id:'bog',name:'Bogotá',x:0,y:0,land:'sa',reg:'SA',cc:'CO',P:400,andes:'m',ix:'Arepa-IX',dc:'2,600 m Above Sea Level DC',note:tr('cities.high_up_in_the_andes_no')}, + {id:'pan',name:'Panama City',x:0,y:0,land:'am',reg:'AM',cc:'PA',P:80,ix:'Canal-IX',dc:'Isthmus Interconnect',note:tr('cities.every_cable_between_the_americas')}, + {id:'del',name:'Delhi',x:0,y:0,land:'eu',reg:'AS',cc:'IN',P:1600,arpu:0.4,india:true,ix:'Butter-Chicken-IX',dc:'Smog-filtered DC',note:tr('cities.an_enormous_very_online_city_a')}, + {id:'maa',name:'Chennai',x:0,y:0,land:'eu',reg:'AS',cc:'IN',P:500,arpu:0.5,india:true,ix:'Dosa-IX',dc:'Cyclone-rated Landing Bay',note:tr('cities.india_s_east_coast_landing_hub')}, + {id:'blr',name:'Bengaluru',x:0,y:0,land:'eu',reg:'AS',cc:'IN',P:600,arpu:0.6,india:true,ix:'Filter-Kaapi-IX',dc:'Traffic-jam-adjacent Campus',note:tr('cities.india_s_tech_capital_packets_move')}, + {id:'hyd',name:'Hyderabad',x:0,y:0,land:'eu',reg:'AS',cc:'IN',P:400,arpu:0.5,india:true,ix:'Biryani-IX',dc:'Hyperscale Hills',note:tr('cities.every_hyperscaler_is_building_a')}, + {id:'tpe',name:'Taipei',x:0,y:0,land:'tw',reg:'AS',cc:'TW',P:450,ix:'Bubble-Tea-IX',dc:'Typhoon-proof Tower',note:tr('cities.makes_most_of_the_world_s')}, + {id:'auh',name:'Abu Dhabi',x:0,y:0,land:'eu',reg:'AS',cc:'AE',P:200,arpu:1.4,uae:true,ix:'',dc:'Oasis-cooled Campus',note:tr('cities.the_capital_sovereign_ai_money_and')}, + {id:'fuj',name:'Fujairah',x:0,y:0,land:'eu',reg:'AS',cc:'AE',P:20,uae:true,ix:'',dc:'Cable Landing Sandcastle',note:tr('cities.most_uae_cables_land_on_this')}, {id:'cpt',name:'Cape Town',x:0,y:0,land:'af',reg:'AF',cc:'ZA',P:250,za:true,ix:'Biltong-IX',dc:'Table Mountain Colo',note:tr('cities.where_the_atlantic_cables_to_africa')}, {id:'dkr',name:'Dakar',x:0,y:0,land:'af',reg:'AF',P:140,cc:'SN',ix:'Thieboudienne-IX',dc:'Teranga Racks',note:tr('cities.africa_s_westernmost_capital_where')}, {id:'abj',name:'Abidjan',x:0,y:0,land:'af',reg:'AF',P:200,cc:'CI',ix:'Attiéké-IX',dc:'Plateau Point DC',note:tr('cities.the_business_capital_of_french')}, @@ -142,14 +142,14 @@ const CITIES=[ {id:'lun',name:'Lusaka',x:0,y:0,land:'af',reg:'AF',P:100,cc:'ZM',blackout:true,ix:'Nshima-IX',dc:'Copperbelt Colo',note:tr('cities.zambia_runs_on_hydro_power_from')}, {id:'hre',name:'Harare',x:0,y:0,land:'af',reg:'AF',P:70,cc:'ZW',blackout:true,ix:'Sadza-IX',dc:'Jacaranda DC',note:tr('cities.purple_jacaranda_trees_and_long')}, {id:'gbe',name:'Gaborone',x:0,y:0,land:'af',reg:'AF',P:25,cc:'BW',ix:'Seswaa-IX',dc:'Diamond Dust DC',note:tr('cities.botswana_quiet_safe_and_rich_in')}, -{id:'mel',name:'Melbourne',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:450,ix:'Flat-White-IX',dc:'Four-Seasons-a-Day DC',dc2:'Next-Door-DC M#',dc2N:3,note:tr('cities.four_seasons_in_one_day_and')}, - {id:'bne',name:'Brisbane',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:250,ix:'Bris-Vegas-IX',dc:'Sunshine State Shed',dc2:'Next-Door-DC B#',dc2N:2,note:tr('cities.brisvegas_big_sky_a_thunderstorm_at')}, - {id:'drw',name:'Darwin',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:15,ix:'Gator-IX',dc:'Crocodile-proof Landing Station',note:tr('cities.tiny_tropical_and_the_closest')}, - {id:'adl',name:'Adelaide',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:150,ix:'Vineyard-IX',dc:'OurDC',dc2:'Next-Door-DC A1',note:tr('cities.twenty_minutes_from_everything')}, - {id:'cbr',capital:true,name:'Canberra',x:0,y:0,land:'oc',reg:'OC',au:true,arpu:AU_ARPU,P:50,ix:'Capital-IX',dc:'Classified Data Cupboard',dc2:'Next-Door-DC C1',note:tr('cities.built_for_the_government_the_data')}, - {id:'chc',name:'Christchurch',x:0,y:0,land:'nzs',reg:'OC',P:40,ix:'Garden-City-IX',dc:'Mainland Colo',note:tr('cities.the_garden_city_and_the_biggest')}, - {id:'ivc',name:'Invercargill',x:0,y:0,land:'nzs',reg:'OC',P:10,ix:'',dc:'Sheargrid Makarewa',note:tr('cities.the_bottom_of_the_country_on')}, - {id:'hba',name:'Hobart',x:0,y:0,land:'tas',reg:'OC',au:true,arpu:AU_ARPU,P:25,ix:'Cousin-IX',dc:'Firmest',note:tr('cities.the_bottom_of_the_map_cool')}, +{id:'mel',name:'Melbourne',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:450,ix:'Flat-White-IX',dc:'Four-Seasons-a-Day DC',dc2:'Next-Door-DC M#',dc2N:3,note:tr('cities.four_seasons_in_one_day_and')}, + {id:'bne',name:'Brisbane',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:250,ix:'Bris-Vegas-IX',dc:'Sunshine State Shed',dc2:'Next-Door-DC B#',dc2N:2,note:tr('cities.brisvegas_big_sky_a_thunderstorm_at')}, + {id:'drw',name:'Darwin',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:15,ix:'Gator-IX',dc:'Crocodile-proof Landing Station',note:tr('cities.tiny_tropical_and_the_closest')}, + {id:'adl',name:'Adelaide',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:150,ix:'Vineyard-IX',dc:'OurDC',dc2:'Next-Door-DC A1',note:tr('cities.twenty_minutes_from_everything')}, + {id:'cbr',capital:true,name:'Canberra',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:50,ix:'Capital-IX',dc:'Classified Data Cupboard',dc2:'Next-Door-DC C1',note:tr('cities.built_for_the_government_the_data')}, + {id:'chc',name:'Christchurch',x:0,y:0,land:'nzs',reg:'OC',cc:'NZ',P:40,ix:'Garden-City-IX',dc:'Mainland Colo',note:tr('cities.the_garden_city_and_the_biggest')}, + {id:'ivc',name:'Invercargill',x:0,y:0,land:'nzs',reg:'OC',cc:'NZ',P:10,ix:'',dc:'Sheargrid Makarewa',note:tr('cities.the_bottom_of_the_country_on')}, + {id:'hba',name:'Hobart',x:0,y:0,land:'tas',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:25,ix:'Cousin-IX',dc:'Firmest',note:tr('cities.the_bottom_of_the_map_cool')}, {id:'hnl',name:'Honolulu',x:0,y:0,land:'hi',reg:'OC',cc:'US',P:70,ix:'Poke-IX',dc:'Dr. Fortress of Solitude',note:tr('cities.halfway_between_california_and')}, {id:'gum',name:'Guam',x:0,y:0,land:'gu',reg:'OC',cc:'GU',P:15,blackout:true,ix:'Spam-IX',dc:'Typhoon-Proof Bunker',note:tr('cities.a_small_island_where_cables_from')}, {id:'ror',name:'Koror',x:0,y:0,land:'pw',reg:'OC',cc:'PW',P:3,ix:'',dc:'Jellyfish Lake Landing',note:tr('cities.palau_on_a_branch_cable_from')}, @@ -168,39 +168,39 @@ const CITIES=[ {id:'tci',name:'Tenerife',x:0,y:0,land:'ic',reg:'EU',cc:'ES',P:25,ix:'',dc:'Mojo Picón DC',note:tr('cities.the_canary_islands_a_short_hop')}, {id:'rai',name:'Praia',x:0,y:0,land:'cv',reg:'AF',cc:'CV',P:5,ix:'Cachupa-IX',dc:'Morabeza Rack',note:tr('cities.cape_verde_s_capital_off_the')}, {id:'jam',name:'St Helena',x:0,y:0,land:'sh',reg:'AF',cc:'SH',P:1,blackout:true,ix:'',dc:'Napoleon’s Last Rack',note:tr('cities.one_of_the_most_remote_islands')}, - {id:'osa',name:'Osaka',x:0,y:0,land:'jp',reg:'AS',P:700,ix:'Takoyaki-IX',dc:'Dojima DC',note:tr('cities.japan_s_second_hub_and_tokyo')}, - {id:'kul',name:'Kuala Lumpur',x:0,y:0,land:'eu',reg:'AS',P:350,ix:'Satay-IX',dc:'Twin Towers Colo',note:tr('cities.cheaper_than_singapore_next_door_the')}, - {id:'bkk',name:'Bangkok',x:0,y:0,land:'eu',reg:'AS',P:600,ix:'Tom-Yum-IX',dc:'Floating Market DC',note:tr('cities.big_busy_and_flooded_with_traffic')}, - {id:'sgn',name:'Ho Chi Minh City',x:0,y:0,land:'eu',reg:'AS',P:500,vn:true,ix:'Pho-IX',dc:'Scooter-cooled DC',note:tr('cities.very_online_and_badly_served_by')}, - {id:'khi',name:'Karachi',x:0,y:0,land:'eu',reg:'AS',P:500,arpu:0.4,ix:'Chai-IX',dc:'Seaview Landing Station',note:tr('cities.pakistan_s_door_to_the_sea')}, - {id:'dac',name:'Dhaka',x:0,y:0,land:'eu',reg:'AS',P:700,arpu:0.3,ix:'Rickshaw-IX',dc:'Monsoon-mapped DC',note:tr('cities.huge_dense_and_hungry_its')}, - {id:'cbo',name:'Colombo',x:0,y:0,land:'lk',reg:'AS',P:120,ix:'Hopper-IX',dc:'Tea-cooled Landing Station',note:tr('cities.a_small_island_at_the_crossroads')}, - {id:'waw',name:'Warsaw',x:0,y:0,land:'eu',reg:'EU',P:550,ix:'Pierogi-IX',dc:'Palace-of-Culture-adjacent DC',note:tr('cities.central_europe_s_rising_hub_more')}, - {id:'prg',name:'Prague',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Pilsner-IX',dc:'Castle-view Colo',note:tr('cities.beer_is_cheaper_than_water_here')}, - {id:'vie',name:'Vienna',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Schnitzel-IX',dc:'Waltz-cooled DC',note:tr('cities.the_old_gateway_to_eastern_europe')}, - {id:'bud',name:'Budapest',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Goulash-IX',dc:'Thermal Bath DC',note:tr('cities.waste_heat_goes_straight_into_the')}, - {id:'buh',name:'Bucharest',x:0,y:0,land:'eu',reg:'EU',P:400,ix:'Sarmale-IX',dc:'Parliament-sized DC',note:tr('cities.gigabit_home_broadband_for_the_price')}, - {id:'tll',name:'Tallinn',x:0,y:0,land:'eu',reg:'EU',P:80,ix:'E-Stonia-IX',dc:'Medieval Wall DC',note:tr('cities.digital_everything_e_residency_for')}, - {id:'ist',name:'Istanbul',x:0,y:0,land:'eu',reg:'EU',P:900,ix:'Baklava-IX',dc:'Bosphorus Bridge DC',note:tr('cities.one_foot_in_europe_one_in')}, - {id:'kyv',name:'Kyiv',x:0,y:0,land:'eu',reg:'EU',P:500,blackout:true,ix:'Varenyky-IX',dc:'Generator-backed Bunker DC',note:tr('cities.ukrainian_network_engineers_kept_the')}, - {id:'jed',name:'Jeddah',x:0,y:0,land:'eu',reg:'AS',P:300,saudi:true,gcc:true,ix:'',dc:'Red Sea Landing Palace',note:tr('cities.saudi_arabia_s_red_sea_cable')}, - {id:'ruh',name:'Riyadh',x:0,y:0,land:'eu',reg:'AS',P:600,saudi:true,gcc:true,ix:'Kabsa-IX',dc:'Desert Megaproject DC',note:tr('cities.the_capital_building_ai_campuses_at')}, - {id:'doh',name:'Doha',x:0,y:0,land:'eu',reg:'AS',P:150,arpu:1.5,qa:true,ix:'Pearl-IX',dc:'Air-cooled Stadium DC',note:tr('cities.small_rich_and_very_well_connected')}, - {id:'mil',name:'Milan',x:0,y:0,land:'eu',reg:'EU',P:450,ix:'MIX-and-Match',dc:'Caldera Park Campus',note:tr('cities.italy_s_digital_capital_fashion_week')}, - {id:'rom',name:'Rome',x:0,y:0,land:'eu',reg:'EU',P:450,ix:'Carbonara-IX',dc:'Colosseum-adjacent Colo',note:tr('cities.all_roads_lead_to_rome_most')}, - {id:'pmo',name:'Palermo',x:0,y:0,land:'eu',reg:'EU',P:60,ix:'Cannoli-IX',dc:'Sicilian Hub-a-Dub',note:tr('cities.a_small_city_on_a_big')}, - {id:'lis',name:'Lisbon',x:0,y:0,land:'eu',reg:'EU',P:300,ix:'Pastel-de-Nata-IX',dc:'Seven Hills Colo',note:tr('cities.europe_s_new_atlantic_gateway_cables')}, - {id:'ath',name:'Athens',x:0,y:0,land:'eu',reg:'EU',P:350,ix:'Souvlaki-IX',dc:'Acropolis-view DC',note:tr('cities.ancient_city_brand_new_cables_greece')}, - {id:'atn',name:'Atlanta',x:0,y:0,land:'am',reg:'AM',P:450,ix:'Peach-IX',dc:'56 Marietta',note:tr('cities.the_southeast_s_carrier_hotel')}, - {id:'den',name:'Denver',x:0,y:0,land:'am',reg:'AM',P:250,ix:'Mile-High-IX',dc:'Thin Air DC',note:tr('cities.a_mile_up_and_halfway_between')}, - {id:'phx',name:'Phoenix',x:0,y:0,land:'am',reg:'AM',P:300,ix:'Cactus-IX',dc:'Dry Heat Campus',note:tr('cities.cheap_land_cheap_power_and_48')}, - {id:'bos',name:'Boston',x:0,y:0,land:'am',reg:'AM',P:350,ix:'Chowder-IX',dc:'One Summer Street',note:tr('cities.universities_biotech_and_a_carrier')}, - {id:'hou',name:'Houston',x:0,y:0,land:'am',reg:'AM',P:450,ix:'Rodeo-IX',dc:'Hurricane-hardened DC',note:tr('cities.oil_gas_and_hurricanes_the')}, - {id:'slc',name:'Salt Lake City',x:0,y:0,land:'am',reg:'AM',P:150,ix:'Fry-Sauce-IX',dc:'Great Salt Lake DC',note:tr('cities.cheap_power_dry_air_and_a')}, - {id:'man',name:'Manchester',x:0,y:0,land:'uk',reg:'EU',P:350,ix:'Rainy-City-IX',dc:'Old Cotton Mill Colo',note:tr('cities.the_north_s_hub_with_its')}, - {id:'edi',name:'Edinburgh',x:0,y:0,land:'uk',reg:'EU',P:200,ix:'Haggis-IX',dc:'Castle Rock Colo',note:tr('cities.scotland_s_capital_north_sea_cables')}, - {id:'bde',name:'Bude',x:0,y:0,land:'uk',reg:'EU',P:3,ix:'',dc:'Clifftop Landing Station',note:tr('cities.a_tiny_surfing_town_in_cornwall')}, - {id:'svg',name:'Stavanger',x:0,y:0,land:'eu',reg:'EU',P:60,ix:'Brunost-IX',dc:'Inside-a-Mountain DC',note:tr('cities.norway_s_oil_capital_now_full')}, + {id:'osa',name:'Osaka',x:0,y:0,land:'jp',reg:'AS',cc:'JP',P:700,ix:'Takoyaki-IX',dc:'Dojima DC',note:tr('cities.japan_s_second_hub_and_tokyo')}, + {id:'kul',name:'Kuala Lumpur',x:0,y:0,land:'eu',reg:'AS',cc:'MY',P:350,ix:'Satay-IX',dc:'Twin Towers Colo',note:tr('cities.cheaper_than_singapore_next_door_the')}, + {id:'bkk',name:'Bangkok',x:0,y:0,land:'eu',reg:'AS',cc:'TH',P:600,ix:'Tom-Yum-IX',dc:'Floating Market DC',note:tr('cities.big_busy_and_flooded_with_traffic')}, + {id:'sgn',name:'Ho Chi Minh City',x:0,y:0,land:'eu',reg:'AS',cc:'VN',P:500,vn:true,ix:'Pho-IX',dc:'Scooter-cooled DC',note:tr('cities.very_online_and_badly_served_by')}, + {id:'khi',name:'Karachi',x:0,y:0,land:'eu',reg:'AS',cc:'PK',P:500,arpu:0.4,ix:'Chai-IX',dc:'Seaview Landing Station',note:tr('cities.pakistan_s_door_to_the_sea')}, + {id:'dac',name:'Dhaka',x:0,y:0,land:'eu',reg:'AS',cc:'BD',P:700,arpu:0.3,ix:'Rickshaw-IX',dc:'Monsoon-mapped DC',note:tr('cities.huge_dense_and_hungry_its')}, + {id:'cbo',name:'Colombo',x:0,y:0,land:'lk',reg:'AS',cc:'LK',P:120,ix:'Hopper-IX',dc:'Tea-cooled Landing Station',note:tr('cities.a_small_island_at_the_crossroads')}, + {id:'waw',name:'Warsaw',x:0,y:0,land:'eu',reg:'EU',cc:'PL',P:550,ix:'Pierogi-IX',dc:'Palace-of-Culture-adjacent DC',note:tr('cities.central_europe_s_rising_hub_more')}, + {id:'prg',name:'Prague',x:0,y:0,land:'eu',reg:'EU',cc:'CZ',P:300,ix:'Pilsner-IX',dc:'Castle-view Colo',note:tr('cities.beer_is_cheaper_than_water_here')}, + {id:'vie',name:'Vienna',x:0,y:0,land:'eu',reg:'EU',cc:'AT',P:300,ix:'Schnitzel-IX',dc:'Waltz-cooled DC',note:tr('cities.the_old_gateway_to_eastern_europe')}, + {id:'bud',name:'Budapest',x:0,y:0,land:'eu',reg:'EU',cc:'HU',P:300,ix:'Goulash-IX',dc:'Thermal Bath DC',note:tr('cities.waste_heat_goes_straight_into_the')}, + {id:'buh',name:'Bucharest',x:0,y:0,land:'eu',reg:'EU',cc:'RO',P:400,ix:'Sarmale-IX',dc:'Parliament-sized DC',note:tr('cities.gigabit_home_broadband_for_the_price')}, + {id:'tll',name:'Tallinn',x:0,y:0,land:'eu',reg:'EU',cc:'EE',P:80,ix:'E-Stonia-IX',dc:'Medieval Wall DC',note:tr('cities.digital_everything_e_residency_for')}, + {id:'ist',name:'Istanbul',x:0,y:0,land:'eu',reg:'EU',cc:'TR',P:900,ix:'Baklava-IX',dc:'Bosphorus Bridge DC',note:tr('cities.one_foot_in_europe_one_in')}, + {id:'kyv',name:'Kyiv',x:0,y:0,land:'eu',reg:'EU',cc:'UA',P:500,blackout:true,ix:'Varenyky-IX',dc:'Generator-backed Bunker DC',note:tr('cities.ukrainian_network_engineers_kept_the')}, + {id:'jed',name:'Jeddah',x:0,y:0,land:'eu',reg:'AS',cc:'SA',P:300,saudi:true,gcc:true,ix:'',dc:'Red Sea Landing Palace',note:tr('cities.saudi_arabia_s_red_sea_cable')}, + {id:'ruh',name:'Riyadh',x:0,y:0,land:'eu',reg:'AS',cc:'SA',P:600,saudi:true,gcc:true,ix:'Kabsa-IX',dc:'Desert Megaproject DC',note:tr('cities.the_capital_building_ai_campuses_at')}, + {id:'doh',name:'Doha',x:0,y:0,land:'eu',reg:'AS',cc:'QA',P:150,arpu:1.5,qa:true,ix:'Pearl-IX',dc:'Air-cooled Stadium DC',note:tr('cities.small_rich_and_very_well_connected')}, + {id:'mil',name:'Milan',x:0,y:0,land:'eu',reg:'EU',cc:'IT',P:450,ix:'MIX-and-Match',dc:'Caldera Park Campus',note:tr('cities.italy_s_digital_capital_fashion_week')}, + {id:'rom',name:'Rome',x:0,y:0,land:'eu',reg:'EU',cc:'IT',P:450,ix:'Carbonara-IX',dc:'Colosseum-adjacent Colo',note:tr('cities.all_roads_lead_to_rome_most')}, + {id:'pmo',name:'Palermo',x:0,y:0,land:'eu',reg:'EU',cc:'IT',P:60,ix:'Cannoli-IX',dc:'Sicilian Hub-a-Dub',note:tr('cities.a_small_city_on_a_big')}, + {id:'lis',name:'Lisbon',x:0,y:0,land:'eu',reg:'EU',cc:'PT',P:300,ix:'Pastel-de-Nata-IX',dc:'Seven Hills Colo',note:tr('cities.europe_s_new_atlantic_gateway_cables')}, + {id:'ath',name:'Athens',x:0,y:0,land:'eu',reg:'EU',cc:'GR',P:350,ix:'Souvlaki-IX',dc:'Acropolis-view DC',note:tr('cities.ancient_city_brand_new_cables_greece')}, + {id:'atn',name:'Atlanta',x:0,y:0,land:'am',reg:'AM',cc:'US',P:450,ix:'Peach-IX',dc:'56 Marietta',note:tr('cities.the_southeast_s_carrier_hotel')}, + {id:'den',name:'Denver',x:0,y:0,land:'am',reg:'AM',cc:'US',P:250,ix:'Mile-High-IX',dc:'Thin Air DC',note:tr('cities.a_mile_up_and_halfway_between')}, + {id:'phx',name:'Phoenix',x:0,y:0,land:'am',reg:'AM',cc:'US',P:300,ix:'Cactus-IX',dc:'Dry Heat Campus',note:tr('cities.cheap_land_cheap_power_and_48')}, + {id:'bos',name:'Boston',x:0,y:0,land:'am',reg:'AM',cc:'US',P:350,ix:'Chowder-IX',dc:'One Summer Street',note:tr('cities.universities_biotech_and_a_carrier')}, + {id:'hou',name:'Houston',x:0,y:0,land:'am',reg:'AM',cc:'US',P:450,ix:'Rodeo-IX',dc:'Hurricane-hardened DC',note:tr('cities.oil_gas_and_hurricanes_the')}, + {id:'slc',name:'Salt Lake City',x:0,y:0,land:'am',reg:'AM',cc:'US',P:150,ix:'Fry-Sauce-IX',dc:'Great Salt Lake DC',note:tr('cities.cheap_power_dry_air_and_a')}, + {id:'man',name:'Manchester',x:0,y:0,land:'uk',reg:'EU',cc:'GB',P:350,ix:'Rainy-City-IX',dc:'Old Cotton Mill Colo',note:tr('cities.the_north_s_hub_with_its')}, + {id:'edi',name:'Edinburgh',x:0,y:0,land:'uk',reg:'EU',cc:'GB',P:200,ix:'Haggis-IX',dc:'Castle Rock Colo',note:tr('cities.scotland_s_capital_north_sea_cables')}, + {id:'bde',name:'Bude',x:0,y:0,land:'uk',reg:'EU',cc:'GB',P:3,ix:'',dc:'Clifftop Landing Station',note:tr('cities.a_tiny_surfing_town_in_cornwall')}, + {id:'svg',name:'Stavanger',x:0,y:0,land:'eu',reg:'EU',cc:'NO',P:60,ix:'Brunost-IX',dc:'Inside-a-Mountain DC',note:tr('cities.norway_s_oil_capital_now_full')}, // The Caribbean (#125) {id:'sju',name:'San Juan',x:0,y:0,land:'pr',reg:'AM',cc:'PR',P:120,ix:'Mofongo-IX',dc:'El Morro Colo',note:tr('cities.puerto_rico_s_capital_where_a')}, {id:'sdq',name:'Santo Domingo',x:0,y:0,land:'hs',reg:'AM',cc:'DO',P:150,ix:'',dc:'Merengue Racks',note:tr('cities.the_dominican_republic_s_capital_the')}, @@ -224,22 +224,22 @@ const CITIES=[ {id:'brw',name:'Utqiaġvik',x:0,y:0,land:'nsl',reg:'AM',cc:'US',P:0.5,blackout:true,ix:'',dc:'Top of the World Colo',note:tr('cities.the_northernmost_town_in_the_united')}, {id:'dut',name:'Unalaska',x:0,y:0,land:'al',reg:'AM',cc:'US',P:0.5,ix:'',dc:'Deadliest Catch DC',note:tr('cities.the_aleutians_fishing_capital')}, {id:'prr',name:'Prince Rupert',x:0,y:0,land:'am',reg:'AM',cc:'CA',ca:true,P:1.5,ix:'',dc:'Rain Gauge Racks',note:tr('cities.a_pacific_port_in_northern_british')}, - {id:'mmk',name:'Murmansk',x:0,y:0,land:'eu',reg:'EU',P:25,ru:true,beach:true,arpu:0.5,ix:'',dc:'Polar Night DC',note:tr('cities.the_biggest_city_north_of_the')}, - {id:'dks',name:'Dikson',x:0,y:0,land:'tay',reg:'AS',P:0.1,ru:true,beach:true,arpu:0.5,blackout:true,ix:'',dc:'Last Weather Station Rack',note:tr('cities.a_weather_station_and_a_port')}, - {id:'tik',name:'Tiksi',x:0,y:0,land:'lap',reg:'AS',P:0.5,ru:true,beach:true,arpu:0.5,blackout:true,ix:'',dc:'Permafrost Colo',note:tr('cities.a_port_on_the_laptev_sea')}, - {id:'pvs',name:'Pevek',x:0,y:0,land:'pvk',reg:'AS',P:0.5,ru:true,beach:true,arpu:0.5,ix:'',dc:'Floating Reactor Rack',note:tr('cities.russia_s_northernmost_town_powered_by')}, - {id:'dyr',name:'Anadyr',x:0,y:0,land:'chu',reg:'AS',P:1.3,ru:true,arpu:0.5,ix:'',dc:'Date Line Colo',note:tr('cities.chukotka_s_capital_closer_to_alaska')}, - {id:'pkc',name:'Petropavlovsk',x:0,y:0,land:'kam',reg:'AS',P:16,ru:true,arpu:0.5,ix:'',dc:'Volcano Row DC',note:tr('cities.kamchatka_s_capital_ringed_by_volcanoes')}, - {id:'gdx',name:'Magadan',x:0,y:0,land:'eu',reg:'AS',P:9,ru:true,arpu:0.5,ix:'',dc:'Kolyma Highway Colo',note:tr('cities.once_the_gateway_to_the_kolyma')}, - {id:'uus',name:'Yuzhno-Sakhalinsk',x:0,y:0,land:'sak',reg:'AS',P:18,ru:true,arpu:0.5,ix:'',dc:'Oil Platform Racks',note:tr('cities.sakhalin_s_capital_on_an_island')}, - {id:'vvo',name:'Vladivostok',x:0,y:0,land:'eu',reg:'AS',P:60,ru:true,arpu:0.5,ix:'Ikra-IX',dc:'Golden Horn Colo',note:tr('cities.the_end_of_the_trans_siberian')}, + {id:'mmk',name:'Murmansk',x:0,y:0,land:'eu',reg:'EU',cc:'RU',P:25,ru:true,beach:true,arpu:0.5,ix:'',dc:'Polar Night DC',note:tr('cities.the_biggest_city_north_of_the')}, + {id:'dks',name:'Dikson',x:0,y:0,land:'tay',reg:'AS',cc:'RU',P:0.1,ru:true,beach:true,arpu:0.5,blackout:true,ix:'',dc:'Last Weather Station Rack',note:tr('cities.a_weather_station_and_a_port')}, + {id:'tik',name:'Tiksi',x:0,y:0,land:'lap',reg:'AS',cc:'RU',P:0.5,ru:true,beach:true,arpu:0.5,blackout:true,ix:'',dc:'Permafrost Colo',note:tr('cities.a_port_on_the_laptev_sea')}, + {id:'pvs',name:'Pevek',x:0,y:0,land:'pvk',reg:'AS',cc:'RU',P:0.5,ru:true,beach:true,arpu:0.5,ix:'',dc:'Floating Reactor Rack',note:tr('cities.russia_s_northernmost_town_powered_by')}, + {id:'dyr',name:'Anadyr',x:0,y:0,land:'chu',reg:'AS',cc:'RU',P:1.3,ru:true,arpu:0.5,ix:'',dc:'Date Line Colo',note:tr('cities.chukotka_s_capital_closer_to_alaska')}, + {id:'pkc',name:'Petropavlovsk',x:0,y:0,land:'kam',reg:'AS',cc:'RU',P:16,ru:true,arpu:0.5,ix:'',dc:'Volcano Row DC',note:tr('cities.kamchatka_s_capital_ringed_by_volcanoes')}, + {id:'gdx',name:'Magadan',x:0,y:0,land:'eu',reg:'AS',cc:'RU',P:9,ru:true,arpu:0.5,ix:'',dc:'Kolyma Highway Colo',note:tr('cities.once_the_gateway_to_the_kolyma')}, + {id:'uus',name:'Yuzhno-Sakhalinsk',x:0,y:0,land:'sak',reg:'AS',cc:'RU',P:18,ru:true,arpu:0.5,ix:'',dc:'Oil Platform Racks',note:tr('cities.sakhalin_s_capital_on_an_island')}, + {id:'vvo',name:'Vladivostok',x:0,y:0,land:'eu',reg:'AS',cc:'RU',P:60,ru:true,arpu:0.5,ix:'Ikra-IX',dc:'Golden Horn Colo',note:tr('cities.the_end_of_the_trans_siberian')}, // More landings around the North Sea and the Baltic, the Gulf of Oman, the Maldives and Kyushu {id:'krs',name:'Kristiansand',x:0,y:0,land:'eu',reg:'EU',cc:'NO',P:12,ix:'',dc:'Skagerrak Shore DC',note:tr('cities.norway_s_southern_tip_where_cables')}, {id:'ebj',name:'Esbjerg',x:0,y:0,land:'eu',reg:'EU',cc:'DK',P:12,ix:'',dc:'Wind Farm Racks',note:tr('cities.denmark_s_west_coast_where_the')}, {id:'rix',name:'Riga',x:0,y:0,land:'eu',reg:'EU',cc:'LV',P:60,ix:'Black-Balsam-IX',dc:'Art Nouveau DC',note:tr('cities.latvia_s_capital_its_cables_to')}, {id:'mct',name:'Muscat',x:0,y:0,land:'eu',reg:'AS',cc:'OM',P:50,ix:'Halwa-IX',dc:'Frankincense Colo',note:tr('cities.oman_s_capital_just_outside_the')}, {id:'mle',name:'Malé',x:0,y:0,land:'mv',reg:'AS',cc:'MV',P:4,ix:'',dc:'One-Metre-Up DC',note:tr('cities.the_maldives_capital_a_stop_on')}, - {id:'fuk',name:'Fukuoka',x:0,y:0,land:'jp',reg:'AS',P:120,ix:'Mentaiko-IX',dc:'Hakata Ramen Racks',note:tr('cities.japan_s_closest_city_to_korea')}, + {id:'fuk',name:'Fukuoka',x:0,y:0,land:'jp',reg:'AS',cc:'JP',P:120,ix:'Mentaiko-IX',dc:'Hakata Ramen Racks',note:tr('cities.japan_s_closest_city_to_korea')}, ]; // Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat. const CITY_NUDGE={ diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index cc3829f..e98bdaa 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -10,7 +10,8 @@ function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TR const netMult=(n,c)=>regionMult(c)*((n&&n.far&&CITY[c]&&n.far[CITY[c].reg])||1); 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; +// Every city has a country (cc), but the border toll is Africa's: elsewhere a wave crosses borders at the plain price. +const borderPair=(a,b)=>CITY[a].reg==='AF'&&CITY[b].reg==='AF'&&CITY[a].cc!==CITY[b].cc; // Perth to the east coast: the sea route round the south coast is domestic (AU_WAVE.ew), and the Nullarbor // fiber costs a little more again because the incumbents own it. const NULLARBOR=1.7,nullPair=(a,b)=>!!CITY[a].au&&!!CITY[b].au&&(a==='per')!==(b==='per'); From 2873ee3435ea24aff1a6015caeb3b323ce360f57 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:14:51 +0100 Subject: [PATCH 030/181] 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 031/181] 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 032/181] 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 033/181] 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 034/181] 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 035/181] 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 036/181] 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 037/181] 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 038/181] =?UTF-8?q?Only=20Sp=C3=A4tzle-IX=20asks=20for=205?= =?UTF-8?q?0%=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 039/181] 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 040/181] 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 041/181] 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 042/181] 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 043/181] 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 044/181] 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 045/181] 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 046/181] 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 047/181] 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 048/181] 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 6d839102b51c99a785c7727b3cfe9025a45273f3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 19:58:25 +0100 Subject: [PATCH 049/181] Pinned attack flows route at their entry port's own rank, not a cone rank base() now takes the target network; pinned junk has none, so coneOf() called every PNI a cone route and the flood was routed late (behind real traffic) or not at all. Pinned flows use the port's own rank (low preference still last), those ranks join RSET, and the reference allocation in the routing test does the same. --- src/game/80-simulation/30-compute.js | 7 ++++--- tests/ddos-floods.test.js | 17 +++++++++++++++++ tests/helpers/reference-allocation.js | 2 +- 3 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 tests/ddos-floods.test.js diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 568b6f6..f02c48a 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -174,8 +174,9 @@ function compute(){ 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],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)); + // Attack flows pinned to their entry port route at the port's own rank: no network to be in a cone of, and RouteScript + // may have left that rank with no list. + const pr=e=>e.pref==='low'?4:e.rank;for(const f of flows)if(f.pin)for(const e of ingressE[f.pin]||[])RSET.add(pr(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. @@ -224,7 +225,7 @@ function compute(){ for(let fi=0,FN=flows.length;fi { + for (const net of ['nfx', 'lvl']) { + 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=5000;S.pops.fra.rgen=RG.length-1;S.pops.fra.routers=8"); + ev(`S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pa',net:'${net}',city:'fra',tier:1}];compute()`); + assert.equal(ev(`R.netEg.${net}.p`), 100, 'the 100G PNI is full of real traffic'); + ev("S.ev.ddos={id:'x',city:'fra',vec:'http',gbps:100,start:S.day,until:S.day+5,entries:[{k:'p',id:'pa',city:'fra',share:1}]};compute()"); + assert.equal(ev('R.usePni.pa'), 100); + assert.ok(!(ev(`R.netEg.${net}?.p||0`) > 1), `${net}: the junk is not routed behind the real traffic as if it were a cone route`); + assert.deepEqual(errors, []); + } +}); diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index 4658ced..00da767 100644 --- a/tests/helpers/reference-allocation.js +++ b/tests/helpers/reference-allocation.js @@ -6,7 +6,7 @@ module.exports = ` 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.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 Date: Wed, 28 Oct 2026 20:01:58 +0100 Subject: [PATCH 050/181] 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 051/181] 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 052/181] 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 053/181] 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 675c63d561c1b2f5dade1a51e823e0e4867da184 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:09:18 +0100 Subject: [PATCH 054/181] Floods cross the backbone to their victim again, whatever order the POPs were built in Each ingress slice gave its junk the ingress city as source, so a flood only filled the port it came in on: it never loaded the backbone or the victim's router, as it did before distributed ingress. Junk is now created at the victim, pinned to its entry port, before any real traffic and in attack order, so S.pops order no longer decides who gets a full port. A port the victim cannot reach still fills. --- src/game/80-simulation/30-compute.js | 21 +++++++++++++-------- tests/ddos-floods.test.js | 23 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index f02c48a..ccdfa59 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -52,7 +52,17 @@ function compute(){ // 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'),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); + 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=[]; + /* Floods first, before any real traffic and in the order the attacks started, so no POP's place in S.pops decides who + gets a full port. Each slice is the flood entering in one city (mitigated and scrubbed there); what leaks is junk at + the victim, pinned to the port it came in on, so it loads that port, the backbone between them and the victim's router. */ + // A port the victim cannot be reached from (down, or no backbone to it) still fills with the junk arriving there. + const VIC={};for(const a of ddosAll()){const v=a.city;(VIC[v]||(VIC[v]=[])).push(a); + for(const part of ddosSlices(a)){const c=part.city;(atkBy[c]||(atkBy[c]=[])).push(part); + const m=ddosMitigation(part,{},bhCities.has(v),false),group={m,flows:[]};R2.ddos.push(m);junkGroups.push(group);if(!popUp(c))m.offline=true; + const src=popUp(v)&&SPD[v][CIDX[c]]0?q.g/m.leak:0});}} + else for(let j=0;jday?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 @@ -64,13 +74,8 @@ function compute(){ // A shaped attack: `rtbh` is the player pulling the plug on the victim IP (junk gone, customer dark too); // `edge` is the crude RouteScript `blackhole ddos` filter (junk gone, 10% of real traffic with it). Flowspec // (a standing licence) and a scrubbing center each knock the flood down before it reaches the sim. - const attacks=atkBy[c]||[],rtbh=bhCities.has(c),edge=!!(attacks.length&&TRX&&TRX.blackhole&&!rtbh); - let dd=0; - 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 attacks=VIC[c]||[],rtbh=bhCities.has(c),edge=!!(attacks.length&&TRX&&TRX.blackhole&&!rtbh); + if(!popUp(c))continue; const bh=rtbh||edge; if(edge)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d*0.1;if(rtbh)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d; R2.cityBlocked=R2.cityBlocked||{}; diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index 7b6adad..3c26cce 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -15,3 +15,26 @@ test('a flood entering over a PNI with NetChill competes on that PNI at its own assert.deepEqual(errors, []); } }); + +// Frankfurt has the eyeballs and no transit; all transit is in Amsterdam, 100G of wave away. +const remoteIngress = (ev, flip) => { + ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'ams'});ACT.launchBB({city:'fra'});S.links.push({id:'L',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:0});ACT.buyTransit({city:'ams',net:NETS.find(n=>sellsAt(n,'ams')).id,tier:1})"); + if (flip) ev("const p=S.pops;S.pops={ams:p.ams,fra:p.fra}"); + ev("compute()"); +}; + +test('a flood entering in another city crosses the backbone to its victim, whatever order the POPs were built in', () => { + const out = []; + for (const flip of [false, true]) { + const { ev, errors } = load({ seed: 5 }); + remoteIngress(ev, flip); + assert.ok(ev("sfOf(R,'fra')") > 0.95, 'fine before the attack'); + ev("S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'http',gbps:300,start:S.day,until:S.day+3,entry:{k:'distributed',lab:''},entries:[{k:'t',id:S.transit[0].id,city:'ams',share:1}]};compute()"); + assert.equal(ev('R.load.L'), 100, 'the junk fills the wave to the victim'); + assert.ok(ev("R.nodeLoad.fra") >= 100, "and the victim's router"); + assert.ok(ev("sfOf(R,'fra')") < 0.05, 'the victim goes dark'); + out.push(ev("JSON.stringify([R.load.L,R.useT[S.transit[0].id],sfOf(R,'fra')])")); + assert.deepEqual(errors, []); + } + assert.equal(out[0], out[1], 'POP build order does not change the outcome'); +}); From 25e3e6db3326d09a7bed3b945e6ce44a2dfc24e1 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:11:06 +0100 Subject: [PATCH 055/181] DDoS attacks are scored and SLA-charged at their victim only ddosSf() took the worst service of every city with an ingress port, so on a big network every attack counted as lost and charged SLA payouts to protected customers anywhere. Held/lost, the SLA check and the far-scrubbing warning now look at the attacked city. --- .../85-incidents/10-incidents-and-ddos.js | 5 +++-- src/game/88-days/10-day-tick.js | 2 +- tests/ddos-floods.test.js | 21 +++++++++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js index ec67168..521026e 100644 --- a/src/game/85-incidents/10-incidents-and-ddos.js +++ b/src/game/85-incidents/10-incidents-and-ddos.js @@ -37,7 +37,8 @@ function ddosSlices(a){if(!a.entries?.length)return [a];const groups={}; 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))); +// An attack is held or lost at its victim: the junk lands there, and other POPs' bad days are not the attacker's doing. +const ddosSf=a=>sfOf(R,a.city); 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)};} @@ -53,7 +54,7 @@ const fsAt=c=>{const p=S.pops[c];return p?(RG[p.rgen||0].fs||0):0;}; 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=>ddosAll().some(a=>ddosCities(a).includes(c))&&(R.haul||[]).find(q=>q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS)||null; +const scrubFar=c=>{for(const a of ddosAll())if(a.city===c){const q=(R.haul||[]).find(q=>q.attack===a.id&&q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS);if(q)return q;}return 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;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 2630903..3aab042 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -36,7 +36,7 @@ function dayTick(){ if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+leadDays(extra));toast(tr('day_tick.construction_delay_n_days_why_a',{n:leadDays(extra),why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('day_tick.archaeologists_found_a_roman'),tr('day_tick.a_protected_hamster_species_lives'),tr('day_tick.the_railway_changed_its_mind_about'),tr('day_tick.the_drilling_crew_hit_a_granite'),tr('day_tick.a_town_council_wants_a_public'),tr('day_tick.somebody_else_s_gas_main_was'),tr('day_tick.the_permit_office_lost_your_permit')]),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). 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){ + for(const b of S.biz)if(b.type==='scrub'&&b.city===a.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('day_tick.sla_breach_name_the_attack_on',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} // businesses mood diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index 3c26cce..fc43217 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -38,3 +38,24 @@ test('a flood entering in another city crosses the backbone to its victim, whate } assert.equal(out[0], out[1], 'POP build order does not change the outcome'); }); + +test('an attack is held or lost at its victim; other POPs and their DDoS-protected customers are not charged', () => { + const { ev, errors } = load({ seed: 5 }); + ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].bb={d:50};S.pops[c].rgen=3}"); + ev("S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:1}];S.scrubMode='always'"); + // New York is struggling on its own (a 10G port for 50G of eyeballs), and has a DDoS-protected customer. + ev("S.pops.nyc.bb.d=200;S.biz.push({id:'sc',type:'scrub',name:'Shield',city:'nyc',bw:1,rate:1000,mood:80,since:0})"); + ev("S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'http',gbps:20,start:S.day,until:S.day+3,entry:{k:'distributed',lab:''},entries:[{k:'t',id:'tf',city:'fra',share:.5},{k:'t',id:'tn',city:'nyc',share:.5}]};compute()"); + assert.ok(ev("sfOf(R,'nyc')") < 0.85, 'New York is under water anyway'); + assert.ok(ev("sfOf(R,'fra')") >= 0.97, 'the victim is fine'); + assert.equal(ev('ddosSf(S.ev.ddos)'), ev("sfOf(R,'fra')")); + const cash = ev('S.cash'); + ev('dayTick()'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ev.ddos.sla||[])')), [], 'no SLA payout for a customer in another city'); + assert.equal(ev('S.stats.sla||0'), 0); + ev('S.day=S.ev.ddos.until;ddosExpire()'); + assert.equal(ev('S.stats.ddosOk||0'), 1, 'held at the victim'); + assert.equal(ev('S.stats.ddosLost||0'), 0); + assert.ok(cash > 0); + 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 056/181] 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 40e4c79139420978c81796d5d6bed0a2ccc5c151 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:16:20 +0100 Subject: [PATCH 057/181] Attacks keep their 12 biggest ingress ports and fold the rest, so saves stay small Every attack stored every ingress port with traffic (over a thousand on a big network), which grew the save from 272 KB to 1.8 MB with 14 attacks. The rest is now one share at the victim, routed like the classic flood over its usual exits; old saves are folded on load. --- src/game/80-simulation/30-compute.js | 3 ++- src/game/80-simulation/50-sanitize.js | 2 +- .../85-incidents/10-incidents-and-ddos.js | 5 ++++ src/game/85-incidents/20-failures.js | 4 +-- tests/ddos-floods.test.js | 25 +++++++++++++++++++ 5 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index ccdfa59..09cd6ce 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -61,7 +61,8 @@ function compute(){ for(const part of ddosSlices(a)){const c=part.city;(atkBy[c]||(atkBy[c]=[])).push(part); const m=ddosMitigation(part,{},bhCities.has(v),false),group={m,flows:[]};R2.ddos.push(m);junkGroups.push(group);if(!popUp(c))m.offline=true; const src=popUp(v)&&SPD[v][CIDX[c]]0?q.g/m.leak:0});}} + if(part.entries?.length){for(const q of m.ingress){const sh=m.leak>0?q.g/m.leak:0;if(q.entry.k==='rest'){for(let j=0;jday?1.4:1);const biz=bizBw[c]??0;const d0=eye+biz; diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 5673200..0222376 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -66,7 +66,7 @@ function sanitize(s){ // 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; + if(Array.isArray(a.entries)){a.entries=a.entries.slice(0,3000).filter(en=>en&&isCity(en.city)&&Number.isFinite(+en.share)&&+en.share>0&&(en.k==='rest'||['t','ix','p'].includes(en.k)&&typeof en.id==='string')).map(en=>en.k==='rest'?{k:'rest',city:en.city,share:+en.share}:{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;a.entries=ddosFold(a.entries,a.city);}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); diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js index 521026e..f1e9df7 100644 --- a/src/game/85-incidents/10-incidents-and-ddos.js +++ b/src/game/85-incidents/10-incidents-and-ddos.js @@ -32,6 +32,11 @@ function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);S.ev.ddos=left 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})):[];} +// A save keeps the biggest ingress ports by name; the long tail is one share (k:'rest') that arrives over the victim's +// usual exits, so a big network's attacks do not each carry hundreds of ports. +const DDOS_KEEP=12; +function ddosFold(entries,city){const L=entries.slice().sort((a,b)=>b.share-a.share);if(L.length<=DDOS_KEEP+1)return L; + const top=L.slice(0,DDOS_KEEP),rest=L.slice(DDOS_KEEP).reduce((n,en)=>n+en.share,0);if(rest>0)top.push({k:'rest',city,share:rest});return top;} 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)}));} diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index 49ea71a..3057019 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -146,10 +146,10 @@ function ddosAttack(recompute=true){const type='ddos',fl=scnRule('ddos');ddosExp 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('common.distributed_ingress')}:entries[0]||entry,entries,bh:false,start:S.day}; + const ports=ddosEntries(),entries=ddosFold(ports,c),a={id:uid(),city:c,vec,gbps,until:S.day+dur,entry:entries.length>1?{k:'distributed',lab:tr('common.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=entries.length>1?tr('failures.across_n_transit_and_peering_ports',{n:entries.length}):entry&&entry.lab?tr('failures.in_via_e',{e:entry.lab}):''; + const how=ports.length>1?tr('failures.across_n_transit_and_peering_ports',{n:ports.length}):entry&&entry.lab?tr('failures.in_via_e',{e:entry.lab}):''; const msg=tr('failures.a_size_vec_attack_is_hitting',{size:fmtG(gbps),vec:V.n,city:CITY[c].name,how})+' '+(soaked?tr('failures.your_mitigation_is_eating_most_of'):tr('failures.junk_traffic_is_eating_your_capacity')); if(fl)a.who=pick(FLOOD_WHO); addInc({type,ref:c,atk:a.id,until:S.day+dur,msg:fl?msg+' '+tr('failures.attacker_who',{who:tr(a.who)}):msg,cost:0}); diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index fc43217..f11eb02 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -59,3 +59,28 @@ test('an attack is held or lost at its victim; other POPs and their DDoS-protect assert.ok(cash > 0); assert.deepEqual(errors, []); }); + +test('an attack keeps its biggest ingress ports and folds the long tail, so saves stay small', () => { + const { ev, errors } = load({ seed: 5 }); + ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['fra','ams','lon','par'])if(!S.pops[c])ACT.buildPop({city:c});for(const c in S.pops){S.pops[c].bb={d:100};S.pops[c].rgen=3}"); + ev("S.transit=[];const nets=NETS.filter(n=>n.type!=='t1').slice(0,40);for(const c in S.pops)for(const n of nets.slice(0,8))S.pni.push({id:n.id+'@'+c,net:n.id,city:c,tier:1});compute()"); + ev("S.day=60;S.ddosStarts=[];ddosAttack()"); + const ports = ev('ddosEntries().length'); + assert.ok(ports > 20, `many ports carry traffic (${ports})`); + const en = JSON.parse(ev('JSON.stringify(S.ev.ddos.entries)')); + assert.equal(en.length, 13, 'twelve named ports and one remainder'); + assert.equal(en.at(-1).k, 'rest'); + assert.equal(en.at(-1).city, ev('S.ev.ddos.city')); + assert.ok(Math.abs(en.reduce((n, x) => n + x.share, 0) - 1) < 1e-9); + assert.match(ev("S.inc.at(-1).msg"), new RegExp(`across ${ports} transit and peering ports`), 'the message still counts every port'); + // The remainder is routed like the rest of the flood, and survives a save. + ev('compute()'); + assert.ok(Math.abs(ev('R.ddos.reduce((n,m)=>n+m.reaching,0)') - ev('S.ev.ddos.gbps')) < 1e-6); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('S.ev.ddos.entries.length'), 13); + // An old save with every port is folded on load. + ev("S.ev.ddos.entries=Array.from({length:300},(_,i)=>({k:'p',id:'x'+i,city:'fra',lab:'',share:1}));S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.ev.ddos.entries.length'), 13); + assert.equal(ev("S.ev.ddos.entries.find(e=>e.k==='rest').share.toFixed(4)"), (288/300).toFixed(4)); + 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 058/181] 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 059/181] 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 060/181] 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 e80fd0e453bb0f521bc549f0c4865756697b0ca9 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:19:41 +0100 Subject: [PATCH 061/181] Spicy chaos stretches exactly what an incident holds down stretchInc() stretched anything ending on the same day: always the primary attack (even when the incident was about another one, never the overlapping ones) and any unrelated outage that happened to end then. It now finds the attack by i.atk and everything else by the incident's ref, as clearInc() does, and saves allow the longest stretched attack (11 days). --- src/game/40-progress/30-rules.js | 22 ++++++++++++++-------- src/game/80-simulation/50-sanitize.js | 2 +- tests/ddos-floods.test.js | 22 ++++++++++++++++++++++ 3 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/game/40-progress/30-rules.js b/src/game/40-progress/30-rules.js index 928a462..c61421b 100644 --- a/src/game/40-progress/30-rules.js +++ b/src/game/40-progress/30-rules.js @@ -31,12 +31,18 @@ function makeRules(preset,o){const p=Object.prototype.hasOwnProperty.call(PRESET // What the HUD and the share card say about the rules. On-call says nothing: it is the game. function ruleTag(){const p=rulePreset();if(S&&S.mode==='sandbox'){const c=CHAOS[rule('chaos')];return tr('common.sandbox')+(c&&rule('chaos')!=='none'?' '+c.i:'');} return p==='oncall'||p==='sandbox'?'':PRESETS[p].i+' '+PRESETS[p].n;} -/* Spicy outages last longer: stretch a fresh incident, and whatever it holds down until the same day, by half. */ +/* Spicy outages last longer: stretch a fresh incident by half, and exactly what it holds down (found by its ref, as + clearInc() finds it), never something else that happens to end the same day. */ function stretchInc(i){if(rule('chaos')!=='spicy'||!i||!(i.until>S.day)||i.start!==S.day)return;const U=i.until,V=S.day+Math.ceil((U-S.day)*SPICY_LONG);if(V===U)return;i.until=V; - const f=(o,k)=>{if(o&&o[k]===U)o[k]=V;},E=S.ev; - for(const l of S.links){f(l,'cut');f(l,'eqDown');f(l,'deg');f(l.loss,'until');f(l.chFail,'until');} - for(const c in S.pops){const p=S.pops[c];f(p,'down');f(p,'ringcut');f(p,'hot');} - for(const t of S.transit){f(t,'down');f(t.lacp,'until');}for(const p of S.pni)f(p.lacp,'until'); - for(const k of ['ixdown','fab'])if(E[k])for(const x in E[k])if(E[k][x]===U)E[k][x]=V; - if(E.ixlacp)for(const x in E.ixlacp)f(E.ixlacp[x],'until'); - for(const k of ['leak','rpki','pmtud','ddos'])f(E[k],'until');} + const f=(o,k)=>{if(o&&o[k]===U)o[k]=V;},E=S.ev,T=i.type,r=i.ref,L=()=>S.links.find(l=>l.id===r); + if(T==='cut'||T==='redsea'){for(const l of S.links)if((l.trench||l.id)===r)f(l,'cut');} + else if(T==='fatwave'||T==='label')f(L(),'cut'); + else if(T==='ctrlplane'){for(const id of Array.isArray(i.links)?i.links:[])f(S.links.find(l=>l.id===id),'cut');} + else if(T==='amp'||T==='roadmff')f(L(),'eqDown');else if(T==='mtu')f(L(),'deg');else if(T==='loss')f(L()?.loss,'until');else if(T==='optic')f(L()?.chFail,'until'); + else if(['crash','power','oops','cleaner','maint','shutdown'].includes(T))f(S.pops[r],'down'); + else if(T==='ring')f(S.pops[r],'ringcut');else if(T==='ac')f(S.pops[r],'hot'); + else if(T==='transit'||T==='prepend')f(S.transit.find(t=>t.id===r),'down'); + else if((T==='ixloop'||T==='maxpfx')&&E.ixdown)f(E.ixdown,r);else if(T==='fabric'&&E.fab)f(E.fab,r); + else if(T==='lacp'){const [k,...x]=String(r).split(':'),id=x.join(':');f(k==='ix'?E.ixlacp&&E.ixlacp[id]:(k==='t'?S.transit:S.pni).find(o=>o.id===id)?.lacp,'until');} + else if(T==='rpki'||T==='hijack')f(E.rpki,'until');else if(T==='leak'||T==='pmtud')f(E[T],'until');else if(T==='krroute'||T==='depeer')f(E,T); + else if(T==='ddos')f(ddosAll(S,false).find(a=>a.id===i.atk),'until');} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 0222376..48c6e55 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -65,7 +65,7 @@ function sanitize(s){ s.scrubMode=s.scrubMode==='ondemand'?'ondemand':'always'; // 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); + 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+Math.ceil(7*SPICY_LONG)); if(Array.isArray(a.entries)){a.entries=a.entries.slice(0,3000).filter(en=>en&&isCity(en.city)&&Number.isFinite(+en.share)&&+en.share>0&&(en.k==='rest'||['t','ix','p'].includes(en.k)&&typeof en.id==='string')).map(en=>en.k==='rest'?{k:'rest',city:en.city,share:+en.share}:{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;a.entries=ddosFold(a.entries,a.city);}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;}; diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index f11eb02..33bc30a 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -84,3 +84,25 @@ test('an attack keeps its biggest ingress ports and folds the long tail, so save assert.equal(ev("S.ev.ddos.entries.find(e=>e.k==='rest').share.toFixed(4)"), (288/300).toFixed(4)); assert.deepEqual(errors, []); }); + +test('spicy chaos stretches exactly the attack (or outage) an incident is about, and saves keep it', () => { + const { ev, errors } = load({ seed: 99 }); + ev("beginGame('R','fra',{mode:'normal',preset:'bgp'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});S.links.push({id:'L',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:0});S.day=50"); + // A link that happens to be cut until the same day as the next attacks must stay as it is. + ev("S.links[0].cut=S.day+2"); + for (let k = 0; k < 4; k++) ev("const old=Math.random;let n=0;Math.random=()=>n++===3?0:old();ddosAttack();Math.random=old"); + const rows = JSON.parse(ev("JSON.stringify(S.inc.filter(i=>i.type==='ddos').map(i=>[i.until,ddosAll(S,false).find(a=>a.id===i.atk).until]))")); + assert.equal(rows.length, 4); + for (const [inc, atk] of rows) { assert.equal(atk, inc, 'the attack lasts as long as its incident'); assert.equal(inc, 52, 'one day, stretched by half'); } + assert.equal(ev('S.links[0].cut'), 52, 'an unrelated cut ending the same day is not stretched'); + // The longest spicy attack (7 days, stretched to 11) survives a reload. + ev("S.ev.ddos.until=S.day+11;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.ev.ddos.until-S.day'), 11); + ev("S.ev.ddos.until=S.day+40;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.ev.ddos.until-S.ev.ddos.start'), 11, 'but not longer'); + // Outages are found by their ref: a fiber cut stretches its own link only. + ev("S.links.push({id:'M',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:S.day+4});S.links[0].cut=S.day+4;S.links[0].trench='T';addInc({type:'cut',ref:'T',until:S.day+4,msg:'x'})"); + assert.equal(ev("S.links[0].cut-S.day"), 6); + assert.equal(ev("S.links.find(l=>l.id==='M').cut-S.day"), 4); + assert.deepEqual(errors, []); +}); From 23634241c028605c75154d499437578b7467e1c3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:19:48 +0100 Subject: [PATCH 062/181] 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 063/181] 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 b5cba3e59168824411eebe0fe789ac0064efafe4 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:23:44 +0100 Subject: [PATCH 064/181] BGP at 3 a.m. brings twice On-call's DDoS, as it says, not twenty times Spicy chaos moved attacks onto the gamers' daily schedule without scaling it, so the preset had about 20x the attacks of On-call. Without gaming customers, attacks stay on the failure schedule (which spicy already runs 1.8x as often, with a slightly heavier DDoS weight to make it 2x); gaming customers still bring their busier one. --- src/game/85-incidents/20-failures.js | 10 ++++++---- tests/ddos-floods.test.js | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index 3057019..404b912 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -7,9 +7,10 @@ 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]); - // Flood Season brings its own; Change Freeze (calm) has none. Spicy chaos or gaming customers put DDoS on its own, - // busier schedule (ddosTick) instead of this one, so it is never counted twice. - if(S.day>40&&!scnRule('ddos')&&!ddosOff()&&!ddosSpicy())opts.push(['ddos',2]); + // Flood Season brings its own; Change Freeze (calm) has none. Gaming customers put DDoS on its own, busier schedule + // (ddosTick) instead of this one, so it is never counted twice. Spicy failures already come 1.8x as often; a slightly + // heavier weight makes that twice On-call's DDoS, as BGP at 3 a.m. promises. + if(S.day>40&&!scnRule('ddos')&&!ddosOff()&&!gamingCount())opts.push(['ddos',rule('chaos')==='spicy'?2.25:2]); 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]); @@ -134,12 +135,13 @@ function ddosSize(vec){const fl=scnRule('ddos'),r=Math.random(),roll=fl?1/3+r*2/ // Calm (Change Freeze) and no chaos at all mean no attacks, gamers or not. const ddosOff=()=>{const c=rule('chaos');return c==='calm'||c==='none';}; // More frequent attacks are opt-in: the spicy chaos setting, or hosting gamers (who attract them in real life). +// Outside Flood Season, only gamers move attacks onto ddosTick's daily schedule; spicy alone doubles the usual one. const ddosSpicy=()=>!ddosOff()&&(rule('chaos')==='spicy'||gamingCount()>0); function ddosTick(){if(ddosOff()&&!scnRule('ddos'))return;if(scnRule('ddos')){let next=+S.scn.nextDdos||3,n=0; // Unless spicy, floods take turns as they always did: the next one waits until the last is over. if(!ddosSpicy()&&ddosAll().length)return; 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); diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index 33bc30a..29d1e4b 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -106,3 +106,20 @@ test('spicy chaos stretches exactly the attack (or outage) an incident is about, assert.equal(ev("S.links.find(l=>l.id==='M').cut-S.day"), 4); assert.deepEqual(errors, []); }); + +test('BGP at 3 a.m. brings about twice On-call\'s DDoS; gaming customers bring their own, busier schedule', () => { + const picks = {}; + for (const preset of ['oncall', 'bgp']) { + const { ev, errors } = load({ seed: 7 }); + ev(`beginGame('R','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.day=100;compute()`); + // No daily attacks without gamers, spicy or not. + ev("window.__n=0;const real=ddosAttack;ddosAttack=()=>{window.__n++;};for(let i=0;i<300;i++)ddosTick();window.__tick=window.__n;window.__n=0;for(let i=0;i<4000;i++)fireFailure();ddosAttack=real"); + assert.equal(ev('window.__tick'), 0, `${preset}: no daily DDoS schedule without gaming customers`); + picks[preset] = ev('window.__n') * ev('chaosMul()'); + ev("S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:1,rate:1,mood:80,since:0});window.__n=0;const real=ddosAttack;ddosAttack=()=>{window.__n++;};for(let i=0;i<300;i++)ddosTick();ddosAttack=real"); + assert.ok(ev('window.__n') > 5, `${preset}: gamers attract attacks on their own schedule`); + assert.deepEqual(errors, []); + } + const ratio = picks.bgp / picks.oncall; + assert.ok(ratio > 1.7 && ratio < 2.3, `about twice the DDoS (${ratio.toFixed(2)}x)`); +}); From e56659f9499337cea39a4eee2b337239564264ef Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:28:50 +0100 Subject: [PATCH 065/181] 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 066/181] 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 067/181] 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 068/181] 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 069/181] 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 94b27eadf3f2930ec6636c41e21f7293ba49997a Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:42:08 +0100 Subject: [PATCH 070/181] Billing: a recompute after the day tick no longer counts today's 95th-percentile sample twice dayTick() routes the day, then appends today's transit use to t.hist. Every compute() after that (any click, the intern, the sales trial) took the last 29 entries of t.hist, which now end on today, and added today's use again: today counted twice and the 30th day back dropped out. So compute() gave a different transit bill the second time after each day. p95() now leaves today's sample out once S.hist says the day has been recorded. This was the only part of compute() that was not a pure function of S. The rest of the drift round 1 saw (R right after dayTick vs. a fresh compute) is dayTick itself changing S after its compute (customers churning, events ending), which is intended: the next day routes the new state. Scenic circuits' hysteresis is documented, with a test that two calls converge. --- CHANGELOG.md | 1 + src/game/80-simulation/30-compute.js | 4 ++- src/game/80-simulation/40-billing.js | 5 +++- tests/compute-idempotent.test.js | 42 ++++++++++++++++++++++++++++ 4 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 tests/compute-idempotent.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a1b51b1..a94afc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. - 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/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 568b6f6..eebd431 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -93,6 +93,8 @@ function compute(){ const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),n:[],d:[]};EL.push(l);}t.g.set(eg,(t.g.get(eg)||0)+a); let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;}; R2.l2route={};R2.l2split={}; + /* compute() reads only S, except here: scenic circuits remember yesterday's path in R.l2route and R.efg (deliberate + hysteresis, so they do not flap). A second call can still move one; the third gives the same answer as the second. */ /* Scenic routing (#28). "Busy" is judged without the customer's own traffic, or it flees its own load and flips paths every day. Two paths that are about as quiet share the load, and yesterday's choice is kept unless today's is clearly better. */ @@ -280,7 +282,7 @@ function compute(){ 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); - C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0);R2.p95[t.id]=q;return a+transitMo(t,q);},0); + const htd=histToday();C.transit=S.transit.reduce((a,t)=>{const q=p95(t,R2.useT[t.id]||0,htd);R2.p95[t.id]=q;return a+transitMo(t,q);},0); C.ix=Object.keys(S.ixp).reduce((a,c)=>a+ixMo(c),0); C.pni=S.pni.reduce((a,p)=>a+pniMo(p,R2.usePni[p.id]||0),0); C.caches=S.caches.length*CACHE_MO; diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index d86b619..c46efa0 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -1,4 +1,7 @@ -function p95(t,cur){const h=(t.hist||[]).slice(-29).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} +// The last 29 days plus today. Once dayTick() has written today into t.hist (S.hist then ends on today too), that +// sample is today's own: leave it out, or every recompute later that day counts today twice and drops a day. +const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;}; +function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0);} function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);} function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);} diff --git a/tests/compute-idempotent.test.js b/tests/compute-idempotent.test.js new file mode 100644 index 0000000..4a2470f --- /dev/null +++ b/tests/compute-idempotent.test.js @@ -0,0 +1,42 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); + +const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); +const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.close()); + h.ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();`); return h; }; +// R as JSON; DDoS reports hold the live attack, whose `worst` dayTick updates, so it is named by id. +const rj = (ev) => ev("JSON.stringify(R,(k,v)=>k==='attack'||k==='parent'?(v&&v.id):v)"); + +test('95th percentile: a recompute later in the day bills the same 30 days as the day tick did', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'lvl',tier:1});closeModal()"); + // Thirty days on file, two of them huge: counting today twice (and dropping the oldest day left) would lose one. + ev("S.offers=[];const t=S.transit[0];t.hist=Array.from({length:30},(_,i)=>i===1||i===3?5000:1);S.nextFail=S.nextEvent=S.day+99;dayTick()"); + const tick = ev('R.p95[S.transit[0].id]'), cost = ev('R.cost.transit'); + assert.equal(tick, 5000, 'the tick bills the 29 days before today and today'); + ev('compute()'); + assert.equal(ev('R.p95[S.transit[0].id]'), tick); + assert.equal(ev('R.cost.transit'), cost); + assert.deepEqual(errors, []); +}); + +test('compute() is a pure function of the game: a second call right after a day changes nothing', (t) => { + const { ev, errors } = big(t); + for (let d = 0; d < 4; d++) { + ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick();compute()'); + const a = rj(ev); ev('compute()'); + assert.equal(rj(ev), a, `day ${d}`); + } + assert.deepEqual(errors, []); +}); + +test('scenic circuits keep the last path unless a new one is clearly better, so two calls converge', (t) => { + const { ev, errors } = big(t); + ev("for(const b of S.biz)if(BIZ_T[b.type].l2)b.route='scenic';R=emptyR();compute()"); + ev('compute()'); const b = rj(ev); + ev('compute()'); assert.equal(rj(ev), b); + assert.deepEqual(errors, []); +}); From 34b72f6d444aaed3e88d235fa3a31c698eb39e79 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:42:37 +0100 Subject: [PATCH 071/181] 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 072/181] 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 073/181] 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 074/181] 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 da8150b7c4489d4626257ced28a95b7b939329e4 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Wed, 28 Oct 2026 20:52:47 +0100 Subject: [PATCH 075/181] Save slots: several networks per browser, one per window, with a cross-window guard --- site/i18n/de.js | 47 +++++- site/i18n/es.js | 47 +++++- site/i18n/fr.js | 47 +++++- site/i18n/it.js | 47 +++++- site/i18n/pt.js | 47 +++++- src/game/60-features/20-scenarios.js | 2 +- src/game/60-features/92-puzzles.js | 10 +- src/game/90-actions/89-game-and-settings.js | 17 ++- src/game/90-actions/91-slots.js | 32 ++++ src/game/91-save.js | 62 ++++---- src/game/91-slots.js | 155 ++++++++++++++++++++ src/game/95-modals/40-title.js | 8 +- src/game/95-modals/45-slots.js | 37 +++++ src/game/95-modals/60-help.js | 2 +- src/game/96-map/95-clicks.js | 2 +- src/game/99-loop.js | 12 +- src/i18n/en.js | 47 +++++- src/styles/40-modal.css | 21 +++ src/styles/60-phone.css | 1 + tests/glowball-sakura-lager.test.js | 2 +- tests/i18n.test.js | 4 +- tests/issues.test.js | 6 +- tests/language-picker.test.js | 2 +- tests/new-game-speed.test.js | 2 +- tests/peering.test.js | 4 +- tests/persist.test.js | 10 +- tests/puzzles.test.js | 10 +- tests/regions.test.js | 8 +- tests/save-size.test.js | 28 ++-- 29 files changed, 595 insertions(+), 124 deletions(-) create mode 100644 src/game/90-actions/91-slots.js create mode 100644 src/game/91-slots.js create mode 100644 src/game/95-modals/45-slots.js diff --git a/site/i18n/de.js b/site/i18n/de.js index 83cfae7..8d08ed3 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1786,14 +1786,9 @@ "game_and_settings.import_a_save_from_a_file":"Spielstand importieren aus einer Datei", "game_and_settings.import_failed_that_save_is_damaged":"Import fehlgeschlagen.
Dieser Spielstand ist beschädigt und konnte nicht geladen werden. Dein aktuelles Spiel ist unberührt.", "game_and_settings.name_and_everything_it_owns_will":"{name} und alles, was dazugehört, wird gelöscht. Das lässt sich nicht rückgängig machen.", -"game_and_settings.name_will_be_replaced_export_it":"{name} wird ersetzt. Exportiere es vorher über das Menü, wenn du es behalten willst.", "game_and_settings.scenarios_amp_weekly_challenge":"Szenarien & Wochen-Challenge", "game_and_settings.share_your_network_image_card":"Dein Netz teilen Bildkarte", "game_and_settings.start_a_new_network":"Ein neues Netz starten?", -"game_and_settings.start_name":"{name} starten?", -"game_and_settings.start_the_challenge":"Challenge starten", -"game_and_settings.start_the_scenario":"Szenario starten", -"game_and_settings.start_the_weekly_challenge":"Die Wochen-Challenge starten?", "game_and_settings.welcome_back_name_imported_and_saved":"Willkommen zurück, {name}.
Importiert und auf diesem Gerät gespeichert.", "game_and_settings.your_game_saves_itself_every_few":"Dein Spiel speichert sich alle paar Sekunden auf diesem Gerät.", "geography_and_latency.a_to_b":"{a} nach {b}", @@ -3004,7 +2999,6 @@ "save.that_network_went_bankrupt_it_cannot":"Dieses Netz ist pleitegegangen. Es lässt sich nicht zurückholen, nur betrauern.", "save.that_save_has_a_pop_in":"Dieser Spielstand hat einen POP in einer Stadt, die diese Version nicht kennt ({city}).", "save.this_browser_is_not_letting_the":"Dein Spiel wird nicht gespeichert. Dieser Browser lässt das Spiel nichts speichern (ein privates Fenster oder deaktivierte Websitedaten). Exportiere einen Spielstand, um dein Netz zu behalten.", -"save.this_replaces_name_export_it_first":"Das ersetzt {name}. Exportiere es vorher, wenn du es behalten willst.", "save.your_network_is_too_big_to":"Dein Spiel wird nicht gespeichert. Dein Netz ist zu groß für den Speicher dieses Browsers geworden. Exportiere jetzt einen Spielstand und bewahre die Datei auf: Sie ist dein Backup.", "scenario_progress.goal_goal_time_d_days_start":"Ziel: {goal} · Zeit: {d} Tage · Start in {city}", "scenario_progress.goal_was_not_reached_in_d":"{goal} wurde in {d} Tagen nicht erreicht. Spiel dieses Netz im freien Spiel weiter oder versuch es nochmal.", @@ -3141,6 +3135,47 @@ "sites_peering_caches.your_account_manager_found_the_order":"Dein Account Manager hat die Bestellung unter einem Schreibtisch gefunden.
Die Lieferung rückt einen Monat näher.", "sites_peering_caches.your_account_manager_is_on_paternity":"Dein Account Manager ist in Elternzeit.
Seine Vertretung ist auch in Elternzeit.", "sites_peering_caches.your_ticket_was_merged_into_another":"Dein Ticket wurde mit einem anderen Ticket zusammengeführt.
Das wurde als Duplikat von deinem geschlossen.", +"slots.continue":"Weiterspielen", +"slots.continue_this_network":"Dieses Netz weiterspielen", +"slots.damaged_export_or_delete":"Beschädigt: exportieren oder löschen", +"slots.delete":"Löschen", +"slots.delete_forever":"Für immer löschen", +"slots.delete_name":"{name} löschen?", +"slots.delete_this_network":"Dieses Netz löschen", +"slots.free_up_space":"Platz schaffen", +"slots.here_it_is_name":"Hier ist es: {name}.
Das ist das Fenster, das du gesucht hast.", +"slots.it_is_open_in_another_window":"Es ist gerade in einem anderen Fenster offen, und das Fenster hört dann auch auf.", +"slots.it_joins_your_networks_on_this":"Es kommt zu deinen Netzen auf diesem Gerät. Das Netz, das du gerade spielst, bleibt gespeichert.", +"slots.just_now":"gerade eben", +"slots.keep_it":"Behalten", +"slots.last_played_ago":"Zuletzt gespielt: {ago}", +"slots.load_the_newest_version":"Neueste Version laden", +"slots.more_for_name":"Mehr zu {name}", +"slots.n_h_ago":{"one":"vor {n} Std.","other":"vor {n} Std."}, +"slots.name_is_open_in_another_window":"{name} ist in einem anderen Fenster offen", +"slots.name_is_waiting_in_your_other":"{name} wartet in deinem anderen Fenster.
Wechsle dorthin, um weiterzuspielen.", +"slots.name_moved_to_another_window_toast":"{name} wird jetzt in einem anderen Fenster gespielt.
Dieses Puzzle läuft weiter; dein Netz ist dort sicher.", +"slots.name_opened_in_another_window":"{name} wurde in einem anderen Fenster geöffnet", +"slots.name_was_deleted_in_another_window":"{name} wurde in einem anderen Fenster gelöscht.", +"slots.name_was_saved_in_another_window":"{name} wurde in einem anderen Fenster gespeichert", +"slots.no_other_networks_here":"Keine anderen Netze auf diesem Gerät. Ein exportierter Spielstand ist dein bestes Backup.", +"slots.only_one_window_can_play_a":"Ein Netz, ein NOC: Nur ein Fenster kann es gleichzeitig spielen, damit sich zwei Kopien nie gegenseitig überschreiben.", +"slots.open_in_another_window":"In anderem Fenster offen", +"slots.rename":"Umbenennen", +"slots.rename_your_network":"Netz umbenennen", +"slots.renamed_to_name":"Umbenannt.
Sag hallo zu {name}.", +"slots.size_on_this_device":"{size} auf diesem Gerät", +"slots.storage_on_this_device":"Speicher auf diesem Gerät", +"slots.switch_to_that_window":"Zu diesem Fenster wechseln", +"slots.take_it_back_here":"Hier zurückholen", +"slots.take_over_here":"Hier übernehmen", +"slots.that_network_is_gone":"Dieses Netz gibt es nicht mehr.
Es wurde gelöscht, vielleicht in einem anderen Fenster.", +"slots.this_window_stepped_aside_so_the":"Du hast es in einem anderen Fenster übernommen, also hat dieses Platz gemacht und speichert nicht mehr. Nichts ist verloren.", +"slots.this_window_stopped_saving_so_it":"In einem anderen Fenster wurde eine neuere Version gespeichert, also speichert dieses nicht mehr, statt sie zu überschreiben.", +"slots.two_windows_one_network":"Zwei Fenster, ein Netz", +"slots.your_networks":"Deine Netze", +"slots.your_networks_switch_or_start_another":"Deine Netze wechseln oder ein neues starten", +"slots.your_other_networks_share_this_browser":"Deine anderen Netze teilen sich den Speicher dieses Browsers. Exportiere die, die du behalten willst, und lösche sie dann hier, um Platz zu schaffen.", "sold_out.a_hyperscaler_bought_every_wave_of":"Ein Hyperscaler hat letzte Woche jede Wave dieser Größe auf dieser Route gekauft.", "sold_out.not_big_enough_yet_list":"Noch nicht groß genug: {list}", "sold_out.only_peers_over_pnis_and_only":"Peert nur über PNIs, und nur mit Netzen, die es für wichtig hält", diff --git a/site/i18n/es.js b/site/i18n/es.js index 445bc53..1de9b14 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1784,14 +1784,9 @@ "game_and_settings.import_a_save_from_a_file":"Importar una partida desde un archivo", "game_and_settings.import_failed_that_save_is_damaged":"Falló la importación.
Esa partida está dañada y no se pudo cargar. Tu partida actual sigue intacta.", "game_and_settings.name_and_everything_it_owns_will":"{name} y todo lo que posee se borrarán. No se puede deshacer.", -"game_and_settings.name_will_be_replaced_export_it":"{name} será reemplazada. Expórtala primero desde el menú si quieres conservarla.", "game_and_settings.scenarios_amp_weekly_challenge":"Escenarios y desafío semanal", "game_and_settings.share_your_network_image_card":"Comparte tu red tarjeta de imagen", "game_and_settings.start_a_new_network":"¿Empezar una red nueva?", -"game_and_settings.start_name":"¿Empezar {name}?", -"game_and_settings.start_the_challenge":"Empezar el desafío", -"game_and_settings.start_the_scenario":"Empezar el escenario", -"game_and_settings.start_the_weekly_challenge":"¿Empezar el desafío semanal?", "game_and_settings.welcome_back_name_imported_and_saved":"Bienvenido de nuevo, {name}.
Importada y guardada en este dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"Tu partida se guarda sola cada pocos segundos en este dispositivo.", "geography_and_latency.a_to_b":"{a} a {b}", @@ -3002,7 +2997,6 @@ "save.that_network_went_bankrupt_it_cannot":"Esa red quebró. No se puede recuperar, solo llorar.", "save.that_save_has_a_pop_in":"Esa partida tiene un POP en una ciudad que esta versión no conoce ({city}).", "save.this_browser_is_not_letting_the":"Tu partida no se está guardando. Este navegador no deja que el juego guarde nada (ventana privada o datos de sitios desactivados). Exporta una partida para no perder tu red.", -"save.this_replaces_name_export_it_first":"Esto reemplaza a {name}. Expórtala primero si quieres conservarla.", "save.your_network_is_too_big_to":"Tu partida no se está guardando. Tu red se ha vuelto demasiado grande para el almacenamiento de este navegador. Exporta una partida ahora y guarda el archivo: es tu copia de seguridad.", "scenario_progress.goal_goal_time_d_days_start":"Objetivo: {goal} · Tiempo: {d} días · empiezas en {city}", "scenario_progress.goal_was_not_reached_in_d":"{goal} no se logró en {d} días. Sigue jugando esta red en modo libre, o inténtalo de nuevo.", @@ -3139,6 +3133,47 @@ "sites_peering_caches.your_account_manager_found_the_order":"Tu gestor de cuenta encontró el pedido bajo un escritorio.
Está un mes más cerca.", "sites_peering_caches.your_account_manager_is_on_paternity":"Tu gestor de cuenta está de baja por paternidad.
Su sustituto también está de baja por paternidad.", "sites_peering_caches.your_ticket_was_merged_into_another":"Tu ticket se fusionó con otro ticket.
Ese ticket se cerró como duplicado del tuyo.", +"slots.continue":"Continuar", +"slots.continue_this_network":"Continuar esta red", +"slots.damaged_export_or_delete":"Dañada: expórtala o bórrala", +"slots.delete":"Borrar", +"slots.delete_forever":"Borrar para siempre", +"slots.delete_name":"¿Borrar {name}?", +"slots.delete_this_network":"Borrar esta red", +"slots.free_up_space":"Liberar espacio", +"slots.here_it_is_name":"Aquí está: {name}.
Esta es la ventana que buscabas.", +"slots.it_is_open_in_another_window":"Ahora mismo está abierta en otra ventana, y esa ventana también se detendrá.", +"slots.it_joins_your_networks_on_this":"Se suma a tus redes en este dispositivo. La que estás jugando sigue guardada.", +"slots.just_now":"ahora mismo", +"slots.keep_it":"Conservarla", +"slots.last_played_ago":"Última partida: {ago}", +"slots.load_the_newest_version":"Cargar la versión más nueva", +"slots.more_for_name":"Más de {name}", +"slots.n_h_ago":{"one":"hace {n} h","other":"hace {n} h"}, +"slots.name_is_open_in_another_window":"{name} está abierta en otra ventana", +"slots.name_is_waiting_in_your_other":"{name} te espera en tu otra ventana.
Cambia a ella para seguir jugando.", +"slots.name_moved_to_another_window_toast":"{name} ahora se juega en otra ventana.
Este puzle sigue; tu red está a salvo allí.", +"slots.name_opened_in_another_window":"{name} se abrió en otra ventana", +"slots.name_was_deleted_in_another_window":"{name} se borró en otra ventana.", +"slots.name_was_saved_in_another_window":"{name} se guardó en otra ventana", +"slots.no_other_networks_here":"No hay otras redes en este dispositivo. Exportar una partida es tu mejor copia de seguridad.", +"slots.only_one_window_can_play_a":"Una red, un NOC: solo una ventana puede jugarla a la vez, para que dos copias nunca se sobrescriban.", +"slots.open_in_another_window":"Abierta en otra ventana", +"slots.rename":"Renombrar", +"slots.rename_your_network":"Renombrar tu red", +"slots.renamed_to_name":"Renombrada.
Saluda a {name}.", +"slots.size_on_this_device":"{size} en este dispositivo", +"slots.storage_on_this_device":"Almacenamiento en este dispositivo", +"slots.switch_to_that_window":"Cambiar a esa ventana", +"slots.take_it_back_here":"Recuperarla aquí", +"slots.take_over_here":"Tomar el control aquí", +"slots.that_network_is_gone":"Esa red ya no existe.
Se borró, quizá en otra ventana.", +"slots.this_window_stepped_aside_so_the":"La abriste en otra ventana, así que esta se hizo a un lado y dejó de guardar. No se perdió nada.", +"slots.this_window_stopped_saving_so_it":"Se guardó una versión más nueva en otra ventana, así que esta dejó de guardar en vez de sobrescribirla.", +"slots.two_windows_one_network":"Dos ventanas, una red", +"slots.your_networks":"Tus redes", +"slots.your_networks_switch_or_start_another":"Tus redes cambia o empieza otra", +"slots.your_other_networks_share_this_browser":"Tus otras redes comparten el almacenamiento de este navegador. Exporta las que quieras conservar y bórralas aquí para hacer sitio.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hiperescalador compró la semana pasada todas las ondas de ese tamaño en esta ruta.", "sold_out.not_big_enough_yet_list":"Aún no es lo bastante grande: {list}", "sold_out.only_peers_over_pnis_and_only":"Solo hace peering por PNIs, y solo con redes que considera importantes", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 9d1e4df..1b5f327 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1784,14 +1784,9 @@ "game_and_settings.import_a_save_from_a_file":"Importer une sauvegarde depuis un fichier", "game_and_settings.import_failed_that_save_is_damaged":"Échec de l’import.
Cette sauvegarde est endommagée et n’a pas pu être chargée. Ta partie en cours est intacte.", "game_and_settings.name_and_everything_it_owns_will":"{name} et tout ce qu’il possède seront supprimés. Impossible de revenir en arrière.", -"game_and_settings.name_will_be_replaced_export_it":"{name} sera remplacé. Exporte-le d’abord depuis le menu si tu veux le garder.", "game_and_settings.scenarios_amp_weekly_challenge":"Scénarios & défi de la semaine", "game_and_settings.share_your_network_image_card":"Partager ton réseau carte image", "game_and_settings.start_a_new_network":"Créer un nouveau réseau ?", -"game_and_settings.start_name":"Lancer {name} ?", -"game_and_settings.start_the_challenge":"Lancer le défi", -"game_and_settings.start_the_scenario":"Lancer le scénario", -"game_and_settings.start_the_weekly_challenge":"Lancer le défi de la semaine ?", "game_and_settings.welcome_back_name_imported_and_saved":"Bon retour, {name}.
Partie importée et sauvegardée sur cet appareil.", "game_and_settings.your_game_saves_itself_every_few":"Ta partie se sauvegarde toute seule sur cet appareil, toutes les quelques secondes.", "geography_and_latency.a_to_b":"{a} → {b}", @@ -3002,7 +2997,6 @@ "save.that_network_went_bankrupt_it_cannot":"Ce réseau a fait faillite. Impossible de le ressusciter, on ne peut que le pleurer.", "save.that_save_has_a_pop_in":"Cette sauvegarde a un POP dans une ville que cette version ne connaît pas ({city}).", "save.this_browser_is_not_letting_the":"Votre partie n'est pas sauvegardée. Ce navigateur n'autorise pas le jeu à stocker quoi que ce soit (fenêtre privée ou données de sites désactivées). Exportez une sauvegarde pour garder votre réseau.", -"save.this_replaces_name_export_it_first":"Cela remplace {name}. Exporte-le d’abord si tu veux le garder.", "save.your_network_is_too_big_to":"Votre partie n'est pas sauvegardée. Votre réseau est devenu trop gros pour le stockage de ce navigateur. Exportez une sauvegarde maintenant et gardez le fichier : c'est votre copie de secours.", "scenario_progress.goal_goal_time_d_days_start":"Objectif : {goal} · Durée : {d} jours · départ à {city}", "scenario_progress.goal_was_not_reached_in_d":"Objectif non atteint en {d} jours : {goal}. Continue avec ce réseau en partie libre, ou réessaie.", @@ -3139,6 +3133,47 @@ "sites_peering_caches.your_account_manager_found_the_order":"Votre account manager a retrouvé la commande sous un bureau.
Elle a un mois d’avance.", "sites_peering_caches.your_account_manager_is_on_paternity":"Votre account manager est en congé paternité.
Son remplaçant aussi.", "sites_peering_caches.your_ticket_was_merged_into_another":"Votre ticket a été fusionné avec un autre ticket.
Ce ticket a été fermé comme doublon du vôtre.", +"slots.continue":"Continuer", +"slots.continue_this_network":"Continuer ce réseau", +"slots.damaged_export_or_delete":"Endommagé : exporte-le ou supprime-le", +"slots.delete":"Supprimer", +"slots.delete_forever":"Supprimer pour de bon", +"slots.delete_name":"Supprimer {name} ?", +"slots.delete_this_network":"Supprimer ce réseau", +"slots.free_up_space":"Libérer de la place", +"slots.here_it_is_name":"Le voici : {name}.
C'est la fenêtre que tu cherchais.", +"slots.it_is_open_in_another_window":"Il est ouvert dans une autre fenêtre en ce moment, et cette fenêtre s'arrêtera aussi.", +"slots.it_joins_your_networks_on_this":"Il rejoint tes réseaux sur cet appareil. Celui que tu joues reste sauvegardé.", +"slots.just_now":"à l'instant", +"slots.keep_it":"Le garder", +"slots.last_played_ago":"Dernière partie : {ago}", +"slots.load_the_newest_version":"Charger la version la plus récente", +"slots.more_for_name":"Plus pour {name}", +"slots.n_h_ago":{"one":"il y a {n} h","other":"il y a {n} h"}, +"slots.name_is_open_in_another_window":"{name} est ouvert dans une autre fenêtre", +"slots.name_is_waiting_in_your_other":"{name} t'attend dans ton autre fenêtre.
Passe dessus pour continuer à jouer.", +"slots.name_moved_to_another_window_toast":"{name} se joue maintenant dans une autre fenêtre.
Ce puzzle continue ; ton réseau est en sécurité là-bas.", +"slots.name_opened_in_another_window":"{name} a été ouvert dans une autre fenêtre", +"slots.name_was_deleted_in_another_window":"{name} a été supprimé dans une autre fenêtre.", +"slots.name_was_saved_in_another_window":"{name} a été sauvegardé dans une autre fenêtre", +"slots.no_other_networks_here":"Aucun autre réseau sur cet appareil. Exporter une sauvegarde reste ta meilleure copie de secours.", +"slots.only_one_window_can_play_a":"Un réseau, un NOC : une seule fenêtre peut le jouer à la fois, pour que deux copies ne s'écrasent jamais.", +"slots.open_in_another_window":"Ouvert dans une autre fenêtre", +"slots.rename":"Renommer", +"slots.rename_your_network":"Renommer ton réseau", +"slots.renamed_to_name":"Renommé.
Dis bonjour à {name}.", +"slots.size_on_this_device":"{size} sur cet appareil", +"slots.storage_on_this_device":"Stockage sur cet appareil", +"slots.switch_to_that_window":"Aller à cette fenêtre", +"slots.take_it_back_here":"Le reprendre ici", +"slots.take_over_here":"Le prendre ici", +"slots.that_network_is_gone":"Ce réseau n'existe plus.
Il a été supprimé, peut-être dans une autre fenêtre.", +"slots.this_window_stepped_aside_so_the":"Tu l'as repris dans une autre fenêtre, alors celle-ci s'est effacée et ne sauvegarde plus. Rien n'est perdu.", +"slots.this_window_stopped_saving_so_it":"Une version plus récente a été sauvegardée dans une autre fenêtre, alors celle-ci a arrêté de sauvegarder au lieu de l'écraser.", +"slots.two_windows_one_network":"Deux fenêtres, un réseau", +"slots.your_networks":"Tes réseaux", +"slots.your_networks_switch_or_start_another":"Tes réseaux changer, ou en lancer un autre", +"slots.your_other_networks_share_this_browser":"Tes autres réseaux partagent le stockage de ce navigateur. Exporte ceux que tu veux garder, puis supprime-les ici pour faire de la place.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hyperscaler a acheté la semaine dernière toutes les ondes de cette taille sur cette route.", "sold_out.not_big_enough_yet_list":"Pas encore assez gros : {list}", "sold_out.only_peers_over_pnis_and_only":"Ne fait du peering qu’en PNI, et seulement avec les réseaux qu’il juge importants", diff --git a/site/i18n/it.js b/site/i18n/it.js index 53c32ec..9d32645 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1784,14 +1784,9 @@ "game_and_settings.import_a_save_from_a_file":"Importa un salvataggio da un file", "game_and_settings.import_failed_that_save_is_damaged":"Importazione fallita.
Quel salvataggio è danneggiato e non si può caricare. La partita in corso non è stata toccata.", "game_and_settings.name_and_everything_it_owns_will":"{name} e tutto ciò che possiede verranno cancellati. Non si torna indietro.", -"game_and_settings.name_will_be_replaced_export_it":"La partita con {name} verrà sostituita. Se vuoi tenerla, prima esportala dal menu.", "game_and_settings.scenarios_amp_weekly_challenge":"Scenari e sfida settimanale", "game_and_settings.share_your_network_image_card":"Condividi la tua rete come immagine", "game_and_settings.start_a_new_network":"Vuoi creare una nuova rete?", -"game_and_settings.start_name":"Vuoi iniziare {name}?", -"game_and_settings.start_the_challenge":"Inizia la sfida", -"game_and_settings.start_the_scenario":"Inizia lo scenario", -"game_and_settings.start_the_weekly_challenge":"Vuoi iniziare la sfida settimanale?", "game_and_settings.welcome_back_name_imported_and_saved":"Bentornato, {name}.
Importato e salvato su questo dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"La partita si salva da sola ogni pochi secondi su questo dispositivo.", "geography_and_latency.a_to_b":"{a} → {b}", @@ -3002,7 +2997,6 @@ "save.that_network_went_bankrupt_it_cannot":"Quella rete è finita in bancarotta. Non si può resuscitare, solo piangere.", "save.that_save_has_a_pop_in":"Quel salvataggio ha un POP in una città che questa versione non conosce ({city}).", "save.this_browser_is_not_letting_the":"La partita non viene salvata. Questo browser non permette al gioco di salvare nulla (finestra privata o dati dei siti disattivati). Esporta un salvataggio per non perdere la tua rete.", -"save.this_replaces_name_export_it_first":"Sostituisce {name}. Esportala prima, se vuoi tenerla.", "save.your_network_is_too_big_to":"La partita non viene salvata. La tua rete è diventata troppo grande per lo spazio di questo browser. Esporta un salvataggio adesso e tieni il file: è il tuo backup.", "scenario_progress.goal_goal_time_d_days_start":"Obiettivo: {goal} · Tempo: {d} giorni · si parte da {city}", "scenario_progress.goal_was_not_reached_in_d":"Obiettivo non raggiunto in {d} giorni: {goal}. Continua a giocare questa rete in modalità libera, o riprova.", @@ -3139,6 +3133,47 @@ "sites_peering_caches.your_account_manager_found_the_order":"Il tuo account manager ha trovato l’ordine sotto una scrivania.
È un mese più vicino.", "sites_peering_caches.your_account_manager_is_on_paternity":"Il tuo account manager è in congedo di paternità.
Anche il suo sostituto è in congedo di paternità.", "sites_peering_caches.your_ticket_was_merged_into_another":"Il tuo ticket è stato unito a un altro ticket.
Quel ticket è stato chiuso come duplicato del tuo.", +"slots.continue":"Continua", +"slots.continue_this_network":"Continua questa rete", +"slots.damaged_export_or_delete":"Danneggiata: esportala o eliminala", +"slots.delete":"Elimina", +"slots.delete_forever":"Elimina per sempre", +"slots.delete_name":"Eliminare {name}?", +"slots.delete_this_network":"Elimina questa rete", +"slots.free_up_space":"Libera spazio", +"slots.here_it_is_name":"Eccola: {name}.
È la finestra che cercavi.", +"slots.it_is_open_in_another_window":"In questo momento è aperta in un'altra finestra, e anche quella finestra si fermerà.", +"slots.it_joins_your_networks_on_this":"Si aggiunge alle tue reti su questo dispositivo. Quella che stai giocando resta salvata.", +"slots.just_now":"proprio ora", +"slots.keep_it":"Tienila", +"slots.last_played_ago":"Ultima partita: {ago}", +"slots.load_the_newest_version":"Carica la versione più recente", +"slots.more_for_name":"Altro per {name}", +"slots.n_h_ago":{"one":"{n} h fa","other":"{n} h fa"}, +"slots.name_is_open_in_another_window":"{name} è aperta in un'altra finestra", +"slots.name_is_waiting_in_your_other":"{name} ti aspetta nell'altra finestra.
Passa lì per continuare a giocare.", +"slots.name_moved_to_another_window_toast":"{name} ora si gioca in un'altra finestra.
Questo puzzle continua; la tua rete è al sicuro di là.", +"slots.name_opened_in_another_window":"{name} è stata aperta in un'altra finestra", +"slots.name_was_deleted_in_another_window":"{name} è stata eliminata in un'altra finestra.", +"slots.name_was_saved_in_another_window":"{name} è stata salvata in un'altra finestra", +"slots.no_other_networks_here":"Nessun'altra rete su questo dispositivo. Esportare un salvataggio è il tuo backup migliore.", +"slots.only_one_window_can_play_a":"Una rete, un NOC: solo una finestra alla volta può giocarla, così due copie non si sovrascrivono mai.", +"slots.open_in_another_window":"Aperta in un'altra finestra", +"slots.rename":"Rinomina", +"slots.rename_your_network":"Rinomina la tua rete", +"slots.renamed_to_name":"Rinominata.
Saluta {name}.", +"slots.size_on_this_device":"{size} su questo dispositivo", +"slots.storage_on_this_device":"Spazio su questo dispositivo", +"slots.switch_to_that_window":"Passa a quella finestra", +"slots.take_it_back_here":"Riprendila qui", +"slots.take_over_here":"Prendila qui", +"slots.that_network_is_gone":"Quella rete non c'è più.
È stata eliminata, forse in un'altra finestra.", +"slots.this_window_stepped_aside_so_the":"L'hai presa in un'altra finestra, quindi questa si è fatta da parte e ha smesso di salvare. Non si è perso nulla.", +"slots.this_window_stopped_saving_so_it":"In un'altra finestra è stata salvata una versione più recente, quindi questa ha smesso di salvare invece di sovrascriverla.", +"slots.two_windows_one_network":"Due finestre, una rete", +"slots.your_networks":"Le tue reti", +"slots.your_networks_switch_or_start_another":"Le tue reti cambia o iniziane un'altra", +"slots.your_other_networks_share_this_browser":"Le tue altre reti condividono lo spazio di questo browser. Esporta quelle che vuoi tenere, poi eliminale qui per fare posto.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hyperscaler ha comprato la settimana scorsa ogni onda di questa misura su questa tratta.", "sold_out.not_big_enough_yet_list":"Non sei ancora abbastanza grande: {list}", "sold_out.only_peers_over_pnis_and_only":"Fa peering solo su PNI, e solo con reti che considera importanti", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 4496d10..73e5559 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1784,14 +1784,9 @@ "game_and_settings.import_a_save_from_a_file":"Importar um save de um arquivo", "game_and_settings.import_failed_that_save_is_damaged":"Falha na importação.
Esse save está corrompido e não pôde ser carregado. Seu jogo atual não foi mexido.", "game_and_settings.name_and_everything_it_owns_will":"{name} e tudo o que ela possui serão apagados. Não dá para desfazer.", -"game_and_settings.name_will_be_replaced_export_it":"{name} será substituído. Exporte pelo menu antes se quiser guardar.", "game_and_settings.scenarios_amp_weekly_challenge":"Cenários & desafio semanal", "game_and_settings.share_your_network_image_card":"Compartilhar sua rede card de imagem", "game_and_settings.start_a_new_network":"Começar uma nova rede?", -"game_and_settings.start_name":"Começar {name}?", -"game_and_settings.start_the_challenge":"Começar o desafio", -"game_and_settings.start_the_scenario":"Começar o cenário", -"game_and_settings.start_the_weekly_challenge":"Começar o desafio semanal?", "game_and_settings.welcome_back_name_imported_and_saved":"Bem-vindo de volta, {name}.
Importado e salvo neste dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"Seu jogo se salva sozinho a cada poucos segundos neste dispositivo.", "geography_and_latency.a_to_b":"{a} → {b}", @@ -3002,7 +2997,6 @@ "save.that_network_went_bankrupt_it_cannot":"Essa rede foi à falência. Não dá para trazer de volta, só chorar.", "save.that_save_has_a_pop_in":"Esse save tem um POP numa cidade que esta versão não conhece ({city}).", "save.this_browser_is_not_letting_the":"Seu jogo não está sendo salvo. Este navegador não deixa o jogo guardar nada (janela anônima ou dados de sites desativados). Exporte um save para não perder sua rede.", -"save.this_replaces_name_export_it_first":"Isso substitui {name}. Exporte antes se quiser guardar.", "save.your_network_is_too_big_to":"Seu jogo não está sendo salvo. Sua rede ficou grande demais para o armazenamento deste navegador. Exporte um save agora e guarde o arquivo: é o seu backup.", "scenario_progress.goal_goal_time_d_days_start":"Objetivo: {goal} · Tempo: {d} dias · começa em {city}", "scenario_progress.goal_was_not_reached_in_d":"Objetivo não alcançado em {d} dias: {goal}. Continue jogando esta rede no modo livre, ou tente de novo.", @@ -3139,6 +3133,47 @@ "sites_peering_caches.your_account_manager_found_the_order":"Seu gerente de contas achou o pedido embaixo de uma mesa.
Está um mês mais perto.", "sites_peering_caches.your_account_manager_is_on_paternity":"Seu gerente de contas está de licença-paternidade.
O substituto dele também está de licença-paternidade.", "sites_peering_caches.your_ticket_was_merged_into_another":"Seu chamado foi juntado a outro chamado.
Esse chamado foi fechado como duplicado do seu.", +"slots.continue":"Continuar", +"slots.continue_this_network":"Continuar esta rede", +"slots.damaged_export_or_delete":"Danificada: exporte ou apague", +"slots.delete":"Apagar", +"slots.delete_forever":"Apagar para sempre", +"slots.delete_name":"Apagar {name}?", +"slots.delete_this_network":"Apagar esta rede", +"slots.free_up_space":"Liberar espaço", +"slots.here_it_is_name":"Aqui está: {name}.
Esta é a janela que você procurava.", +"slots.it_is_open_in_another_window":"Ela está aberta em outra janela agora, e essa janela também vai parar.", +"slots.it_joins_your_networks_on_this":"Ela entra nas suas redes neste dispositivo. A que você está jogando continua salva.", +"slots.just_now":"agora mesmo", +"slots.keep_it":"Manter", +"slots.last_played_ago":"Jogada pela última vez {ago}", +"slots.load_the_newest_version":"Carregar a versão mais nova", +"slots.more_for_name":"Mais para {name}", +"slots.n_h_ago":{"one":"há {n} h","other":"há {n} h"}, +"slots.name_is_open_in_another_window":"{name} está aberta em outra janela", +"slots.name_is_waiting_in_your_other":"{name} está esperando na sua outra janela.
Vá para ela para continuar jogando.", +"slots.name_moved_to_another_window_toast":"{name} agora é jogada em outra janela.
Este puzzle continua; sua rede está segura lá.", +"slots.name_opened_in_another_window":"{name} foi aberta em outra janela", +"slots.name_was_deleted_in_another_window":"{name} foi apagada em outra janela.", +"slots.name_was_saved_in_another_window":"{name} foi salva em outra janela", +"slots.no_other_networks_here":"Nenhuma outra rede neste dispositivo. Exportar o jogo é o seu melhor backup.", +"slots.only_one_window_can_play_a":"Uma rede, um NOC: só uma janela pode jogá-la por vez, para que duas cópias nunca se sobrescrevam.", +"slots.open_in_another_window":"Aberta em outra janela", +"slots.rename":"Renomear", +"slots.rename_your_network":"Renomear sua rede", +"slots.renamed_to_name":"Renomeada.
Diga olá para {name}.", +"slots.size_on_this_device":"{size} neste dispositivo", +"slots.storage_on_this_device":"Armazenamento neste dispositivo", +"slots.switch_to_that_window":"Ir para essa janela", +"slots.take_it_back_here":"Trazer de volta para cá", +"slots.take_over_here":"Assumir aqui", +"slots.that_network_is_gone":"Essa rede não existe mais.
Ela foi apagada, talvez em outra janela.", +"slots.this_window_stepped_aside_so_the":"Você assumiu em outra janela, então esta saiu da frente e parou de salvar. Nada foi perdido.", +"slots.this_window_stopped_saving_so_it":"Uma versão mais nova foi salva em outra janela, então esta parou de salvar em vez de sobrescrevê-la.", +"slots.two_windows_one_network":"Duas janelas, uma rede", +"slots.your_networks":"Suas redes", +"slots.your_networks_switch_or_start_another":"Suas redes trocar ou começar outra", +"slots.your_other_networks_share_this_browser":"Suas outras redes dividem o armazenamento deste navegador. Exporte as que quiser manter e apague-as aqui para abrir espaço.", "sold_out.a_hyperscaler_bought_every_wave_of":"Um hyperscaler comprou semana passada todas as ondas desse tamanho nesta rota.", "sold_out.not_big_enough_yet_list":"Você ainda não é grande o bastante: {list}", "sold_out.only_peers_over_pnis_and_only":"Só faz peering via PNI, e só com redes que considera importantes", diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index abd4507..37dbae1 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -30,7 +30,7 @@ const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chao function weekly(){const {y,w}=isoWeek(new Date());let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};} const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} -function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}newGame(nm,city);S.mode=o.mode||'normal'; +function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);S.mode=o.mode||'normal'; // The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules. {const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);} if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}} diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index b0ca38e..7ebdfcd 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -69,9 +69,9 @@ 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 ---------- -// 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;} +// The running game gets its usual save first and is kept in memory, set aside: save() keeps writing it to its slot +// (leaving the page mid-puzzle), and leaving the puzzle picks it up again. +function pzFlush(){save(true);UI.pzKeep=S;} function pzBegin(def){if(!def)return; 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}; @@ -84,7 +84,9 @@ function pzBegin(def){if(!def)return; 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; 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;}}} + if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} + // It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told. + if(UI.slot&&(sv||UI.loadBad)){slotBroke(UI.slot);return;}} renderAll();showTitle();} // The camera frames the puzzle's cities beside the puzzle card: left on wide screens, right on phones on their side, a bottom sheet on phones. function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity; diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 29e3baf..0a2ec5c 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -9,21 +9,24 @@ Object.assign(ACT,{ // Puzzles live in their own module; until it ships, the door says so. puzzleDoor:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||randomNetworkName()).slice(0,24);if(typeof ACT.puzzleMenu==='function')ACT.puzzleMenu();else toast(tr('title.puzzles_are_coming_soon'),'goal');}, scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();}, - startScn:({id,sure})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`

${tr('game_and_settings.start_name',{name:esc(sc.n)})}

${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}

${btn(tr('game_and_settings.start_the_scenario'),'startScn',{id,sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);return;}beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});}, - startWeekly:({sure}={})=>{if(!sure&&S&&UI.started&&!S.lost&&!(S.scn&&(S.scn.done||S.scn.failed))){openModal(`

${tr('game_and_settings.start_the_weekly_challenge')}

${tr('game_and_settings.name_will_be_replaced_export_it',{name:esc(S.name)})}

${btn(tr('game_and_settings.start_the_challenge'),'startWeekly',{sure:1},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);return;}const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, + startScn:({id})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});}, + startWeekly:()=>{const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, pickStart:({city})=>{if(!homeOk(city))return;UI.startCity=city;document.querySelectorAll('.start').forEach(b=>b.classList.toggle('on',b.dataset.city===city||(b.classList.contains('own')&&!START5.includes(city))));const s=$('homeSel');if(s&&START5.includes(city))s.value='';const w=$('homeWhat');if(w)w.innerHTML=homeWhat();}, pickHome:({v})=>{if(v)ACT.pickStart({city:v});else ACT.pickStart({city:'fra'});}, - cont:()=>{migrate(S);track('game_continue',true);UI.started=true;closeModal();renderAll();}, - newgame:()=>{try{localStorage.removeItem('sot-save-v1');}catch(e){}S=null;UI.started=false;UI.sel=null;UI.nm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();showTitle();}, + // Delete this window's network and go back to the title (the other networks stay). + newgame:()=>{if(pzOn())pzLeave();const id=UI.slot;if(id){slotDrop(id);slotFree(id);}gameClear();showTitle();}, keepPlaying:()=>{closeModal();}, exportSave:()=>exportSave(), importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();}, - importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;try{S=migrate(JSON.parse(JSON.stringify(s0)));compute();checkGoals();renderAll();}catch(e){S=prev;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;compute();renderAll();save();toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, - menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`
AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}

${esc(S.name)}

+ importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S; + // An import is a new network next to the others: the one playing here is saved and kept. + try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, + menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`
AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}

${esc(S.name)}

${saveFailing()?`

${saveFailMsg()}

`:`

${tr('game_and_settings.your_game_saves_itself_every_few')}

`}${isPhone()?installRow():''} `; return h;} diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index 404b912..d688fe6 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -148,10 +148,10 @@ function ddosAttack(recompute=true){const type='ddos',fl=scnRule('ddos');ddosExp 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 ports=ddosEntries(),entries=ddosFold(ports,c),a={id:uid(),city:c,vec,gbps,until:S.day+dur,entry:entries.length>1?{k:'distributed',lab:tr('common.distributed_ingress')}:entries[0]||entry,entries,bh:false,start:S.day}; + const a={id:uid(),city:c,vec,gbps,until:S.day+dur,entry,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=ports.length>1?tr('failures.across_n_transit_and_peering_ports',{n:ports.length}):entry&&entry.lab?tr('failures.in_via_e',{e:entry.lab}):''; + const how=entry&&entry.lab?tr('failures.in_via_e',{e:entry.lab}):''; const msg=tr('failures.a_size_vec_attack_is_hitting',{size:fmtG(gbps),vec:V.n,city:CITY[c].name,how})+' '+(soaked?tr('failures.your_mitigation_is_eating_most_of'):tr('failures.junk_traffic_is_eating_your_capacity')); if(fl)a.who=pick(FLOOD_WHO); addInc({type,ref:c,atk:a.id,until:S.day+dur,msg:fl?msg+' '+tr('failures.attacker_who',{who:tr(a.who)}):msg,cost:0}); diff --git a/src/game/90-actions/80-security-and-china.js b/src/game/90-actions/80-security-and-china.js index 9e7fd87..3cba21f 100644 --- a/src/game/90-actions/80-security-and-china.js +++ b/src/game/90-actions/80-security-and-china.js @@ -7,7 +7,7 @@ Object.assign(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('security_and_china.clean_pipe_add_on_enabled_on',{net:NET[t.net].name,mo:fmt$(cleanMo(t))}):tr('security_and_china.clean_pipe_add_on_removed_from',{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('security_and_china.net_pni_is_now_a_sacrificial',{net:NET[p.net].name}):tr('security_and_china.net_pni_is_back_to_normal',{net:NET[p.net].name}),p.sacrif?'good':'');after();}, - ixbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}if(!ddosHasIx(a)){toast(tr('security_and_china.no_ix_in_city_to_announce',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('security_and_china.ix_blackhole_announced_in_city_about',{city:ddosCities(a).filter(hasIxAt).map(c=>CITY[c].name).join(', ')}):tr('security_and_china.ix_blackhole_withdrawn'),a.ixbh?'good':'');sfx('alert');after();}, + ixbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}if(!hasIxAt(a.city)){toast(tr('security_and_china.no_ix_in_city_to_announce',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('security_and_china.ix_blackhole_announced_in_city_about',{city:CITY[a.city].name}):tr('security_and_china.ix_blackhole_withdrawn'),a.ixbh?'good':'');sfx('alert');after();}, rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('security_and_china.no_attack_to_blackhole_right_now'),'');return;}a.bh=true;S.stats.rtbh=(S.stats.rtbh||0)+1;toast(tr('security_and_china.rtbh_announced_you_blackholed_the',{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('security_and_china.blackhole_withdrawn_city_is',{city:CITY[a.city].name}),'');after();}, hackback:({id}={})=>{const a=ddosFind(id);if(!a||a.until<=S.day){toast(tr('security_and_china.nothing_to_hack_back_right_now'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1; diff --git a/src/i18n/en.js b/src/i18n/en.js index 9e5308b..309e046 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -909,7 +909,6 @@ "common.demand":"Demand", "common.deploy":"Deploy", "common.deployed":"deployed", -"common.distributed_ingress":"Distributed ingress", "common.diverse":"diverse", "common.diverse_route":"diverse route", "common.dns_reflection":"DNS reflection", @@ -1634,7 +1633,6 @@ "failures.a_trawler_off_ostend_dragged_its":"A trawler off Ostend dragged its gear straight through your {a}–{b} cable. The North Sea is about thirty metres deep and full of boats.", "failures.a_visiting_engineer_from_london":"A visiting engineer from London brought Marmite to the {city} NOC. Diplomatic relations broke down, and so did your router while everyone argued.", "failures.a_wind_farm_service_vessel_dropped":"A wind-farm service vessel dropped anchor on your {a}–{b} cable. It was there to fix a turbine.", -"failures.across_n_transit_and_peering_ports":", across {n} transit and peering ports", "failures.all_n_links_in_that_trench":"All {n} links in that trench went down with it.", "failures.an_automation_script_in_city_ran":"An automation script in {city} ran “sed” on the whole config instead of one line. Every interface is now named “TODO”.", "failures.an_earthquake_shook_your_a_b":"An earthquake shook your {a}–{b} fiber loose somewhere above 4,000 metres.", @@ -2008,7 +2006,6 @@ "incidents_and_ddos.edge_filters_dropping_g":"Edge filters dropping: {g}", "incidents_and_ddos.flowspec_cannot_catch_vec":"Flowspec cannot catch {vec}", "incidents_and_ddos.flowspec_dropping_g":"Flowspec dropping: {g}", -"incidents_and_ddos.flowspec_dropping_g_some_ingress":"Flowspec dropping: {g}; some ingress routers have no TCAM", "incidents_and_ddos.g_is_leaking_through":"{g} is leaking through", "incidents_and_ddos.hackback_3000tm_20k":"HackBack 3000™ $20k", "incidents_and_ddos.it_was_dns":"It was DNS", diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index 29d1e4b..98efc9f 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -3,85 +3,75 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); -test('a flood entering over a PNI with NetChill competes on that PNI at its own rank, as real traffic does', () => { - for (const net of ['nfx', 'lvl']) { - 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=5000;S.pops.fra.rgen=RG.length-1;S.pops.fra.routers=8"); - ev(`S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pa',net:'${net}',city:'fra',tier:1}];compute()`); - assert.equal(ev(`R.netEg.${net}.p`), 100, 'the 100G PNI is full of real traffic'); - ev("S.ev.ddos={id:'x',city:'fra',vec:'http',gbps:100,start:S.day,until:S.day+5,entries:[{k:'p',id:'pa',city:'fra',share:1}]};compute()"); - assert.equal(ev('R.usePni.pa'), 100); - assert.ok(!(ev(`R.netEg.${net}?.p||0`) > 1), `${net}: the junk is not routed behind the real traffic as if it were a cone route`); - assert.deepEqual(errors, []); - } -}); - // Frankfurt has the eyeballs and no transit; all transit is in Amsterdam, 100G of wave away. -const remoteIngress = (ev, flip) => { +const remoteTransit = (ev, flip) => { ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'ams'});ACT.launchBB({city:'fra'});S.links.push({id:'L',a:'fra',b:'ams',kind:'wave',tier:1,km:400,mo:1,cut:0});ACT.buyTransit({city:'ams',net:NETS.find(n=>sellsAt(n,'ams')).id,tier:1})"); if (flip) ev("const p=S.pops;S.pops={ams:p.ams,fra:p.fra}"); ev("compute()"); }; -test('a flood entering in another city crosses the backbone to its victim, whatever order the POPs were built in', () => { +test('a flood loads the backbone and the victim as on main, whatever order the POPs were built in', () => { const out = []; for (const flip of [false, true]) { const { ev, errors } = load({ seed: 5 }); - remoteIngress(ev, flip); + remoteTransit(ev, flip); assert.ok(ev("sfOf(R,'fra')") > 0.95, 'fine before the attack'); - ev("S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'http',gbps:300,start:S.day,until:S.day+3,entry:{k:'distributed',lab:''},entries:[{k:'t',id:S.transit[0].id,city:'ams',share:1}]};compute()"); - assert.equal(ev('R.load.L'), 100, 'the junk fills the wave to the victim'); - assert.ok(ev("R.nodeLoad.fra") >= 100, "and the victim's router"); + ev("S.day=60;ddosAttack();Object.assign(S.ev.ddos,{city:'fra',vec:'http',gbps:300});compute()"); + assert.equal(ev('S.ev.ddos.entries'), undefined, 'no per-port shares'); + assert.equal(ev('R.load.L'), 100, 'the junk fills the wave between the transit and the victim'); + assert.ok(ev('R.nodeLoad.fra') >= 100, "and the victim's router"); assert.ok(ev("sfOf(R,'fra')") < 0.05, 'the victim goes dark'); - out.push(ev("JSON.stringify([R.load.L,R.useT[S.transit[0].id],sfOf(R,'fra')])")); + assert.equal(ev("sfOf(R,'ams')"), 1); + out.push(ev("JSON.stringify([R.load.L,Object.values(R.useT)[0],sfOf(R,'fra'),R.ddos.length])")); assert.deepEqual(errors, []); } assert.equal(out[0], out[1], 'POP build order does not change the outcome'); }); +test('the same flood lands exactly as it does on main (one entry port, the victim\'s router filters it)', () => { + const { ev, errors } = load({ seed: 5 }); + remoteTransit(ev, false); + ev("S.pops.fra.rgen=RG.findIndex(r=>r.fs===2);S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'dns',gbps:200,start:S.day,until:S.day+3,entry:{k:'t',id:S.transit[0].id,lab:''},bh:false};compute()"); + // Full Flowspec leaves 15%: 30G of junk on the 100G wave, next to Frankfurt's own traffic. + assert.ok(Math.abs(ev('R.ddos[0].leak') - 30) < 1e-9); + assert.ok(Math.abs(ev("R.ef[edgeKey(S.links[0])].net.junk") - 30) < 1e-6); + assert.deepEqual(errors, []); +}); + test('an attack is held or lost at its victim; other POPs and their DDoS-protected customers are not charged', () => { const { ev, errors } = load({ seed: 5 }); ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=1e9;S.nextEvent=1e9;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].bb={d:50};S.pops[c].rgen=3}"); - ev("S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:1}];S.scrubMode='always'"); - // New York is struggling on its own (a 10G port for 50G of eyeballs), and has a DDoS-protected customer. + ev("S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:0}];S.scrubs=[{city:'fra',tier:1}];S.scrubMode='always'"); + // New York is struggling on its own (a 10G port for 200G of eyeballs), and has a DDoS-protected customer. ev("S.pops.nyc.bb.d=200;S.biz.push({id:'sc',type:'scrub',name:'Shield',city:'nyc',bw:1,rate:1000,mood:80,since:0})"); - ev("S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'http',gbps:20,start:S.day,until:S.day+3,entry:{k:'distributed',lab:''},entries:[{k:'t',id:'tf',city:'fra',share:.5},{k:'t',id:'tn',city:'nyc',share:.5}]};compute()"); + ev("S.day=60;S.ev.ddos={id:'a',city:'fra',vec:'http',gbps:20,start:S.day,until:S.day+3,entry:{k:'t',id:'tf',lab:''}};compute()"); assert.ok(ev("sfOf(R,'nyc')") < 0.85, 'New York is under water anyway'); assert.ok(ev("sfOf(R,'fra')") >= 0.97, 'the victim is fine'); assert.equal(ev('ddosSf(S.ev.ddos)'), ev("sfOf(R,'fra')")); - const cash = ev('S.cash'); ev('dayTick()'); assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ev.ddos.sla||[])')), [], 'no SLA payout for a customer in another city'); assert.equal(ev('S.stats.sla||0'), 0); ev('S.day=S.ev.ddos.until;ddosExpire()'); assert.equal(ev('S.stats.ddosOk||0'), 1, 'held at the victim'); assert.equal(ev('S.stats.ddosLost||0'), 0); - assert.ok(cash > 0); assert.deepEqual(errors, []); }); -test('an attack keeps its biggest ingress ports and folds the long tail, so saves stay small', () => { - const { ev, errors } = load({ seed: 5 }); - ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['fra','ams','lon','par'])if(!S.pops[c])ACT.buildPop({city:c});for(const c in S.pops){S.pops[c].bb={d:100};S.pops[c].rgen=3}"); - ev("S.transit=[];const nets=NETS.filter(n=>n.type!=='t1').slice(0,40);for(const c in S.pops)for(const n of nets.slice(0,8))S.pni.push({id:n.id+'@'+c,net:n.id,city:c,tier:1});compute()"); - ev("S.day=60;S.ddosStarts=[];ddosAttack()"); - const ports = ev('ddosEntries().length'); - assert.ok(ports > 20, `many ports carry traffic (${ports})`); - const en = JSON.parse(ev('JSON.stringify(S.ev.ddos.entries)')); - assert.equal(en.length, 13, 'twelve named ports and one remainder'); - assert.equal(en.at(-1).k, 'rest'); - assert.equal(en.at(-1).city, ev('S.ev.ddos.city')); - assert.ok(Math.abs(en.reduce((n, x) => n + x.share, 0) - 1) < 1e-9); - assert.match(ev("S.inc.at(-1).msg"), new RegExp(`across ${ports} transit and peering ports`), 'the message still counts every port'); - // The remainder is routed like the rest of the flood, and survives a save. - ev('compute()'); - assert.ok(Math.abs(ev('R.ddos.reduce((n,m)=>n+m.reaching,0)') - ev('S.ev.ddos.gbps')) < 1e-6); - ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); - assert.equal(ev('S.ev.ddos.entries.length'), 13); - // An old save with every port is folded on load. - ev("S.ev.ddos.entries=Array.from({length:300},(_,i)=>({k:'p',id:'x'+i,city:'fra',lab:'',share:1}));S=migrate(JSON.parse(JSON.stringify(S)))"); - assert.equal(ev('S.ev.ddos.entries.length'), 13); - assert.equal(ev("S.ev.ddos.entries.find(e=>e.k==='rest').share.toFixed(4)"), (288/300).toFixed(4)); +test('fourteen attacks on a big network keep the save small, and 2.0 beta saves with per-port shares still load', () => { + const fs = require('node:fs'), path = require('node:path'); + const fx = JSON.parse(fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8')); + const { ev, errors } = load({ seed: 3 }); + ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(fx.S || fx))}));UI.started=true;compute()`); + const before = ev('JSON.stringify(S).length'); + ev("S.day=Math.max(S.day,50);for(let i=0;i<14;i++){S.ddosStarts=[];ddosAttack(false);}compute()"); + assert.equal(ev('ddosAll().length'), 14); + assert.ok(ev('JSON.stringify(S).length') - before < 10000, 'a few hundred bytes per attack'); + // A beta save spread each attack over every port: the shares are dropped and the attack carries on. + ev("S.ev.ddos.entries=Array.from({length:300},(_,i)=>({k:'p',id:'x'+i,city:S.ev.ddos.city,lab:'',share:1}));S.ev.ddos.entry={k:'distributed',lab:'Distributed ingress'};S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + assert.equal(ev('S.ev.ddos.entries'), undefined); + assert.equal(ev('S.ev.ddos.entry.k'), 'edge'); + assert.equal(ev('ddosAll().length'), 14); + assert.match(ev('ddosPanel()'), /Live attack/); assert.deepEqual(errors, []); }); diff --git a/tests/game.test.js b/tests/game.test.js index ad9c729..5102de3 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -4,8 +4,8 @@ const { load, seed } = require('./harness'); test('daily DDoS spawns share one routing calculation and score their first active day', () => { const { ev, errors } = load(); - // The busier DDoS schedule needs spicy chaos (BGP at 3 a.m.) or gaming customers. - ev("ACT.start({});S.rules=makeRules('bgp');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"); + // The busier daily DDoS schedule comes with gaming customers. + ev("ACT.start({});S.biz=[{type:'game',id:'g',name:'G',city:'fra',bw:1,rate:1,reqs:[]}];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'); @@ -209,7 +209,7 @@ test('Flowspec is a router-model capability, and each tool answers a flood', () 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()"); + 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,entry:{k:'edge',lab:''}};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/); @@ -230,29 +230,22 @@ test('a distributed SYN flood reports actual Flowspec drops and sends only the r assert.deepEqual(errors, []); }); -test('Flowspec accounts for each ingress router, upstream cleaning and other edge filters separately', () => { +test('Flowspec, upstream cleaning and other edge filters are each accounted for 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/); + ev("ACT.start({});S.cash=1e9;S.lvl=6;S.pops.fra.rgen=1;S.transit=[{id:'tf',city:'fra',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:0}];S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entry:{k:'t',id:'tf'}};compute()"); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-18.12)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-12.08)<1e-9); + assert.match(ev('ddosPanel()'), /✓ Flowspec dropping: 18\.1 Gbps/); + ev('S.transit[0].clean=true;compute()'); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).reaching')-3.02)<1e-9, 'clean pipe leaves a tenth'); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-1.812)<1e-9); + assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 3\.0 Gbps/); + ev("S.ixp={fra:1};S.ev.ddos.ixbh=true;compute()"); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).flowspec')-0.604)<1e-9); + assert.match(ev('ddosPanel()'), /✓ Edge filters dropping: 0\.6 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()"); @@ -793,8 +786,8 @@ test('DDoS frequency rises with level and signed gaming customers, with a rollin 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 (with spicy chaos on), then verify each rolling seven-day window. - ev("S.rules=makeRules('bgp');"); + // Force every random spawn opportunity (gamers on board), then verify each rolling seven-day window. + ev("S.biz=[{type:'game',city:'fra'}];"); 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))`); @@ -832,39 +825,6 @@ test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood 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}); @@ -875,8 +835,8 @@ test('scrubbing hauls retain their real source on each link when several cities {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()`); + S.ev.ddos={id:'b',city:'ber',vec:'ack',gbps:50,start:0,until:7,entry:{k:'t',id:'tb'}}; + S.ev.ddosMore=[{id:'p',city:'prg',vec:'ack',gbps:50,start:0,until:7,entry:{k:'t',id:'tp'}}];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'); @@ -892,8 +852,8 @@ test('scrubbing hauls retain their real source on each link when several cities 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()"); + // Swapping the attacks' order and adding an overlapping flood must not change the attribution. + ev("S.ev.ddosMore.push(S.ev.ddos,{...S.ev.ddos,id:'overlap',gbps:20});S.ev.ddos=S.ev.ddosMore.shift();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. @@ -914,29 +874,9 @@ function setupScrubLatency(ev) { 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()`); + entry:{k:'edge',lab:''}};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); @@ -946,11 +886,11 @@ test('each attack shows only the nearest scrubbing detour using precise one-way 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()"); + ev("S.ev.ddosMore=[{id:'other',city:'ams',vec:'ack',gbps:10,start:0,until:7,entry:{k:'edge',lab:''}}];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()"); + ev("S.pops.fra.down=10;S.links.push({id:'pa',a:'par',b:'ams',kind:'wave',tier:3,km:2000,mo:100});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/); @@ -970,17 +910,6 @@ test('a constrained remote haul leaves scrubbing capacity for the next overlappi 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()"); @@ -1004,7 +933,7 @@ test('RackNet and TeamSpooked require signed gaming customers, bypass Flowspec, assert.deepEqual(errors, []); }); -test('normal DDoS starts average half an attack per week without gaming and never exceed a seven-per-week expected rate', () => { +test('gamers\' DDoS starts rise gradually from half an attack per week and never exceed a seven-per-week expected rate', () => { const { ev, errors } = load(); ev("ACT.start({});S.rules=makeRules('bgp');S.day=50"); const checks = JSON.parse(ev(` @@ -1020,9 +949,9 @@ test('normal DDoS starts average half an attack per week without gaming and neve JSON.stringify(out) `)); for(const row of checks){ + if(row.games===0){assert.equal(row.observed,0,'without gamers attacks stay on the failure schedule');continue;} 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(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'); @@ -1116,7 +1045,7 @@ test('Flood Season retains its existing size quantiles and escalation when norma assert.deepEqual(errors, []); }); -test('the busier DDoS schedule needs spicy chaos or gaming customers; otherwise attacks come as before', () => { +test('the busier DDoS schedule needs gaming customers; otherwise attacks come with the other incidents', () => { const { ev, errors } = load(); ev("ACT.start({});S.cash=1e9;S.day=50;S.lvl=13;S.biz=[];S.nextFail=1e9;S.nextEvent=1e9"); const ticks = () => ev("(()=>{const old=Math.random,oa=ddosAttack;let n=0;ddosAttack=()=>{n++};Math.random=()=>0;try{for(let i=0;i<30;i++)ddosTick();}finally{Math.random=old;ddosAttack=oa;}return n;})()"); @@ -1127,14 +1056,15 @@ test('the busier DDoS schedule needs spicy chaos or gaming customers; otherwise ev("S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]"); assert.ok(ticks() > 0, 'gaming customers bring their own attacks'); ev("S.biz=[];S.rules=makeRules('bgp')"); - assert.ok(ticks() > 0, 'spicy chaos brings more attacks'); + assert.equal(ticks(), 0, 'spicy chaos alone has no daily schedule: it doubles the incident one'); ev("S.rules=makeRules('freeze')"); assert.equal(ticks(), 0, 'Change Freeze has no attacks on either schedule'); ev("S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]"); assert.equal(ticks(), 0, 'not even with gamers'); assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'and fireFailure never rolls one'); - ev("S.rules=makeRules('bgp');S.biz=[]"); - assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'spicy attacks come from their own schedule only, never twice'); + ev("S.rules=makeRules('oncall');S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]"); + assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'gamers\' attacks come from their own schedule only, never twice'); + ev("S.biz=[]"); ev("S.rules=makeRules('oncall')"); // Flood Season, not spicy: one flood at a time, 3 to 7 days apart, however old the scenario is. ev("ACT.startScn({id:'flood',sure:1});S.biz=[]"); diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index 00da767..a69d199 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 Date: Wed, 28 Oct 2026 20:54:34 +0100 Subject: [PATCH 078/181] 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 f4c8400df19793cde580570d1890197058d665f4 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 01:57:32 +0000 Subject: [PATCH 079/181] Submarine upgrades that change nothing on a cable can't be bought (#198) Premium submarine terminals and Optical engineering only extend the long-haul modes of the coherent optics. On many cable lengths (all of the Atlantic, and about 17,000-18,500 km like Atlanta to Sydney) neither changes what any optic carries, yet both could be bought. subHelps() compares every optic's rate with and without the upgrade, counting an upgrade that only helps together with the other one. The link panel disables Install with a note, ACT.subUpgrade refuses, and the cable order screen disables the toggle and only quotes and charges picks that still help on the chosen design. --- CHANGELOG.md | 2 + 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/10-catalog/60-reach-and-subsea.js | 4 + src/game/90-actions/87-fiber-and-hardware.js | 7 +- src/game/93-ui/70-link-panels.js | 4 +- src/game/95-modals/80-own-cable.js | 8 +- src/i18n/en.js | 1 + tests/regions.test.js | 12 ++- tests/subsea-upgrade-timing.test.js | 18 ++-- tests/useless-subsea-upgrades.test.js | 86 ++++++++++++++++++++ 14 files changed, 127 insertions(+), 20 deletions(-) create mode 100644 tests/useless-subsea-upgrades.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index eb2f3d5..57684cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Premium submarine terminals and Optical engineering can no longer be bought on a cable where they would change nothing (#198). The button now says so, and an upgrade that only helps together with the other one stays available. + ## [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. diff --git a/site/i18n/de.js b/site/i18n/de.js index 0b751b2..406acb4 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2661,6 +2661,7 @@ "progress.under_attack_now":"Gerade unter Beschuss", "progress.your_score_peak_traffic":"Dein Ergebnis: Spitzen-Traffic", "progress.your_traffic_to_and_from_asia":"Dein Traffic von und nach Asien", +"reach_and_subsea.makes_no_difference_on_this_cable":"Bringt auf diesem Kabel nichts", "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 2f2a645..d602285 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2659,6 +2659,7 @@ "progress.under_attack_now":"Bajo ataque ahora", "progress.your_score_peak_traffic":"Tu puntuación: tráfico pico", "progress.your_traffic_to_and_from_asia":"Tu tráfico desde y hacia Asia", +"reach_and_subsea.makes_no_difference_on_this_cable":"No cambia nada en este cable", "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 413ae5f..6c5dc0e 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2659,6 +2659,7 @@ "progress.under_attack_now":"Sous attaque", "progress.your_score_peak_traffic":"Ton score : pic de trafic", "progress.your_traffic_to_and_from_asia":"Ton trafic vers et depuis l’Asie", +"reach_and_subsea.makes_no_difference_on_this_cable":"Ne change rien sur ce câble", "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 103bc61..339a2d3 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2659,6 +2659,7 @@ "progress.under_attack_now":"Sotto attacco ora", "progress.your_score_peak_traffic":"Il tuo punteggio: picco di traffico", "progress.your_traffic_to_and_from_asia":"Il tuo traffico da e per l’Asia", +"reach_and_subsea.makes_no_difference_on_this_cable":"Su questo cavo non cambia nulla", "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 046f9a8..1dc3071 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2659,6 +2659,7 @@ "progress.under_attack_now":"Sob ataque agora", "progress.your_score_peak_traffic":"Sua pontuação: pico de tráfego", "progress.your_traffic_to_and_from_asia":"Seu tráfego de e para a Ásia", +"reach_and_subsea.makes_no_difference_on_this_cable":"Não faz diferença neste cabo", "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/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index 9ff08a3..3e46b70 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -53,6 +53,10 @@ const subMaxTier=km=>{let t=0;LT.forEach((T,i)=>{if(!subWaveWhy(i,km,true))t=i;} // What an optic carries depends only on the optic, the span length and subsea or not; the map and compute() ask a lot. // Cached per optic, span and cable state: subsea, and which submarine upgrades are in service (#78). const OPTG={};const optG=(o,l)=>{const km=spanKm(l),fl=l.sub?1+(subUpgradeReady(l,'terminal')?2:0)+(subUpgradeReady(l,'engineering')?4:0):0,c=OPTG[o]||(OPTG[o]=[]),m=c[fl]||(c[fl]=new Map());let g=m.get(km);if(g===undefined){const x=optMode(o,l);m.set(km,g=x?x.g:0);}return g;}; +// Whether upgrade k changes what any optic carries on a subsea cable this long (#198). has: the other upgrade is +// already in; otherwise k also counts when it only helps together with the other one. +const subOther=k=>k==='terminal'?'engineering':'terminal',subHelps=(km,k,has)=>{const j=subOther(k),c=(on,o)=>({kind:'df',own:true,sub:true,km,['sub'+k]:on?0:undefined,['sub'+j]:o?0:undefined}); + return (has?[1]:[0,1]).some(o=>Object.keys(OPT).some(x=>optG(x,c(1,o))!==optG(x,c(0,o))));}; const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/OPT[o].reach)-1); // The map asks for every fiber's capacity several times per frame (width, colour, label, up or down), each time over // all its channels. Nothing changes while a frame is drawn, so draw() keeps the answers in DFC for that frame. diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js index af3a450..474d618 100644 --- a/src/game/90-actions/87-fiber-and-hardware.js +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -1,12 +1,13 @@ Object.assign(ACT,{ dfMode:({m})=>{UI.lmode=m;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, - seaPackage:({k})=>{if(!own(SUB_UPGRADES,k))return;UI['sea'+k]=!UI['sea'+k];if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, - subUpgrade:({id,k})=>{const l=S.links.find(l=>l.id===id);if(!l||l.kind!=='df'||!l.own||!l.sub||!own(SUB_UPGRADES,k)||lvl()<4||l['sub'+k]!==undefined)return;if(!spend(subUpgradeCost(l,k)))return;l.paid=(l.paid>0?l.paid:ownCabCost(l.km))+subUpgradeCost(l,k);l['sub'+k]=Math.max(S.day,l.ready||0)+SUB_UPGRADES[k].days;after();}, + seaPackage:({k})=>{const p=UI.pending;if(!own(SUB_UPGRADES,k)||!p)return;const km=seaQuote(p.a,p.b,own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard').km,up=seaUps(km); + if(!up[k]&&!subHelps(km,k,up[subOther(k)]))return;UI.seaterminal=up.terminal;UI.seaengineering=up.engineering;UI['sea'+k]=!up[k];openLinkModal(p.a,p.b);}, + subUpgrade:({id,k})=>{const l=S.links.find(l=>l.id===id);if(!l||l.kind!=='df'||!l.own||!l.sub||!own(SUB_UPGRADES,k)||lvl()<4||l['sub'+k]!==undefined||!subHelps(l.km,k,l['sub'+subOther(k)]!==undefined))return;if(!spend(subUpgradeCost(l,k)))return;l.paid=(l.paid>0?l.paid:ownCabCost(l.km))+subUpgradeCost(l,k);l['sub'+k]=Math.max(S.day,l.ready||0)+SUB_UPGRADES[k].days;after();}, seaDesign:({v})=>{if(!own(SEA_DESIGNS,v))return;UI.seaDesign=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, ownCab:()=>{UI.lmode='df';UI.dfSrc='cable';UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, dfSrc:({v})=>{UI.dfSrc=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, dfSys:({v})=>{UI.dfSys=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, - orderCable:()=>{const p=UI.pending;if(!p)return;const {a,b}=p;if(ownCabWhy(a,b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up={terminal:!!UI.seaterminal,engineering:!!UI.seaengineering},q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return; + orderCable:()=>{const p=UI.pending;if(!p)return;const {a,b}=p;if(ownCabWhy(a,b))return;const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',up=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,up),km=q.km,cost=q.cost+(S.pops[b]?0:popCost(b));if(seaLack(km,up).length||!spend(cost))return; if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}; const used=new Set(S.links.map(l=>l.cname).filter(Boolean)),cname=OWNCAB_NAMES.find(n=>!used.has(n))||`${pick(OWNCAB_NAMES)} ${used.size+1}`,ship=pick(OWNCAB_SHIPS),id=uid(),days=q.days; S.links.push({id,a,b,kind:'df',own:true,sub:true,seaDesign:design,seaPath:q.pts.map(p=>p.slice()),sys:'roadm',ch:[],km,cable:null,cname,mo:Math.round(km*OWNCAB_OM),trench:'own:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:1}); diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 0378b3f..582542a 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -66,9 +66,9 @@ function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.d if(R.gfwCross>0.5)h+=`
${tr('link_panels.your_traffic_crossing_the_border')}${fmtG(R.gfwCross)}
${tr('link_panels.lost_on_the_way')}${fmtG(R.gfwLost)}
`; return h+``;} function subUpgradePanel(l){return `

${tr('common.submarine_transmission')}

${tr('common.better_terminals_and_optical_tuning')}

`+Object.entries(SUB_UPGRADES).map(([k,U])=>{ - const at=l['sub'+k],done=subUpgradeReady(l,k),cost=subUpgradeCost(l,k),preview={...l,['sub'+k]:S.day}; + const at=l['sub'+k],done=subUpgradeReady(l,k),cost=subUpgradeCost(l,k),preview={...l,['sub'+k]:S.day},use=at!==undefined||subHelps(l.km,k,l['sub'+subOther(k)]!==undefined); const status=done?tr('common.installed'):at!==undefined?tr('link_panels.ready_in_n_days',{n:Math.max(0,at-S.day)}):tr('link_panels.price_n_days',{price:fmt$(cost),n:U.days}); - return `
${tr(U.n)}
${status}
${tr('common.up_to_g_per_channel',{g:fmtG(submarineRate(preview))})}
${at===undefined?btn(tr('common.install'),'subUpgrade',{id:l.id,k},'sm',lvl()<4||S.cash`;}).join('');} + return `
${tr(U.n)}
${status}
${tr('common.up_to_g_per_channel',{g:fmtG(submarineRate(preview))})}
${use?'':`
${tr('reach_and_subsea.makes_no_difference_on_this_cable')}
`}
${at===undefined?btn(tr('common.install'),'subUpgrade',{id:l.id,k},'sm',!use||lvl()<4||S.cash`;}).join('');} function dfPanel(l){ const load=R.load[l.id]||0,cap=dfCap(l),u=cap?load/cap:0,bld=l.ready>S.day,A=CITY[l.a].name,B=CITY[l.b].name,inc=S.inc.find(i=>i.ref===l.id||i.ref===(l.trench||l.id)),amps=ampCount(l.km),sysD=DF_SYS[l.sys]; let h=`
${tr('link_panels.dark_fiber_kind_km_km',{kind:l.own?tr('link_panels.your_own_build'):tr('common.leased_iru'),km:l.km.toLocaleString()})}

${A} ⇄ ${B}

`; diff --git a/src/game/95-modals/80-own-cable.js b/src/game/95-modals/80-own-cable.js index aaa986e..630d0c9 100644 --- a/src/game/95-modals/80-own-cable.js +++ b/src/game/95-modals/80-own-cable.js @@ -183,6 +183,10 @@ function seaQuote(a,b,design='standard',upgrades={}){ const ms=linkLat({a,b,kind:'df',own:true,sub:true,km,seaDesign:design}); return {km,cost,days,ms,pts:route?.pts,shore:route?.shore,cor:!!cor&&route===cor}; } +// The picked upgrades that change something on a cable this long (#198): a pick can stop helping when the design +// or the other pick changes. When each makes the other redundant, keep the cheaper terminals. +const seaUps=km=>{const up={terminal:!!UI.seaterminal,engineering:!!UI.seaengineering}; + for(const k of ['engineering','terminal'])if(up[k]&&!subHelps(km,k,up[subOther(k)]))up[k]=false;return up;}; // Some pairs share a landmass and still have cables between them (Marseille–Singapore, Cairo–Palermo) (#67). const seaCab=(a,b)=>isSub(a,b)||(landing(a)&&landing(b)&&cablesFor(a,b).length>0); // What you get back for giving up your own subsea cable (#88): what you paid for it (design and upgrades included) @@ -200,10 +204,10 @@ function ownCabWhy(a,b){if(!seaCab(a,b))return tr('own_cable.this_route_is_on_la return '';} function ownCabTeaser(a,b){const why=ownCabWhy(a,b);return `
${btn(S.won?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},S.won&&!why?'pink':'ghost',!!why)}
${why&&S.won?`

${esc(why)}

`:''}`;} function ownCabBody(a,b,pop){const why=ownCabWhy(a,b);if(why)return `

${esc(why)}

${btn(tr('common.back'),'dfSrc',{v:'lease'},'ghost sm')}`; - const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',upgrades={terminal:!!UI.seaterminal,engineering:!!UI.seaengineering},q=seaQuote(a,b,design,upgrades),{km,cost,days}=q,lack=seaLack(km,upgrades),mo=ownCabMo(km),wt=subMaxTier(km),w=Math.round(waveMo(km,true,wt)*waveMarket(a,b,true).m),save=10*w*LT[4].g/LT[wt].g-mo,pay=save>0?Math.ceil(cost/save):0; + const design=own(SEA_DESIGNS,UI.seaDesign)?UI.seaDesign:'standard',upgrades=seaUps(seaQuote(a,b,design).km),q=seaQuote(a,b,design,upgrades),{km,cost,days}=q,lack=seaLack(km,upgrades),mo=ownCabMo(km),wt=subMaxTier(km),w=Math.round(waveMo(km,true,wt)*waveMarket(a,b,true).m),save=10*w*LT[4].g/LT[wt].g-mo,pay=save>0?Math.ceil(cost/save):0; return `

${tr('own_cable.your_very_own_subsea_cable_a')}

${tr('common.cable_design')}

${Object.entries(SEA_DESIGNS).map(([v,D])=>{const o=seaQuote(a,b,v,upgrades);return ``;}).join('')}
-

${tr('common.submarine_transmission')}

${Object.entries(SUB_UPGRADES).map(([k,U])=>btn(`${tr(U.n)} ${upgrades[k]?'✓ · ':''}${fmt$(subUpgradeCost({km},k))} · ${tr('own_cable.n_days',{n:U.days})}`,'seaPackage',{k},upgrades[k]?'green sm':'ghost sm')).join('')} +

${tr('common.submarine_transmission')}

${Object.entries(SUB_UPGRADES).map(([k,U])=>btn(`${tr(U.n)} ${upgrades[k]?'✓ · ':''}${fmt$(subUpgradeCost({km},k))} · ${tr('own_cable.n_days',{n:U.days})}`,'seaPackage',{k},upgrades[k]?'green sm':'ghost sm',!upgrades[k]&&!subHelps(km,k,upgrades[subOther(k)]))).join('')} ${lack.length?`

${lack[0]==='design'?tr('own_cable.this_design_s_route_is_km',{km:km.toLocaleString()}):tr('own_cable.km_km_is_too_far_for',{km:km.toLocaleString(),what:lack.length>1?tr('own_cable.a_and_b',{a:tr(SUB_UPGRADES[lack[0]].n),b:tr(SUB_UPGRADES[lack[1]].n)}):tr(SUB_UPGRADES[lack[0]].n)})}

`:`

${tr('common.up_to_g_per_channel',{g:fmtG(submarineRate({a,b,km,kind:'df',own:true,sub:true,subterminal:upgrades.terminal?S.day:undefined,subengineering:upgrades.engineering?S.day:undefined}))})} · ${tr('common.better_terminals_and_optical_tuning')}

`}
${tr('common.estimated_latency')}${tr('common.ms_ms_one_way',{ms:q.ms.toFixed(1)})}
${tr('common.route')}${tr('own_cable.km_km_of_seabed',{km:km.toLocaleString()})}
diff --git a/src/i18n/en.js b/src/i18n/en.js index 008cdfd..4212756 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2660,6 +2660,7 @@ "progress.under_attack_now":"Under attack now", "progress.your_score_peak_traffic":"Your score: peak traffic", "progress.your_traffic_to_and_from_asia":"Your traffic to and from Asia", +"reach_and_subsea.makes_no_difference_on_this_cable":"Makes no difference on this cable", "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/tests/regions.test.js b/tests/regions.test.js index 1ac3be1..b2dc55c 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -898,10 +898,11 @@ test('submarine terminal and engineering upgrades commission independently and c test('new subsea builds include chosen transmission packages in the quote and saved order', () => { const { ev, dom, errors } = load(); try { - ev("ACT.start({});S.cash=1e9;S.lvl=4;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'lon'});ACT.buildPop({city:'nyc'});UI.lmode='df';UI.dfSrc='cable';openLinkModal('lon','nyc')"); - const baseline = JSON.parse(ev("JSON.stringify(seaQuote('lon','nyc'))")); + ev("ACT.start({});S.cash=1e9;S.lvl=4;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'sin'});ACT.buildPop({city:'lax'});UI.lmode='df';UI.dfSrc='cable';openLinkModal('sin','lax')"); + // Across the Pacific, where the two packages together lift it from 400G to 800G (#198). + const baseline = JSON.parse(ev("JSON.stringify(seaQuote('sin','lax'))")); ev("document.querySelector('#modalCard [data-act=seaPackage][data-args*=terminal]').click();document.querySelector('#modalCard [data-act=seaPackage][data-args*=engineering]').click()"); - const quote = JSON.parse(ev("JSON.stringify(seaQuote('lon','nyc','standard',{terminal:true,engineering:true}))")); + const quote = JSON.parse(ev("JSON.stringify(seaQuote('sin','lax','standard',{terminal:true,engineering:true}))")); assert.equal(quote.days, baseline.days + 210); assert.equal(quote.cost, baseline.cost + 5000000 + 12000000 + baseline.km * 1000); assert.equal(quote.ms, baseline.ms); @@ -972,9 +973,12 @@ test('own subsea cables after #78: refunds of what was paid, upgrades a route ne const syd = JSON.parse(ev("JSON.stringify(S.links.at(-1))")); assert.equal(syd.b, 'syd'); assert.equal(syd.subterminal, syd.ready); ev('S.day=S.links.at(-1).ready'); assert.equal(ev("optG('tp16',S.links.at(-1))"), 400, 'lit across 18,387 km'); - // upgrades bought later count toward the price; sanitize keeps a sane price and drops junk + // engineering adds nothing once the terminals light it (#198); upgrades bought later count toward the price ev("S.links.at(-1).subengineering=undefined;ACT.subUpgrade({id:S.links.at(-1).id,k:'engineering'})"); + assert.equal(ev('S.links.at(-1).paid'), syd.paid); + ev("S.links.at(-1).subterminal=undefined;ACT.subUpgrade({id:S.links.at(-1).id,k:'engineering'})"); assert.ok(ev('S.links.at(-1).paid') > syd.paid); + // sanitize keeps a sane price and drops junk ev("S.links.at(-1).paid='lots';S.links[0].paid=-5;S=sanitize(S)"); assert.equal(ev('S.links.at(-1).paid'), undefined); assert.equal(ev('S.links[0].paid'), undefined); // advice about upgrades only on cables you own diff --git a/tests/subsea-upgrade-timing.test.js b/tests/subsea-upgrade-timing.test.js index d2d6a55..0f88d39 100644 --- a/tests/subsea-upgrade-timing.test.js +++ b/tests/subsea-upgrade-timing.test.js @@ -4,7 +4,7 @@ const { load } = require('./harness'); function setup(ev) { ev(`ACT.start({});S.cash=1e11;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0; - S.links=[{id:'cable',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:7000,ch:[],day:100,ready:1000,cut:0,mo:1}];`); + S.links=[{id:'cable',a:'lag',b:'bde',kind:'df',own:true,sub:true,sys:'roadm',km:15000,ch:[],day:100,ready:1000,cut:0,mo:1}];`); } function dates(ev) { @@ -55,7 +55,7 @@ test('packages included in the original order stay aligned with its accelerated const { ev, dom } = load(); try { setup(ev); - ev("S.won=true;UI.pending={a:'lag',b:'bde'};UI.seaterminal=UI.seaengineering=true;ACT.orderCable();S.links=[S.links.at(-1)]"); + ev("S.won=true;UI.pending={a:'sin',b:'lax'};UI.seaterminal=UI.seaengineering=true;ACT.orderCable();S.links=[S.links.at(-1)]"); assert.equal(ev('S.links[0].subterminal'), ev('S.links[0].ready')); assert.equal(ev('S.links[0].subengineering'), ev('S.links[0].ready')); ev("ACT.crews({id:S.links[0].id})"); @@ -129,11 +129,11 @@ test('one-click completion costs the same as repeated crew hires and advances pe const button = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all); assert.ok(button && !button.disabled, 'one-click option is available'); const cash = ev('S.cash'); - assert.ok(button.textContent.includes(ev('fmt$(30*Math.round(15000+7000*6))')), 'full price is shown before purchase'); + assert.ok(button.textContent.includes(ev('fmt$(30*Math.round(15000+15000*6))')), 'full price is shown before purchase'); button.click(); const bulkDates = dates(ev), bulkCash = ev('S.cash'); assert.deepEqual(bulkDates, [101, 131, 281]); - assert.equal(cash - bulkCash, 30 * 57000); + assert.equal(cash - bulkCash, 30 * 105000); const after = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')]; assert.ok(after.every(b => b.disabled), 'both options stop at one day'); ev("ACT.crews({id:'cable',all:1})"); @@ -150,18 +150,18 @@ test('one-click completion is atomic when unaffordable and handles short or comp const { ev, dom } = load(); try { setup(ev); - ev("S.cash=30*57000-1;UI.sel={type:'link',id:'cable'};renderPanel()"); + ev("S.cash=30*105000-1;UI.sel={type:'link',id:'cable'};renderPanel()"); const bulk = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')].find(b => JSON.parse(b.dataset.args).all); assert.equal(bulk.disabled, true); ev("ACT.crews({id:'cable',all:1})"); - assert.equal(ev('S.cash'), 30 * 57000 - 1); + assert.equal(ev('S.cash'), 30 * 105000 - 1); assert.equal(ev('S.links[0].ready'), 1000, 'no partial purchase'); - ev("S.cash=57000;S.links[0].ready=102;ACT.crews({id:'cable',all:1})"); + ev("S.cash=105000;S.links[0].ready=102;ACT.crews({id:'cable',all:1})"); assert.equal(ev('S.cash'), 0); assert.equal(ev('S.links[0].ready'), 101, 'two days remaining costs one normal hire'); assert.match(dom.window.document.body.textContent, /Construction is 1 day ahead\./); - ev("S.cash=57000;S.day=101;ACT.crews({id:'cable',all:1})"); - assert.equal(ev('S.cash'), 57000, 'completed construction cannot be rushed'); + ev("S.cash=105000;S.day=101;ACT.crews({id:'cable',all:1})"); + assert.equal(ev('S.cash'), 105000, 'completed construction cannot be rushed'); ev("S.day=100;S.links[0].ready=1000;S.links[0].own=false;ACT.crews({id:'cable',all:1})"); assert.equal(ev('S.links[0].ready'), 1000, 'leased handovers cannot buy construction crews'); } finally { dom.window.close(); } diff --git a/tests/useless-subsea-upgrades.test.js b/tests/useless-subsea-upgrades.test.js new file mode 100644 index 0000000..b0f790c --- /dev/null +++ b/tests/useless-subsea-upgrades.test.js @@ -0,0 +1,86 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// #198: submarine upgrades that change nothing on a cable can't be bought. +function cable(ev, km) { + ev(`ACT.start({});S.cash=1e11;S.lvl=13;S.day=100;S.won=true;for(const g of GOALS)S.done[g.id]=0; + S.links=[{id:'c',a:'atn',b:'syd',kind:'df',own:true,sub:true,sys:'roadm',km:${km},ch:['tp16'],day:0,ready:50,cut:0,mo:1}]; + UI.sel={type:'link',id:'c'};renderPanel()`); +} +const installBtn = (dom, k) => dom.window.document.querySelector(`#panelBody [data-act=subUpgrade][data-args*="${k}"]`); + +test('#198 upgrades that do nothing on a long Pacific cable are disabled and refused', () => { + const { ev, dom, errors } = load(); + try { + cable(ev, 17500); // about Atlanta to Sydney: 400G per channel with or without upgrades + for (const k of ['terminal', 'engineering']) { + assert.equal(installBtn(dom, k).disabled, true, `${k} button disabled`); + const cash = ev('S.cash'); + ev(`ACT.subUpgrade({id:'c',k:'${k}'})`); + assert.equal(ev('S.cash'), cash, `${k}: no charge`); + assert.equal(ev(`S.links[0].sub${k}`), undefined, `${k}: not installed`); + } + assert.match(dom.window.document.getElementById('panelBody').textContent, /Makes no difference on this cable/); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); + +test('#198 upgrades that only help together stay buyable, and one made useless by the other is not', () => { + const { ev, dom, errors } = load(); + try { + cable(ev, 15000); // each alone: 400G, both: 800G + assert.equal(installBtn(dom, 'terminal').disabled, false); + assert.equal(installBtn(dom, 'engineering').disabled, false); + ev("ACT.subUpgrade({id:'c',k:'terminal'})"); + assert.ok(ev('S.links[0].subterminal') > 0, 'terminal bought'); + ev('renderPanel()'); + assert.equal(installBtn(dom, 'engineering').disabled, false, 'engineering finishes the job'); + ev("ACT.subUpgrade({id:'c',k:'engineering'})"); + assert.ok(ev('S.links[0].subengineering') > 0, 'engineering bought'); + + cable(ev, 20000); // terminal lights it; engineering adds nothing once terminal is in + ev("ACT.subUpgrade({id:'c',k:'terminal'});renderPanel()"); + assert.ok(ev('S.links[0].subterminal') > 0); + assert.equal(installBtn(dom, 'engineering').disabled, true); + ev("ACT.subUpgrade({id:'c',k:'engineering'})"); + assert.equal(ev('S.links[0].subengineering'), undefined); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); + +test('#198 ordering a cable: useless upgrades can not be picked, and stale picks are not charged', () => { + const { ev, dom, errors } = load(); + try { + ev("ACT.start({});S.cash=1e11;S.lvl=13;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'lon'});ACT.buildPop({city:'nyc'});UI.lmode='df';UI.dfSrc='cable';UI.seaDesign='standard';openLinkModal('lon','nyc')"); + // A transatlantic cable already runs every optic at its long-haul best. + const btn = k => dom.window.document.querySelector(`#modalCard [data-act=seaPackage][data-args*="${k}"]`); + assert.equal(btn('terminal').disabled, true); + assert.equal(btn('engineering').disabled, true); + ev("ACT.seaPackage({k:'terminal'})"); + assert.equal(ev('!!UI.seaterminal'), false, 'refused'); + // Picks left over from a longer route (or a different design) neither show as picked nor get charged. + ev("UI.seaterminal=true;UI.seaengineering=true;ACT.seaDesign({v:'standard'})"); + assert.equal(btn('terminal').textContent.includes('✓'), false); + assert.equal(btn('engineering').textContent.includes('✓'), false); + const cash = ev('S.cash'), cost = ev("seaQuote('lon','nyc','standard').cost"); + ev('ACT.orderCable()'); + assert.equal(cash - ev('S.cash'), cost, 'no upgrade charged'); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); + +test('#198 ordering a transpacific cable: both upgrades help together, and the redundant one of a pair drops out', () => { + const { ev, dom, errors } = load(); + try { + ev("ACT.start({});S.cash=1e11;S.lvl=13;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'sin'});ACT.buildPop({city:'lax'});UI.lmode='df';UI.dfSrc='cable';ACT.ownCab();UI.pending={a:'sin',b:'lax'};openLinkModal('sin','lax')"); + const km = ev("seaQuote('sin','lax','standard').km"); + assert.ok(km > 14000 && km < 17000, 'a route where only both upgrades together beat 400G'); + ev("ACT.seaPackage({k:'terminal'});ACT.seaPackage({k:'engineering'})"); + assert.equal(ev('!!UI.seaterminal&&!!UI.seaengineering'), true, 'both picked'); + assert.equal(ev("JSON.stringify(seaUps(seaQuote('sin','lax','standard').km))"), '{"terminal":true,"engineering":true}'); + // At 20,000 km either one alone lights the cable, so a pair keeps only the cheaper terminals. + assert.equal(ev("JSON.stringify(seaUps(20000))"), '{"terminal":true,"engineering":false}'); + assert.deepEqual(errors, []); + } finally { dom.window.close(); } +}); From b9b55f1deb40861d7891299b6665d486fca78fdb Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 06:58:34 +0100 Subject: [PATCH 080/181] Networks name their home consumer markets (cc): eyeball networks and the Tier 2 incumbents that sell to homes --- src/game/30-networks/10-networks.js | 164 +++++++++++++-------------- src/game/30-networks/30-long-tail.js | 84 +++++++------- 2 files changed, 124 insertions(+), 124 deletions(-) diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index 722e735..e24249d 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -6,14 +6,14 @@ const NETS=[ {id:'cog',name:'Cogentle',asn:714,type:'t1',pol:'restrictive',share:.04,price:3,col:'#B35CF0',pops:['hfx','bde','man','edi','bcn','mil','rom','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','dub','hel','sof','beg','tor','lax','mex','cph','icn','sea','sjc','dal','chi','ash','nyc','mia','sao','lon','ams','fra','par','mad','mrs','sto','sin','hkg','tok','rio','bue','scl','bog','lim','osa','waw','prg','vie','bud','buh','ist','kyv','kcy','van','ott','bru','oos','bet','ham','muc','dus','syd','per'],ix:[],blurb:tr('networks.cheapest_transit_on_the_map_famously')}, {id:'tat',name:'Ta-Ta Comms',asn:6543,type:'t1',pol:'restrictive',share:.04,price:9,col:'#6A4C93',pops:['tci','gum','mil','pmo','lis','nbo','cai','jkt','dxb','nyc','ash','lon','fra','mrs','lag','jnb','bom','sin','hkg','tok','del','maa','blr','hyd','cpt','fuj','auh','tpe','khi','dac','cbo','kul','bkk','jed','ruh','doh','jib','dar','mba','dkr'],ix:[],blurb:tr('networks.waves_goodbye_to_latency_across_the')}, {id:'drz',name:'Drizzle Electric',asn:9369,type:'t2',pol:'open',share:.04,price:4,col:'#1E90FF',auIx:['syd','mel','bne','per'],pops:['man','chc','edi','svg','bde','bcn','mil','rom','pmo','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','nbo','akl','per','jkt','mnl','dub','rek','tor','mtl','lax','mex','sof','osl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','hkg','sin','tok','syd','jnb','for','rio','bue','scl','lim','bog','pan','del','maa','blr','hyd','tpe','auh','cpt','mel','bne','osa','kul','bkk','sgn','khi','dac','cbo','waw','prg','vie','bud','buh','tll','ist','kyv','jed','ruh','doh','kcy','cal','van','ott','bru','oos','bet','ham','muc','ccs','lpb','alg','tun','cas','dkr','dus'],ix:'ALL',blurb:tr('networks.will_peer_with_anyone_anywhere')}, - {id:'tng',name:'Tangerine Telecom',asn:5115,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['tci','bcn','cai','nbo','dxb','par','mrs','mad','lon','ams','lag','jnb','waw','buh','dkr','abj','cas','tun','dla','fih','fdf','run','tnr'],ix:['bcn','par','mrs','mad','lon','ams','lag','jnb','waw','dkr','abj','cas','tun','dla','fih'],blurb:tr('networks.juicy_reach_into_europe_and_africa')}, - {id:'sgt',name:'SingTell',asn:7474,type:'t2',pol:'selective',minIx:15,minPni:40,share:.03,price:7,col:'#00A6A6',pops:['jkt','mnl','per','akl','icn','sin','hkg','tok','syd','bom','tpe','maa','kul','bkk','sgn','mel','bne'],ix:['sin','hkg','tok','bom','tpe','maa','kul','bkk'],blurb:tr('networks.sings_your_packets_across_asia')}, - {id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',pol:'paid',freeLv:7,paidFee:8000,share:.03,price:6,col:'#E63946',pops:['man','edi','mil','rom','lis','ath','nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa','ist','prg','bud','buh','doh','acc','dar','fih','mpm','dus'],ix:[],blurb:tr('networks.ended_free_peering_across_europe_and')}, - {id:'ctc',name:'China Telecomet',asn:4314,type:'t2',pol:'restrictive',share:.02,price:22,premium:2.5,premAt:['hkg','mos'],premOnly:['mos'],cn:true,col:'#0B5CAD',pops:['pek','sha','hkg','sin','tok','lon','fra','nyc','sjc'],ix:[],blurb:tr('networks.the_biggest_network_in_china_its')}, - {id:'cun',name:'China Unicorn',asn:4837,type:'t2',pol:'restrictive',share:.015,price:16,cn:true,col:'#D7000F',pops:['pek','sha','hkg','fra','sjc','lon'],ix:[],blurb:tr('networks.number_two_in_china_with_a')}, - {id:'cmb',name:'China Moble',asn:9880,type:'eye',pol:'paid',freeLv:10,paidFee:12000,share:.01,cn:true,col:'#0085CA',pops:['pek','sha','hkg'],ix:[],blurb:tr('networks.the_largest_mobile_network_on_earth')}, - {id:'cmc',name:'Comecast',asn:7227,type:'eye',pol:'selective',minIx:10,minPni:30,share:.03,col:'#2C7A7B',pops:['atn','den','bos','hou','phx','slc','ash','nyc','chi','sjc','sea','mia'],ix:['atn','den','bos','ash','nyc','chi','sjc','sea'],blurb:tr('networks.huge_eyeball_network_come_for_the')}, - {id:'dtk',name:'Doitsche Telekomm',asn:3203,type:'eye',pol:'paid',freeLv:6,paidFee:9000,share:.03,col:'#E20074',pops:['fra','ams','lon','ham','muc','dus'],ix:[],blurb:tr('networks.pink_eyeball_giant_peering_is')}, + {id:'tng',name:'Tangerine Telecom',asn:5115,type:'t2',cc:['CD','CI','CM','EG','ES','FR','MA','MG','MQ','PL','RE','RO','SN','TN'],pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['tci','bcn','cai','nbo','dxb','par','mrs','mad','lon','ams','lag','jnb','waw','buh','dkr','abj','cas','tun','dla','fih','fdf','run','tnr'],ix:['bcn','par','mrs','mad','lon','ams','lag','jnb','waw','dkr','abj','cas','tun','dla','fih'],blurb:tr('networks.juicy_reach_into_europe_and_africa')}, + {id:'sgt',name:'SingTell',asn:7474,type:'t2',cc:'SG',pol:'selective',minIx:15,minPni:40,share:.03,price:7,col:'#00A6A6',pops:['jkt','mnl','per','akl','icn','sin','hkg','tok','syd','bom','tpe','maa','kul','bkk','sgn','mel','bne'],ix:['sin','hkg','tok','bom','tpe','maa','kul','bkk'],blurb:tr('networks.sings_your_packets_across_asia')}, + {id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',cc:['CD','CZ','DE','EG','ES','GB','GR','IE','MZ','QA','TR','TZ','ZA'],pol:'paid',freeLv:7,paidFee:8000,share:.03,price:6,col:'#E63946',pops:['man','edi','mil','rom','lis','ath','nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa','ist','prg','bud','buh','doh','acc','dar','fih','mpm','dus'],ix:[],blurb:tr('networks.ended_free_peering_across_europe_and')}, + {id:'ctc',name:'China Telecomet',asn:4314,type:'t2',cc:'CN',pol:'restrictive',share:.02,price:22,premium:2.5,premAt:['hkg','mos'],premOnly:['mos'],cn:true,col:'#0B5CAD',pops:['pek','sha','hkg','sin','tok','lon','fra','nyc','sjc'],ix:[],blurb:tr('networks.the_biggest_network_in_china_its')}, + {id:'cun',name:'China Unicorn',asn:4837,type:'t2',cc:'CN',pol:'restrictive',share:.015,price:16,cn:true,col:'#D7000F',pops:['pek','sha','hkg','fra','sjc','lon'],ix:[],blurb:tr('networks.number_two_in_china_with_a')}, + {id:'cmb',name:'China Moble',asn:9880,type:'eye',cc:'CN',pol:'paid',freeLv:10,paidFee:12000,share:.01,cn:true,col:'#0085CA',pops:['pek','sha','hkg'],ix:[],blurb:tr('networks.the_largest_mobile_network_on_earth')}, + {id:'cmc',name:'Comecast',asn:7227,type:'eye',cc:'US',pol:'selective',minIx:10,minPni:30,share:.03,col:'#2C7A7B',pops:['atn','den','bos','hou','phx','slc','ash','nyc','chi','sjc','sea','mia'],ix:['atn','den','bos','ash','nyc','chi','sjc','sea'],blurb:tr('networks.huge_eyeball_network_come_for_the')}, + {id:'dtk',name:'Doitsche Telekomm',asn:3203,type:'eye',cc:'DE',pol:'paid',freeLv:6,paidFee:9000,share:.03,col:'#E20074',pops:['fra','ams','lon','ham','muc','dus'],ix:[],blurb:tr('networks.pink_eyeball_giant_peering_is')}, {id:'nfx',name:'NetChill',asn:2906,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.15,cache:{name:'Open Couch',min:12},col:'#C8102E',auIx:['syd','mel'],pops:ALLC,ix:'ALL',blurb:tr('networks.streams_40_of_evening_traffic_hands')}, {id:'ggl',name:'Goggle',asn:15961,type:'cdn',pol:'selective',minIx:5,minPni:30,share:.13,cache:{name:'Goggle Global Cache',min:15},col:'#3A7BEA',auIx:['syd','mel'],pops:ALLC,ix:'ALL',blurb:tr('networks.search_video_and_goggles_mostly')}, {id:'fbk',name:'Faceplant',asn:32943,type:'cdn',pol:'selective',minIx:5,minPni:25,share:.08,cache:{name:'Faceplant Node Thingy',min:10},col:'#3B5BDB',auIx:['syd','mel'],pops:BIGC,ix:'ALL',blurb:tr('networks.social_media_everyone_keeps_falling')}, @@ -29,96 +29,96 @@ NETS.push( {id:'abc',name:'AliBubble Cloud',asn:37936,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.015,cn:true,col:'#FF6A00',pops:['pek','sha','hkg','sin','tok','fra','sjc','syd'],ix:['hkg','sin','tok','fra','sjc'],blurb:tr('networks.shopping_festivals_that_melt_traffic')}, {id:'byd',name:'Bye-du',asn:38635,type:'cdn',pol:'selective',minIx:5,minPni:20,share:.01,cn:true,col:'#2932E1',pops:['pek','sha','hkg'],ix:['hkg'],blurb:tr('networks.search_maps_and_a_cheerful_goodbye')}); NETS.push( - {id:'rtc',name:'Rostelecomedy',asn:12389,type:'t2',pol:'selective',minIx:20,minPni:40,share:.01,price:6,col:'#7700FF',pops:['mos','hel','sto','fra','ams','mmk','vvo','uus','pkc','gdx','dyr','pvs','tik','dks'],ix:['mos','fra','ams'],blurb:tr('networks.the_national_carrier_every_punchline')}, + {id:'rtc',name:'Rostelecomedy',asn:12389,type:'t2',cc:'RU',pol:'selective',minIx:20,minPni:40,share:.01,price:6,col:'#7700FF',pops:['mos','hel','sto','fra','ams','mmk','vvo','uus','pkc','gdx','dyr','pvs','tik','dks'],ix:['mos','fra','ams'],blurb:tr('networks.the_national_carrier_every_punchline')}, {id:'ydx',name:'Yawndex',asn:13238,type:'cdn',pol:'open',share:.008,col:'#FC3F1D',pops:['mos','hel','fra','ams'],ix:['mos','hel','fra','ams'],blurb:tr('networks.search_taxis_and_maps_slightly')}, {id:'vkl',name:'VKontakt-lens',asn:47541,type:'cdn',pol:'open',share:.006,col:'#0077FF',pops:['mos','hel'],ix:['mos','hel'],blurb:tr('networks.social_network_with_perfect_vision')}, - {id:'ets',name:'Etis-a-lot',asn:5384,type:'eye',pol:'paid',freeLv:9,paidFee:8000,share:.006,col:'#719E19',pops:['dxb','mrs','lon','fra','sin','auh','fuj','doh'],ix:[],blurb:tr('networks.charges_a_lot_paid_peering_only')}, - {id:'tmx',name:'Tel-Mess',asn:8151,type:'eye',pol:'paid',freeLv:8,paidFee:7000,share:.008,col:'#00A0DF',pops:['mex','dal','lax','mia','qro','mty','gdl'],ix:[],blurb:tr('networks.mexico_s_giant_paid_peering_only')}, - {id:'bcd',name:'Bell Canad-eh',asn:577,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#00549A',pops:['hfx','tor','mtl','nyc','chi','ott','cal','van'],ix:['tor','mtl','ott'],blurb:tr('networks.polite_enormous_and_sorry_about_the')}); + {id:'ets',name:'Etis-a-lot',asn:5384,type:'eye',cc:'AE',pol:'paid',freeLv:9,paidFee:8000,share:.006,col:'#719E19',pops:['dxb','mrs','lon','fra','sin','auh','fuj','doh'],ix:[],blurb:tr('networks.charges_a_lot_paid_peering_only')}, + {id:'tmx',name:'Tel-Mess',asn:8151,type:'eye',cc:'MX',pol:'paid',freeLv:8,paidFee:7000,share:.008,col:'#00A0DF',pops:['mex','dal','lax','mia','qro','mty','gdl'],ix:[],blurb:tr('networks.mexico_s_giant_paid_peering_only')}, + {id:'bcd',name:'Bell Canad-eh',asn:577,type:'eye',cc:'CA',pol:'selective',minIx:10,minPni:30,share:.01,col:'#00549A',pops:['hfx','tor','mtl','nyc','chi','ott','cal','van'],ix:['tor','mtl','ott'],blurb:tr('networks.polite_enormous_and_sorry_about_the')}); NETS.push( - {id:'tsf',name:'Telkom-selfie',asn:7713,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,col:'#E4002B',pops:['jkt','sin'],ix:['jkt','sin'],blurb:tr('networks.indonesia_s_mobile_giant_every')}, - {id:'pld',name:'PLDTea Time',asn:9299,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,up:['ntt','tat'],col:'#D62027',pops:['mnl','hkg','sin'],ix:['hkg'],blurb:tr('networks.philippine_giant_peering_requests')}, - {id:'spk',name:'Spark-le',asn:4771,type:'eye',pol:'open',share:.005,col:'#6A2C91',pops:['akl','syd','chc','ivc'],ix:['akl','syd','chc'],blurb:tr('networks.new_zealand_s_shiniest_isp')}, - {id:'tsy',name:'Telstraya',asn:1221,type:'t2',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['hnl','gum','suv','pom','nou','hir','syd','per','sin','hkg','lax','tpe','mel','bne','drw','adl','cbr','hba'],ix:['gum','sin','hkg'],blurb:tr('networks.australia_s_big_one_g_day')}); + {id:'tsf',name:'Telkom-selfie',asn:7713,type:'eye',cc:'ID',pol:'selective',minIx:10,minPni:30,share:.01,col:'#E4002B',pops:['jkt','sin'],ix:['jkt','sin'],blurb:tr('networks.indonesia_s_mobile_giant_every')}, + {id:'pld',name:'PLDTea Time',asn:9299,type:'eye',cc:'PH',pol:'selective',minIx:10,minPni:30,share:.008,up:['ntt','tat'],col:'#D62027',pops:['mnl','hkg','sin'],ix:['hkg'],blurb:tr('networks.philippine_giant_peering_requests')}, + {id:'spk',name:'Spark-le',asn:4771,type:'eye',cc:'NZ',pol:'open',share:.005,col:'#6A2C91',pops:['akl','syd','chc','ivc'],ix:['akl','syd','chc'],blurb:tr('networks.new_zealand_s_shiniest_isp')}, + {id:'tsy',name:'Telstraya',asn:1221,type:'t2',cc:'AU',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['hnl','gum','suv','pom','nou','hir','syd','per','sin','hkg','lax','tpe','mel','bne','drw','adl','cbr','hba'],ix:['gum','sin','hkg'],blurb:tr('networks.australia_s_big_one_g_day')}); NETS.push( - {id:'liq',name:'Liquid Lunch Networks',asn:30846,type:'t2',pol:'open',up:['tat','tly'],share:.006,price:6,col:'#00A0DF',pops:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],ix:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],blurb:tr('networks.cape_to_cairo_fiber_across_a')}, + {id:'liq',name:'Liquid Lunch Networks',asn:30846,type:'t2',cc:['ZW'],pol:'open',up:['tat','tly'],share:.006,price:6,col:'#00A0DF',pops:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],ix:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],blurb:tr('networks.cape_to_cairo_fiber_across_a')}, {id:'scm',name:'Sea-Comedy Networks',asn:37102,type:'t2',pol:'open',up:['ntt','tat'],share:.005,price:5,col:'#1C3F94',pops:['jnb','cpt','dur','mpm','dar','mba','nbo','kla','kgl','jib','cai','mrs','bom','lon'],ix:['jnb','cpt','dur','mpm','dar','mba','nbo','kla','jib','mrs'],blurb:tr('networks.owns_the_cable_that_brought_east')}, {id:'agc',name:'Angle-a Cables',asn:37470,type:'t2',pol:'open',up:['tly','cog'],share:.004,price:5,col:'#E30613',pops:['lad','fih','for','sao','mia','lon'],ix:['lad','for','sao','mia'],blurb:tr('networks.owns_the_cables_from_luanda_to')}, - {id:'djt',name:'Djibouti Calling',asn:30992,type:'t2',pol:'selective',up:['tat','tly'],minIx:3,minPni:15,share:.003,price:8,col:'#0D7F3F',pops:['jib','add','mrs','bom','jed'],ix:['jib'],blurb:tr('networks.a_tiny_telco_in_a_country')}, - {id:'mtx',name:'Empty-N',asn:29977,type:'eye',pol:'selective',up:['tat','lvl'],minIx:5,minPni:20,share:.008,col:'#FFCB05',pops:['lag','acc','abj','dla','kla','kgl','jnb','cpt','dur','lun','gbe','lad'],ix:['lag','acc','abj','dla','kla','kgl','jnb','cpt','dur','lun','gbe','lad'],blurb:tr('networks.africa_s_mobile_giant_in_a')}, - {id:'art',name:'Air-Tell Africa',asn:36928,type:'eye',pol:'selective',up:['tat','tly'],minIx:4,minPni:18,share:.006,col:'#ED1C24',pops:['lag','kla','kgl','dar','lun','fih','nbo','tnr','sez'],ix:['lag','kla','kgl','dar','lun','fih','nbo'],blurb:tr('networks.mobile_money_and_prepaid_data_in')}, - {id:'eth',name:'Ethio-Tele-Calm',asn:24759,type:'eye',pol:'selective',up:['tat'],minIx:2,minPni:12,share:.005,col:'#8DC63F',pops:['add'],ix:['add'],blurb:tr('networks.ethiopia_s_state_telco_a_hundred')}, - {id:'mrc',name:'Atlas Shrugged Telecom',asn:36905,type:'eye',pol:'selective',up:['lvl','tly'],minIx:3,minPni:15,share:.004,col:'#F28C00',pops:['cas','abj','dkr'],ix:['cas'],blurb:tr('networks.morocco_s_incumbent_with_sister')}, - {id:'sfc',name:'Safari-Comic',asn:33771,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,up:['cog','lvl','scm'],col:'#4CB848',pops:['nbo','mba','add'],ix:['nbo','mba','add'],blurb:tr('networks.kenya_s_mobile_giant_pays_you')}, - {id:'teg',name:'Tele-Comet Egypt',asn:8452,type:'t2',pol:'selective',minIx:15,minPni:40,share:.006,price:8,col:'#5B2D8E',pops:['cai','mrs','fra','lon'],ix:['cai','mrs'],blurb:tr('networks.owns_the_land_crossing_every_red')}); + {id:'djt',name:'Djibouti Calling',asn:30992,type:'t2',cc:'DJ',pol:'selective',up:['tat','tly'],minIx:3,minPni:15,share:.003,price:8,col:'#0D7F3F',pops:['jib','add','mrs','bom','jed'],ix:['jib'],blurb:tr('networks.a_tiny_telco_in_a_country')}, + {id:'mtx',name:'Empty-N',asn:29977,type:'eye',cc:['NG','GH','CI','CM','UG','RW','ZA','ZM'],pol:'selective',up:['tat','lvl'],minIx:5,minPni:20,share:.008,col:'#FFCB05',pops:['lag','acc','abj','dla','kla','kgl','jnb','cpt','dur','lun','gbe','lad'],ix:['lag','acc','abj','dla','kla','kgl','jnb','cpt','dur','lun','gbe','lad'],blurb:tr('networks.africa_s_mobile_giant_in_a')}, + {id:'art',name:'Air-Tell Africa',asn:36928,type:'eye',cc:['NG','UG','RW','TZ','ZM','CD','KE','MG','SC'],pol:'selective',up:['tat','tly'],minIx:4,minPni:18,share:.006,col:'#ED1C24',pops:['lag','kla','kgl','dar','lun','fih','nbo','tnr','sez'],ix:['lag','kla','kgl','dar','lun','fih','nbo'],blurb:tr('networks.mobile_money_and_prepaid_data_in')}, + {id:'eth',name:'Ethio-Tele-Calm',asn:24759,type:'eye',cc:'ET',pol:'selective',up:['tat'],minIx:2,minPni:12,share:.005,col:'#8DC63F',pops:['add'],ix:['add'],blurb:tr('networks.ethiopia_s_state_telco_a_hundred')}, + {id:'mrc',name:'Atlas Shrugged Telecom',asn:36905,type:'eye',cc:'MA',pol:'selective',up:['lvl','tly'],minIx:3,minPni:15,share:.004,col:'#F28C00',pops:['cas','abj','dkr'],ix:['cas'],blurb:tr('networks.morocco_s_incumbent_with_sister')}, + {id:'sfc',name:'Safari-Comic',asn:33771,type:'eye',cc:['KE','ET'],pol:'selective',minIx:5,minPni:20,share:.006,up:['cog','lvl','scm'],col:'#4CB848',pops:['nbo','mba','add'],ix:['nbo','mba','add'],blurb:tr('networks.kenya_s_mobile_giant_pays_you')}, + {id:'teg',name:'Tele-Comet Egypt',asn:8452,type:'t2',cc:'EG',pol:'selective',minIx:15,minPni:40,share:.006,price:8,col:'#5B2D8E',pops:['cai','mrs','fra','lon'],ix:['cai','mrs'],blurb:tr('networks.owns_the_land_crossing_every_red')}); NETS.push( - {id:'clr',name:'Clarovision',asn:28537,type:'t2',pol:'selective',minIx:10,minPni:30,share:.012,price:5,col:'#DA291C',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog','pan','mex','mia','sju','sdq'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog'],blurb:tr('networks.the_big_regional_carrier_sees')}, - {id:'viv',name:'Viva Vivo',asn:26959,type:'eye',pol:'selective',minIx:8,minPni:25,share:.01,col:'#660099',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.brazil_s_mobile_giant_very_much')}, - {id:'oio',name:'Oi Oi',asn:7739,type:'eye',pol:'selective',up:['lvl','tly'],minIx:6,minPni:20,share:.008,col:'#FFD000',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.says_oi_to_every_home_in')}, - {id:'tmt',name:'TIM-TIM Mobile',asn:26616,type:'eye',pol:'selective',up:['skl'],minIx:6,minPni:20,share:.007,col:'#004691',pops:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],ix:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],blurb:tr('networks.a_mobile_network_named_after_the')}, - {id:'bsn',name:'Brisanada',asn:28127,type:'eye',pol:'open',up:['lvl'],share:.004,col:'#F7941D',pops:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],ix:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],blurb:tr('networks.fiber_across_the_sertao_of_the')}, - {id:'mvs',name:'Moviestar',asn:12957,type:'t2',pol:'selective',up:['tly','lvl'],minIx:8,minPni:25,share:.008,price:6,col:'#019DF4',pops:['mex','gua','bog','mde','uio','lim','lpb','scl','bue','cor','mvd','ccs','sao','mia'],ix:['mex','bog','lim','scl','bue','mvd','ccs','sao'],blurb:tr('networks.a_spanish_carrier_starring_in_every')}, - {id:'llt',name:'Liberty Latte America',asn:23521,type:'t2',pol:'open',up:['lvl','cog'],share:.005,price:5,col:'#6C2C91',pops:['mia','pan','sjo','gua','bog','mde','ccs','sju','kin','nas','pos','bgi','cur'],ix:['pan','sjo','gua','bog','kin','pos'],blurb:tr('networks.cables_all_around_the_caribbean')}, - {id:'ant',name:'Antelope',asn:6058,type:'eye',pol:'selective',up:['skl','tly'],minIx:3,minPni:15,share:.004,col:'#0072BC',pops:['mvd'],ix:['mvd'],blurb:tr('networks.uruguay_s_state_telco_fast')}, - {id:'tgo',name:'Tiger Mobile',asn:27743,type:'eye',pol:'selective',up:['lvl'],minIx:4,minPni:15,share:.005,col:'#00377B',pops:['asu','lpb','gua','sjo','pan','bog','mde'],ix:['asu','lpb','gua','sjo','bog'],blurb:tr('networks.prepaid_mobile_from_paraguay_to')}, + {id:'clr',name:'Clarovision',asn:28537,type:'t2',cc:['AR','BR','CL','CO','CR','DO','EC','GT','PE','PR','PY','UY'],pol:'selective',minIx:10,minPni:30,share:.012,price:5,col:'#DA291C',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog','pan','mex','mia','sju','sdq'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix','mvd','asu','cor','uio','mde','gua','sjo','qro','mty','gdl','bue','scl','lim','bog'],blurb:tr('networks.the_big_regional_carrier_sees')}, + {id:'viv',name:'Viva Vivo',asn:26959,type:'eye',cc:'BR',pol:'selective',minIx:8,minPni:25,share:.01,col:'#660099',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.brazil_s_mobile_giant_very_much')}, + {id:'oio',name:'Oi Oi',asn:7739,type:'eye',cc:'BR',pol:'selective',up:['lvl','tly'],minIx:6,minPni:20,share:.008,col:'#FFD000',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.says_oi_to_every_home_in')}, + {id:'tmt',name:'TIM-TIM Mobile',asn:26616,type:'eye',cc:'BR',pol:'selective',up:['skl'],minIx:6,minPni:20,share:.007,col:'#004691',pops:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],ix:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],blurb:tr('networks.a_mobile_network_named_after_the')}, + {id:'bsn',name:'Brisanada',asn:28127,type:'eye',cc:'BR',pol:'open',up:['lvl'],share:.004,col:'#F7941D',pops:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],ix:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],blurb:tr('networks.fiber_across_the_sertao_of_the')}, + {id:'mvs',name:'Moviestar',asn:12957,type:'t2',cc:['CL','MX','VE'],pol:'selective',up:['tly','lvl'],minIx:8,minPni:25,share:.008,price:6,col:'#019DF4',pops:['mex','gua','bog','mde','uio','lim','lpb','scl','bue','cor','mvd','ccs','sao','mia'],ix:['mex','bog','lim','scl','bue','mvd','ccs','sao'],blurb:tr('networks.a_spanish_carrier_starring_in_every')}, + {id:'llt',name:'Liberty Latte America',asn:23521,type:'t2',cc:['BB','BS','CR','CW','JM','PA','PR','TT'],pol:'open',up:['lvl','cog'],share:.005,price:5,col:'#6C2C91',pops:['mia','pan','sjo','gua','bog','mde','ccs','sju','kin','nas','pos','bgi','cur'],ix:['pan','sjo','gua','bog','kin','pos'],blurb:tr('networks.cables_all_around_the_caribbean')}, + {id:'ant',name:'Antelope',asn:6058,type:'eye',cc:'UY',pol:'selective',up:['skl','tly'],minIx:3,minPni:15,share:.004,col:'#0072BC',pops:['mvd'],ix:['mvd'],blurb:tr('networks.uruguay_s_state_telco_fast')}, + {id:'tgo',name:'Tiger Mobile',asn:27743,type:'eye',cc:['PY','BO','GT','CR','PA','CO'],pol:'selective',up:['lvl'],minIx:4,minPni:15,share:.005,col:'#00377B',pops:['asu','lpb','gua','sjo','pan','bog','mde'],ix:['asu','lpb','gua','sjo','bog'],blurb:tr('networks.prepaid_mobile_from_paraguay_to')}, {id:'mlv',name:'Mercado Livre-ly',asn:52850,type:'cdn',pol:'open',share:.006,col:'#FFE600',pops:['sao','rio','bue','scl','bog','lim','mia'],ix:['sao','rio','bue','scl','bog','lim'],blurb:tr('networks.ships_parcels_and_packets_both')}, - {id:'jio',name:'Jio-graphy',asn:55863,type:'eye',pol:'selective',minIx:10,minPni:30,share:.02,col:'#0F3CC9',pops:['bom','del','maa','blr','hyd'],ix:['bom','del','maa','blr','hyd'],blurb:tr('networks.gave_a_billion_people_cheap_data')}, - {id:'atl',name:'Airtel-tale',asn:9849,type:'t2',pol:'selective',minIx:15,minPni:40,share:.01,price:7,col:'#E40000',pops:['bom','del','maa','blr','hyd','sin','lon','dxb','dac','cbo'],ix:['bom','del','maa','blr'],blurb:tr('networks.india_s_other_giant_every_outage')}, - {id:'cht',name:'Chunghwa Tele-calm',asn:3426,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#00A0E9',pops:['tpe','hkg','tok','lax','sin'],ix:['tpe','hkg'],blurb:tr('networks.taiwan_s_incumbent_stays_calm_while')}, - {id:'duu',name:'Du-opoly',asn:15820,type:'eye',pol:'paid',freeLv:11,paidFee:6000,share:.004,up:['tat','tly'],col:'#00A9CE',pops:['dxb','auh','fuj'],ix:[],blurb:tr('networks.the_other_half_of_the_uae')}); + {id:'jio',name:'Jio-graphy',asn:55863,type:'eye',cc:'IN',pol:'selective',minIx:10,minPni:30,share:.02,col:'#0F3CC9',pops:['bom','del','maa','blr','hyd'],ix:['bom','del','maa','blr','hyd'],blurb:tr('networks.gave_a_billion_people_cheap_data')}, + {id:'atl',name:'Airtel-tale',asn:9849,type:'t2',cc:'IN',pol:'selective',minIx:15,minPni:40,share:.01,price:7,col:'#E40000',pops:['bom','del','maa','blr','hyd','sin','lon','dxb','dac','cbo'],ix:['bom','del','maa','blr'],blurb:tr('networks.india_s_other_giant_every_outage')}, + {id:'cht',name:'Chunghwa Tele-calm',asn:3426,type:'t2',cc:'TW',pol:'selective',minIx:10,minPni:30,share:.008,price:7,col:'#00A0E9',pops:['tpe','hkg','tok','lax','sin'],ix:['tpe','hkg'],blurb:tr('networks.taiwan_s_incumbent_stays_calm_while')}, + {id:'duu',name:'Du-opoly',asn:15820,type:'eye',cc:'AE',pol:'paid',freeLv:11,paidFee:6000,share:.004,up:['tat','tly'],col:'#00A9CE',pops:['dxb','auh','fuj'],ix:[],blurb:tr('networks.the_other_half_of_the_uae')}); NETS.push( - {id:'kdi',name:'KD-DIY',asn:2561,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#E85D04',pops:['tok','osa','lax','sin','hkg','fuk'],ix:['tok','osa','fuk'],blurb:tr('networks.japanese_carrier_that_builds')}, - {id:'opt',name:'Floptus',asn:4804,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,up:['sgt'],col:'#00837E',pops:['syd','mel','bne','per'],ix:[],blurb:tr('networks.australia_s_number_two_once_took')}, - {id:'tpr',name:'Toilet Paper Group',asn:7545,type:'eye',pol:'selective',minIx:8,minPni:25,share:.0035,col:'#4E2A84',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.stockpiled_bandwidth_in_2020_and')}, - {id:'abb',name:'Aussie Boyband',asn:4764,type:'eye',pol:'open',share:.002,col:'#00B140',pops:['syd','mel','bne','per','adl','cbr','drw','hba'],ix:['syd','mel','bne','per','adl','drw'],blurb:tr('networks.matching_outfits_perfect_harmonies')}, + {id:'kdi',name:'KD-DIY',asn:2561,type:'t2',cc:'JP',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#E85D04',pops:['tok','osa','lax','sin','hkg','fuk'],ix:['tok','osa','fuk'],blurb:tr('networks.japanese_carrier_that_builds')}, + {id:'opt',name:'Floptus',asn:4804,type:'eye',cc:'AU',pol:'selective',minIx:8,minPni:25,share:.006,up:['sgt'],col:'#00837E',pops:['syd','mel','bne','per'],ix:[],blurb:tr('networks.australia_s_number_two_once_took')}, + {id:'tpr',name:'Toilet Paper Group',asn:7545,type:'eye',cc:'AU',pol:'selective',minIx:8,minPni:25,share:.0035,col:'#4E2A84',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.stockpiled_bandwidth_in_2020_and')}, + {id:'abb',name:'Aussie Boyband',asn:4764,type:'eye',cc:'AU',pol:'open',share:.002,col:'#00B140',pops:['syd','mel','bne','per','adl','cbr','drw','hba'],ix:['syd','mel','bne','per','adl','drw'],blurb:tr('networks.matching_outfits_perfect_harmonies')}, {id:'voc',name:'Hocus Pocus',asn:4826,type:'t2',pol:'open',up:['ntt','tly'],share:.002,price:7,col:'#E4002B',pops:['syd','mel','bne','per','adl','cbr','drw','hba','sin'],ix:['syd','mel','bne','per','adl','hba','drw','sin'],blurb:tr('networks.now_you_see_the_fibre_now')}, - {id:'ddo',name:'Doodoo',asn:9443,type:'eye',pol:'open',up:['voc'],share:.0011,col:'#FFC20E',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.the_cheapest_plan_in_the_country')}, - {id:'stb',name:'Musklink',asn:14593,type:'eye',pol:'selective',minIx:3,minPni:10,share:.001,col:'#1B1F24',pops:['syd','mel','bne','per','drw','sea','lax','dal','chi','ash'],ix:['mel','bne','per','drw'],blurb:tr('networks.beams_the_outback_online_from_550')}, - {id:'spl',name:'Speedyloop',asn:38195,type:'t2',pol:'open',up:['tly'],share:.001,price:6,col:'#FF5F00',pops:['syd','mel','bne','per','adl','sin','hkg','cbr','drw'],ix:['mel','bne','per','adl','hba','drw','sin','hkg'],blurb:tr('networks.speedy_by_name_owns_a_slice')}, - {id:'blg',name:'Beshort',asn:135887,type:'eye',pol:'selective',minIx:8,minPni:25,up:['tsy'],share:.0005,col:'#FF5A00',pops:['syd','mel','bne'],ix:[],blurb:tr('networks.telstraya_s_budget_brand_cheaper')}, - {id:'spn',name:'Spin2wintel',asn:18390,type:'eye',pol:'open',up:['voc'],share:.00015,col:'#0072CE',pops:['syd','mel','bne','per','adl'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.cheap_broadband_with_the_sales_pitch')}, - {id:'lpt',name:'Frogtel',asn:134090,type:'eye',pol:'open',share:.0001,col:'#7AC143',pops:['syd','mel','bne','adl','per','drw'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.small_fast_and_always_leaping_to')}, - {id:'ext',name:'Lintel',asn:10143,type:'eye',pol:'open',up:['spl'],share:.0001,col:'#F26522',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.bought_by_speedyloop_and_still')}, - {id:'tru',name:'Mostly-True Move',asn:7740,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#E4002B',pops:['bkk'],ix:['bkk'],blurb:tr('networks.thailand_s_mobile_giant_its_coverage')}, - {id:'vtl',name:'Viet-tell',asn:7525,type:'t2',pol:'selective',minIx:10,minPni:30,share:.005,price:7,col:'#EE0033',pops:['sgn','hkg','sin'],ix:['sgn'],blurb:tr('networks.vietnam_s_giant_will_tell_you')}, - {id:'ptc',name:'PTC-hell',asn:17577,type:'t2',pol:'selective',minIx:10,minPni:30,share:.004,price:8,col:'#00843D',pops:['khi','dxb'],ix:['khi'],blurb:tr('networks.pakistan_s_incumbent_every_session')}, - {id:'tmy',name:'Telekom Ma-lazy-sia',asn:4877,type:'t2',pol:'selective',minIx:10,minPni:30,share:.004,price:6,col:'#1F2A6B',pops:['kul','sin'],ix:['kul'],blurb:tr('networks.malaysia_s_incumbent_in_no_hurry')}, - {id:'ttk',name:'Türk Tele-komik',asn:9211,type:'t2',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#1D3F8F',pops:['ath','ist','fra','sof','lon'],ix:['ist'],blurb:tr('networks.bridges_europe_and_asia_and')}, - {id:'dgi',name:'Digi-tally Cheap',asn:8798,type:'eye',pol:'open',share:.006,col:'#2A5CAA',pops:['buh','bud','mad'],ix:['buh','bud','mad'],blurb:tr('networks.gigabit_to_every_flat_for_the')}, - {id:'ups',name:'UPC-You-Later',asn:6380,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,col:'#D8001B',pops:['waw','prg','vie','bud','zrh','kyv'],ix:['waw','prg','vie','kyv'],blurb:tr('networks.cable_broadband_across_central')}); + {id:'ddo',name:'Doodoo',asn:9443,type:'eye',cc:'AU',pol:'open',up:['voc'],share:.0011,col:'#FFC20E',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.the_cheapest_plan_in_the_country')}, + {id:'stb',name:'Musklink',asn:14593,type:'eye',cc:'US',pol:'selective',minIx:3,minPni:10,share:.001,col:'#1B1F24',pops:['syd','mel','bne','per','drw','sea','lax','dal','chi','ash'],ix:['mel','bne','per','drw'],blurb:tr('networks.beams_the_outback_online_from_550')}, + {id:'spl',name:'Speedyloop',asn:38195,type:'t2',cc:'AU',pol:'open',up:['tly'],share:.001,price:6,col:'#FF5F00',pops:['syd','mel','bne','per','adl','sin','hkg','cbr','drw'],ix:['mel','bne','per','adl','hba','drw','sin','hkg'],blurb:tr('networks.speedy_by_name_owns_a_slice')}, + {id:'blg',name:'Beshort',asn:135887,type:'eye',cc:'AU',pol:'selective',minIx:8,minPni:25,up:['tsy'],share:.0005,col:'#FF5A00',pops:['syd','mel','bne'],ix:[],blurb:tr('networks.telstraya_s_budget_brand_cheaper')}, + {id:'spn',name:'Spin2wintel',asn:18390,type:'eye',cc:'AU',pol:'open',up:['voc'],share:.00015,col:'#0072CE',pops:['syd','mel','bne','per','adl'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.cheap_broadband_with_the_sales_pitch')}, + {id:'lpt',name:'Frogtel',asn:134090,type:'eye',cc:'AU',pol:'open',share:.0001,col:'#7AC143',pops:['syd','mel','bne','adl','per','drw'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.small_fast_and_always_leaping_to')}, + {id:'ext',name:'Lintel',asn:10143,type:'eye',cc:'AU',pol:'open',up:['spl'],share:.0001,col:'#F26522',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.bought_by_speedyloop_and_still')}, + {id:'tru',name:'Mostly-True Move',asn:7740,type:'eye',cc:'TH',pol:'selective',minIx:5,minPni:20,share:.006,col:'#E4002B',pops:['bkk'],ix:['bkk'],blurb:tr('networks.thailand_s_mobile_giant_its_coverage')}, + {id:'vtl',name:'Viet-tell',asn:7525,type:'t2',cc:'VN',pol:'selective',minIx:10,minPni:30,share:.005,price:7,col:'#EE0033',pops:['sgn','hkg','sin'],ix:['sgn'],blurb:tr('networks.vietnam_s_giant_will_tell_you')}, + {id:'ptc',name:'PTC-hell',asn:17577,type:'t2',cc:'PK',pol:'selective',minIx:10,minPni:30,share:.004,price:8,col:'#00843D',pops:['khi','dxb'],ix:['khi'],blurb:tr('networks.pakistan_s_incumbent_every_session')}, + {id:'tmy',name:'Telekom Ma-lazy-sia',asn:4877,type:'t2',cc:'MY',pol:'selective',minIx:10,minPni:30,share:.004,price:6,col:'#1F2A6B',pops:['kul','sin'],ix:['kul'],blurb:tr('networks.malaysia_s_incumbent_in_no_hurry')}, + {id:'ttk',name:'Türk Tele-komik',asn:9211,type:'t2',cc:'TR',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#1D3F8F',pops:['ath','ist','fra','sof','lon'],ix:['ist'],blurb:tr('networks.bridges_europe_and_asia_and')}, + {id:'dgi',name:'Digi-tally Cheap',asn:8798,type:'eye',cc:['ES','RO'],pol:'open',share:.006,col:'#2A5CAA',pops:['buh','bud','mad'],ix:['buh','bud','mad'],blurb:tr('networks.gigabit_to_every_flat_for_the')}, + {id:'ups',name:'UPC-You-Later',asn:6380,type:'eye',cc:['PL','CZ','AT','HU','CH'],pol:'selective',minIx:8,minPni:25,share:.006,col:'#D8001B',pops:['waw','prg','vie','bud','zrh','kyv'],ix:['waw','prg','vie','kyv'],blurb:tr('networks.cable_broadband_across_central')}); NETS.push( - {id:'tlu',name:'Tell Us',asn:852,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,up:['lvl','tly'],col:'#4B286D',pops:['van','cal','tor','mtl','ott','sea','prr'],ix:['van','cal','tor'],blurb:tr('networks.western_canada_s_incumbent_tell_us')}, - {id:'rgc',name:'Bodgers Communications',asn:812,type:'eye',pol:'selective',minIx:10,minPni:30,share:.01,up:['cog','ntt'],col:'#DA291C',pops:['tor','ott','mtl','van','cal'],ix:['tor','ott','van'],blurb:tr('networks.canada_s_cable_giant_held_together')}); + {id:'tlu',name:'Tell Us',asn:852,type:'eye',cc:'CA',pol:'selective',minIx:10,minPni:30,share:.008,up:['lvl','tly'],col:'#4B286D',pops:['van','cal','tor','mtl','ott','sea','prr'],ix:['van','cal','tor'],blurb:tr('networks.western_canada_s_incumbent_tell_us')}, + {id:'rgc',name:'Bodgers Communications',asn:812,type:'eye',cc:'CA',pol:'selective',minIx:10,minPni:30,share:.01,up:['cog','ntt'],col:'#DA291C',pops:['tor','ott','mtl','van','cal'],ix:['tor','ott','van'],blurb:tr('networks.canada_s_cable_giant_held_together')}); NETS.push( - {id:'tny',name:'Telenyet',asn:6848,type:'eye',pol:'selective',minIx:10,minPni:30,share:.008,up:['lvl'],col:'#FFC421',pops:['bru','oos','ams','fra','lon'],ix:['bru'],blurb:tr('networks.half_of_the_flanders_duopoly_on')}, - {id:'pxm',name:'Proxyminus',asn:5432,type:'eye',pol:'selective',minIx:15,minPni:40,share:.008,up:['bgs','lvl'],col:'#5C2D91',pops:['bru','oos','ams'],ix:['bru'],blurb:tr('networks.the_other_half_of_the_duopoly')}, + {id:'tny',name:'Telenyet',asn:6848,type:'eye',cc:'BE',pol:'selective',minIx:10,minPni:30,share:.008,up:['lvl'],col:'#FFC421',pops:['bru','oos','ams','fra','lon'],ix:['bru'],blurb:tr('networks.half_of_the_flanders_duopoly_on')}, + {id:'pxm',name:'Proxyminus',asn:5432,type:'eye',cc:'BE',pol:'selective',minIx:15,minPni:40,share:.008,up:['bgs','lvl'],col:'#5C2D91',pops:['bru','oos','ams'],ix:['bru'],blurb:tr('networks.the_other_half_of_the_duopoly')}, {id:'bgs',name:'B.I.G.S.',asn:6774,type:'t2',pol:'selective',minIx:10,minPni:30,share:.005,price:5,up:['lvl'],col:'#7B2D8E',pops:['bru','bet','ams','fra','lon','par','mrs','nyc','sin'],ix:['bru','bet','ams','fra','lon','par'],blurb:tr('networks.proxyminus_s_wholesale_arm_present')}, - {id:'cit',name:'Citrus Belgium',asn:47377,type:'eye',pol:'selective',minIx:10,minPni:30,share:.005,up:['lvl'],col:'#FF7900',pops:['bru','par'],ix:['bru'],blurb:tr('networks.tangerine_s_belgian_daughter_mobile')}, - {id:'pst',name:'Poste Restante',asn:6663,type:'eye',pol:'selective',minIx:4,minPni:15,share:.001,up:['lvl','tly'],col:'#FFCC00',pops:['bet','fra','ams'],ix:['bet','fra'],blurb:tr('networks.luxembourg_s_post_office_which_also')}, - {id:'cms',name:'CityMess',asn:199095,type:'eye',pol:'open',share:.002,up:['cog'],col:'#00B2A9',pops:['oos','bru'],ix:['bru'],blurb:tr('networks.private_5g_and_business_fiber_from')}); -NETS.push({id:'kys',name:'Kyiv Superstar',asn:15859,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,up:['cog','tly'],col:'#0055B8',pops:['kyv','waw','fra'],ix:['kyv'],blurb:tr('networks.ukraine_s_biggest_mobile_network_has')}); -NETS.push({id:'stc',name:'Sticky Telecom',asn:39368,type:'t2',pol:'selective',minIx:10,minPni:30,share:.01,price:8,col:'#4F008C',pops:['ruh','jed','dxb','fra','lon','cai'],ix:['ruh'],blurb:tr('networks.the_kingdom_s_incumbent_once_you')}, - {id:'ord',name:'Ooh-redoo',asn:8871,type:'eye',pol:'paid',freeLv:11,paidFee:5000,share:.004,up:['tat','tly'],col:'#ED1C24',pops:['doh','dxb','jkt','mct'],ix:[],blurb:tr('networks.qatar_s_big_operator_paid_peering')}); + {id:'cit',name:'Citrus Belgium',asn:47377,type:'eye',cc:'BE',pol:'selective',minIx:10,minPni:30,share:.005,up:['lvl'],col:'#FF7900',pops:['bru','par'],ix:['bru'],blurb:tr('networks.tangerine_s_belgian_daughter_mobile')}, + {id:'pst',name:'Poste Restante',asn:6663,type:'eye',cc:'LU',pol:'selective',minIx:4,minPni:15,share:.001,up:['lvl','tly'],col:'#FFCC00',pops:['bet','fra','ams'],ix:['bet','fra'],blurb:tr('networks.luxembourg_s_post_office_which_also')}, + {id:'cms',name:'CityMess',asn:199095,type:'eye',cc:'BE',pol:'open',share:.002,up:['cog'],col:'#00B2A9',pops:['oos','bru'],ix:['bru'],blurb:tr('networks.private_5g_and_business_fiber_from')}); +NETS.push({id:'kys',name:'Kyiv Superstar',asn:15859,type:'eye',cc:'UA',pol:'selective',minIx:5,minPni:20,share:.006,up:['cog','tly'],col:'#0055B8',pops:['kyv','waw','fra'],ix:['kyv'],blurb:tr('networks.ukraine_s_biggest_mobile_network_has')}); +NETS.push({id:'stc',name:'Sticky Telecom',asn:39368,type:'t2',cc:'SA',pol:'selective',minIx:10,minPni:30,share:.01,price:8,col:'#4F008C',pops:['ruh','jed','dxb','fra','lon','cai'],ix:['ruh'],blurb:tr('networks.the_kingdom_s_incumbent_once_you')}, + {id:'ord',name:'Ooh-redoo',asn:8871,type:'eye',cc:['QA','OM','ID'],pol:'paid',freeLv:11,paidFee:5000,share:.004,up:['tat','tly'],col:'#ED1C24',pops:['doh','dxb','jkt','mct'],ix:[],blurb:tr('networks.qatar_s_big_operator_paid_peering')}); NETS.push( - {id:'tim',name:'TIM-Tam Italia',asn:3269,type:'eye',pol:'selective',minIx:8,minPni:25,share:.008,up:['skl'],col:'#004691',pops:['mil','rom','pmo'],ix:['mil','rom'],blurb:tr('networks.italy_s_incumbent_sweet_on_the')}, + {id:'tim',name:'TIM-Tam Italia',asn:3269,type:'eye',cc:'IT',pol:'selective',minIx:8,minPni:25,share:.008,up:['skl'],col:'#004691',pops:['mil','rom','pmo'],ix:['mil','rom'],blurb:tr('networks.italy_s_incumbent_sweet_on_the')}, {id:'skl',name:'Sparkly Seabone',asn:6762,type:'t1',pol:'restrictive',share:.04,price:6,col:'#5B2C83',pops:['pmo','mil','rom','ath','mrs','bcn','mad','lis','par','lon','ams','fra','zrh','vie','bud','prg','waw','buh','sof','ist','ber','sto','nyc','ash','mia','atn','dal','chi','lax','sjc','tor','mex','pan','bog','lim','scl','bue','sao','rio','for','cai','jed','dxb','bom','sin','hkg','tok','hav'],ix:[],blurb:tr('networks.the_tier_1_that_grew_up')}, - {id:'fwb',name:'Fast-Webby',asn:12874,type:'eye',pol:'open',share:.004,col:'#FDC300',pops:['mil','rom'],ix:['mil','rom'],blurb:tr('networks.fiber_to_the_italian_home_with')}, - {id:'meo',name:'MEO-w Portugal',asn:3243,type:'eye',pol:'selective',minIx:5,minPni:20,share:.004,col:'#00A3E0',pops:['pdl','lis','mad'],ix:['lis'],blurb:tr('networks.portugal_s_incumbent_purrs_when_you')}, - {id:'nos',name:'NOS-y Neighbour',asn:2860,type:'eye',pol:'open',share:.003,col:'#111111',pops:['lis'],ix:['lis'],blurb:tr('networks.peers_with_anyone_and_wants_to')}, - {id:'cos',name:'Cosmo-Note',asn:6799,type:'eye',pol:'selective',minIx:5,minPni:20,share:.004,col:'#7DC242',pops:['ath','sof'],ix:['ath'],blurb:tr('networks.greece_s_incumbent_takes_careful')}, - {id:'spc',name:'Spectre-um Cable',asn:20115,type:'eye',pol:'selective',minIx:12,minPni:35,share:.02,col:'#0099D8',pops:['nyc','lax','dal','chi','atn','den','phx','slc','hou','bos','sjc'],ix:['nyc','lax','dal','chi','atn','den'],blurb:tr('networks.cable_broadband_for_half_of_america')}, - {id:'vzn',name:'Very-Zone',asn:701,type:'eye',pol:'paid',paidFee:9000,share:.015,col:'#CD040B',pops:['nyc','ash','bos','dal','lax','chi','atn','mia'],ix:[],blurb:tr('networks.can_you_hear_me_now_only')}); + {id:'fwb',name:'Fast-Webby',asn:12874,type:'eye',cc:'IT',pol:'open',share:.004,col:'#FDC300',pops:['mil','rom'],ix:['mil','rom'],blurb:tr('networks.fiber_to_the_italian_home_with')}, + {id:'meo',name:'MEO-w Portugal',asn:3243,type:'eye',cc:'PT',pol:'selective',minIx:5,minPni:20,share:.004,col:'#00A3E0',pops:['pdl','lis','mad'],ix:['lis'],blurb:tr('networks.portugal_s_incumbent_purrs_when_you')}, + {id:'nos',name:'NOS-y Neighbour',asn:2860,type:'eye',cc:'PT',pol:'open',share:.003,col:'#111111',pops:['lis'],ix:['lis'],blurb:tr('networks.peers_with_anyone_and_wants_to')}, + {id:'cos',name:'Cosmo-Note',asn:6799,type:'eye',cc:'GR',pol:'selective',minIx:5,minPni:20,share:.004,col:'#7DC242',pops:['ath','sof'],ix:['ath'],blurb:tr('networks.greece_s_incumbent_takes_careful')}, + {id:'spc',name:'Spectre-um Cable',asn:20115,type:'eye',cc:'US',pol:'selective',minIx:12,minPni:35,share:.02,col:'#0099D8',pops:['nyc','lax','dal','chi','atn','den','phx','slc','hou','bos','sjc'],ix:['nyc','lax','dal','chi','atn','den'],blurb:tr('networks.cable_broadband_for_half_of_america')}, + {id:'vzn',name:'Very-Zone',asn:701,type:'eye',cc:'US',pol:'paid',paidFee:9000,share:.015,col:'#CD040B',pops:['nyc','ash','bos','dal','lax','chi','atn','mia'],ix:[],blurb:tr('networks.can_you_hear_me_now_only')}); NETS.push( {id:'att',name:'AT&Tease',asn:7018,type:'t1',pol:'restrictive',share:.02,price:8,col:'#00A8E0',pops:['nyc','ash','chi','dal','atn','lax','sjc','sea','mia','hou','lon','fra','ams','par'],ix:[],blurb:tr('networks.the_phone_company_s_favourite_child')}, - {id:'tmo',name:'Tee-Hee Mobile',asn:21928,type:'eye',pol:'selective',minIx:6,minPni:20,share:.01,up:['lvl','ntt'],col:'#E20074',pops:['nyc','bos','den','sea','sjc','lax','mia','chi','sju'],ix:['nyc','bos','den','sea','sjc','lax','mia','sju'],blurb:tr('networks.pink_loud_and_almost_entirely_ipv6')}, - {id:'cxc',name:'Coax Communications',asn:22773,type:'eye',pol:'selective',minIx:8,minPni:25,share:.006,up:['spc'],col:'#0072CE',pops:['ash','atn','bos','chi','dal','kcy','lax','nyc','sjc','phx'],ix:[],blurb:tr('networks.cable_broadband_for_the_sun_belt')}, - {id:'pes',name:'Pessimum',asn:6128,type:'eye',pol:'open',share:.005,up:['cog','lvl'],col:'#1A3D8F',pops:['nyc','ash','chi'],ix:['nyc','ash','chi'],blurb:tr('networks.expects_the_worst_from_every_link')}, - {id:'ftr',name:'Final Frontear',asn:5650,type:'eye',pol:'selective',minIx:6,minPni:20,share:.005,up:['vzn'],col:'#D2232A',pops:['ash','chi','dal','nyc','mia','lax'],ix:['ash','chi','dal','nyc','mia','lax'],blurb:tr('networks.fiber_to_30_million_homes_and')}, - {id:'gfb',name:'GFibber',asn:16591,type:'eye',pol:'open',share:.002,up:['lvl','cog'],col:'#34A853',pops:['kcy','ash','atn','chi','dal','den','nyc','phx','slc','sjc'],ix:['kcy','ash','atn','chi','dal','den','nyc','phx','slc','sjc'],blurb:tr('networks.started_in_kansas_city_in_2012')}, - {id:'snc',name:'Sonic Boomer',asn:46375,type:'eye',pol:'open',share:.0008,up:['cog','lvl'],col:'#F7A600',pops:['sjc'],ix:['sjc'],blurb:tr('networks.bay_area_fiber_with_an_old')}); + {id:'tmo',name:'Tee-Hee Mobile',asn:21928,type:'eye',cc:['US','PR'],pol:'selective',minIx:6,minPni:20,share:.01,up:['lvl','ntt'],col:'#E20074',pops:['nyc','bos','den','sea','sjc','lax','mia','chi','sju'],ix:['nyc','bos','den','sea','sjc','lax','mia','sju'],blurb:tr('networks.pink_loud_and_almost_entirely_ipv6')}, + {id:'cxc',name:'Coax Communications',asn:22773,type:'eye',cc:'US',pol:'selective',minIx:8,minPni:25,share:.006,up:['spc'],col:'#0072CE',pops:['ash','atn','bos','chi','dal','kcy','lax','nyc','sjc','phx'],ix:[],blurb:tr('networks.cable_broadband_for_the_sun_belt')}, + {id:'pes',name:'Pessimum',asn:6128,type:'eye',cc:'US',pol:'open',share:.005,up:['cog','lvl'],col:'#1A3D8F',pops:['nyc','ash','chi'],ix:['nyc','ash','chi'],blurb:tr('networks.expects_the_worst_from_every_link')}, + {id:'ftr',name:'Final Frontear',asn:5650,type:'eye',cc:'US',pol:'selective',minIx:6,minPni:20,share:.005,up:['vzn'],col:'#D2232A',pops:['ash','chi','dal','nyc','mia','lax'],ix:['ash','chi','dal','nyc','mia','lax'],blurb:tr('networks.fiber_to_30_million_homes_and')}, + {id:'gfb',name:'GFibber',asn:16591,type:'eye',cc:'US',pol:'open',share:.002,up:['lvl','cog'],col:'#34A853',pops:['kcy','ash','atn','chi','dal','den','nyc','phx','slc','sjc'],ix:['kcy','ash','atn','chi','dal','den','nyc','phx','slc','sjc'],blurb:tr('networks.started_in_kansas_city_in_2012')}, + {id:'snc',name:'Sonic Boomer',asn:46375,type:'eye',cc:'US',pol:'open',share:.0008,up:['cog','lvl'],col:'#F7A600',pops:['sjc'],ix:['sjc'],blurb:tr('networks.bay_area_fiber_with_an_old')}); NETS.push( - {id:'npt',name:'Neptoon Internet',asn:151660,type:'eye',pol:'open',share:.00008,col:'#3D5AFE',pops:['syd','mel','bne','per','adl'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.privacy_first_broadband_from_melbourne')}, - {id:'lnt',name:'Lawn-tel',asn:134697,type:'eye',pol:'selective',minIx:2,minPni:10,share:.00015,col:'#3FA34D',pops:['hba','syd','mel','bne','per','adl'],ix:['hba','syd','mel','bne','per','adl'],blurb:tr('networks.tasmania_s_own_mowing_its_way')}, - {id:'pnt',name:'Pent-Up Net',asn:10214,type:'eye',pol:'open',share:.0003,col:'#8E24AA',pops:['per','syd'],ix:['per','syd'],blurb:tr('networks.perth_wireless_and_fibre_pent_up')}, + {id:'npt',name:'Neptoon Internet',asn:151660,type:'eye',cc:'AU',pol:'open',share:.00008,col:'#3D5AFE',pops:['syd','mel','bne','per','adl'],ix:['syd','mel','bne','per','adl'],blurb:tr('networks.privacy_first_broadband_from_melbourne')}, + {id:'lnt',name:'Lawn-tel',asn:134697,type:'eye',cc:'AU',pol:'selective',minIx:2,minPni:10,share:.00015,col:'#3FA34D',pops:['hba','syd','mel','bne','per','adl'],ix:['hba','syd','mel','bne','per','adl'],blurb:tr('networks.tasmania_s_own_mowing_its_way')}, + {id:'pnt',name:'Pent-Up Net',asn:10214,type:'eye',cc:'AU',pol:'open',share:.0003,col:'#8E24AA',pops:['per','syd'],ix:['per','syd'],blurb:tr('networks.perth_wireless_and_fibre_pent_up')}, {id:'mag',name:'Dive-Bomb Magpie',asn:58511,type:'t2',pol:'open',up:['ntt','cog'],share:.0003,price:7,col:'#212121',pops:['syd','mel','bne','per','adl','akl','sin','sjc','sea','lon','ams','fra','par'],ix:['syd','mel','bne','per','adl','akl','sin','sjc','sea','lon','ams','fra','par'],blurb:tr('networks.dive_bombs_every_exchange_in_the')}, - {id:'inp',name:'Internope',asn:4739,type:'eye',pol:'restrictive',up:['tpr'],share:.0015,col:'#F57C00',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.once_the_nerds_favourite_isp_now')}); + {id:'inp',name:'Internope',asn:4739,type:'eye',cc:'AU',pol:'restrictive',up:['tpr'],share:.0015,col:'#F57C00',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.once_the_nerds_favourite_isp_now')}); diff --git a/src/game/30-networks/30-long-tail.js b/src/game/30-networks/30-long-tail.js index 321f35f..fd83534 100644 --- a/src/game/30-networks/30-long-tail.js +++ b/src/game/30-networks/30-long-tail.js @@ -74,51 +74,51 @@ TAIL.forEach(([name,type,home,blurb,sh],i)=>{const h=hstr(name),cand=home.flatMa const sel=(h>>>4)%10>=8; NETS.push({id:'tail'+i,name,asn:200000+(h%190000),type,tail:true,up:tailUp(name,home),pol:sel?'selective':'open',...(sel?{minIx:1+(h>>>16)%3,minPni:6+(h>>>18)%8}:{}),share:sh||+(0.0006+((h>>>20)%15)*0.0001).toFixed(4),col:`hsl(${h%360} 55% 46%)`,pops:home.slice(),ix,blurb});}); NETS.push( - {id:'ktt',name:'Kay-Tea',asn:4766,type:'eye',pol:'paid',paidFee:5000,perG:90,kr:true,share:.012,col:'#E4002B',pops:['icn','hkg','tok','lax'],ix:[],blurb:tr('long_tail.korea_s_incumbent_sender_pays_every')}, - {id:'skb',name:'SK Broadbandit',asn:9318,type:'eye',pol:'paid',paidFee:4000,perG:110,kr:true,share:.01,col:'#EA002C',pops:['icn','hkg','sjc'],ix:[],blurb:tr('long_tail.took_a_streaming_giant_to_court')}, - {id:'lgu',name:'LG You-Pay-Plus',asn:3786,type:'eye',pol:'paid',paidFee:3000,perG:80,kr:true,share:.008,col:'#E6007E',pops:['icn','tok'],ix:[],blurb:tr('long_tail.the_plus_is_a_usage_fee')}); + {id:'ktt',name:'Kay-Tea',asn:4766,type:'eye',cc:'KR',pol:'paid',paidFee:5000,perG:90,kr:true,share:.012,col:'#E4002B',pops:['icn','hkg','tok','lax'],ix:[],blurb:tr('long_tail.korea_s_incumbent_sender_pays_every')}, + {id:'skb',name:'SK Broadbandit',asn:9318,type:'eye',cc:'KR',pol:'paid',paidFee:4000,perG:110,kr:true,share:.01,col:'#EA002C',pops:['icn','hkg','sjc'],ix:[],blurb:tr('long_tail.took_a_streaming_giant_to_court')}, + {id:'lgu',name:'LG You-Pay-Plus',asn:3786,type:'eye',cc:'KR',pol:'paid',paidFee:3000,perG:80,kr:true,share:.008,col:'#E6007E',pops:['icn','tok'],ix:[],blurb:tr('long_tail.the_plus_is_a_usage_fee')}); NETS.push( - {id:'btt',name:'Bee-Tee',asn:2856,type:'eye',pol:'selective',minIx:10,minPni:30,share:.012,col:'#5514B4',pops:['lon','man','edi','bde'],ix:['lon','man'],blurb:tr('long_tail.the_uk_s_incumbent_buzzes_politely')}, - {id:'sky',name:'Sky-High Broadband',asn:5607,type:'eye',pol:'selective',minIx:6,minPni:25,share:.008,up:['tly','lvl'],col:'#0072C9',pops:['lon','man','edi','dub'],ix:['lon','man','edi'],blurb:tr('long_tail.football_films_and_a_router_that')}, - {id:'vmo',name:'Virgin Mediocre',asn:5089,type:'eye',pol:'selective',minIx:6,minPni:25,share:.007,up:['lvl','ntt'],col:'#E10A0A',pops:['lon','man','edi'],ix:['lon','man'],blurb:tr('long_tail.cable_broadband_for_half_of_britain')}, - {id:'tnr',name:'Tele-Nor-Way',asn:2119,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,up:['tly','lvl'],col:'#00A9E0',pops:['osl','svg','sto','cph','krs'],ix:['osl','svg'],blurb:tr('long_tail.norway_s_incumbent_neither_yes_nor')}); + {id:'btt',name:'Bee-Tee',asn:2856,type:'eye',cc:'GB',pol:'selective',minIx:10,minPni:30,share:.012,col:'#5514B4',pops:['lon','man','edi','bde'],ix:['lon','man'],blurb:tr('long_tail.the_uk_s_incumbent_buzzes_politely')}, + {id:'sky',name:'Sky-High Broadband',asn:5607,type:'eye',cc:['GB','IE'],pol:'selective',minIx:6,minPni:25,share:.008,up:['tly','lvl'],col:'#0072C9',pops:['lon','man','edi','dub'],ix:['lon','man','edi'],blurb:tr('long_tail.football_films_and_a_router_that')}, + {id:'vmo',name:'Virgin Mediocre',asn:5089,type:'eye',cc:'GB',pol:'selective',minIx:6,minPni:25,share:.007,up:['lvl','ntt'],col:'#E10A0A',pops:['lon','man','edi'],ix:['lon','man'],blurb:tr('long_tail.cable_broadband_for_half_of_britain')}, + {id:'tnr',name:'Tele-Nor-Way',asn:2119,type:'eye',cc:['NO','SE'],pol:'selective',minIx:5,minPni:20,share:.006,up:['tly','lvl'],col:'#00A9E0',pops:['osl','svg','sto','cph','krs'],ix:['osl','svg'],blurb:tr('long_tail.norway_s_incumbent_neither_yes_nor')}); NETS.push( - {id:'hwt',name:'Hawaiian Telecombo',asn:36149,type:'eye',pol:'selective',minIx:3,minPni:15,share:.004,up:['ntt','lvl'],col:'#5B2A86',pops:['hnl'],ix:['hnl'],blurb:tr('long_tail.hawaii_s_incumbent_every_plan_comes')}, - {id:'gtg',name:'Grand Theft Teleguam',asn:9246,type:'t2',pol:'open',share:.002,price:8,up:['ntt','tat'],col:'#0072CE',pops:['gum','ror','maj','hnl','tok'],ix:['gum','hnl'],blurb:tr('long_tail.guam_s_incumbent_and_the_way')}, - {id:'dcp',name:'Docomoco Pacific',asn:3605,type:'eye',pol:'selective',minIx:2,minPni:10,share:.002,up:['ntt'],col:'#E4002B',pops:['gum','ror'],ix:['gum'],blurb:tr('long_tail.guam_s_mobile_network_rice_a')}, - {id:'dsp',name:'Digi-Sell Pacific',asn:38442,type:'t2',pol:'open',share:.005,price:9,up:['ntt','tat'],col:'#E2001A',pops:['pom','suv','tbu','apw','syd'],ix:['suv'],blurb:tr('long_tail.phones_on_every_island_from_papua')}, + {id:'hwt',name:'Hawaiian Telecombo',asn:36149,type:'eye',cc:'US',pol:'selective',minIx:3,minPni:15,share:.004,up:['ntt','lvl'],col:'#5B2A86',pops:['hnl'],ix:['hnl'],blurb:tr('long_tail.hawaii_s_incumbent_every_plan_comes')}, + {id:'gtg',name:'Grand Theft Teleguam',asn:9246,type:'t2',cc:'GU',pol:'open',share:.002,price:8,up:['ntt','tat'],col:'#0072CE',pops:['gum','ror','maj','hnl','tok'],ix:['gum','hnl'],blurb:tr('long_tail.guam_s_incumbent_and_the_way')}, + {id:'dcp',name:'Docomoco Pacific',asn:3605,type:'eye',cc:'GU',pol:'selective',minIx:2,minPni:10,share:.002,up:['ntt'],col:'#E4002B',pops:['gum','ror'],ix:['gum'],blurb:tr('long_tail.guam_s_mobile_network_rice_a')}, + {id:'dsp',name:'Digi-Sell Pacific',asn:38442,type:'t2',cc:['FJ','PG','TO','WS'],pol:'open',share:.005,price:9,up:['ntt','tat'],col:'#E2001A',pops:['pom','suv','tbu','apw','syd'],ix:['suv'],blurb:tr('long_tail.phones_on_every_island_from_papua')}, {id:'fnt',name:'FINTEL-ligent',asn:9241,type:'t2',pol:'open',share:.002,price:8,up:['ntt','tly'],col:'#00A3AD',pops:['suv','tbu','apw','ppg','syd','hnl'],ix:['suv'],blurb:tr('long_tail.fiji_s_international_gateway_very')}, - {id:'pft',name:'Postes et Télé-Croissant',asn:56055,type:'t2',pol:'selective',minIx:3,minPni:15,share:.003,price:10,up:['tly','cog'],col:'#F7B500',pops:['nou','ppt','syd','lax'],ix:['nou'],blurb:tr('long_tail.runs_the_post_the_phones_and')}, - {id:'tkp',name:'Telly-Kom PNG',asn:17828,type:'eye',pol:'selective',minIx:2,minPni:10,share:.003,up:['tat'],col:'#C8102E',pops:['pom'],ix:[],blurb:tr('long_tail.papua_new_guinea_s_state_telco')}, - {id:'otk',name:'Ours-Truly Telekom',asn:45891,type:'eye',pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#00843D',pops:['hir'],ix:['hir'],blurb:tr('long_tail.the_solomon_islands_incumbent_yours')}, - {id:'tcc',name:'Tongue-in-Cheek Comms',asn:38201,type:'eye',pol:'selective',minIx:1,minPni:8,share:.001,up:['ntt'],col:'#C10230',pops:['tbu'],ix:[],blurb:tr('long_tail.tonga_s_own_telco_lived_through')}, - {id:'bsk',name:'Blue-Sky-Pie Samoa',asn:17993,type:'eye',pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#0096D6',pops:['apw','ppg'],ix:[],blurb:tr('long_tail.samoa_s_broadband_promised_with_a')}, - {id:'pnc',name:'PNC-See',asn:9534,type:'eye',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#1B75BB',pops:['ror'],ix:[],blurb:tr('long_tail.palau_s_telco_snorkel_down_and')}, - {id:'nta',name:'Never Too Atoll',asn:21581,type:'eye',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#2E8B57',pops:['maj'],ix:[],blurb:tr('long_tail.the_marshall_islands_telco_two')}); + {id:'pft',name:'Postes et Télé-Croissant',asn:56055,type:'t2',cc:['NC','PF'],pol:'selective',minIx:3,minPni:15,share:.003,price:10,up:['tly','cog'],col:'#F7B500',pops:['nou','ppt','syd','lax'],ix:['nou'],blurb:tr('long_tail.runs_the_post_the_phones_and')}, + {id:'tkp',name:'Telly-Kom PNG',asn:17828,type:'eye',cc:'PG',pol:'selective',minIx:2,minPni:10,share:.003,up:['tat'],col:'#C8102E',pops:['pom'],ix:[],blurb:tr('long_tail.papua_new_guinea_s_state_telco')}, + {id:'otk',name:'Ours-Truly Telekom',asn:45891,type:'eye',cc:'SB',pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#00843D',pops:['hir'],ix:['hir'],blurb:tr('long_tail.the_solomon_islands_incumbent_yours')}, + {id:'tcc',name:'Tongue-in-Cheek Comms',asn:38201,type:'eye',cc:'TO',pol:'selective',minIx:1,minPni:8,share:.001,up:['ntt'],col:'#C10230',pops:['tbu'],ix:[],blurb:tr('long_tail.tonga_s_own_telco_lived_through')}, + {id:'bsk',name:'Blue-Sky-Pie Samoa',asn:17993,type:'eye',cc:['WS','AS'],pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#0096D6',pops:['apw','ppg'],ix:[],blurb:tr('long_tail.samoa_s_broadband_promised_with_a')}, + {id:'pnc',name:'PNC-See',asn:9534,type:'eye',cc:'PW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#1B75BB',pops:['ror'],ix:[],blurb:tr('long_tail.palau_s_telco_snorkel_down_and')}, + {id:'nta',name:'Never Too Atoll',asn:21581,type:'eye',cc:'MH',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#2E8B57',pops:['maj'],ix:[],blurb:tr('long_tail.the_marshall_islands_telco_two')}); NETS.push( - {id:'onc',name:'One Commotion',asn:3855,type:'eye',pol:'selective',minIx:1,minPni:8,share:.001,up:['lvl','tly'],col:'#E4007C',pops:['bda'],ix:[],blurb:tr('long_tail.bermuda_s_phones_tv_and_internet')}, - {id:'cvt',name:'Curriculum Vitae Telecom',asn:37517,type:'t2',pol:'open',share:.002,price:8,up:['tat','tly'],col:'#004B87',pops:['rai','lis','for','dkr'],ix:['rai'],blurb:tr('long_tail.cape_verde_s_incumbent_and_the')}, - {id:'pss',name:'Pretty Sure South Atlantic',asn:210841,type:'t2',pol:'open',share:.0005,price:12,up:['tat'],col:'#7D2B8B',pops:['jam','cpt'],ix:[],blurb:tr('long_tail.the_telco_for_st_helena_ascension')}, - {id:'bst',name:'Beastlink',asn:11260,type:'eye',pol:'selective',minIx:2,minPni:10,share:.002,up:['cog','lvl'],col:'#EE3124',pops:['hfx','tor'],ix:['hfx'],blurb:tr('long_tail.atlantic_canada_s_cable_company')}); + {id:'onc',name:'One Commotion',asn:3855,type:'eye',cc:'BM',pol:'selective',minIx:1,minPni:8,share:.001,up:['lvl','tly'],col:'#E4007C',pops:['bda'],ix:[],blurb:tr('long_tail.bermuda_s_phones_tv_and_internet')}, + {id:'cvt',name:'Curriculum Vitae Telecom',asn:37517,type:'t2',cc:'CV',pol:'open',share:.002,price:8,up:['tat','tly'],col:'#004B87',pops:['rai','lis','for','dkr'],ix:['rai'],blurb:tr('long_tail.cape_verde_s_incumbent_and_the')}, + {id:'pss',name:'Pretty Sure South Atlantic',asn:210841,type:'t2',cc:'SH',pol:'open',share:.0005,price:12,up:['tat'],col:'#7D2B8B',pops:['jam','cpt'],ix:[],blurb:tr('long_tail.the_telco_for_st_helena_ascension')}, + {id:'bst',name:'Beastlink',asn:11260,type:'eye',cc:'CA',pol:'selective',minIx:2,minPni:10,share:.002,up:['cog','lvl'],col:'#EE3124',pops:['hfx','tor'],ix:['hfx'],blurb:tr('long_tail.atlantic_canada_s_cable_company')}); NETS.push( - {id:'dgc',name:'Digi-Sell Caribbean',asn:40786,type:'eye',pol:'open',share:.002,up:['tly','lvl'],col:'#E2001A',pops:['kin','pos','bgi','fdf','cur','mia'],ix:['kin'],blurb:tr('long_tail.the_same_phone_company_as_in')}, - {id:'wnt',name:'Whirled Net',asn:11367,type:'eye',pol:'open',share:.0005,up:['lvl'],col:'#1F6FB2',pops:['sju'],ix:['sju'],blurb:tr('long_tail.puerto_rico_s_own_business_isp')}, - {id:'cbh',name:'Cable Bahamamama',asn:15146,type:'eye',pol:'selective',minIx:2,minPni:10,share:.0008,up:['lvl','cog'],col:'#00A3AD',pops:['nas','mia'],ix:[],blurb:tr('long_tail.cable_tv_and_broadband_for_the')}, - {id:'etc',name:'Etecs-ah',asn:27725,type:'eye',pol:'open',share:.002,up:['skl'],col:'#0055A4',pops:['hav'],ix:[],blurb:tr('long_tail.cuba_s_state_telco_and_only')}, - {id:'tst',name:'TSTT (This Should Take Time)',asn:5639,type:'eye',pol:'selective',minIx:2,minPni:10,share:.001,up:['lvl'],col:'#C8102E',pops:['pos'],ix:['pos'],blurb:tr('long_tail.trinidad_and_tobago_s_incumbent_your')}, - {id:'cwt',name:'Curaçao Teal-ecom',asn:27660,type:'eye',pol:'open',share:.0004,up:['tly'],col:'#00A6A6',pops:['cur'],ix:['cur'],blurb:tr('long_tail.the_island_s_own_telco_the')}, - {id:'cnp',name:'Canal Minus',asn:21351,type:'eye',pol:'selective',minIx:2,minPni:8,share:.0006,up:['tly'],col:'#111111',pops:['fdf','run','par'],ix:['run'],blurb:tr('long_tail.french_pay_tv_that_also_runs')}, - {id:'zeo',name:'Zealot',asn:37002,type:'eye',pol:'open',share:.0005,up:['tly'],col:'#7A1FA2',pops:['run'],ix:['run'],blurb:tr('long_tail.r_union_s_fiber_challenger_very')}, - {id:'srr',name:'Signal Frequently Ruined',asn:49902,type:'eye',pol:'selective',minIx:1,minPni:8,share:.0005,up:['tly'],col:'#E2001A',pops:['run'],ix:['run'],blurb:tr('long_tail.mobile_and_broadband_on_r_union')}, - {id:'mtc',name:'Dodo Telecom',asn:23889,type:'t2',pol:'open',share:.001,price:9,up:['tat','tly'],col:'#D52B1E',pops:['mru','run','tnr','jnb','mrs'],ix:['mru'],blurb:tr('long_tail.the_island_s_incumbent_and_a')}, - {id:'emt',name:'Em-Tell',asn:30999,type:'eye',pol:'open',share:.0004,up:['tat'],col:'#00953B',pops:['mru'],ix:['mru'],blurb:tr('long_tail.mauritius_number_two_telling_everyone')}, - {id:'tlm',name:'Telmaybe',asn:37054,type:'t2',pol:'open',share:.0015,price:10,up:['tat','tly'],col:'#FFCC00',pops:['tnr','run','mru','jnb'],ix:['tnr'],blurb:tr('long_tail.madagascar_s_incumbent_and_the_only')}, - {id:'cws',name:'Cable & Witless Seychelles',asn:36958,type:'t2',pol:'open',share:.0003,price:12,up:['tat'],col:'#E4007C',pops:['sez','mba'],ix:[],blurb:tr('long_tail.the_seychelles_old_telco_open_to')}, - {id:'acs',name:'Alaska Commotions',asn:7782,type:'eye',pol:'open',share:.0008,up:['lvl','cog'],col:'#0072CE',pops:['anc','jnu','sea'],ix:['anc'],blurb:tr('long_tail.alaska_s_old_phone_company_and')}, - {id:'gci',name:'Glacier Comms Inc.',asn:8047,type:'t2',pol:'open',share:.0015,price:11,up:['lvl','ntt'],col:'#00467F',pops:['anc','jnu','ome','brw','dut','sea'],ix:['sea'],blurb:tr('long_tail.alaska_s_biggest_network_from_anchorage')}, - {id:'mgf',name:'MegaPhone',asn:31133,type:'eye',pol:'selective',minIx:4,minPni:15,share:.003,up:['rtc'],col:'#00B956',pops:['mos','vvo','uus','pkc','mmk','gdx'],ix:['mos','vvo'],blurb:tr('long_tail.one_of_russia_s_big_mobile')}, - {id:'ert',name:'Er-Um Telecom',asn:9049,type:'eye',pol:'open',share:.002,up:['rtc'],col:'#E30613',pops:['mos','vvo'],ix:['mos','vvo'],blurb:tr('long_tail.broadband_in_dozens_of_russian_cities')}); + {id:'dgc',name:'Digi-Sell Caribbean',asn:40786,type:'eye',cc:['JM','TT','BB','MQ','CW'],pol:'open',share:.002,up:['tly','lvl'],col:'#E2001A',pops:['kin','pos','bgi','fdf','cur','mia'],ix:['kin'],blurb:tr('long_tail.the_same_phone_company_as_in')}, + {id:'wnt',name:'Whirled Net',asn:11367,type:'eye',cc:'PR',pol:'open',share:.0005,up:['lvl'],col:'#1F6FB2',pops:['sju'],ix:['sju'],blurb:tr('long_tail.puerto_rico_s_own_business_isp')}, + {id:'cbh',name:'Cable Bahamamama',asn:15146,type:'eye',cc:'BS',pol:'selective',minIx:2,minPni:10,share:.0008,up:['lvl','cog'],col:'#00A3AD',pops:['nas','mia'],ix:[],blurb:tr('long_tail.cable_tv_and_broadband_for_the')}, + {id:'etc',name:'Etecs-ah',asn:27725,type:'eye',cc:'CU',pol:'open',share:.002,up:['skl'],col:'#0055A4',pops:['hav'],ix:[],blurb:tr('long_tail.cuba_s_state_telco_and_only')}, + {id:'tst',name:'TSTT (This Should Take Time)',asn:5639,type:'eye',cc:'TT',pol:'selective',minIx:2,minPni:10,share:.001,up:['lvl'],col:'#C8102E',pops:['pos'],ix:['pos'],blurb:tr('long_tail.trinidad_and_tobago_s_incumbent_your')}, + {id:'cwt',name:'Curaçao Teal-ecom',asn:27660,type:'eye',cc:'CW',pol:'open',share:.0004,up:['tly'],col:'#00A6A6',pops:['cur'],ix:['cur'],blurb:tr('long_tail.the_island_s_own_telco_the')}, + {id:'cnp',name:'Canal Minus',asn:21351,type:'eye',cc:['MQ','RE'],pol:'selective',minIx:2,minPni:8,share:.0006,up:['tly'],col:'#111111',pops:['fdf','run','par'],ix:['run'],blurb:tr('long_tail.french_pay_tv_that_also_runs')}, + {id:'zeo',name:'Zealot',asn:37002,type:'eye',cc:'RE',pol:'open',share:.0005,up:['tly'],col:'#7A1FA2',pops:['run'],ix:['run'],blurb:tr('long_tail.r_union_s_fiber_challenger_very')}, + {id:'srr',name:'Signal Frequently Ruined',asn:49902,type:'eye',cc:'RE',pol:'selective',minIx:1,minPni:8,share:.0005,up:['tly'],col:'#E2001A',pops:['run'],ix:['run'],blurb:tr('long_tail.mobile_and_broadband_on_r_union')}, + {id:'mtc',name:'Dodo Telecom',asn:23889,type:'t2',cc:'MU',pol:'open',share:.001,price:9,up:['tat','tly'],col:'#D52B1E',pops:['mru','run','tnr','jnb','mrs'],ix:['mru'],blurb:tr('long_tail.the_island_s_incumbent_and_a')}, + {id:'emt',name:'Em-Tell',asn:30999,type:'eye',cc:'MU',pol:'open',share:.0004,up:['tat'],col:'#00953B',pops:['mru'],ix:['mru'],blurb:tr('long_tail.mauritius_number_two_telling_everyone')}, + {id:'tlm',name:'Telmaybe',asn:37054,type:'t2',cc:'MG',pol:'open',share:.0015,price:10,up:['tat','tly'],col:'#FFCC00',pops:['tnr','run','mru','jnb'],ix:['tnr'],blurb:tr('long_tail.madagascar_s_incumbent_and_the_only')}, + {id:'cws',name:'Cable & Witless Seychelles',asn:36958,type:'t2',cc:'SC',pol:'open',share:.0003,price:12,up:['tat'],col:'#E4007C',pops:['sez','mba'],ix:[],blurb:tr('long_tail.the_seychelles_old_telco_open_to')}, + {id:'acs',name:'Alaska Commotions',asn:7782,type:'eye',cc:'US',pol:'open',share:.0008,up:['lvl','cog'],col:'#0072CE',pops:['anc','jnu','sea'],ix:['anc'],blurb:tr('long_tail.alaska_s_old_phone_company_and')}, + {id:'gci',name:'Glacier Comms Inc.',asn:8047,type:'t2',cc:'US',pol:'open',share:.0015,price:11,up:['lvl','ntt'],col:'#00467F',pops:['anc','jnu','ome','brw','dut','sea'],ix:['sea'],blurb:tr('long_tail.alaska_s_biggest_network_from_anchorage')}, + {id:'mgf',name:'MegaPhone',asn:31133,type:'eye',cc:'RU',pol:'selective',minIx:4,minPni:15,share:.003,up:['rtc'],col:'#00B956',pops:['mos','vvo','uus','pkc','mmk','gdx'],ix:['mos','vvo'],blurb:tr('long_tail.one_of_russia_s_big_mobile')}, + {id:'ert',name:'Er-Um Telecom',asn:9049,type:'eye',cc:'RU',pol:'open',share:.002,up:['rtc'],col:'#E30613',pops:['mos','vvo'],ix:['mos','vvo'],blurb:tr('long_tail.broadband_in_dozens_of_russian_cities')}); NETS.push( - {id:'tet',name:'Tet-à-Tête',asn:12578,type:'eye',pol:'selective',minIx:2,minPni:10,share:.001,up:['tly'],col:'#3F2A56',pops:['rix','sto'],ix:['rix'],blurb:tr('long_tail.latvia_s_incumbent_peers_face_to')}, - {id:'omt',name:'Omantell',asn:8529,type:'t2',pol:'selective',minIx:3,minPni:12,share:.002,price:9,up:['tat','tly'],col:'#2F6E3B',pops:['mct','fuj','mrs','lon','bom'],ix:['mct'],blurb:tr('long_tail.oman_s_incumbent_and_owner_of')}, - {id:'dhr',name:'Dhiraa-goo',asn:7642,type:'t2',pol:'open',share:.0003,price:12,up:['tat'],col:'#E2231A',pops:['mle','cbo'],ix:[],blurb:tr('long_tail.the_maldives_telco_on_islands_one')}); + {id:'tet',name:'Tet-à-Tête',asn:12578,type:'eye',cc:'LV',pol:'selective',minIx:2,minPni:10,share:.001,up:['tly'],col:'#3F2A56',pops:['rix','sto'],ix:['rix'],blurb:tr('long_tail.latvia_s_incumbent_peers_face_to')}, + {id:'omt',name:'Omantell',asn:8529,type:'t2',cc:'OM',pol:'selective',minIx:3,minPni:12,share:.002,price:9,up:['tat','tly'],col:'#2F6E3B',pops:['mct','fuj','mrs','lon','bom'],ix:['mct'],blurb:tr('long_tail.oman_s_incumbent_and_owner_of')}, + {id:'dhr',name:'Dhiraa-goo',asn:7642,type:'t2',cc:'MV',pol:'open',share:.0003,price:12,up:['tat'],col:'#E2231A',pops:['mle','cbo'],ix:[],blurb:tr('long_tail.the_maldives_telco_on_islands_one')}); From 8d722595006753cf18024b964657c006d9ea4e0d Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:00:34 +0100 Subject: [PATCH 081/181] 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; } From adc312f27b4685b71d3c7c3c84d022f48a746ddb Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:00:53 +0100 Subject: [PATCH 082/181] Map: test land polygons against their bounding box first The sea waves, hills and the far view's islet list test points against every coastline polygon while the page loads: about 0.8 s of a throttled phone's load. A point outside a ring's box is outside the ring, so nearly every test stops there. Waves, hills and the far view's islands come out byte-identical. --- src/game/96-map/20-land-and-clouds.js | 5 ++++- tests/load-time.test.js | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 tests/load-time.test.js diff --git a/src/game/96-map/20-land-and-clouds.js b/src/game/96-map/20-land-and-clouds.js index ed77503..00e3f3a 100644 --- a/src/game/96-map/20-land-and-clouds.js +++ b/src/game/96-map/20-land-and-clouds.js @@ -1,5 +1,8 @@ function rng(seed){return()=>{seed|=0;seed=seed+0x6D2B79F5|0;let t=Math.imul(seed^seed>>>15,1|seed);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};} -function inPoly(x,y,pts){let ins=false;for(let i=0,j=pts.length-1;iy)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;} +// A point outside a ring's bounding box is outside the ring: the box is kept on the ring, so the hundreds of tests +// at load (sea waves, hills, which islets the far view keeps) skip nearly every coastline without walking it. +const polyBox=pts=>{let b=pts.box;if(!b){let x0=Infinity,y0=Infinity,x1=-Infinity,y1=-Infinity;for(const [x,y] of pts){if(xx1)x1=x;if(yy1)y1=y;}b=pts.box=[x0,y0,x1,y1];}return b;}; +function inPoly(x,y,pts){const b=polyBox(pts);if(xb[2]||yb[3])return false;let ins=false;for(let i=0,j=pts.length-1;iy)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;} function smoothPath(pts){const p=new Path2D();const n=pts.length;const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(pts[n-1],pts[0]);p.moveTo(m[0],m[1]);for(let i=0;i { + const { ev, dom, errors } = load(); t.after(() => dom.window.close()); + const bad = ev(`(()=>{const plain=(x,y,pts)=>{let ins=false;for(let i=0,j=pts.length-1;iy)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;}; + let bad=0;for(let x=0;x Date: Thu, 29 Oct 2026 07:01:01 +0100 Subject: [PATCH 083/181] Map: a link's curve only measures the cities that could be in its way bezGeom() measured every city against every candidate curve, for every link the first time the map drew it. A curve stays inside the box of its end and control points, so a city further than the clearance it needs outside that box always measures as clear; leaving it out gives the same curve. About 4x faster, and the curves on the big fixture are byte-identical. --- src/game/96-map/50-link-geometry.js | 9 +++++++-- tests/load-time.test.js | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index f23175c..422b708 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -39,13 +39,18 @@ function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:l const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} const base=Math.max(4,Math.min(len*0.1,90)),step=Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?0.2:1)+Math.ceil(i/2)*step); const mx=(A.x+bx)/2,my=(A.y+by)/2; - const obs=CITIES.filter(c=>c.id!==l.a&&c.id!==l.b).map(c=>[mx+wrapDx(mx,c.x),c.y]); - const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(dMath.sign(o)*Math.min(Math.abs(o),cap); const cand=[1,1.5,2.1,2.9,3.8].map(k=>lim(sg*mag*k)).concat([1,1.5,2.1,2.9,3.8].map(k=>lim(-sg*Math.max(mag,base)*k))); + /* Only cities that could come within `need` of a candidate curve count: a curve stays inside the box of its end and + control points, so a city further than `need` outside the box of all of them only ever measures as clear, and + min(clearance, need) comes out the same without it (the map's first frame did this for every city and link). */ + let x0=Math.min(A.x,bx),x1=Math.max(A.x,bx),y0=Math.min(A.y,by),y1=Math.max(A.y,by); + for(const off of cand){const cx=mx+nx*off,cy=my+ny*off;if(cxx1)x1=cx;if(cyy1)y1=cy;} + const obs=[];for(const c of CITIES){if(c.id===l.a||c.id===l.b)continue;const ox=mx+wrapDx(mx,c.x),oy=c.y;if(ox>=x0-need&&ox<=x1+need&&oy>=y0-need&&oy<=y1+need)obs.push([ox,oy]);} + const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(d=need){best=[cx,cy];break;}const sc=Math.min(c,need)-Math.abs(off)*0.35;if(sc>bs){bs=sc;best=[cx,cy];}} const g={ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};GEO.set(key,g);return g;} diff --git a/tests/load-time.test.js b/tests/load-time.test.js index 3289529..b1a7a68 100644 --- a/tests/load-time.test.js +++ b/tests/load-time.test.js @@ -5,6 +5,24 @@ const { load } = require('./harness'); // Work done once when a game loads (the possible-diversity map, link curves, the map's sea and hills) has shortcuts; // each must give exactly what the plain version gives. +test('link curves: skipping far-away cities gives the same bend around the ones in the way', (t) => { + const { ev, dom, errors } = load(); t.after(() => dom.window.close()); + ev('ACT.start({})'); + // bezGeom() as it was: every other city is measured against every candidate curve. + ev(`window.plainGeom=(l,i)=>{const A=CITY[l.a],B=CITY[l.b];const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} + const base=Math.max(4,Math.min(len*0.1,90)),step=Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?0.2:1)+Math.ceil(i/2)*step);const mx=(A.x+bx)/2,my=(A.y+by)/2; + const obs=CITIES.filter(c=>c.id!==l.a&&c.id!==l.b).map(c=>[mx+wrapDx(mx,c.x),c.y]); + const clear=(cx,cy)=>{let m=Infinity;const g={ax:A.x,ay:A.y,bx,by,cx,cy};for(let t=0.08;t<0.93;t+=0.06){const [px,py]=qpt(g,t);for(const [ox,oy] of obs){const d=Math.hypot(px-ox,py-oy);if(dMath.sign(o)*Math.min(Math.abs(o),cap); + const cand=[1,1.5,2.1,2.9,3.8].map(k=>lim(sg*mag*k)).concat([1,1.5,2.1,2.9,3.8].map(k=>lim(-sg*Math.max(mag,base)*k)));let best=null,bs=-Infinity; + for(const off of cand){const cx=mx+nx*off,cy=my+ny*off,c=clear(cx,cy);if(c>=need){best=[cx,cy];break;}const sc=Math.min(c,need)-Math.abs(off)*0.35;if(sc>bs){bs=sc;best=[cx,cy];}} + return {ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};}`); + const bad = JSON.parse(ev(`(()=>{const ids=CITIES.map(c=>c.id),bad=[];for(let i=0;i { const { ev, dom, errors } = load(); t.after(() => dom.window.close()); const bad = ev(`(()=>{const plain=(x,y,pts)=>{let ins=false;for(let i=0,j=pts.length-1;iy)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;}; From 537ec4efd0d7a60f830635ab34457b9fa5f98926 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:01:18 +0100 Subject: [PATCH 084/181] Saves get the rules of their mode, whatever their rules say sanitize() trusted any preset and override in a save, so an edited or imported save could run a Normal game on puzzle rules (no clock, ever), On-call with infinite money and open gates, sandbox powers without the sandbox tag, or a scenario off On-call. Rules now follow the mode: scenarios and the weekly are On-call, a sandbox keeps only its chaos, a Normal game one of the three Normal presets unchanged. --- src/game/80-simulation/50-sanitize.js | 7 +++-- tests/rules-locked.test.js | 45 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 tests/rules-locked.test.js diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 44e8205..bdb268a 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -77,8 +77,11 @@ function sanitize(s){ 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';} 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:{});} + /* The rules (2.0) follow from the mode, as the doors set them, and nothing else: a save without them is the classic + game, On-call. Scenarios and the weekly run on On-call; a sandbox keeps only its chaos; a Normal game one of the + three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */ + {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; + const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} 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;} function migrate(s){sanitize(s); diff --git a/tests/rules-locked.test.js b/tests/rules-locked.test.js new file mode 100644 index 0000000..61d3941 --- /dev/null +++ b/tests/rules-locked.test.js @@ -0,0 +1,45 @@ +// The rules follow from the mode when a save loads: an edited or imported save cannot change them (2.0). +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('a loaded save gets the rules of its mode, whatever its rules say', () => { + const { ev, errors } = load(); + ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()"); + const base = JSON.parse(ev('JSON.stringify(packSave(S))')); + const loadAs = (mut) => { const s = JSON.parse(JSON.stringify(base)); mut(s); ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(s))}))`); return JSON.parse(ev('JSON.stringify(S.rules)')); }; + const preset = (p, o) => JSON.parse(ev(`JSON.stringify(makeRules('${p}'${o ? ',' + JSON.stringify(o) : ''}))`)); + // Normal games keep one of the three Normal presets, with nothing changed. + for (const p of ['freeze', 'oncall', 'bgp']) assert.deepEqual(loadAs(s => { s.rules = { preset: p }; }), preset(p)); + assert.deepEqual(loadAs(s => { s.rules = { preset: 'oncall', money: 'infinite', gates: 'open', chaos: 'none', lead: 'quick' }; }), preset('oncall'), 'no free money or open gates in On-call'); + assert.deepEqual(loadAs(s => { s.rules = { preset: 'freeze', clock: false }; }), preset('freeze'), 'the clock always runs'); + assert.deepEqual(loadAs(s => { s.rules = { preset: 'puzzle' }; }), preset('oncall'), 'no puzzle rules (clock off for ever) in a Normal game'); + assert.deepEqual(loadAs(s => { s.rules = { preset: 'sandbox' }; }), preset('oncall'), 'no sandbox powers without the sandbox tag'); + assert.deepEqual(loadAs(s => { delete s.rules; }), preset('oncall'), 'a save from before 2.0 is On-call'); + // Sandboxes keep only their chaos. + assert.deepEqual(loadAs(s => { s.mode = 'sandbox'; s.rules = { preset: 'sandbox', chaos: 'spicy', clock: false, money: 'normal' }; }), preset('sandbox', { chaos: 'spicy' })); + assert.deepEqual(loadAs(s => { s.mode = 'sandbox'; s.rules = { preset: 'bgp' }; }), preset('sandbox')); + // Scenarios and the weekly run on On-call. + const scn = { id: 'pac', rules: {}, days: 1095, name: 'x', mods: [] }; + for (const r of [{ preset: 'bgp' }, { preset: 'oncall', chaos: 'none' }, { preset: 'sandbox' }, { preset: 'freeze' }]) + assert.deepEqual(loadAs(s => { s.mode = 'scenario'; s.scn = scn; s.rules = r; }), preset('oncall'), JSON.stringify(r)); + assert.deepEqual(loadAs(s => { s.mode = 'scenario'; s.scn = { ...scn, id: 'weekly', key: '2026-W44' }; s.rules = { preset: 'freeze' }; }), preset('oncall'), 'the weekly too'); + assert.deepEqual(errors, []); +}); + +test('a save that claims to be a puzzle loads as a Normal On-call game with the clock running', () => { + const { ev, errors } = load(); + ev("beginGame('T','fra',{mode:'normal'});if(UI.pendGame)ACT.pitchSkip()"); + const s = JSON.parse(ev('JSON.stringify(packSave(S))')); + s.mode = 'puzzle'; s.rules = { preset: 'puzzle' }; + ev(`S=migrate(JSON.parse(${JSON.stringify(JSON.stringify(s))}));UI.started=true;compute()`); + assert.equal(ev('S.mode'), 'normal'); + assert.equal(ev('pzOn()'), false); + assert.equal(ev("rule('clock')"), true); + ev('for(let i=0;i<3;i++)dayTick()'); + assert.equal(ev('S.day'), 3, 'days pass'); + ev(`UI.importing=JSON.parse(${JSON.stringify(JSON.stringify(s))});ACT.importGo()`); + assert.equal(ev('S.mode'), 'normal'); + assert.equal(ev('rulePreset()'), 'oncall'); + assert.deepEqual(errors, []); +}); From 1692217549f4f81697ed22a9a16c4c6163a7eeb3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:03:39 +0100 Subject: [PATCH 085/181] Flood Season attacker names come only from the game's own list An imported save could put raw HTML in an attack's attacker name, which reached the end-of-flood toast unescaped. sanitize() keeps only names from the list, and the toast escapes the name and city anyway. --- src/game/80-simulation/50-sanitize.js | 1 + src/game/85-incidents/20-failures.js | 2 +- tests/ddos-floods.test.js | 10 ++++++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index bdb268a..c5bc597 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -67,6 +67,7 @@ function sanitize(s){ 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+Math.ceil(7*SPICY_LONG)); delete a.entries; // 2.0 betas spread attacks over every ingress port; they arrive on one again + if(a.who!==undefined&&!FLOOD_WHO.includes(a.who))delete a.who; // a label from the list, never text from the file 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'||!['t','ix','p','edge'].includes(a.entry.k))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); diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index d688fe6..33d4843 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -162,7 +162,7 @@ function ddosAttack(recompute=true){const type='ddos',fl=scnRule('ddos');ddosExp // 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=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('failures.flood_held_g_who_gave_up',{g:fmtG(a.gbps),who:who.charAt(0).toUpperCase()+who.slice(1)}):tr('failures.that_one_got_through_g_city',{g:fmtG(a.gbps),city:CITY[a.city]?CITY[a.city].name:tr('common.your_network'),p:pct(a.worst||0),who}),ok?'goal':'bad');}} + if(scnRule('ddos')){const w=tr(FLOOD_WHO.includes(a.who)?a.who:FLOOD_WHO[0]),who=esc(w.charAt(0).toUpperCase()+w.slice(1));toast(ok?tr('failures.flood_held_g_who_gave_up',{g:fmtG(a.gbps),who}):tr('failures.that_one_got_through_g_city',{g:fmtG(a.gbps),city:esc(CITY[a.city]?CITY[a.city].name:tr('common.your_network')),p:pct(a.worst||0),who:esc(w)}),ok?'goal':'bad');}} // Flood Season: 3 to 7 days apart as before, shrinking with age, level and gamers only when attacks are spicy. const floodGap=()=>!ddosSpicy()?3+Math.floor(Math.random()*5):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_('failures.a_botnet_of_40_000_smart'),N_('failures.every_unpatched_baby_monitor_in'),N_('failures.a_gaming_clan_that_lost_one'),N_('failures.a_fridge_that_achieved_sentience_and'),N_('failures.a_crypto_bro_shorting_your_stock'),N_('failures.a_teenager_with_a_stolen_credit'),N_('failures.a_rival_isp_s_stress_test'),N_('failures.ten_thousand_smart_light_bulbs'),N_('failures.a_printer_just_one_printer_nobody'),N_('failures.a_botnet_run_from_a_cloud'),N_('failures.somebody_who_did_not_like_your'),N_('failures.the_internet_connected_kettles_of_a')]; diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index 98efc9f..d6b0d40 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -113,3 +113,13 @@ test('BGP at 3 a.m. brings about twice On-call\'s DDoS; gaming customers bring t const ratio = picks.bgp / picks.oncall; assert.ok(ratio > 1.7 && ratio < 2.3, `about twice the DDoS (${ratio.toFixed(2)}x)`); }); + +test('an imported save cannot put HTML in a Flood Season attacker\'s name', () => { + const { ev, dom, errors } = load({ seed: 5 }); + ev("ACT.startScn({id:'flood',sure:1});S.day=10;ddosAttack();S.ev.ddos.who='';S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.ev.ddos.who'), undefined, 'only names from the list survive a load'); + ev('S.ev.ddos.who="";ddosDone(S.ev.ddos)'); + assert.equal(dom.window.document.getElementById('pwn'), null); + assert.equal(dom.window.document.getElementById('pwn2'), null, 'and the toast escapes it anyway'); + assert.deepEqual(errors, []); +}); From 4bb5e07c2847c7ae0e33c1043370e172c915e621 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:04:45 +0100 Subject: [PATCH 086/181] The China licence follows quick lead times: about 5 days instead of 45 Change Freeze and Sandbox deliver everything in a tenth of the time, but the licence still took 45 days and the button said so. It now waits leadDays(45), and the button shows that number. --- 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/90-actions/80-security-and-china.js | 2 +- src/game/93-ui/70-link-panels.js | 2 +- src/i18n/en.js | 2 +- tests/ddos-floods.test.js | 11 +++++++++++ 9 files changed, 19 insertions(+), 8 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 47eb899..b710e76 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2128,7 +2128,7 @@ "link_panels.add_parallel_link":"Parallelen Link hinzufügen", "link_panels.additional_traffic_lost":"Zusätzlich verlorener Traffic", "link_panels.an_alternate_path_exists_but_current":"Es gibt einen anderen Weg, aber mit dem jetzigen Routing und der Kapazität kommt weniger Traffic an.", -"link_panels.apply_for_a_license_price_mo":"Lizenz beantragen {price} + {mo}/Monat · ~45 Tage", +"link_panels.apply_for_a_license_price_mo_n_days":"Lizenz beantragen {price} + {mo}/Monat · ~{n} Tage", "link_panels.back_in_n_days":"Zurück in {n} Tagen.", "link_panels.behind_the_great_firewall":"Hinter der Großen Firewall", "link_panels.biggest_fabric_money_can_buy":"Die größte Fabric, die man für Geld kaufen kann.", diff --git a/site/i18n/es.js b/site/i18n/es.js index c5e8b29..e670864 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2126,7 +2126,7 @@ "link_panels.add_parallel_link":"Añadir enlace paralelo", "link_panels.additional_traffic_lost":"Tráfico perdido adicional", "link_panels.an_alternate_path_exists_but_current":"Hay un camino alternativo, pero con el routing y la capacidad actuales llega menos tráfico.", -"link_panels.apply_for_a_license_price_mo":"Solicitar una licencia {price} + {mo}/mes · ~45 días", +"link_panels.apply_for_a_license_price_mo_n_days":"Solicitar una licencia {price} + {mo}/mes · ~{n} días", "link_panels.back_in_n_days":"De vuelta en {n} días.", "link_panels.behind_the_great_firewall":"Tras el Gran Cortafuegos", "link_panels.biggest_fabric_money_can_buy":"La fabric más grande que el dinero puede comprar.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 30a346d..63f3195 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2126,7 +2126,7 @@ "link_panels.add_parallel_link":"Ajouter un lien parallèle", "link_panels.additional_traffic_lost":"Trafic perdu en plus", "link_panels.an_alternate_path_exists_but_current":"Un autre chemin existe, mais avec le routage et la capacité actuels, moins de trafic arrive.", -"link_panels.apply_for_a_license_price_mo":"Demander une licence {price} + {mo}/mois · ~45 jours", +"link_panels.apply_for_a_license_price_mo_n_days":"Demander une licence {price} + {mo}/mois · ~{n} jours", "link_panels.back_in_n_days":"Retour dans {n} jours.", "link_panels.behind_the_great_firewall":"Derrière le Grand Pare-feu", "link_panels.biggest_fabric_money_can_buy":"Le plus gros fabric que l’argent puisse acheter.", diff --git a/site/i18n/it.js b/site/i18n/it.js index a4b5b11..c183fe3 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2126,7 +2126,7 @@ "link_panels.add_parallel_link":"Aggiungi link parallelo", "link_panels.additional_traffic_lost":"Ulteriore traffico perso", "link_panels.an_alternate_path_exists_but_current":"Esiste un percorso alternativo, ma con routing e capacità attuali viene consegnato meno traffico.", -"link_panels.apply_for_a_license_price_mo":"Richiedi una licenza {price} + {mo}/mese · ~45 giorni", +"link_panels.apply_for_a_license_price_mo_n_days":"Richiedi una licenza {price} + {mo}/mese · ~{n} giorni", "link_panels.back_in_n_days":"Torna tra {n} giorni.", "link_panels.behind_the_great_firewall":"Dietro il Great Firewall", "link_panels.biggest_fabric_money_can_buy":"Il fabric più grosso che si possa comprare.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 4ac6bb9..e5b091c 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2126,7 +2126,7 @@ "link_panels.add_parallel_link":"Adicionar link paralelo", "link_panels.additional_traffic_lost":"Tráfego perdido a mais", "link_panels.an_alternate_path_exists_but_current":"Existe um caminho alternativo, mas com o roteamento e a capacidade atuais chega menos tráfego.", -"link_panels.apply_for_a_license_price_mo":"Pedir licença {price} + {mo}/mês · ~45 dias", +"link_panels.apply_for_a_license_price_mo_n_days":"Pedir licença {price} + {mo}/mês · ~{n} dias", "link_panels.back_in_n_days":"Volta em {n} dias.", "link_panels.behind_the_great_firewall":"Atrás do Great Firewall", "link_panels.biggest_fabric_money_can_buy":"O maior fabric que o dinheiro pode comprar.", diff --git a/src/game/90-actions/80-security-and-china.js b/src/game/90-actions/80-security-and-china.js index 3cba21f..b909a8c 100644 --- a/src/game/90-actions/80-security-and-china.js +++ b/src/game/90-actions/80-security-and-china.js @@ -1,5 +1,5 @@ Object.assign(ACT,{ - applyCn:()=>{if(S.cnLic.state!=='none')return;if(!spend(CN_LIC))return;S.cnLic={state:'pending',ready:S.day+45};toast(tr('security_and_china.application_filed_your_local_partner'),'goal');after();}, + applyCn:()=>{if(S.cnLic.state!=='none')return;if(!spend(CN_LIC))return;S.cnLic={state:'pending',ready:S.day+leadDays(45)};toast(tr('security_and_china.application_filed_your_local_partner'),'goal');after();}, togglePrem:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t||!premCity(NET[t.net],t.city)||premOnlyAt(NET[t.net],t.city))return;t.premium=!t.premium;sfx('click');after();}, buildScrub:({city,tier})=>{if(!S.pops[city]||S.scrubs.some(x=>x.city===city))return;const T=SCRUB_TIERS[tier||0];if(!T)return;if((lvl()||1){const x=S.scrubs.find(q=>q.city===city);tier=+tier;if(!x||!SCRUB_TIERS[tier]||tier<=(x.tier||0))return;const T=SCRUB_TIERS[tier];if((lvl()||1)`;} function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2; let h=`

${tr('link_panels.behind_the_great_firewall')}

${tr('link_panels.mainland_china_plays_by_its_own',{list:CN_BLOCKED.slice(0,4).map(esc).join(', '),pct:pct(loss)})}

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

${tr('link_panels.foreign_networks_need_a_local_joint')}

${btn(tr('link_panels.apply_for_a_license_price_mo',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO)}),'applyCn',{},'pink',S.cash${tr('link_panels.foreign_networks_need_a_local_joint')}

${btn(tr('link_panels.apply_for_a_license_price_mo_n_days',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO),n:leadDays(45)}),'applyCn',{},'pink',S.cash${tr('link_panels.license_paperwork_in_progress_n_days',{n:Math.max(0,S.cnLic.ready-S.day)})}

`; else h+=`

${tr('link_panels.your_joint_venture_holds_an')}

`; if(R.gfwCross>0.5)h+=`
${tr('link_panels.your_traffic_crossing_the_border')}${fmtG(R.gfwCross)}
${tr('link_panels.lost_on_the_way')}${fmtG(R.gfwLost)}
`; diff --git a/src/i18n/en.js b/src/i18n/en.js index 309e046..2b6cf52 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2127,7 +2127,7 @@ "link_panels.add_parallel_link":"Add parallel link", "link_panels.additional_traffic_lost":"Additional traffic lost", "link_panels.an_alternate_path_exists_but_current":"An alternate path exists, but current routing and capacity deliver less traffic.", -"link_panels.apply_for_a_license_price_mo":"Apply for a license {price} + {mo}/mo · ~45 days", +"link_panels.apply_for_a_license_price_mo_n_days":"Apply for a license {price} + {mo}/mo · ~{n} days", "link_panels.back_in_n_days":"Back in {n} days.", "link_panels.behind_the_great_firewall":"Behind the Great Firewall", "link_panels.biggest_fabric_money_can_buy":"Biggest fabric money can buy.", diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index d6b0d40..4415ad9 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -123,3 +123,14 @@ test('an imported save cannot put HTML in a Flood Season attacker\'s name', () = assert.equal(dom.window.document.getElementById('pwn2'), null, 'and the toast escapes it anyway'); assert.deepEqual(errors, []); }); + +test('the China licence arrives in a tenth of the time with quick lead times, and the button says so', () => { + for (const [preset, days] of [['oncall', 45], ['freeze', 5]]) { + const { ev, errors } = load(); + ev(`beginGame('C','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9`); + assert.match(ev("tr('link_panels.apply_for_a_license_price_mo_n_days',{price:'$1',mo:'$1',n:leadDays(45)})"), new RegExp(`~${days} days`)); + ev('ACT.applyCn()'); + assert.equal(ev('S.cnLic.ready-S.day'), days, preset); + assert.deepEqual(errors, []); + } +}); From cd46128c09aeb4a3d34d0bd2aa9664c54f90020d Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:05:11 +0100 Subject: [PATCH 087/181] Save slots: tests for migration, two windows, take-over, stale writes, delete, import/export, puzzles --- src/game/91-slots.js | 17 +- tests/harness.js | 45 +++- tests/save-slots.test.js | 435 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 487 insertions(+), 10 deletions(-) create mode 100644 tests/save-slots.test.js diff --git a/src/game/91-slots.js b/src/game/91-slots.js index 9d35a7a..4a5f77b 100644 --- a/src/game/91-slots.js +++ b/src/game/91-slots.js @@ -6,7 +6,7 @@ writes over a newer one that another window saved. Each tab keeps its slot in sessionStorage: a reload continues it. Only one window plays a slot at a time: a Web Lock where the browser has them, else a heartbeat key, sot-open:. */ const SLOT_K='sot-save-v1:',SLOT_IX='sot-slots',SLOT_OLD='sot-save-v1',SLOT_HB='sot-open:',SLOT_SS='sot-slot',SLOT_MAIN='main'; -const SLOT={sq:{},top:{},no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''}; +const SLOT={sq:{},top:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''}; function slotRid(){try{const a=new Uint32Array(2);crypto.getRandomValues(a);return (a[0].toString(36)+a[1].toString(36)).slice(0,10);}catch(e){return (Date.now().toString(36)+(uidN++).toString(36)).slice(-10);}} const WIN=slotRid();// this page load; a reload is a new window that takes its tab's slot back const lsGet=k=>{try{return localStorage.getItem(k);}catch(e){return null;}}; @@ -21,7 +21,7 @@ function slotClean(e){if(!e||typeof e!=='object'||!slotOkId(e.id))return null; preset:typeof e.preset==='string'&&own(PRESETS,e.preset)?e.preset:'oncall',scn:typeof e.scn==='string'?e.scn.slice(0,60):null,day:int(e.day,0,1e7,0), tier:['Tier 1','Tier 2','Tier 3'].includes(e.tier)?e.tier:null,cash:num(e.cash,0),at:num(e.at,0),size:int(e.size,0,1e10,0),seq:int(e.seq,0,1e15,0),gz:!!e.gz,broken:!!e.broken};} const slotMeta=(s,tier)=>({name:s.name,asn:s.asn,mode:s.mode,preset:s.rules&&s.rules.preset,scn:s.scn&&s.scn.name||null,day:s.day,cash:s.cash,tier}); -function slotKeys(){const out=[];try{for(let i=0;i!seen.has(e.id)&&seen.add(e.id));} - if(scan||bad){const keys=new Set(slotKeys());let ch=bad;const n=list.length; - if(lsGet(SLOT_OLD)!=null&&list.some(e=>e.id===SLOT_MAIN))keys.add(SLOT_MAIN); + if(scan||bad){const ks=slotKeys(),keys=new Set(ks);let ch=bad;const n=list.length; + if(ks.old&&list.some(e=>e.id===SLOT_MAIN))keys.add(SLOT_MAIN); list=list.filter(e=>keys.has(e.id));if(list.length!==n)ch=true; for(const id of keys)if(!list.some(e=>e.id===id)){list.push(slotFromKey(id));ch=true;} if(ch)slotIdxPut(list);if(list.some(e=>e.gz&&!e.name&&!e.broken))slotFix(list);} @@ -54,18 +54,18 @@ function slotBeat(){const id=UI.slot;if(!id)return;const h=slotHb(id); function slotUnbeat(id){const h=slotHb(id);if(h&&h.w===WIN)lsDel(SLOT_HB+id);} const LOCKS=()=>{try{const l=navigator.locks;return l&&typeof l.request==='function'?l:null;}catch(e){return null;}}; // cb(true) when this window may play the slot, cb(false) when another window has it. steal takes it over. -function slotClaim(id,steal,cb){const once=v=>{try{cb(v);}catch(e){console.error('[tubes] opening a network failed',e);}}; +function slotClaim(id,steal,cb,n=4){const once=v=>{try{cb(v);}catch(e){console.error('[tubes] opening a network failed',e);}}; if(SLOT.locks.has(id)){slotBeatFor(id);once(true);return;} const L=LOCKS(); if(L){let got=false; - L.request('sot-slot:'+id,steal?{steal:true}:{ifAvailable:true},lock=>{if(!lock){once(false);return;}got=true; + L.request('sot-slot:'+id,steal?{steal:true}:{ifAvailable:true},lock=>{if(!lock){if(n>0&&(SLOT.rel.has(id)||!slotBusy(id)))setTimeout(()=>slotClaim(id,steal,cb,n-1),120);else once(false);return;}got=true;SLOT.rel.delete(id); return new Promise(r=>{SLOT.locks.set(id,r);slotBeatFor(id);once(true);});}) .catch(()=>{SLOT.locks.delete(id);if(got)slotLost(id,'take');});// stolen: another window took over return;} if(!steal&&slotBusy(id)){once(false);return;} slotBeatFor(id);once(true);} function slotBeatFor(id){try{localStorage.setItem(SLOT_HB+id,JSON.stringify({w:WIN,t:Date.now(),h:0}));}catch(e){}} -function slotFree(id){if(UI.slot===id)return;slotUnbeat(id);const r=SLOT.locks.get(id);SLOT.locks.delete(id);if(r)r();} +function slotFree(id){if(UI.slot===id)return;slotUnbeat(id);const r=SLOT.locks.get(id);SLOT.locks.delete(id);if(r){SLOT.rel.add(id);r();}} // Saves still compressing land before a slot is handed back. function whenIdle(f){if(!UI.gzBusy&&!SLOT.gzQ.size)f();else SLOT.idle.push(f);} function slotIdle(){if(UI.gzBusy||SLOT.gzQ.size)return;const l=SLOT.idle.splice(0);for(const f of l)try{f();}catch(e){console.error(e);}} @@ -131,8 +131,7 @@ function slotBoot(go){slotMigrate(()=>{const list=slotIdx(true),mine=ssGet(SLOT_ let id=list.some(e=>e.id===mine&&!e.broken)?mine:null;if(!id&&mine)ssSet(SLOT_SS,null); const auto=!id&&list.length===1&&!list[0].broken&&!slotBusy(list[0].id)?list[0].id:null; if(!id&&!auto){go();return;} - const claim=(n,f)=>slotClaim(id||auto,false,ok=>!ok&&n&&LOCKS()?setTimeout(()=>claim(n-1,f),400):f(ok)); - claim(id?1:0,ok=>{const w=id||auto; + slotClaim(id||auto,false,ok=>{const w=id||auto; if(!ok){if(id){ssSet(SLOT_SS,null);UI.bootBusy=id;}go();return;} UI.slot=w;const raw=slotRaw(w); if(raw&&raw.startsWith(GZ)&&raw!==UI.gzRaw){if(!gzOk()){go();return;}gunzip(raw).then(t=>{UI.gzRaw=raw;UI.gzText=t;go();},e=>{console.error('[tubes] unpacking the save failed',e);go();});} diff --git a/tests/harness.js b/tests/harness.js index 1dcffe0..df7b5d8 100644 --- a/tests/harness.js +++ b/tests/harness.js @@ -27,6 +27,9 @@ function load(opts = {}) { window.__TUBES_TEST__ = true; // Seed before the game script runs, so nothing random happens at load time either. if (opts.seed !== false) { let r = opts.seed || 12345; window.Math.random = () => { r = (r * 16807) % 2147483647; return r / 2147483647; }; window.__reseed = (n) => { r = n; }; } + // opts.browser (from browser()): windows of one browser share localStorage, its storage events, a broadcast + // channel and Web Locks, like real tabs; opts.tab is one tab's sessionStorage, which survives a reload. + if (opts.browser) opts.browser.attach(window, opts.tab || new Map(), opts); for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v); if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage }); // A non-English game: jsdom does not fetch the dictionary script, so register it up front. @@ -62,4 +65,44 @@ function seed(ev, n) { ev(`if(window.__reseed)__reseed(${n});else Math.random=(()=>{let s=${n};return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();`); } -module.exports = { load, seed }; +// A fake browser for several windows at once (see opts.browser). Storage events, broadcast messages and lock +// hand-overs arrive asynchronously, as in browsers: await settle() or flush() before checking them. +function browser({ locks = true, channel = true } = {}) { + const ls = new Map(), wins = new Set(), held = new Map(), log = []; + const later = (f) => setTimeout(f, 0); + const store = (map, win, shared) => { + const fire = (key, oldValue, newValue) => { if (shared) for (const w of wins) if (w !== win && !w.closed) later(() => { try { w.dispatchEvent(new w.StorageEvent('storage', { key, oldValue, newValue })); } catch (e) {} }); }; + return { + getItem: (k) => { if (shared) log.push(['get', String(k)]); return map.has(String(k)) ? map.get(String(k)) : null; }, + setItem: (k, v) => { if (win.closed) return; k = String(k); v = String(v); if (shared && b.quota && k.startsWith('sot-save-v1:') && v.length > b.quota) { const e = new win.Error('full'); e.name = 'QuotaExceededError'; throw e; } const o = map.has(k) ? map.get(k) : null; map.set(k, v); if (shared) { log.push(['set', k]); fire(k, o, v); } }, + removeItem: (k) => { k = String(k); if (!map.has(k)) return; const o = map.get(k); map.delete(k); if (shared) fire(k, o, null); }, + key: (i) => [...map.keys()][i] ?? null, + get length() { return map.size; }, + clear: () => map.clear(), + }; + }; + const b = { ls, wins, log, quota: 0, + attach(win, tab, opts) { + wins.add(win); + Object.defineProperty(win, 'localStorage', { configurable: true, get: () => store(ls, win, true) }); + Object.defineProperty(win, 'sessionStorage', { configurable: true, get: () => store(tab, win, false) }); + if (channel) win.BroadcastChannel = class { constructor(name) { this.name = name; (b.chans = b.chans || []).push({ c: this, win }); } + postMessage(data) { const msg = JSON.parse(JSON.stringify(data)); for (const o of b.chans) if (o.c !== this && o.c.name === this.name && !o.win.closed && o.c.onmessage) later(() => o.c.onmessage({ data: msg })); } + close() {} }; + if (locks) Object.defineProperty(win.navigator, 'locks', { configurable: true, value: { + request(name, o, cb) { + const cur = held.get(name); + if (cur && !cur.win.closed && !o.steal) { if (o.ifAvailable) return win.Promise.resolve().then(() => cb(null)); return win.Promise.reject(new win.Error('busy')); } + if (cur) { held.delete(name); cur.reject(new win.DOMException('stolen', 'AbortError')); } + return new win.Promise((res, rej) => { const me = { win, reject: rej }; held.set(name, me); + win.Promise.resolve().then(() => cb({ name })).then((v) => { if (held.get(name) === me) held.delete(name); res(v); }, rej); }); + } } }); + }, + // A tab closing: its locks go with it. + close(win) { win.closed = true; for (const [k, v] of held) if (v.win === win) held.delete(k); wins.delete(win); }, + }; + return b; +} +const flush = (n = 3) => new Promise((r) => { const go = (i) => (i ? setTimeout(() => go(i - 1), 2) : r()); go(n); }); + +module.exports = { load, seed, browser, flush }; diff --git a/tests/save-slots.test.js b/tests/save-slots.test.js new file mode 100644 index 0000000..1f7a183 --- /dev/null +++ b/tests/save-slots.test.js @@ -0,0 +1,435 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load, browser, flush } = require('./harness'); + +// Two windows of one browser share localStorage, its storage events, a BroadcastChannel and Web Locks; a reload is a +// new window with the same tab (sessionStorage). +const settle = async (ev, cond, what) => { for (let i = 0; i < 400 && !ev(cond); i++) await new Promise((r) => setTimeout(r, 5)); assert.ok(ev(cond), what || cond); }; +const play = (ev, name, city = 'fra', days = 5) => ev(`UI.pitched=true;UI.nm=${JSON.stringify(name)};if($('nmIn'))$('nmIn').value=UI.nm;ACT.pickStart({city:'${city}'});ACT.start({});ACT.launchBB({city:'${city}'});for(let i=0;i<${days};i++)dayTick();save(true)`); +const idx = (ev) => JSON.parse(ev("JSON.stringify(slotIdx())")); +const card = (ev) => ev("document.getElementById('modalCard').textContent"); + +// A save as the previous version wrote it: one key, no index. +function legacySave() { + const a = load(); + a.ev("$('nmIn').value='Old Faithful';ACT.start({});ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<30;i++)dayTick();UI.speed=2"); + return { txt: a.ev('JSON.stringify(packSave((S.uiSpeed=UI.speed,S.cam={x:cam.x,y:cam.y,z:cam.z},S)))'), snap: a.ev('JSON.stringify([S.name,S.day,S.cash,S.asn,Object.keys(S.pops),S.transit.length])') }; +} + +test('the single save of older versions becomes the first network, losslessly, and loads exactly as before', async () => { + const { txt, snap } = legacySave(); + const b = browser(); + const a = load({ browser: b, storage: { 'sot-save-v1': txt } }); + await settle(a.ev, 'UI.started===true'); + assert.equal(a.ev('JSON.stringify([S.name,S.day,S.cash,S.asn,Object.keys(S.pops),S.transit.length])'), snap, 'the same network'); + assert.equal(a.ev('UI.speed'), 2); + assert.equal(b.ls.get('sot-save-v1:main'), txt, 'copied byte for byte'); + assert.equal(b.ls.get('sot-save-v1'), txt, 'the old key stays as a fallback until the network saves again'); + const e = idx(a.ev); + assert.equal(e.length, 1); + assert.equal(e[0].id, 'main'); + assert.equal(e[0].name, 'Old Faithful'); + assert.equal(e[0].day, 30); + // The copy was read back before the index was written. + const i = b.log.findIndex((x) => x[0] === 'set' && x[1] === 'sot-save-v1:main'), r = b.log.findIndex((x, n) => n > i && x[0] === 'get' && x[1] === 'sot-save-v1:main'), w = b.log.findIndex((x) => x[0] === 'set' && x[1] === 'sot-slots'); + assert.ok(i >= 0 && r > i && w > r, 'write new, read it back, then the index'); + a.ev('dayTick();save(true)'); + assert.equal(b.ls.has('sot-save-v1'), false, 'after a later save, the old key is retired'); + assert.equal(JSON.parse(b.ls.get('sot-save-v1:main')).day, 31); + assert.deepEqual(a.errors, []); +}); + +test('a browser with no room for the copy keeps playing from the old key', async () => { + const { txt } = legacySave(); + const b = browser(); + b.quota = 10;// every slot write is refused + const a = load({ browser: b, storage: { 'sot-save-v1': txt } }); + await settle(a.ev, 'UI.started===true'); + assert.equal(a.ev('S.name'), 'Old Faithful'); + assert.equal(b.ls.has('sot-save-v1:main'), false); + assert.equal(b.ls.get('sot-save-v1'), txt, 'never touched'); + assert.deepEqual(a.errors, []); +}); + +test('a compressed (gz) single save migrates and loads the same network', async () => { + const g = load({ gzip: true }); + const raw = await g.dom.window.eval(`(async()=>{$('nmIn').value='Squeezed';ACT.start({});for(let i=0;i<8;i++)dayTick();return gzip(JSON.stringify(packSave(S)));})()`); + const day = g.ev('S.day'); + assert.ok(raw.startsWith('gz:')); + const b = browser(); + const a = load({ browser: b, gzip: true, storage: { 'sot-save-v1': raw } }); + await settle(a.ev, 'UI.started===true'); + assert.equal(a.ev('S.name'), 'Squeezed'); + assert.equal(a.ev('S.day'), day); + assert.equal(b.ls.get('sot-save-v1:main'), raw); + assert.equal(idx(a.ev)[0].name, 'Squeezed', 'the index knows its name without unpacking it again'); + assert.deepEqual(a.errors, []); +}); + +test('two networks coexist and load independently; the title lists them, newest first', async () => { + const b = browser(); + const a = load({ browser: b }); + play(a.ev, 'First Net', 'fra', 4); + const first = a.ev('UI.slot'); + a.ev('ACT.toTitle()'); + assert.equal(a.ev('S'), null); + play(a.ev, 'Second Net', 'nyc', 9); + const second = a.ev('UI.slot'); + assert.notEqual(first, second); + a.ev('ACT.toTitle()'); + const list = a.ev("[...document.querySelectorAll('#slotList .slot b')].map(b=>b.textContent).join('|')"); + assert.equal(list, 'Second Net|First Net', 'most recent first'); + assert.match(card(a.ev), /Your networks/); + a.ev(`ACT.cont({id:'${first}'})`); + await settle(a.ev, 'UI.started===true'); + assert.equal(a.ev('S.name'), 'First Net'); + assert.equal(a.ev('S.day'), 4); + assert.equal(a.ev('S.home'), 'fra'); + a.ev('ACT.toTitle()'); + a.ev(`ACT.cont({id:'${second}'})`); + await settle(a.ev, 'UI.started===true'); + assert.equal(a.ev('S.name'), 'Second Net'); + assert.equal(a.ev('S.day'), 9); + assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + first)).name, 'First Net', 'each in its own key'); + assert.deepEqual(a.errors, []); +}); + +test('the title lists networks from the index alone, without reading any save', () => { + const b = browser(); + const a = load({ browser: b }); + play(a.ev, 'One'); + a.ev('ACT.toTitle()'); + play(a.ev, 'Two'); + a.ev('ACT.toTitle()'); + b.log.length = 0; + a.ev('showTitle()'); + assert.deepEqual(b.log.filter((x) => x[1].startsWith('sot-save-v1')), [], 'no save was read'); + assert.equal(a.ev("document.querySelectorAll('#slotList .slot').length"), 2); +}); + +test('each tab continues its own network on reload, and two tabs play two networks at once', async () => { + const b = browser(); + const tab1 = new Map(), tab2 = new Map(); + const w1 = load({ browser: b, tab: tab1 }); + play(w1.ev, 'Tab One', 'fra', 3); + const w2 = load({ browser: b, tab: tab2 }); + await flush(); + assert.equal(w2.ev('!!UI.started'), false, 'the only network is open in tab one, so tab two shows the title'); + play(w2.ev, 'Tab Two', 'sin', 6); + // Both keep saving, each into its own slot. + w1.ev('dayTick();save(true)');w2.ev('dayTick();save(true)'); + // Reload tab one: it comes back to its own network, not the newer one. + b.close(w1.dom.window); + const r1 = load({ browser: b, tab: tab1 }); + await settle(r1.ev, 'UI.started===true'); + assert.equal(r1.ev('S.name'), 'Tab One'); + assert.equal(r1.ev('S.day'), 4); + b.close(w2.dom.window); + const r2 = load({ browser: b, tab: tab2 }); + await settle(r2.ev, 'UI.started===true'); + assert.equal(r2.ev('S.name'), 'Tab Two'); + // A brand-new tab: the title with both, and Continue offers neither, since both are open. + const w3 = load({ browser: b }); + await flush(); + assert.equal(w3.ev('!!UI.started'), false); + assert.equal(w3.ev("document.querySelectorAll('#slotList .slot.busy').length"), 2); + assert.equal(w3.ev("!!document.querySelector('#modalCard [data-act=cont].pink')"), false, 'no Continue for a network open elsewhere'); + // Tab two goes back to the title: its network is free again and becomes the one to continue. + r2.ev('ACT.toTitle()'); + await flush(); + w3.ev('showTitle()'); + assert.match(w3.ev("document.querySelector('#modalCard [data-act=cont].pink').textContent"), /Tab Two/); + for (const w of [r1, r2, w3]) assert.deepEqual(w.errors, []); +}); + +test('opening a network open in another window offers to switch or take over, and take-over hands it across', async () => { + const b = browser(); + const w1 = load({ browser: b }); + play(w1.ev, 'Shared Net', 'fra', 3); + const id = w1.ev('UI.slot'); + const w2 = load({ browser: b }); + await flush(); + w2.ev(`ACT.cont({id:'${id}'})`); + await flush(); + assert.match(card(w2.ev), /open in another window/); + assert.equal(w2.ev('!!UI.started'), false, 'not forked'); + assert.ok(w2.ev("!!document.querySelector('#modalCard [data-act=slotSwitch]')&&!!document.querySelector('#modalCard [data-act=slotTake]')")); + // Switch: the other window says hello, this one stays on the title. + w2.ev(`ACT.slotSwitch({id:'${id}'})`); + await flush(); + assert.match(w1.ev("document.getElementById('toasts').textContent"), /Here it is/); + // Take over: window one saves what it has, steps aside calmly and stops saving. + w1.ev('dayTick()'); + w2.ev(`ACT.slotTake({id:'${id}'})`); + await settle(w2.ev, 'UI.started===true', 'taken over'); + assert.equal(w2.ev('S.day'), 4, 'with the last day played in the other window'); + await settle(w1.ev, '/opened in another window/.test(document.getElementById(\'modalCard\').textContent)'); + assert.equal(w1.ev('UI.slot'), null); + assert.equal(w1.ev('S'), null); + w2.ev('dayTick();save(true)'); + const before = b.ls.get('sot-save-v1:' + id); + w1.ev("save(true);dispatchEvent(new Event('pagehide'))"); + assert.equal(b.ls.get('sot-save-v1:' + id), before, 'the window that stepped aside never writes again'); + assert.equal(JSON.parse(before).day, 5); + assert.deepEqual(w1.errors, []); + assert.deepEqual(w2.errors, []); +}); + +test('without Web Locks or BroadcastChannel the heartbeat still keeps one writer per network', async () => { + const b = browser({ locks: false, channel: false }); + const w1 = load({ browser: b }); + play(w1.ev, 'Old Browser Net'); + const id = w1.ev('UI.slot'); + w1.ev('slotBeat()'); + const w2 = load({ browser: b }); + await flush(); + assert.equal(w2.ev('slotBusy(' + JSON.stringify(id) + ')'), true); + w2.ev(`ACT.cont({id:'${id}'})`); + await flush(); + assert.match(card(w2.ev), /open in another window/); + w2.ev(`ACT.slotTake({id:'${id}'})`); + await settle(w2.ev, 'UI.started===true'); + w2.ev('slotBeat()'); + await settle(w1.ev, 'UI.slot===null', 'the first window notices the new heartbeat'); + assert.deepEqual(w1.errors, []); + assert.deepEqual(w2.errors, []); +}); + +test('a stale write is refused: a newer save of the same network from another window is never overwritten', async () => { + const b = browser(); + const w1 = load({ browser: b }); + play(w1.ev, 'Contested'); + const id = w1.ev('UI.slot'); + // Another window (a forked tab, a crashed lock) saves a newer version behind this one's back. + const ix = JSON.parse(b.ls.get('sot-slots')); + const newer = JSON.parse(b.ls.get('sot-save-v1:' + id));newer.day = 99;newer.sv = { seq: 1000, at: Date.now() }; + b.ls.set('sot-save-v1:' + id, JSON.stringify(newer)); + ix.slots[0].seq = 1000;ix.slots[0].day = 99;b.ls.set('sot-slots', JSON.stringify(ix)); + w1.ev('dayTick();save(true)'); + assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + id)).day, 99, 'the newer save stays'); + assert.match(card(w1.ev), /saved in another window/); + assert.equal(w1.ev('UI.slot'), null, 'and this window stops saving'); + assert.ok(w1.ev("!!document.querySelector('#modalCard [data-act=cont]')"), 'with a way to load the newest version'); + // The storage event alone also stops it, before it even tries. + const w2 = load({ browser: b }); + await flush(); + play(w2.ev, 'Watcher'); + const id2 = w2.ev('UI.slot'), ix2 = JSON.parse(b.ls.get('sot-slots')), e = ix2.slots.find((x) => x.id === id2); + e.seq += 50; + w1.dom.window.localStorage.setItem('sot-slots', JSON.stringify(ix2));// written by another window: w2 gets the event + await settle(w2.ev, 'UI.slot===null'); + assert.deepEqual(w1.errors, []); + assert.deepEqual(w2.errors, []); +}); + +test('saves are written slot first, then the index, and every write moves the sequence on', () => { + const b = browser(); + const a = load({ browser: b }); + play(a.ev, 'Ordered'); + const id = a.ev('UI.slot'); + b.log.length = 0; + a.ev('dayTick();save(true)'); + const sets = b.log.filter((x) => x[0] === 'set').map((x) => x[1]); + assert.ok(sets.indexOf('sot-save-v1:' + id) < sets.indexOf('sot-slots'), sets.join()); + const s = JSON.parse(b.ls.get('sot-save-v1:' + id)), e = idx(a.ev).find((x) => x.id === id); + assert.equal(s.sv.seq, e.seq, 'the save and its index entry agree'); + a.ev('save(true)'); + assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + id)).sv.seq, e.seq + 1); + assert.equal(a.ev('"sv" in S'), false, 'the stamp lives in storage, not in the game'); +}); + +test('deleting a network removes its save and its line, after a confirmation', async () => { + const b = browser(); + const a = load({ browser: b }); + play(a.ev, 'Keeper'); + a.ev('ACT.toTitle()'); + play(a.ev, 'Goner'); + const gone = a.ev('UI.slot'); + a.ev('ACT.toTitle()'); + a.ev(`document.querySelector('#slotList .slot[data-slot="${gone}"] .slot-more').click()`); + assert.match(card(a.ev), /Goner/); + a.ev("document.querySelector('#modalCard [data-act=slotDel]').click()"); + assert.match(card(a.ev), /cannot be undone/); + assert.ok(b.ls.has('sot-save-v1:' + gone), 'nothing deleted before the confirmation'); + a.ev("document.querySelector('#modalCard [data-act=slotDelGo]').click()"); + assert.equal(b.ls.has('sot-save-v1:' + gone), false); + assert.deepEqual(idx(a.ev).map((e) => e.name), ['Keeper']); + assert.match(card(a.ev), /Continue Keeper/); + assert.deepEqual(a.errors, []); +}); + +test('a network deleted in another window is never written back by the window playing it', async () => { + const b = browser(); + const w1 = load({ browser: b }); + play(w1.ev, 'Doomed'); + const id = w1.ev('UI.slot'); + const w2 = load({ browser: b }); + await flush(); + w2.ev(`ACT.slotDelGo({id:'${id}'})`); + await settle(w1.ev, 'UI.slot===null'); + w1.ev("save(true);dispatchEvent(new Event('pagehide'))"); + assert.equal(b.ls.has('sot-save-v1:' + id), false); + assert.equal(idx(w2.ev).length, 0); + assert.match(w1.ev("document.getElementById('toasts').textContent"), /deleted in another window/); +}); + +test('export the network on screen, or any network from the list; import adds a new network and keeps the old', async () => { + const b = browser(); + const a = load({ browser: b }); + const files = []; + a.dom.window.URL.createObjectURL = (blob) => { files.push(blob); return 'blob:x'; }; + const text = (blob) => new Promise((r) => { const f = new a.dom.window.FileReader(); f.onload = () => r(f.result); f.readAsText(blob); }); + a.dom.window.URL.revokeObjectURL = () => {}; + play(a.ev, 'Exported Net', 'fra', 7); + const first = a.ev('UI.slot'); + a.ev('ACT.exportSave({})'); + const txt = await text(files[0]); + // Import it back: a second network, the first untouched. + a.ev(`UI.importing=parseSave(${JSON.stringify(txt)}).s;ACT.importGo()`); + assert.notEqual(a.ev('UI.slot'), first, 'a new slot'); + assert.equal(a.ev('S.name'), 'Exported Net'); + assert.equal(a.ev('S.day'), 7); + assert.equal(idx(a.ev).length, 2); + assert.equal(JSON.parse(b.ls.get('sot-save-v1:' + first)).day, 7, 'the first network is still there'); + // Export from the list: straight from storage, the same network. + a.ev('ACT.toTitle()'); + a.ev(`ACT.slotExport({id:'${first}'})`); + await settle(a.ev, 'true');await flush(5); + const j = JSON.parse(await text(files[1])); + assert.equal(j.app, 'series-of-tubes'); + assert.equal(j.S.name, 'Exported Net'); + assert.equal(a.ev(`parseSave(${JSON.stringify(JSON.stringify(j))}).err||null`), null, 'and it imports'); + assert.deepEqual(a.errors, []); +}); + +test('renaming the network renames it in the list', () => { + const b = browser(); + const a = load({ browser: b }); + play(a.ev, 'Before'); + a.ev("ACT.menu();document.querySelector('#modalCard [data-act=rename]').click()"); + a.ev("document.getElementById('rnIn').value=' After Rename ';ACT.renameGo()"); + assert.equal(a.ev('S.name'), 'After Rename'); + assert.equal(idx(a.ev)[0].name, 'After Rename'); +}); + +test('puzzles never write a network, and a tab closed mid-puzzle keeps the network it set aside', async () => { + const b = browser(); + const a = load({ browser: b }); + // A puzzle from the title: nothing saved at all. + a.ev("ACT.pzStart({id:'hello'})"); + a.ev("save(true);dispatchEvent(new Event('pagehide'))"); + assert.equal(idx(a.ev).length, 0); + a.ev('ACT.pzLeave({})'); + play(a.ev, 'Set Aside', 'fra', 3); + const id = a.ev('UI.slot'); + a.ev("ACT.pzStart({id:'hello'})"); + const kept = b.ls.get('sot-save-v1:' + id); + a.ev("S.pops.lon={day:0};save(true);for(let i=0;i<5;i++)frame(performance.now()+6000*i);dispatchEvent(new Event('pagehide'))"); + assert.equal(b.ls.get('sot-save-v1:' + id), kept, 'the puzzle never writes the slot'); + assert.equal(JSON.parse(kept).name, 'Set Aside'); + assert.ok(b.ls.has('sot-puzzles') || true); + // The tab closes mid-puzzle; the next one continues the network. + b.close(a.dom.window); + const r = load({ browser: b }); + await settle(r.ev, 'UI.started===true'); + assert.equal(r.ev('S.name'), 'Set Aside'); + assert.equal(r.ev('S.mode'), 'normal'); + assert.deepEqual(a.errors, []); + assert.deepEqual(r.errors, []); +}); + +test('a big save still compressing when a puzzle starts lands in its network, and so does the next one', async () => { + const b = browser(); + const a = load({ browser: b, gzip: true }); + play(a.ev, 'Big One', 'fra', 1); + a.ev("S.cash=1e9;ACT.buildPop({city:'ams'});S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',own:true,km:450,sys:'roadm',ch:[],ready:0,mo:500,day:0,cut:0});for(let i=0;i<12000;i++)S.biz.push({id:'h'+i,city:'fra',city2:'ams',name:'Huge Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots:1,what:''});compute()"); + const id = a.ev('UI.slot'); + a.ev("S.name='Big One v1';save(true);S.name='Big One v2';save(true)");// one compressing, one queued + a.ev("ACT.pzStart({id:'hello'})"); + await settle(a.ev, '!UI.gzBusy&&!SLOT.gzQ.size'); + const t = await a.dom.window.eval(`gunzip(slotRaw(${JSON.stringify(id)}))`); + assert.equal(JSON.parse(t).name, 'Big One v2', 'the queued save landed too'); + a.ev('ACT.pzLeave({})'); + assert.equal(a.ev('S.name'), 'Big One v2'); + assert.deepEqual(a.errors, []); +}); + +test('leaving a puzzle when the network cannot be loaded marks it damaged, and Continue does not crash', async () => { + const b = browser(); + const a = load({ browser: b }); + play(a.ev, 'Fragile'); + const id = a.ev('UI.slot'); + a.ev("ACT.pzStart({id:'hello'})"); + // The network set aside is gone from memory and its save is unreadable (another version, a broken disk…). + a.ev(`UI.pzKeep=null;localStorage.setItem(SLOT_K+${JSON.stringify(id)},'{"v":1,"day":"x","pops":7}')`); + a.ev(`window.__m=migrate;migrate=s=>{if(s&&s.pops===7)throw new Error('bad');return __m(s);}`); + a.ev('ACT.pzLeave({})'); + a.ev('migrate=__m'); + assert.match(a.ev("document.getElementById('toasts').textContent"), /could not be loaded/); + assert.equal(idx(a.ev)[0].broken, true); + assert.ok(b.ls.has('sot-save-v1:' + id), 'kept, so it can be exported'); + a.ev(`ACT.cont({id:${JSON.stringify(id)}})`); + await flush(); + assert.equal(a.ev('!!UI.started'), false); + a.ev('ACT.cont({})'); + assert.match(card(a.ev), /Series/); + assert.deepEqual(a.errors, []); +}); + +test('a corrupted index is rebuilt from the saves themselves', async () => { + const b = browser(); + const a = load({ browser: b }); + play(a.ev, 'Alpha', 'fra', 2); + a.ev('ACT.toTitle()'); + play(a.ev, 'Beta', 'nyc', 3); + a.ev('ACT.toTitle()'); + b.ls.set('sot-slots', '{not json'); + b.ls.set('sot-save-v1:junk1', 'garbage'); + const c = load({ browser: b }); + await flush(); + const names = idx(c.ev).map((e) => e.name || (e.broken ? '(damaged)' : '?')).sort(); + assert.deepEqual(names, ['(damaged)', 'Alpha', 'Beta']); + assert.match(c.ev("document.getElementById('slotList').textContent"), /Damaged/); + // An index line whose save is gone is dropped. + const ix = JSON.parse(b.ls.get('sot-slots'));ix.slots.push({ id: 'ghost', name: 'Ghost', day: 1, at: Date.now() });b.ls.set('sot-slots', JSON.stringify(ix)); + c.ev('showTitle()'); + assert.equal(c.ev("idx=slotIdx().map(e=>e.name).includes('Ghost')"), false); + assert.deepEqual(c.errors, []); +}); + +test('out of room: the warning offers to free up space, listing the other networks by size', () => { + const b = browser(); + const a = load({ browser: b }); + play(a.ev, 'Small Other'); + a.ev('ACT.toTitle()'); + play(a.ev, 'Growing'); + b.quota = 100; + a.ev('UI.saveFail=null;dayTick();save(true)'); + assert.match(a.ev("document.getElementById('toasts').textContent"), /not being saved/); + a.ev("document.querySelector('#toasts [data-act=slotSpace]').click()"); + assert.match(card(a.ev), /Small Other/); + assert.ok(a.ev("!!document.querySelector('#modalCard [data-act=slotExport]')&&!!document.querySelector('#modalCard [data-act=slotDel]')")); + a.ev('ACT.menu()'); + assert.ok(a.ev("!!document.querySelector('#modalCard [data-act=slotSpace]')"), 'the menu offers it too'); + assert.deepEqual(a.errors, []); +}); + +test('the networks list fits a 360 px phone and has a tap target and a ⋯ menu per network, in every language', () => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const b = browser(); + const a = load({ browser: b, lang: lang === 'en' ? undefined : lang }); + a.ev('window.innerWidth=360'); + play(a.ev, 'Phone Net One'); + a.ev('ACT.toTitle()'); + a.ev("UI.mode='sandbox'"); + play(a.ev, 'Sandy'); + a.ev('ACT.toTitle()'); + const rows = a.ev("document.querySelectorAll('#slotList .slot').length"); + assert.equal(rows, 2, lang); + assert.ok(a.ev("[...document.querySelectorAll('#slotList .slot')].every(r=>r.querySelector('.slot-go')&&r.querySelector('.slot-more[aria-label]'))"), lang); + assert.match(a.ev("document.getElementById('slotList').textContent"), /🏖️/, `${lang}: preset icon`); + assert.equal(a.ev("document.querySelector('#slotList').previousElementSibling.textContent"), a.ev("tr('slots.your_networks')")); + assert.doesNotMatch(card(a.ev), /slots\.|undefined|NaN|\{[a-z]+\}/, lang); + assert.deepEqual(a.errors, [], lang); + } +}); From 732c32984446f540f2041db54bc5f916411e93f5 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:05:23 +0100 Subject: [PATCH 088/181] Requirements: build the possible-diversity map on city indices The first diversityPossible() call after a save loads (migrate() checks every customer's requirements) built a graph of every buildable link between all ~28k city pairs, scanning all 475 cable segments for each pair, with string ids and objects for each of ~19k links: about 0.8 s on a fast machine, ~0.9 s of a throttled phone's boot. Now the cables come from a table per pair and the graph holds city indices and one number per risk (each land trench and own cable on its own; every segment of a cable, or a fabric, sharing one). The answers match disjointRoutes() over the old link list for all 14,042 sampled pairs, won or not and with scenario bans. --- src/game/80-simulation/60-requirements.js | 33 +++++++++++++++-------- tests/load-time.test.js | 23 ++++++++++++++++ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js index ab9f52c..53306c0 100644 --- a/src/game/80-simulation/60-requirements.js +++ b/src/game/80-simulation/60-requirements.js @@ -37,20 +37,31 @@ function diversityPossible(a,b,state=S){ if(!CITY[a]||!CITY[b]||a===b)return false; const rules=state.scn&&state.scn.rules||{},key=JSON.stringify([!!state.won,rules]); if(!diversityMap||diversityMap.key!==key){ - const links=[],cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id); - const add=(a,b,id)=>links.push({a,b,id}); - for(let i=0;ip===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(a,b,'cab:'+c.cid); - if(state.won&&seaCab(a,b)&&landing(a)&&landing(b)&&!cnCity(a)&&!cnCity(b))add(a,b,'own:'+a+':'+b); - for(const f of FABS)if(f.cities.includes(a)&&f.cities.includes(b))add(a,b,'fab:'+f.id); + /* Built once per ruleset, over every city pair, so it runs on the first load of every save: on city indices, with + the cables between each pair from a table. A link is the number of its risk: each land trench and your own cable + on its own, every segment of one cable (or one fabric) the same; adj[i] lists [neighbour, risk] in the order the + links were added, as a graph built from a list of them would. */ + const cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id),N=cities.length,ix=new Map(cities.map((c,i)=>[c,i])); + const cab=new Map();for(const c of CABLE_PAIRS){const k=c.alands(CITY[c])),land=cities.map(landing),cn=cities.map(cnCity),fab=cities.map(c=>FABS.filter(f=>f.cities.includes(c))),ban=rules.banPairs||[]; + const adj=cities.map(()=>[]),grp=new Map();let n=0,k=0;const add=(i,j,g)=>{let r;if(g===undefined)r=k++;else{r=grp.get(g);if(r===undefined)grp.set(g,r=k++);}adj[i].push(j,r);adj[j].push(i,r);n++;}; + for(let i=0;iLS[j].includes(x)); + if(!sub){add(i,j);add(i,j);} + if(cs)for(const c of cs)if(!ban.some(p=>p===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(i,j,'cab:'+c.cid); + if(state.won&&land[i]&&land[j]&&(sub||cs)&&!cn[i]&&!cn[j])add(i,j); + if(fab[i].length&&fab[j].length)for(const f of FABS)if(fab[i].includes(f)&&fab[j].includes(f))add(i,j,'fab:'+f.id); } - diversityMap={key,links,answers:{}}; + diversityMap={key,ix,adj,links:n,answers:{}}; } - const pair=[a,b].sort().join(':'); - return diversityMap.answers[pair]??(diversityMap.answers[pair]=disjointRoutes(a,b,diversityMap.links)); + const pair=[a,b].sort().join(':'),M=diversityMap; + return M.answers[pair]??(M.answers[pair]=M.ix.has(a)&&M.ix.has(b)&&disjointOn(M.adj,M.ix.get(a),M.ix.get(b))); } +// disjointRoutes() on such a graph: a shortest path by hops, then another one that shares none of its risks. +function disjointOn(adj,a,b){const N=adj.length,bfs=skip=>{const prev=new Int32Array(N).fill(-1),pl=new Int32Array(N),q=[a];prev[a]=a; + for(let h=0;h{const m=new Map();for(const l of S.links)if(!m.has(l.id))m.set(l.id,l);return m;}; diff --git a/tests/load-time.test.js b/tests/load-time.test.js index b1a7a68..9106cab 100644 --- a/tests/load-time.test.js +++ b/tests/load-time.test.js @@ -5,6 +5,29 @@ const { load } = require('./harness'); // Work done once when a game loads (the possible-diversity map, link curves, the map's sea and hills) has shortcuts; // each must give exactly what the plain version gives. +test('diversity map: the indexed graph answers like disjointRoutes() over every possible link', (t) => { + const { ev, dom, errors } = load(); t.after(() => dom.window.close()); + ev('ACT.start({})'); + // The plain map: one record per possible link, in the order the indexed one adds them. + ev(`window.plainLinks=state=>{const rules=state.scn&&state.scn.rules||{},links=[],cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id),add=(a,b,id)=>links.push({a,b,id}); + for(let i=0;ip===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(a,b,'cab:'+c.cid); + if(state.won&&seaCab(a,b)&&landing(a)&&landing(b)&&!cnCity(a)&&!cnCity(b))add(a,b,'own:'+a+':'+b); + for(const f of FABS)if(f.cities.includes(a)&&f.cities.includes(b))add(a,b,'fab:'+f.id);}return links;}`); + const cp = ev('CABLE_PAIRS[0].cid+":"+CABLE_PAIRS[0].a+"-"+CABLE_PAIRS[0].b'); + for (const st of [{ won: false }, { won: true }, { won: false, scn: { rules: { banCities: ['jam', 'lon'], banPairs: [cp] } } }]) { + const r = JSON.parse(ev(`(()=>{const st=${JSON.stringify(st)},L=plainLinks(st);diversityMap=null;diversityPossible('fra','nyc',st); + const ids=CITIES.map(c=>c.id),bad=[];let n=0;for(let i=0;ix===a||x===b))?diversityPossible(a,b,st):disjointRoutes(a,b,L);if(diversityPossible(a,b,st)!==want)bad.push(a+'-'+b);} + return JSON.stringify({links:L.length,mine:diversityMap.links,n,bad})})()`)); + assert.equal(r.mine, r.links, 'the same possible links'); + assert.ok(r.n > 2000); + assert.deepEqual(r.bad, [], JSON.stringify(st)); + } + assert.deepEqual(errors, []); +}); + test('link curves: skipping far-away cities gives the same bend around the ones in the way', (t) => { const { ev, dom, errors } = load(); t.after(() => dom.window.close()); ev('ACT.start({})'); From df8edddfe6c6b5a966bd025cbcb5f85a3dcbbc97 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:05:31 +0100 Subject: [PATCH 089/181] CHANGELOG: faster loading of big networks --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a94afc6..791600c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner. - Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. - 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. From 871b3409109e74cb08431aaaacb70160b2d2cbad Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:05:32 +0100 Subject: [PATCH 090/181] Homegrown eyeballs: 63 real consumer networks so every country has two of its own, translated --- site/i18n/de.js | 63 +++++++++++++++++ site/i18n/es.js | 63 +++++++++++++++++ site/i18n/fr.js | 63 +++++++++++++++++ site/i18n/it.js | 63 +++++++++++++++++ site/i18n/pt.js | 63 +++++++++++++++++ src/game/30-networks/10-networks.js | 4 +- src/game/30-networks/32-homegrown-eyeballs.js | 70 +++++++++++++++++++ src/i18n/en.js | 63 +++++++++++++++++ 8 files changed, 450 insertions(+), 2 deletions(-) create mode 100644 src/game/30-networks/32-homegrown-eyeballs.js diff --git a/site/i18n/de.js b/site/i18n/de.js index c6b6e91..5cb729b 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1927,6 +1927,69 @@ "hint.release_to_plan_a_link":"Loslassen, um einen Link zu planen", "hint.tap_your_city_then_launch_broadband":"Tippe auf deine Stadt, dann auf Breitband starten", "hint.tip_drag_from_your_pink_router":"Tipp: Zieh von einer Stadt zur anderen, um Glasfaser zu verlegen", +"homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister":"Die bulgarische Schwester von A-Wan Telekom: dasselbe WAN, mehr Berge.", +"homegrown_eyeballs.algeria_s_biggest_mobile_network_easy":"Algeriens größtes Mobilfunknetz. Immer mit der Ruhe, die Bandbreite kommt.", +"homegrown_eyeballs.algeria_s_state_incumbent_some_days":"Algeriens staatlicher Platzhirsch: An manchen Tagen ist das Internet so lala, an manchen wegen Prüfungen ganz weg.", +"homegrown_eyeballs.american_samoa_s_own_telco_prepaid":"Amerikanisch-Samoas eigene Telco: Prepaid, du zahlst, wie du gehst.", +"homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours":"Angolas Mobilfunkriese, hochachtungsvoll in jeder Provinz.", +"homegrown_eyeballs.angola_s_number_two_always_on":"Angolas Nummer zwei, immer in Bewegung und immer am Verkaufen.", +"homegrown_eyeballs.austria_s_incumbent_first_in_line":"Österreichs Platzhirsch, bei jedem WAN als Erster in der Schlange.", +"homegrown_eyeballs.bangladesh_s_biggest_mobile_network_a":"Bangladeschs größtes Mobilfunknetz, hundert Millionen SIM-Karten stark.", +"homegrown_eyeballs.bermuda_s_newest_mobile_network_the":"Bermudas neuestes Mobilfunknetz. Das Signal geht manchmal im Dreieck verloren.", +"homegrown_eyeballs.bolivia_s_state_telco_thinking_hard":"Boliviens Staats-Telco denkt angestrengt nach, auf 3.600 Metern.", +"homegrown_eyeballs.botswana_s_biggest_mobile_network_with":"Botswanas größtes Mobilfunknetz, mit einem Maskottchen an jedem Mast.", +"homegrown_eyeballs.botswana_s_incumbent_counts_subscribers_like":"Botswanas Platzhirsch zählt seine Kunden wie Rinder.", +"homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida":"Bulgariens Platzhirsch, lebt la vida Breitband.", +"homegrown_eyeballs.cape_verde_s_challenger_one_more":"Der Herausforderer auf Kap Verde, eine Insel nach der anderen.", +"homegrown_eyeballs.danish_fibre_from_the_power_company":"Dänische Glasfaser vom Stromversorger: Gehen die Lichter aus, geht auch das WLAN.", +"homegrown_eyeballs.denmark_s_incumbent_you_see_it":"Dänemarks Platzhirsch: Du siehst ihn an jeder Straßenecke.", +"homegrown_eyeballs.doitsche_telekomm_s_hungarian_daughter_pink":"Die ungarische Tochter von Doitsche Telekomm: pink und leicht scharf.", +"homegrown_eyeballs.fibre_to_every_tower_block_rung":"Glasfaser in jedes Hochhaus, eingeläutet wie die Trams: ding ding.", +"homegrown_eyeballs.fiji_s_fixed_line_incumbent_never":"Fidschis Festnetz-Platzhirsch, der nie stillsitzen kann.", +"homegrown_eyeballs.finland_s_biggest_mobile_network_unlimited":"Finnlands größtes Mobilfunknetz, unbegrenzte Daten, gespielt wie auf dem Klavier.", +"homegrown_eyeballs.finnish_broadband_and_mobile_it_s":"Finnisches Breitband und Mobilfunk. Liegt ihnen in der DNA; das Testergebnis steht noch aus.", +"homegrown_eyeballs.french_polynesia_s_mobile_network_came":"Das Mobilfunknetz Französisch-Polynesiens: Es kam, sah und vernetzte die Atolle.", +"homegrown_eyeballs.fur_elisa_across_the_gulf_of":"Für Elisa über den Finnischen Meerbusen: dieselbe Melodie, auf Estnisch.", +"homegrown_eyeballs.ghana_s_number_two_a_new":"Ghanas Nummer zwei: neuer Name, dieselben Kabel, sehr gute Verkäufer.", +"homegrown_eyeballs.hong_kong_s_incumbent_broadband_full":"Hongkongs Breitband-Platzhirsch, voller Elan und Milchtee.", +"homegrown_eyeballs.iceland_s_incumbent_when_simon_says":"Islands Platzhirsch. Wenn Símon „los“ sagt, nimmt jedes Paket das Kabel nach Europa.", +"homegrown_eyeballs.iceland_s_mobile_challenger_burning_bright":"Islands Mobilfunk-Herausforderer, strahlend hell dank Erdwärme.", +"homegrown_eyeballs.japan_s_biggest_mobile_network_bows":"Japans größtes Mobilfunknetz, das sich tief vor seinem großen Geschwister Not That Telecom verbeugt.", +"homegrown_eyeballs.latvia_s_mobile_leader_let_me":"Lettlands Mobilfunk-Marktführer: Lass mich reden, dann verkaufe ich dir 5G.", +"homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom":"Malaysias größtes Mobilfunknetz: selten aufgebuddelt, selten down.", +"homegrown_eyeballs.mozambique_s_rural_mobile_network_towers":"Mosambiks Mobilfunknetz fürs Land, mit Masten in Dörfern, die sonst niemand angeschlossen hat.", +"homegrown_eyeballs.namibia_s_mobile_network_lots_of":"Namibias Mobilfunknetz: viel Wüste, wenig Meer.", +"homegrown_eyeballs.namibia_s_state_incumbent_wired_across":"Namibias staatlicher Platzhirsch, verkabelt durch die Namib, eine Düne nach der anderen.", +"homegrown_eyeballs.new_caledonia_s_cable_operator_can":"Neukaledoniens Kabelnetzbetreiber: kann, wird, irgendwann.", +"homegrown_eyeballs.new_zealand_s_number_two_renamed":"Neuseelands Nummer zwei, umbenannt und neu verpackt. Angeblich hat sie gewonnen.", +"homegrown_eyeballs.norwegian_fibre_from_the_power_company":"Norwegische Glasfaser vom Stromversorger aus Stavanger: Man weiß nie, was man kriegt.", +"homegrown_eyeballs.ooh_redoo_s_maldives_branch_four":"Der Malediven-Ableger von Ooh-redoo: volle Balken auf jeder Sandbank.", +"homegrown_eyeballs.ooh_redoo_s_tunisian_network_mint":"Das tunesische Netz von Ooh-redoo: erst Minztee, dann Megabits.", +"homegrown_eyeballs.pakistan_s_biggest_mobile_network_improvising":"Pakistans größtes Mobilfunknetz, improvisiert sich durch jeden Ausfall.", +"homegrown_eyeballs.palau_s_mobile_challenger_your_pal":"Palaus Mobilfunk-Herausforderer, dein Kumpel auf jeder Felseninsel.", +"homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg":"Die tanzende Marke von Proxyminus in Luxemburg: Zum Tango gehören zwei.", +"homegrown_eyeballs.senegal_s_number_two_freshly_renamed":"Senegals Nummer zwei, frisch umbenannt und sehr von sich überzeugt.", +"homegrown_eyeballs.serbia_s_incumbent_at_your_service":"Serbiens Platzhirsch, stets zu Diensten.", +"homegrown_eyeballs.singapore_s_number_two_with_a":"Singapurs Nummer zwei, mit einem Teleskop, das auf SingTell gerichtet ist.", +"homegrown_eyeballs.sri_lanka_s_biggest_mobile_network_talks":"Sri Lankas größtes Mobilfunknetz: redet mit allen, am meisten mit sich selbst.", +"homegrown_eyeballs.sri_lanka_s_incumbent_adds_a":"Sri Lankas Platzhirsch: gibt jeder Route eine Prise Latenz dazu.", +"homegrown_eyeballs.sweden_s_challenger_that_took_on":"Schwedens Herausforderer, der sich mit Tell-Ya angelegt hat. Eine Telco zu viel, sagt Tell-Ya.", +"homegrown_eyeballs.switzerland_s_incumbent_the_holes_in":"Der Schweizer Platzhirsch. Die Löcher in der Abdeckung sind ein Designmerkmal.", +"homegrown_eyeballs.taiwan_s_number_three_never_hears":"Taiwans Nummer drei, die eine Peering-Anfrage nie beim ersten Mal hört.", +"homegrown_eyeballs.takes_from_the_big_carriers_and":"Nimmt es den großen Carriern und gibt Dhaka billige Datenpakete.", +"homegrown_eyeballs.tell_ya_s_estonian_daughter_e":"Die estnische Tochter von Tell-Ya, die jede Peering-Anfrage digital signiert.", +"homegrown_eyeballs.thailand_s_biggest_mobile_network_cool":"Thailands größtes Mobilfunknetz, kühl in der Hitze von Bangkok.", +"homegrown_eyeballs.the_challenger_that_made_french_broadband":"Der Herausforderer, der französisches Breitband billig gemacht hat: frei wie Freibier, nicht wie freies Peering.", +"homegrown_eyeballs.the_dominican_republic_s_other_big":"Das andere große Netz der Dominikanischen Republik. Im Zweifel: neu starten.", +"homegrown_eyeballs.the_dutch_incumbent_peers_for_peanuts":"Der niederländische Platzhirsch: Peering für Peanuts, Glasfaser in jeden Polder.", +"homegrown_eyeballs.the_kingdom_s_challenger_always_mobilising":"Der Herausforderer im Königreich, ständig mobilisiert für das nächste Megaprojekt.", +"homegrown_eyeballs.the_mobile_network_formerly_known_as":"Das Mobilfunknetz, das früher anders hieß, und noch nicht fertig mit dem Umbenennen ist.", +"homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"Der andere Mobilfunkriese der Philippinen, unterwegs durch den ganzen Archipel.", +"homegrown_eyeballs.the_solomon_islands_mobile_challenger_to":"Der Mobilfunk-Herausforderer der Salomonen: Online sein oder nicht sein.", +"homegrown_eyeballs.ukraine_s_third_mobile_network_kept":"Das dritte Mobilfunknetz der Ukraine, am Leben gehalten von Akkus und Sturheit.", +"homegrown_eyeballs.venezuela_s_state_telco_can_t":"Venezuelas Staats-Telco: Kann sie nicht reparieren, nicht verkaufen, nicht abschalten.", +"homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant":"Vietnams Post- und Telekom-Riese: Die Pakete kommen per Moped.", +"homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_what":"Simbabwes Festnetz-Platzhirsch. Was in der Leitung passiert, bleibt unter uns.", "hot_ports_and_rank.add_a_lag_member_or_upgrade":"Füg ein LAG-Mitglied hinzu oder rüste den PNI auf.", "hot_ports_and_rank.add_a_lag_member_upgrade_the":"Füg ein LAG-Mitglied hinzu, rüste den Port auf oder kauf einen zweiten Upstream.", "hot_ports_and_rank.and_n_more":"und {n} weitere", diff --git a/site/i18n/es.js b/site/i18n/es.js index 4ab93d8..3af769b 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1925,6 +1925,69 @@ "hint.release_to_plan_a_link":"Suelta para planificar un enlace", "hint.tap_your_city_then_launch_broadband":"Toca tu ciudad y luego Lanzar banda ancha", "hint.tip_drag_from_your_pink_router":"Consejo: arrastra desde tu router rosa hasta otra ciudad para tender fibra", +"homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister":"La hermana búlgara de A-Wan Telekom: la misma WAN, más montañas.", +"homegrown_eyeballs.algeria_s_biggest_mobile_network_easy":"La mayor red móvil de Argelia. Con calma, que el ancho de banda ya llega.", +"homegrown_eyeballs.algeria_s_state_incumbent_some_days":"El operador estatal de Argelia: unos días internet va así así, otros se apaga por los exámenes.", +"homegrown_eyeballs.american_samoa_s_own_telco_prepaid":"La telco propia de Samoa Americana: prepago, pagas a medida que vas.", +"homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours":"El gigante móvil de Angola, atentamente suyo en cada provincia.", +"homegrown_eyeballs.angola_s_number_two_always_on":"El número dos de Angola, siempre en movimiento y siempre vendiendo.", +"homegrown_eyeballs.austria_s_incumbent_first_in_line":"El operador histórico de Austria, el primero de la fila en cada WAN.", +"homegrown_eyeballs.bangladesh_s_biggest_mobile_network_a":"La mayor red móvil de Bangladés, con cien millones de SIM.", +"homegrown_eyeballs.bermuda_s_newest_mobile_network_the":"La red móvil más nueva de Bermudas. A veces la señal se pierde en el Triángulo.", +"homegrown_eyeballs.bolivia_s_state_telco_thinking_hard":"La telco estatal de Bolivia, pensando a fondo a 3.600 metros.", +"homegrown_eyeballs.botswana_s_biggest_mobile_network_with":"La mayor red móvil de Botsuana, con una mascota en cada torre.", +"homegrown_eyeballs.botswana_s_incumbent_counts_subscribers_like":"El operador histórico de Botsuana, que cuenta a sus clientes como cabezas de ganado.", +"homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida":"El operador histórico de Bulgaria, viviendo la vida banda ancha.", +"homegrown_eyeballs.cape_verde_s_challenger_one_more":"El aspirante de Cabo Verde, que suma una isla más cada vez.", +"homegrown_eyeballs.danish_fibre_from_the_power_company":"Fibra danesa de la eléctrica: cuando se va la luz, se va el wifi.", +"homegrown_eyeballs.denmark_s_incumbent_you_see_it":"El operador histórico de Dinamarca: lo ves en cada calle.", +"homegrown_eyeballs.doitsche_telekomm_s_hungarian_daughter_pink":"La hija húngara de Doitsche Telekomm: rosa y algo picante.", +"homegrown_eyeballs.fibre_to_every_tower_block_rung":"Fibra en cada torre de pisos, anunciada como los tranvías: ding ding.", +"homegrown_eyeballs.fiji_s_fixed_line_incumbent_never":"El operador histórico de telefonía fija de Fiyi, que nunca se está quieto.", +"homegrown_eyeballs.finland_s_biggest_mobile_network_unlimited":"La mayor red móvil de Finlandia, datos ilimitados tocados como al piano.", +"homegrown_eyeballs.finnish_broadband_and_mobile_it_s":"Banda ancha y móvil finlandeses. Lo llevan en el ADN; resultados del test pendientes.", +"homegrown_eyeballs.french_polynesia_s_mobile_network_came":"La red móvil de la Polinesia Francesa: llegó, vio y conectó los atolones.", +"homegrown_eyeballs.fur_elisa_across_the_gulf_of":"Für Elisa al otro lado del golfo de Finlandia: la misma melodía, en estonio.", +"homegrown_eyeballs.ghana_s_number_two_a_new":"El número dos de Ghana: nombre nuevo, los mismos cables, muy buenos vendedores.", +"homegrown_eyeballs.hong_kong_s_incumbent_broadband_full":"La banda ancha histórica de Hong Kong, llena de energía y té con leche.", +"homegrown_eyeballs.iceland_s_incumbent_when_simon_says":"El operador histórico de Islandia. Cuando Símon dice «ya», cada paquete toma el cable a Europa.", +"homegrown_eyeballs.iceland_s_mobile_challenger_burning_bright":"El aspirante móvil de Islandia, brillando con fuerza gracias a la geotermia.", +"homegrown_eyeballs.japan_s_biggest_mobile_network_bows":"La mayor red móvil de Japón, que hace una profunda reverencia a su hermano mayor Not That Telecom.", +"homegrown_eyeballs.latvia_s_mobile_leader_let_me":"El líder móvil de Letonia: déjame hablar y luego te vendo 5G.", +"homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom":"La mayor red móvil de Malasia: rara vez excavada, rara vez caída.", +"homegrown_eyeballs.mozambique_s_rural_mobile_network_towers":"La red móvil rural de Mozambique, con torres en pueblos que nadie más conectó.", +"homegrown_eyeballs.namibia_s_mobile_network_lots_of":"La red móvil de Namibia: mucho desierto, poco mar.", +"homegrown_eyeballs.namibia_s_state_incumbent_wired_across":"El operador estatal de Namibia, cableado por el Namib duna a duna.", +"homegrown_eyeballs.new_caledonia_s_cable_operator_can":"El operador de cable de Nueva Caledonia: puede, lo hará, algún día.", +"homegrown_eyeballs.new_zealand_s_number_two_renamed":"El número dos de Nueva Zelanda, renombrado y con nueva imagen. Al parecer, ha ganado.", +"homegrown_eyeballs.norwegian_fibre_from_the_power_company":"Fibra noruega de la eléctrica de Stavanger: nunca sabes lo que te va a tocar.", +"homegrown_eyeballs.ooh_redoo_s_maldives_branch_four":"La filial de Ooh-redoo en Maldivas: cobertura completa en cada banco de arena.", +"homegrown_eyeballs.ooh_redoo_s_tunisian_network_mint":"La red tunecina de Ooh-redoo: primero té a la menta, luego megabits.", +"homegrown_eyeballs.pakistan_s_biggest_mobile_network_improvising":"La mayor red móvil de Pakistán, improvisando en cada caída.", +"homegrown_eyeballs.palau_s_mobile_challenger_your_pal":"El aspirante móvil de Palaos, tu colega en cada isla de roca.", +"homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg":"La marca bailarina de Proxyminus en Luxemburgo: hacen falta dos para bailar un tango.", +"homegrown_eyeballs.senegal_s_number_two_freshly_renamed":"El número dos de Senegal, recién rebautizado y muy seguro de sí mismo.", +"homegrown_eyeballs.serbia_s_incumbent_at_your_service":"El operador histórico de Serbia, a su servicio.", +"homegrown_eyeballs.singapore_s_number_two_with_a":"El número dos de Singapur, con un telescopio apuntando a SingTell.", +"homegrown_eyeballs.sri_lanka_s_biggest_mobile_network_talks":"La mayor red móvil de Sri Lanka: habla con todos, sobre todo consigo misma.", +"homegrown_eyeballs.sri_lanka_s_incumbent_adds_a":"El operador histórico de Sri Lanka: añade una pizca de latencia a cada ruta.", +"homegrown_eyeballs.sweden_s_challenger_that_took_on":"El aspirante sueco que se enfrentó a Tell-Ya. Una telco de más, dice Tell-Ya.", +"homegrown_eyeballs.switzerland_s_incumbent_the_holes_in":"El operador histórico de Suiza. Los agujeros en la cobertura son una característica de diseño.", +"homegrown_eyeballs.taiwan_s_number_three_never_hears":"El número tres de Taiwán, que nunca oye una petición de peering a la primera.", +"homegrown_eyeballs.takes_from_the_big_carriers_and":"Les quita a los grandes operadores y regala paquetes de datos baratos a Daca.", +"homegrown_eyeballs.tell_ya_s_estonian_daughter_e":"La hija estonia de Tell-Ya, que firma electrónicamente cada petición de peering.", +"homegrown_eyeballs.thailand_s_biggest_mobile_network_cool":"La mayor red móvil de Tailandia, fresquita en el calor de Bangkok.", +"homegrown_eyeballs.the_challenger_that_made_french_broadband":"El aspirante que abarató la banda ancha francesa: libre como la cerveza gratis, no como el peering.", +"homegrown_eyeballs.the_dominican_republic_s_other_big":"La otra gran red de la República Dominicana. Ante la duda, reinicia.", +"homegrown_eyeballs.the_dutch_incumbent_peers_for_peanuts":"El operador histórico neerlandés: peering por cacahuetes, fibra en cada pólder.", +"homegrown_eyeballs.the_kingdom_s_challenger_always_mobilising":"El aspirante del Reino, siempre movilizado para el próximo megaproyecto.", +"homegrown_eyeballs.the_mobile_network_formerly_known_as":"La red móvil antes conocida como otra cosa, y que aún no ha terminado de renombrarse.", +"homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"El otro gigante móvil de Filipinas, recorriendo el archipiélago.", +"homegrown_eyeballs.the_solomon_islands_mobile_challenger_to":"El aspirante móvil de las Islas Salomón: estar o no estar en línea.", +"homegrown_eyeballs.ukraine_s_third_mobile_network_kept":"La tercera red móvil de Ucrania, viva a base de baterías y testarudez.", +"homegrown_eyeballs.venezuela_s_state_telco_can_t":"La telco estatal de Venezuela: no se puede arreglar, ni vender, ni apagar.", +"homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant":"El gigante de correos y telecomunicaciones de Vietnam: los paquetes llegan en moto.", +"homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_what":"El operador histórico de telefonía fija de Zimbabue. Lo que pasa en la línea, no se lo cuentes a nadie.", "hot_ports_and_rank.add_a_lag_member_or_upgrade":"Añade un miembro LAG o mejora el PNI.", "hot_ports_and_rank.add_a_lag_member_upgrade_the":"Añade un miembro LAG, mejora el puerto o compra un segundo upstream.", "hot_ports_and_rank.and_n_more":"y {n} más", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 26a6ad8..b3104f0 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1925,6 +1925,69 @@ "hint.release_to_plan_a_link":"Relâche pour planifier un lien", "hint.tap_your_city_then_launch_broadband":"Touche ta ville, puis Lancer le haut débit", "hint.tip_drag_from_your_pink_router":"Astuce : glisse depuis ton routeur rose vers une autre ville pour poser de la fibre", +"homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister":"La sœur bulgare d’A-Wan Telekom : le même WAN, plus de montagnes.", +"homegrown_eyeballs.algeria_s_biggest_mobile_network_easy":"Le plus grand réseau mobile d’Algérie. Doucement, la bande passante arrive.", +"homegrown_eyeballs.algeria_s_state_incumbent_some_days":"L’opérateur public algérien : certains jours, Internet va comme ci comme ça, d’autres il est coupé pour le bac.", +"homegrown_eyeballs.american_samoa_s_own_telco_prepaid":"La télécom des Samoa américaines : prépayée, on paie au fur et à mesure.", +"homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours":"Le géant mobile angolais, sincèrement vôtre dans chaque province.", +"homegrown_eyeballs.angola_s_number_two_always_on":"Le numéro deux angolais, toujours en mouvement et toujours en train de vendre.", +"homegrown_eyeballs.austria_s_incumbent_first_in_line":"L’opérateur historique autrichien, premier de la file pour chaque WAN.", +"homegrown_eyeballs.bangladesh_s_biggest_mobile_network_a":"Le plus grand réseau mobile du Bangladesh, fort de cent millions de cartes SIM.", +"homegrown_eyeballs.bermuda_s_newest_mobile_network_the":"Le plus récent réseau mobile des Bermudes. Le signal se perd parfois dans le Triangle.", +"homegrown_eyeballs.bolivia_s_state_telco_thinking_hard":"La télécom d’État bolivienne, qui réfléchit fort à 3 600 mètres.", +"homegrown_eyeballs.botswana_s_biggest_mobile_network_with":"Le plus grand réseau mobile du Botswana, avec une mascotte sur chaque pylône.", +"homegrown_eyeballs.botswana_s_incumbent_counts_subscribers_like":"L’opérateur historique du Botswana, qui compte ses abonnés comme du bétail.", +"homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida":"L’opérateur historique bulgare, qui vit la vida haut débit.", +"homegrown_eyeballs.cape_verde_s_challenger_one_more":"Le challenger du Cap-Vert, qui ajoute une île à la fois.", +"homegrown_eyeballs.danish_fibre_from_the_power_company":"De la fibre danoise de l’électricien : quand la lumière s’éteint, le Wi-Fi aussi.", +"homegrown_eyeballs.denmark_s_incumbent_you_see_it":"L’opérateur historique danois : on le voit à chaque coin de rue.", +"homegrown_eyeballs.doitsche_telekomm_s_hungarian_daughter_pink":"La fille hongroise de Doitsche Telekomm : rose, et légèrement épicée.", +"homegrown_eyeballs.fibre_to_every_tower_block_rung":"La fibre dans chaque tour, annoncée comme les trams : ding ding.", +"homegrown_eyeballs.fiji_s_fixed_line_incumbent_never":"L’opérateur historique du fixe aux Fidji, qui ne tient jamais en place.", +"homegrown_eyeballs.finland_s_biggest_mobile_network_unlimited":"Le plus grand réseau mobile de Finlande, des données illimitées jouées comme au piano.", +"homegrown_eyeballs.finnish_broadband_and_mobile_it_s":"Haut débit et mobile finlandais. C’est dans leur ADN ; résultats du test en attente.", +"homegrown_eyeballs.french_polynesia_s_mobile_network_came":"Le réseau mobile de Polynésie française : il est venu, il a vu, il a connecté les atolls.", +"homegrown_eyeballs.fur_elisa_across_the_gulf_of":"Für Elisa de l’autre côté du golfe de Finlande : le même air, en estonien.", +"homegrown_eyeballs.ghana_s_number_two_a_new":"Le numéro deux du Ghana : nouveau nom, mêmes câbles, très bons vendeurs.", +"homegrown_eyeballs.hong_kong_s_incumbent_broadband_full":"Le haut débit historique de Hong Kong, plein de vigueur et de thé au lait.", +"homegrown_eyeballs.iceland_s_incumbent_when_simon_says":"L’opérateur historique islandais. Quand Símon dit « go », chaque paquet prend le câble vers l’Europe.", +"homegrown_eyeballs.iceland_s_mobile_challenger_burning_bright":"Le challenger mobile islandais, qui brille de mille feux grâce à la géothermie.", +"homegrown_eyeballs.japan_s_biggest_mobile_network_bows":"Le plus grand réseau mobile du Japon, qui s’incline bien bas devant son grand frère Not That Telecom.", +"homegrown_eyeballs.latvia_s_mobile_leader_let_me":"Le leader mobile letton : laisse-moi parler, puis je te vends de la 5G.", +"homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom":"Le plus grand réseau mobile de Malaisie : rarement creusé, rarement en panne.", +"homegrown_eyeballs.mozambique_s_rural_mobile_network_towers":"Le réseau mobile rural du Mozambique, avec des pylônes dans des villages que personne d’autre n’a câblés.", +"homegrown_eyeballs.namibia_s_mobile_network_lots_of":"Le réseau mobile namibien : beaucoup de désert, peu de mer.", +"homegrown_eyeballs.namibia_s_state_incumbent_wired_across":"L’opérateur public namibien, câblé à travers le Namib, une dune à la fois.", +"homegrown_eyeballs.new_caledonia_s_cable_operator_can":"Le câblo-opérateur de Nouvelle-Calédonie : peut, va, un jour.", +"homegrown_eyeballs.new_zealand_s_number_two_renamed":"Le numéro deux néo-zélandais, renommé et relooké. Il a gagné, paraît-il.", +"homegrown_eyeballs.norwegian_fibre_from_the_power_company":"De la fibre norvégienne de l’électricien de Stavanger : on ne sait jamais sur quoi on va tomber.", +"homegrown_eyeballs.ooh_redoo_s_maldives_branch_four":"La filiale d’Ooh-redoo aux Maldives : quatre barres sur chaque banc de sable.", +"homegrown_eyeballs.ooh_redoo_s_tunisian_network_mint":"Le réseau tunisien d’Ooh-redoo : d’abord le thé à la menthe, ensuite les mégabits.", +"homegrown_eyeballs.pakistan_s_biggest_mobile_network_improvising":"Le plus grand réseau mobile du Pakistan, qui improvise à chaque panne.", +"homegrown_eyeballs.palau_s_mobile_challenger_your_pal":"Le challenger mobile des Palaos, ton pote sur chaque îlot rocheux.", +"homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg":"La marque dansante de Proxyminus au Luxembourg : il faut être deux pour danser le tango.", +"homegrown_eyeballs.senegal_s_number_two_freshly_renamed":"Le numéro deux du Sénégal, fraîchement rebaptisé et très sûr de lui.", +"homegrown_eyeballs.serbia_s_incumbent_at_your_service":"L’opérateur historique serbe, à votre service.", +"homegrown_eyeballs.singapore_s_number_two_with_a":"Le numéro deux de Singapour, avec un télescope braqué sur SingTell.", +"homegrown_eyeballs.sri_lanka_s_biggest_mobile_network_talks":"Le plus grand réseau mobile du Sri Lanka : parle à tout le monde, surtout à lui-même.", +"homegrown_eyeballs.sri_lanka_s_incumbent_adds_a":"L’opérateur historique du Sri Lanka : ajoute une pincée de latence à chaque route.", +"homegrown_eyeballs.sweden_s_challenger_that_took_on":"Le challenger suédois qui s’est attaqué à Tell-Ya. Une télécom de trop, dit Tell-Ya.", +"homegrown_eyeballs.switzerland_s_incumbent_the_holes_in":"L’opérateur historique suisse. Les trous dans la couverture sont voulus.", +"homegrown_eyeballs.taiwan_s_number_three_never_hears":"Le numéro trois de Taïwan, qui n’entend jamais une demande de peering du premier coup.", +"homegrown_eyeballs.takes_from_the_big_carriers_and":"Prend aux gros opérateurs et donne des forfaits data bon marché à Dacca.", +"homegrown_eyeballs.tell_ya_s_estonian_daughter_e":"La fille estonienne de Tell-Ya, qui signe électroniquement chaque demande de peering.", +"homegrown_eyeballs.thailand_s_biggest_mobile_network_cool":"Le plus grand réseau mobile de Thaïlande, bien frais dans la chaleur de Bangkok.", +"homegrown_eyeballs.the_challenger_that_made_french_broadband":"Le challenger qui a rendu le haut débit français bon marché : libre comme une bière gratuite, pas comme le peering.", +"homegrown_eyeballs.the_dominican_republic_s_other_big":"L’autre grand réseau de la République dominicaine. Dans le doute, on redémarre.", +"homegrown_eyeballs.the_dutch_incumbent_peers_for_peanuts":"L’opérateur historique néerlandais : du peering pour des cacahuètes, la fibre dans chaque polder.", +"homegrown_eyeballs.the_kingdom_s_challenger_always_mobilising":"Le challenger du Royaume, toujours mobilisé pour le prochain mégaprojet.", +"homegrown_eyeballs.the_mobile_network_formerly_known_as":"Le réseau mobile autrefois connu sous un autre nom, et qui n’a pas encore fini de changer de nom.", +"homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"L’autre géant mobile des Philippines, qui parcourt tout l’archipel.", +"homegrown_eyeballs.the_solomon_islands_mobile_challenger_to":"Le challenger mobile des Îles Salomon : être en ligne ou ne pas être.", +"homegrown_eyeballs.ukraine_s_third_mobile_network_kept":"Le troisième réseau mobile d’Ukraine, maintenu en vie par des batteries et de l’obstination.", +"homegrown_eyeballs.venezuela_s_state_telco_can_t":"La télécom d’État vénézuélienne : impossible à réparer, à vendre ou à éteindre.", +"homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant":"Le géant des postes et télécoms du Vietnam : les paquets arrivent en scooter.", +"homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_what":"L’opérateur historique du fixe au Zimbabwe. Ce qui se passe sur la ligne, ne le dis à personne.", "hot_ports_and_rank.add_a_lag_member_or_upgrade":"Ajoute un membre au LAG ou mets à niveau le PNI.", "hot_ports_and_rank.add_a_lag_member_upgrade_the":"Ajoute un membre au LAG, mets à niveau le port ou achète un second upstream.", "hot_ports_and_rank.and_n_more":"et {n} autres", diff --git a/site/i18n/it.js b/site/i18n/it.js index b2547d1..7de3959 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1925,6 +1925,69 @@ "hint.release_to_plan_a_link":"Rilascia per pianificare un link", "hint.tap_your_city_then_launch_broadband":"Tocca la tua città, poi Lancia la banda larga", "hint.tip_drag_from_your_pink_router":"Suggerimento: trascina dal tuo router rosa a un’altra città per posare la fibra", +"homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister":"La sorella bulgara di A-Wan Telekom: stessa WAN, più montagne.", +"homegrown_eyeballs.algeria_s_biggest_mobile_network_easy":"La più grande rete mobile dell’Algeria. Con calma, la banda sta arrivando.", +"homegrown_eyeballs.algeria_s_state_incumbent_some_days":"L’incumbent statale algerino: certi giorni internet va così così, altri si spegne per gli esami.", +"homegrown_eyeballs.american_samoa_s_own_telco_prepaid":"La telco delle Samoa Americane: prepagata, paghi man mano che vai.", +"homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours":"Il gigante mobile dell’Angola, cordialmente vostro in ogni provincia.", +"homegrown_eyeballs.angola_s_number_two_always_on":"Il numero due dell’Angola, sempre in movimento e sempre a vendere.", +"homegrown_eyeballs.austria_s_incumbent_first_in_line":"L’incumbent austriaco, primo in fila per ogni WAN.", +"homegrown_eyeballs.bangladesh_s_biggest_mobile_network_a":"La più grande rete mobile del Bangladesh, forte di cento milioni di SIM.", +"homegrown_eyeballs.bermuda_s_newest_mobile_network_the":"La rete mobile più nuova delle Bermuda. A volte il segnale si perde nel Triangolo.", +"homegrown_eyeballs.bolivia_s_state_telco_thinking_hard":"La telco di stato boliviana, che pensa intensamente a 3.600 metri.", +"homegrown_eyeballs.botswana_s_biggest_mobile_network_with":"La più grande rete mobile del Botswana, con una mascotte su ogni traliccio.", +"homegrown_eyeballs.botswana_s_incumbent_counts_subscribers_like":"L’incumbent del Botswana, che conta gli abbonati come capi di bestiame.", +"homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida":"L’incumbent bulgaro, che vive la vida banda larga.", +"homegrown_eyeballs.cape_verde_s_challenger_one_more":"Lo sfidante di Capo Verde, che aggiunge un’isola alla volta.", +"homegrown_eyeballs.danish_fibre_from_the_power_company":"Fibra danese dalla compagnia elettrica: quando va via la luce, va via anche il Wi-Fi.", +"homegrown_eyeballs.denmark_s_incumbent_you_see_it":"L’incumbent danese: lo vedi in ogni strada.", +"homegrown_eyeballs.doitsche_telekomm_s_hungarian_daughter_pink":"La figlia ungherese di Doitsche Telekomm: rosa e un po’ piccante.", +"homegrown_eyeballs.fibre_to_every_tower_block_rung":"Fibra in ogni grattacielo, annunciata come i tram: ding ding.", +"homegrown_eyeballs.fiji_s_fixed_line_incumbent_never":"L’incumbent della rete fissa delle Figi, che non sta mai fermo.", +"homegrown_eyeballs.finland_s_biggest_mobile_network_unlimited":"La più grande rete mobile della Finlandia, dati illimitati suonati come al pianoforte.", +"homegrown_eyeballs.finnish_broadband_and_mobile_it_s":"Banda larga e mobile finlandesi. Ce l’hanno nel DNA; risultati del test in arrivo.", +"homegrown_eyeballs.french_polynesia_s_mobile_network_came":"La rete mobile della Polinesia Francese: venne, vide e collegò gli atolli.", +"homegrown_eyeballs.fur_elisa_across_the_gulf_of":"Für Elisa dall’altra parte del golfo di Finlandia: la stessa melodia, in estone.", +"homegrown_eyeballs.ghana_s_number_two_a_new":"Il numero due del Ghana: nome nuovo, stessi cavi, ottimi venditori.", +"homegrown_eyeballs.hong_kong_s_incumbent_broadband_full":"La banda larga storica di Hong Kong, piena di vigore e tè al latte.", +"homegrown_eyeballs.iceland_s_incumbent_when_simon_says":"L’incumbent islandese. Quando Símon dice «via», ogni pacchetto prende il cavo per l’Europa.", +"homegrown_eyeballs.iceland_s_mobile_challenger_burning_bright":"Lo sfidante mobile islandese, luminosissimo grazie alla geotermia.", +"homegrown_eyeballs.japan_s_biggest_mobile_network_bows":"La più grande rete mobile del Giappone, che fa un profondo inchino al fratello maggiore Not That Telecom.", +"homegrown_eyeballs.latvia_s_mobile_leader_let_me":"Il leader mobile della Lettonia: lasciami parlare, poi ti vendo il 5G.", +"homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom":"La più grande rete mobile della Malesia: raramente scavata, raramente giù.", +"homegrown_eyeballs.mozambique_s_rural_mobile_network_towers":"La rete mobile rurale del Mozambico, con tralicci in villaggi che nessun altro ha collegato.", +"homegrown_eyeballs.namibia_s_mobile_network_lots_of":"La rete mobile della Namibia: tanto deserto, poco mare.", +"homegrown_eyeballs.namibia_s_state_incumbent_wired_across":"L’incumbent statale della Namibia, cablato attraverso il Namib una duna alla volta.", +"homegrown_eyeballs.new_caledonia_s_cable_operator_can":"L’operatore via cavo della Nuova Caledonia: può, lo farà, prima o poi.", +"homegrown_eyeballs.new_zealand_s_number_two_renamed":"Il numero due della Nuova Zelanda, ribattezzato e rinnovato. A quanto pare, ha vinto.", +"homegrown_eyeballs.norwegian_fibre_from_the_power_company":"Fibra norvegese dalla compagnia elettrica di Stavanger: non sai mai quello che ti capita.", +"homegrown_eyeballs.ooh_redoo_s_maldives_branch_four":"La filiale di Ooh-redoo alle Maldive: quattro tacche su ogni banco di sabbia.", +"homegrown_eyeballs.ooh_redoo_s_tunisian_network_mint":"La rete tunisina di Ooh-redoo: prima il tè alla menta, poi i megabit.", +"homegrown_eyeballs.pakistan_s_biggest_mobile_network_improvising":"La più grande rete mobile del Pakistan, che improvvisa a ogni guasto.", +"homegrown_eyeballs.palau_s_mobile_challenger_your_pal":"Lo sfidante mobile di Palau, il tuo amico su ogni isola di roccia.", +"homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg":"Il marchio danzante di Proxyminus in Lussemburgo: per il tango bisogna essere in due.", +"homegrown_eyeballs.senegal_s_number_two_freshly_renamed":"Il numero due del Senegal, appena ribattezzato e molto sicuro di sé.", +"homegrown_eyeballs.serbia_s_incumbent_at_your_service":"L’incumbent serbo, al vostro servizio.", +"homegrown_eyeballs.singapore_s_number_two_with_a":"Il numero due di Singapore, con un telescopio puntato su SingTell.", +"homegrown_eyeballs.sri_lanka_s_biggest_mobile_network_talks":"La più grande rete mobile dello Sri Lanka: parla con tutti, soprattutto con sé stessa.", +"homegrown_eyeballs.sri_lanka_s_incumbent_adds_a":"L’incumbent dello Sri Lanka: aggiunge un pizzico di latenza a ogni percorso.", +"homegrown_eyeballs.sweden_s_challenger_that_took_on":"Lo sfidante svedese che ha sfidato Tell-Ya. Una telco di troppo, dice Tell-Ya.", +"homegrown_eyeballs.switzerland_s_incumbent_the_holes_in":"L’incumbent svizzero. I buchi nella copertura sono una scelta di design.", +"homegrown_eyeballs.taiwan_s_number_three_never_hears":"Il numero tre di Taiwan, che non sente mai una richiesta di peering alla prima.", +"homegrown_eyeballs.takes_from_the_big_carriers_and":"Prende ai grandi carrier e regala pacchetti dati economici a Dacca.", +"homegrown_eyeballs.tell_ya_s_estonian_daughter_e":"La figlia estone di Tell-Ya, che firma digitalmente ogni richiesta di peering.", +"homegrown_eyeballs.thailand_s_biggest_mobile_network_cool":"La più grande rete mobile della Thailandia, fresca nel caldo di Bangkok.", +"homegrown_eyeballs.the_challenger_that_made_french_broadband":"Lo sfidante che ha reso economica la banda larga francese: libero come la birra gratis, non come il peering.", +"homegrown_eyeballs.the_dominican_republic_s_other_big":"L’altra grande rete della Repubblica Dominicana. Nel dubbio, riavvia.", +"homegrown_eyeballs.the_dutch_incumbent_peers_for_peanuts":"L’incumbent olandese: peering per noccioline, fibra in ogni polder.", +"homegrown_eyeballs.the_kingdom_s_challenger_always_mobilising":"Lo sfidante del Regno, sempre mobilitato per il prossimo megaprogetto.", +"homegrown_eyeballs.the_mobile_network_formerly_known_as":"La rete mobile un tempo nota con un altro nome, che non ha ancora finito di cambiarlo.", +"homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"L’altro gigante mobile delle Filippine, in giro per l’arcipelago.", +"homegrown_eyeballs.the_solomon_islands_mobile_challenger_to":"Lo sfidante mobile delle Isole Salomone: essere o non essere online.", +"homegrown_eyeballs.ukraine_s_third_mobile_network_kept":"La terza rete mobile dell’Ucraina, tenuta in vita da batterie e testardaggine.", +"homegrown_eyeballs.venezuela_s_state_telco_can_t":"La telco di stato del Venezuela: non si può aggiustare, né vendere, né spegnere.", +"homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant":"Il gigante delle poste e telecomunicazioni del Vietnam: i pacchetti arrivano in motorino.", +"homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_what":"L’incumbent della rete fissa dello Zimbabwe. Quello che succede sulla linea, non dirlo a nessuno.", "hot_ports_and_rank.add_a_lag_member_or_upgrade":"Aggiungi un membro al LAG o fai l’upgrade del PNI.", "hot_ports_and_rank.add_a_lag_member_upgrade_the":"Aggiungi un membro al LAG, fai l’upgrade della porta o compra un secondo upstream.", "hot_ports_and_rank.and_n_more":"e altri {n}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a05f651..dc6b6e9 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1925,6 +1925,69 @@ "hint.release_to_plan_a_link":"Solte para planejar um link", "hint.tap_your_city_then_launch_broadband":"Toque na sua cidade e depois em Lançar banda larga", "hint.tip_drag_from_your_pink_router":"Dica: arraste do seu router rosa até outra cidade para lançar fibra", +"homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister":"A irmã búlgara da A-Wan Telekom: a mesma WAN, mais montanhas.", +"homegrown_eyeballs.algeria_s_biggest_mobile_network_easy":"A maior rede móvel da Argélia. Com calma, a largura de banda está a chegar.", +"homegrown_eyeballs.algeria_s_state_incumbent_some_days":"A operadora estatal da Argélia: uns dias a internet vai mais ou menos, outros é desligada por causa dos exames.", +"homegrown_eyeballs.american_samoa_s_own_telco_prepaid":"A operadora da Samoa Americana: pré-paga, paga conforme vai.", +"homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours":"O gigante móvel de Angola, atenciosamente seu em cada província.", +"homegrown_eyeballs.angola_s_number_two_always_on":"O número dois de Angola, sempre em movimento e sempre a vender.", +"homegrown_eyeballs.austria_s_incumbent_first_in_line":"A operadora histórica da Áustria, a primeira da fila em cada WAN.", +"homegrown_eyeballs.bangladesh_s_biggest_mobile_network_a":"A maior rede móvel do Bangladesh, com cem milhões de SIM.", +"homegrown_eyeballs.bermuda_s_newest_mobile_network_the":"A rede móvel mais nova das Bermudas. Às vezes o sinal perde-se no Triângulo.", +"homegrown_eyeballs.bolivia_s_state_telco_thinking_hard":"A operadora estatal da Bolívia, a pensar muito a 3.600 metros.", +"homegrown_eyeballs.botswana_s_biggest_mobile_network_with":"A maior rede móvel do Botsuana, com uma mascote em cada torre.", +"homegrown_eyeballs.botswana_s_incumbent_counts_subscribers_like":"A operadora histórica do Botsuana, que conta os assinantes como cabeças de gado.", +"homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida":"A operadora histórica da Bulgária, a viver la vida banda larga.", +"homegrown_eyeballs.cape_verde_s_challenger_one_more":"A desafiante de Cabo Verde, a juntar mais uma ilha de cada vez.", +"homegrown_eyeballs.danish_fibre_from_the_power_company":"Fibra dinamarquesa da companhia elétrica: quando a luz vai, o Wi-Fi vai também.", +"homegrown_eyeballs.denmark_s_incumbent_you_see_it":"A operadora histórica da Dinamarca: vês em cada rua.", +"homegrown_eyeballs.doitsche_telekomm_s_hungarian_daughter_pink":"A filha húngara da Doitsche Telekomm: cor-de-rosa e ligeiramente picante.", +"homegrown_eyeballs.fibre_to_every_tower_block_rung":"Fibra em cada torre de apartamentos, anunciada como os elétricos: ding ding.", +"homegrown_eyeballs.fiji_s_fixed_line_incumbent_never":"A operadora histórica da rede fixa das Fiji, que nunca está quieta.", +"homegrown_eyeballs.finland_s_biggest_mobile_network_unlimited":"A maior rede móvel da Finlândia, dados ilimitados tocados como ao piano.", +"homegrown_eyeballs.finnish_broadband_and_mobile_it_s":"Banda larga e móvel finlandeses. Está no ADN deles; resultados do teste pendentes.", +"homegrown_eyeballs.french_polynesia_s_mobile_network_came":"A rede móvel da Polinésia Francesa: veio, viu e ligou os atóis.", +"homegrown_eyeballs.fur_elisa_across_the_gulf_of":"Für Elisa do outro lado do golfo da Finlândia: a mesma melodia, em estónio.", +"homegrown_eyeballs.ghana_s_number_two_a_new":"O número dois do Gana: nome novo, os mesmos cabos, ótimos vendedores.", +"homegrown_eyeballs.hong_kong_s_incumbent_broadband_full":"A banda larga histórica de Hong Kong, cheia de vigor e chá com leite.", +"homegrown_eyeballs.iceland_s_incumbent_when_simon_says":"A operadora histórica da Islândia. Quando o Símon diz «já», cada pacote apanha o cabo para a Europa.", +"homegrown_eyeballs.iceland_s_mobile_challenger_burning_bright":"A desafiante móvel da Islândia, a brilhar com energia geotérmica.", +"homegrown_eyeballs.japan_s_biggest_mobile_network_bows":"A maior rede móvel do Japão, que faz uma vénia profunda ao irmão mais velho Not That Telecom.", +"homegrown_eyeballs.latvia_s_mobile_leader_let_me":"O líder móvel da Letónia: deixa-me falar e depois vendo-te 5G.", +"homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom":"A maior rede móvel da Malásia: raramente escavada, raramente fora do ar.", +"homegrown_eyeballs.mozambique_s_rural_mobile_network_towers":"A rede móvel rural de Moçambique, com torres em aldeias que mais ninguém ligou.", +"homegrown_eyeballs.namibia_s_mobile_network_lots_of":"A rede móvel da Namíbia: muito deserto, pouco mar.", +"homegrown_eyeballs.namibia_s_state_incumbent_wired_across":"A operadora estatal da Namíbia, cablada pelo Namibe, uma duna de cada vez.", +"homegrown_eyeballs.new_caledonia_s_cable_operator_can":"A operadora de cabo da Nova Caledónia: pode, vai, um dia.", +"homegrown_eyeballs.new_zealand_s_number_two_renamed":"O número dois da Nova Zelândia, renomeado e com nova imagem. Ao que parece, ganhou.", +"homegrown_eyeballs.norwegian_fibre_from_the_power_company":"Fibra norueguesa da companhia elétrica de Stavanger: nunca se sabe o que vai sair.", +"homegrown_eyeballs.ooh_redoo_s_maldives_branch_four":"A filial da Ooh-redoo nas Maldivas: rede cheia em cada banco de areia.", +"homegrown_eyeballs.ooh_redoo_s_tunisian_network_mint":"A rede tunisina da Ooh-redoo: primeiro chá de menta, depois megabits.", +"homegrown_eyeballs.pakistan_s_biggest_mobile_network_improvising":"A maior rede móvel do Paquistão, a improvisar a cada falha.", +"homegrown_eyeballs.palau_s_mobile_challenger_your_pal":"A desafiante móvel de Palau, o teu amigo em cada ilha rochosa.", +"homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg":"A marca dançante da Proxyminus no Luxemburgo: são precisos dois para dançar o tango.", +"homegrown_eyeballs.senegal_s_number_two_freshly_renamed":"O número dois do Senegal, acabado de rebatizar e muito seguro de si.", +"homegrown_eyeballs.serbia_s_incumbent_at_your_service":"A operadora histórica da Sérvia, ao seu serviço.", +"homegrown_eyeballs.singapore_s_number_two_with_a":"O número dois de Singapura, com um telescópio apontado à SingTell.", +"homegrown_eyeballs.sri_lanka_s_biggest_mobile_network_talks":"A maior rede móvel do Sri Lanka: fala com todos, sobretudo consigo mesma.", +"homegrown_eyeballs.sri_lanka_s_incumbent_adds_a":"A operadora histórica do Sri Lanka: junta uma pitada de latência a cada rota.", +"homegrown_eyeballs.sweden_s_challenger_that_took_on":"A desafiante sueca que enfrentou a Tell-Ya. Uma operadora a mais, diz a Tell-Ya.", +"homegrown_eyeballs.switzerland_s_incumbent_the_holes_in":"A operadora histórica da Suíça. Os buracos na cobertura são uma escolha de design.", +"homegrown_eyeballs.taiwan_s_number_three_never_hears":"O número três de Taiwan, que nunca ouve um pedido de peering à primeira.", +"homegrown_eyeballs.takes_from_the_big_carriers_and":"Tira às grandes operadoras e dá pacotes de dados baratos a Daca.", +"homegrown_eyeballs.tell_ya_s_estonian_daughter_e":"A filha estónia da Tell-Ya, que assina digitalmente cada pedido de peering.", +"homegrown_eyeballs.thailand_s_biggest_mobile_network_cool":"A maior rede móvel da Tailândia, fresquinha no calor de Bangkok.", +"homegrown_eyeballs.the_challenger_that_made_french_broadband":"A desafiante que tornou barata a banda larga francesa: livre como cerveja grátis, não como o peering.", +"homegrown_eyeballs.the_dominican_republic_s_other_big":"A outra grande rede da República Dominicana. Na dúvida, reinicia.", +"homegrown_eyeballs.the_dutch_incumbent_peers_for_peanuts":"A operadora histórica neerlandesa: peering por amendoins, fibra em cada pólder.", +"homegrown_eyeballs.the_kingdom_s_challenger_always_mobilising":"A desafiante do Reino, sempre mobilizada para o próximo megaprojeto.", +"homegrown_eyeballs.the_mobile_network_formerly_known_as":"A rede móvel antes conhecida por outro nome, e que ainda não acabou de mudar de nome.", +"homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"O outro gigante móvel das Filipinas, a percorrer o arquipélago.", +"homegrown_eyeballs.the_solomon_islands_mobile_challenger_to":"A desafiante móvel das Ilhas Salomão: estar ou não estar online.", +"homegrown_eyeballs.ukraine_s_third_mobile_network_kept":"A terceira rede móvel da Ucrânia, mantida viva por baterias e teimosia.", +"homegrown_eyeballs.venezuela_s_state_telco_can_t":"A operadora estatal da Venezuela: não dá para consertar, nem vender, nem desligar.", +"homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant":"O gigante dos correios e telecomunicações do Vietname: os pacotes chegam de mota.", +"homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_what":"A operadora histórica da rede fixa do Zimbabué. O que acontece na linha, não contes a ninguém.", "hot_ports_and_rank.add_a_lag_member_or_upgrade":"Adicione um membro ao LAG ou faça upgrade do PNI.", "hot_ports_and_rank.add_a_lag_member_upgrade_the":"Adicione um membro ao LAG, faça upgrade da porta ou compre um segundo upstream.", "hot_ports_and_rank.and_n_more":"e mais {n}", diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index e24249d..217baa3 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -8,7 +8,7 @@ const NETS=[ {id:'drz',name:'Drizzle Electric',asn:9369,type:'t2',pol:'open',share:.04,price:4,col:'#1E90FF',auIx:['syd','mel','bne','per'],pops:['man','chc','edi','svg','bde','bcn','mil','rom','pmo','lis','ath','atn','den','phx','bos','hou','slc','ber','zrh','nbo','akl','per','jkt','mnl','dub','rek','tor','mtl','lax','mex','sof','osl','icn','sea','sjc','dal','chi','ash','nyc','mia','lon','ams','fra','par','sto','mad','hkg','sin','tok','syd','jnb','for','rio','bue','scl','lim','bog','pan','del','maa','blr','hyd','tpe','auh','cpt','mel','bne','osa','kul','bkk','sgn','khi','dac','cbo','waw','prg','vie','bud','buh','tll','ist','kyv','jed','ruh','doh','kcy','cal','van','ott','bru','oos','bet','ham','muc','ccs','lpb','alg','tun','cas','dkr','dus'],ix:'ALL',blurb:tr('networks.will_peer_with_anyone_anywhere')}, {id:'tng',name:'Tangerine Telecom',asn:5115,type:'t2',cc:['CD','CI','CM','EG','ES','FR','MA','MG','MQ','PL','RE','RO','SN','TN'],pol:'selective',minIx:15,minPni:40,share:.03,price:6,col:'#FF8C42',pops:['tci','bcn','cai','nbo','dxb','par','mrs','mad','lon','ams','lag','jnb','waw','buh','dkr','abj','cas','tun','dla','fih','fdf','run','tnr'],ix:['bcn','par','mrs','mad','lon','ams','lag','jnb','waw','dkr','abj','cas','tun','dla','fih'],blurb:tr('networks.juicy_reach_into_europe_and_africa')}, {id:'sgt',name:'SingTell',asn:7474,type:'t2',cc:'SG',pol:'selective',minIx:15,minPni:40,share:.03,price:7,col:'#00A6A6',pops:['jkt','mnl','per','akl','icn','sin','hkg','tok','syd','bom','tpe','maa','kul','bkk','sgn','mel','bne'],ix:['sin','hkg','tok','bom','tpe','maa','kul','bkk'],blurb:tr('networks.sings_your_packets_across_asia')}, - {id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',cc:['CD','CZ','DE','EG','ES','GB','GR','IE','MZ','QA','TR','TZ','ZA'],pol:'paid',freeLv:7,paidFee:8000,share:.03,price:6,col:'#E63946',pops:['man','edi','mil','rom','lis','ath','nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa','ist','prg','bud','buh','doh','acc','dar','fih','mpm','dus'],ix:[],blurb:tr('networks.ended_free_peering_across_europe_and')}, + {id:'vdp',name:'Voda-Phony',asn:1373,type:'t2',cc:['CD','CZ','DE','EG','ES','GB','GR','IE','MZ','NL','PT','QA','RO','TR','TZ','ZA'],pol:'paid',freeLv:7,paidFee:8000,share:.03,price:6,col:'#E63946',pops:['man','edi','mil','rom','lis','ath','nbo','cai','ber','dub','dxb','lon','fra','ams','mad','mrs','jnb','bom','lag','cpt','del','maa','ist','prg','bud','buh','doh','acc','dar','fih','mpm','dus'],ix:[],blurb:tr('networks.ended_free_peering_across_europe_and')}, {id:'ctc',name:'China Telecomet',asn:4314,type:'t2',cc:'CN',pol:'restrictive',share:.02,price:22,premium:2.5,premAt:['hkg','mos'],premOnly:['mos'],cn:true,col:'#0B5CAD',pops:['pek','sha','hkg','sin','tok','lon','fra','nyc','sjc'],ix:[],blurb:tr('networks.the_biggest_network_in_china_its')}, {id:'cun',name:'China Unicorn',asn:4837,type:'t2',cc:'CN',pol:'restrictive',share:.015,price:16,cn:true,col:'#D7000F',pops:['pek','sha','hkg','fra','sjc','lon'],ix:[],blurb:tr('networks.number_two_in_china_with_a')}, {id:'cmb',name:'China Moble',asn:9880,type:'eye',cc:'CN',pol:'paid',freeLv:10,paidFee:12000,share:.01,cn:true,col:'#0085CA',pops:['pek','sha','hkg'],ix:[],blurb:tr('networks.the_largest_mobile_network_on_earth')}, @@ -57,7 +57,7 @@ NETS.push( {id:'oio',name:'Oi Oi',asn:7739,type:'eye',cc:'BR',pol:'selective',up:['lvl','tly'],minIx:6,minPni:20,share:.008,col:'#FFD000',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.says_oi_to_every_home_in')}, {id:'tmt',name:'TIM-TIM Mobile',asn:26616,type:'eye',cc:'BR',pol:'selective',up:['skl'],minIx:6,minPni:20,share:.007,col:'#004691',pops:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],ix:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],blurb:tr('networks.a_mobile_network_named_after_the')}, {id:'bsn',name:'Brisanada',asn:28127,type:'eye',cc:'BR',pol:'open',up:['lvl'],share:.004,col:'#F7941D',pops:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],ix:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],blurb:tr('networks.fiber_across_the_sertao_of_the')}, - {id:'mvs',name:'Moviestar',asn:12957,type:'t2',cc:['CL','MX','VE'],pol:'selective',up:['tly','lvl'],minIx:8,minPni:25,share:.008,price:6,col:'#019DF4',pops:['mex','gua','bog','mde','uio','lim','lpb','scl','bue','cor','mvd','ccs','sao','mia'],ix:['mex','bog','lim','scl','bue','mvd','ccs','sao'],blurb:tr('networks.a_spanish_carrier_starring_in_every')}, + {id:'mvs',name:'Moviestar',asn:12957,type:'t2',cc:['AR','CL','CO','EC','MX','PE','UY','VE'],pol:'selective',up:['tly','lvl'],minIx:8,minPni:25,share:.008,price:6,col:'#019DF4',pops:['mex','gua','bog','mde','uio','lim','lpb','scl','bue','cor','mvd','ccs','sao','mia'],ix:['mex','bog','lim','scl','bue','mvd','ccs','sao'],blurb:tr('networks.a_spanish_carrier_starring_in_every')}, {id:'llt',name:'Liberty Latte America',asn:23521,type:'t2',cc:['BB','BS','CR','CW','JM','PA','PR','TT'],pol:'open',up:['lvl','cog'],share:.005,price:5,col:'#6C2C91',pops:['mia','pan','sjo','gua','bog','mde','ccs','sju','kin','nas','pos','bgi','cur'],ix:['pan','sjo','gua','bog','kin','pos'],blurb:tr('networks.cables_all_around_the_caribbean')}, {id:'ant',name:'Antelope',asn:6058,type:'eye',cc:'UY',pol:'selective',up:['skl','tly'],minIx:3,minPni:15,share:.004,col:'#0072BC',pops:['mvd'],ix:['mvd'],blurb:tr('networks.uruguay_s_state_telco_fast')}, {id:'tgo',name:'Tiger Mobile',asn:27743,type:'eye',cc:['PY','BO','GT','CR','PA','CO'],pol:'selective',up:['lvl'],minIx:4,minPni:15,share:.005,col:'#00377B',pops:['asu','lpb','gua','sjo','pan','bog','mde'],ix:['asu','lpb','gua','sjo','bog'],blurb:tr('networks.prepaid_mobile_from_paraguay_to')}, diff --git a/src/game/30-networks/32-homegrown-eyeballs.js b/src/game/30-networks/32-homegrown-eyeballs.js new file mode 100644 index 0000000..6d94cb8 --- /dev/null +++ b/src/game/30-networks/32-homegrown-eyeballs.js @@ -0,0 +1,70 @@ +/* Homegrown eyeballs: every country on the map has at least two consumer networks of its own (gameplay rule W2, + tests/gameplay-rules.test.js). Each is a real operator of that country, with its real ASN, a traffic share scaled by + subscribers like the rest, presence where it really peers, and a realistic upstream (a big carrier where it sits, or + its group's own carrier), so it sits in a founding Tier 1's customer cone: Tier 1 is no harder for anyone, old saves included, + and older saves reach them by the courtesy route for their first 60 days (sanitize(), S.seen). One per line, sorted by id. + Sits before 40-traffic-shares.js, which indexes NETS. */ +NETS.push( + {id:'a1b',name:'A-Wan Bulgaria',asn:8717,type:'eye',cc:'BG',pol:'open',share:.0015,up:['aat'],col:'#DA291C',pops:['sof','vie'],ix:['sof'],blurb:tr('homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister')}, + {id:'aat',name:'A-Wan Telekom',asn:8447,type:'eye',cc:'AT',pol:'selective',minIx:6,minPni:20,share:.003,up:['tly','lvl'],col:'#DA291C',pops:['vie','fra','prg','bud'],ix:['vie'],blurb:tr('homegrown_eyeballs.austria_s_incumbent_first_in_line')}, + {id:'agt',name:'Algérie Comme-Ci Comme-Ça',asn:36947,type:'eye',cc:'DZ',pol:'selective',minIx:2,minPni:12,share:.003,up:['tly','cog'],col:'#0B7A3E',pops:['alg','mrs'],ix:['alg'],blurb:tr('homegrown_eyeballs.algeria_s_state_incumbent_some_days')}, + {id:'ais',name:'AIS-cream',asn:45430,type:'eye',cc:'TH',pol:'selective',minIx:4,minPni:15,share:.006,up:['ntt','tat'],col:'#B5D334',pops:['bkk','sin','hkg'],ix:['bkk'],blurb:tr('homegrown_eyeballs.thailand_s_biggest_mobile_network_cool')}, + {id:'alb',name:'Altibox of Chocolates',asn:29695,type:'eye',cc:'NO',pol:'open',share:.002,up:['tly','cog'],col:'#2D2A6E',pops:['osl','svg','krs'],ix:['osl','svg'],blurb:tr('homegrown_eyeballs.norwegian_fibre_from_the_power_company')}, + {id:'alt',name:'Alt-Ctrl-Dominicana',asn:28118,type:'eye',cc:'DO',pol:'selective',minIx:2,minPni:10,share:.0015,up:['lvl','cog'],col:'#1A1A1A',pops:['sdq','mia'],ix:[],blurb:tr('homegrown_eyeballs.the_dominican_republic_s_other_big')}, + {id:'ast',name:'Pay-Go Pay-Go Telecom',asn:9751,type:'eye',cc:'AS',pol:'selective',minIx:1,minPni:8,share:.0004,up:['fnt'],col:'#00539B',pops:['ppg'],ix:[],blurb:tr('homegrown_eyeballs.american_samoa_s_own_telco_prepaid')}, + {id:'bmo',name:'To Be Mobile',asn:132462,type:'eye',cc:'SB',pol:'open',share:.0002,up:['tly'],col:'#E4007C',pops:['hir'],ix:['hir'],blurb:tr('homegrown_eyeballs.the_solomon_islands_mobile_challenger_to')}, + {id:'btc',name:'Botswana Tele-cow',asn:14988,type:'eye',cc:'BW',pol:'selective',minIx:1,minPni:8,share:.0006,up:['liq'],col:'#0072BC',pops:['gbe','jnb'],ix:['gbe'],blurb:tr('homegrown_eyeballs.botswana_s_incumbent_counts_subscribers_like')}, + {id:'clc',name:'Seldom-Digi',asn:10030,type:'eye',cc:'MY',pol:'selective',minIx:4,minPni:15,share:.003,up:['ntt','tat'],col:'#0019FF',pops:['kul','sin'],ix:['kul'],blurb:tr('homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom')}, + {id:'cnl',name:'Can’t’L',asn:17480,type:'eye',cc:'NC',pol:'open',share:.0003,up:['pft'],col:'#E30613',pops:['nou'],ix:['nou'],blurb:tr('homegrown_eyeballs.new_caledonia_s_cable_operator_can')}, + {id:'ctv',name:'Can’t-V',asn:8048,type:'eye',cc:'VE',pol:'selective',minIx:2,minPni:10,share:.002,up:['tly','lvl'],col:'#0055A5',pops:['ccs','mia'],ix:['ccs'],blurb:tr('homegrown_eyeballs.venezuela_s_state_telco_can_t')}, + {id:'dcm',name:'Docomo Arigato',asn:9605,type:'eye',cc:'JP',pol:'selective',minIx:6,minPni:20,share:.008,up:['ntt'],col:'#CC0033',pops:['tok','osa','fuk'],ix:['tok','osa'],blurb:tr('homegrown_eyeballs.japan_s_biggest_mobile_network_bows')}, + {id:'djz',name:'Djezzy Does It',asn:327931,type:'eye',cc:'DZ',pol:'open',share:.002,up:['tly'],col:'#E2001A',pops:['alg'],ix:['alg'],blurb:tr('homegrown_eyeballs.algeria_s_biggest_mobile_network_easy')}, + {id:'dlg',name:'Inner Dialog',asn:18001,type:'eye',cc:'LK',pol:'open',share:.0015,up:['tat','ntt'],col:'#E5202E',pops:['cbo'],ix:['cbo'],blurb:tr('homegrown_eyeballs.sri_lanka_s_biggest_mobile_network_talks')}, + {id:'dna',name:'DNA Test Results',asn:16086,type:'eye',cc:'FI',pol:'open',share:.002,up:['tly'],col:'#FF4F00',pops:['hel'],ix:['hel'],blurb:tr('homegrown_eyeballs.finnish_broadband_and_mobile_it_s')}, + {id:'ele',name:'Für Elisa Eesti',asn:2586,type:'eye',cc:'EE',pol:'open',share:.0008,up:['els'],col:'#0068B4',pops:['tll'],ix:['tll'],blurb:tr('homegrown_eyeballs.fur_elisa_across_the_gulf_of')}, + {id:'els',name:'Für Elisa',asn:719,type:'eye',cc:'FI',pol:'selective',minIx:5,minPni:20,share:.003,up:['tly','cog'],col:'#0068B4',pops:['hel','sto'],ix:['hel'],blurb:tr('homegrown_eyeballs.finland_s_biggest_mobile_network_unlimited')}, + {id:'ent',name:'Entel-ligence',asn:6568,type:'eye',cc:'BO',pol:'selective',minIx:2,minPni:10,share:.0012,up:['tly','lvl'],col:'#0033A0',pops:['lpb'],ix:['lpb'],blurb:tr('homegrown_eyeballs.bolivia_s_state_telco_thinking_hard')}, + {id:'fet',name:'Far EasTone-Deaf',asn:9674,type:'eye',cc:'TW',pol:'selective',minIx:3,minPni:12,share:.003,up:['ntt'],col:'#E60012',pops:['tpe','hkg'],ix:['tpe'],blurb:tr('homegrown_eyeballs.taiwan_s_number_three_never_hears')}, + {id:'fre',name:'Free as in Beer',asn:12322,type:'eye',cc:'FR',pol:'selective',minIx:6,minPni:20,share:.006,up:['cog','lvl'],col:'#CD1E25',pops:['par','mrs','ams','lon','fra'],ix:['par','mrs'],blurb:tr('homegrown_eyeballs.the_challenger_that_made_french_broadband')}, + {id:'frs',name:'Yas Queen Sénégal',asn:37649,type:'eye',cc:'SN',pol:'open',share:.0008,up:['tat','tly'],col:'#FFD100',pops:['dkr'],ix:['dkr'],blurb:tr('homegrown_eyeballs.senegal_s_number_two_freshly_renamed')}, + {id:'glb',name:'Globe-Trotter Telecom',asn:4775,type:'eye',cc:'PH',pol:'selective',minIx:3,minPni:15,share:.006,up:['ntt','tat'],col:'#0056A2',pops:['mnl','hkg','sin'],ix:['hkg','sin'],blurb:tr('homegrown_eyeballs.the_philippines_other_mobile_giant_roaming')}, + {id:'gph',name:'Grameen Machine',asn:24389,type:'eye',cc:'BD',pol:'selective',minIx:3,minPni:12,share:.004,up:['tat','ntt'],col:'#19AAF8',pops:['dac','sin'],ix:['dac'],blurb:tr('homegrown_eyeballs.bangladesh_s_biggest_mobile_network_a')}, + {id:'hkb',name:'Ding-Ding Broadband',asn:9269,type:'eye',cc:'HK',pol:'open',share:.002,up:['ntt','cog'],col:'#6A2C91',pops:['hkg'],ix:['hkg'],blurb:tr('homegrown_eyeballs.fibre_to_every_tower_block_rung')}, + {id:'hkt',name:'Net-Vigour HK',asn:4760,type:'eye',cc:'HK',pol:'selective',minIx:5,minPni:20,share:.004,up:['ntt','tat'],col:'#00A0E1',pops:['hkg','sin','tok','lax'],ix:['hkg'],blurb:tr('homegrown_eyeballs.hong_kong_s_incumbent_broadband_full')}, + {id:'jaz',name:'All That Jazz',asn:45669,type:'eye',cc:'PK',pol:'selective',minIx:2,minPni:10,share:.004,up:['tat'],col:'#ED1C24',pops:['khi','dxb'],ix:['khi'],blurb:tr('homegrown_eyeballs.pakistan_s_biggest_mobile_network_improvising')}, + {id:'kpn',name:'Kay-Pea-Nuts',asn:1136,type:'eye',cc:'NL',pol:'selective',minIx:6,minPni:20,share:.005,up:['lvl','tly'],col:'#00C300',pops:['ams','fra','lon'],ix:['ams'],blurb:tr('homegrown_eyeballs.the_dutch_incumbent_peers_for_peanuts')}, + {id:'lfc',name:'Half-Life-cell',asn:34058,type:'eye',cc:'UA',pol:'open',share:.002,up:['cog','tly'],col:'#FFCC00',pops:['kyv','waw','fra'],ix:['kyv'],blurb:tr('homegrown_eyeballs.ukraine_s_third_mobile_network_kept')}, + {id:'lmt',name:'Let Me Talk',asn:12847,type:'eye',cc:'LV',pol:'selective',minIx:2,minPni:8,share:.0008,up:['tly'],col:'#4E2C82',pops:['rix','sto'],ix:['rix'],blurb:tr('homegrown_eyeballs.latvia_s_mobile_leader_let_me')}, + {id:'mca',name:'MT-Sea',asn:37009,type:'eye',cc:'NA',pol:'selective',minIx:1,minPni:8,share:.0005,up:['liq'],col:'#0067B1',pops:['wdh'],ix:['wdh'],blurb:tr('homegrown_eyeballs.namibia_s_mobile_network_lots_of')}, + {id:'mgt',name:'Magenta Paprika',asn:5483,type:'eye',cc:'HU',pol:'selective',minIx:4,minPni:15,share:.003,up:['dtk','tly'],col:'#E20074',pops:['bud','vie','fra'],ix:['bud'],blurb:tr('homegrown_eyeballs.doitsche_telekomm_s_hungarian_daughter_pink')}, + {id:'mob',name:'Mobily-zation',asn:35819,type:'eye',cc:'SA',pol:'selective',minIx:3,minPni:12,share:.004,up:['tat','tly'],col:'#00A7E1',pops:['ruh','jed','dxb','fra'],ix:['ruh'],blurb:tr('homegrown_eyeballs.the_kingdom_s_challenger_always_mobilising')}, + {id:'msc',name:'Mascot Wireless',asn:37014,type:'eye',cc:'BW',pol:'open',share:.0006,up:['liq'],col:'#008FD5',pops:['gbe'],ix:['gbe'],blurb:tr('homegrown_eyeballs.botswana_s_biggest_mobile_network_with')}, + {id:'mts',name:'Serve-ia Telekom',asn:8400,type:'eye',cc:'RS',pol:'selective',minIx:3,minPni:12,share:.003,up:['tly','cog'],col:'#E2001A',pops:['beg','fra','sof'],ix:[],blurb:tr('homegrown_eyeballs.serbia_s_incumbent_at_your_service')}, + {id:'mvc',name:'Movi-Sell',asn:37081,type:'eye',cc:'AO',pol:'open',share:.0008,up:['agc'],col:'#F7941D',pops:['lad'],ix:['lad'],blurb:tr('homegrown_eyeballs.angola_s_number_two_always_on')}, + {id:'mvt',name:'Movie-Tell',asn:37342,type:'eye',cc:'MZ',pol:'open',share:.0006,up:['liq'],col:'#E30613',pops:['mpm'],ix:['mpm'],blurb:tr('homegrown_eyeballs.mozambique_s_rural_mobile_network_towers')}, + {id:'nov',name:'Super-Nova hf.',asn:43571,type:'eye',cc:'IS',pol:'open',share:.0004,up:['tly','cog'],col:'#ED1F7F',pops:['rek'],ix:[],blurb:tr('homegrown_eyeballs.iceland_s_mobile_challenger_burning_bright')}, + {id:'nrl',name:'Northern Lights Out',asn:8273,type:'eye',cc:'DK',pol:'open',share:.002,up:['tly','cog'],col:'#00A651',pops:['cph','ebj'],ix:['cph'],blurb:tr('homegrown_eyeballs.danish_fibre_from_the_power_company')}, + {id:'omv',name:'Ooh-redoo Atolls',asn:55944,type:'eye',cc:'MV',pol:'open',share:.0003,up:['ord','tat'],col:'#ED1C24',pops:['mle'],ix:[],blurb:tr('homegrown_eyeballs.ooh_redoo_s_maldives_branch_four')}, + {id:'onz',name:'Won New Zealand',asn:4768,type:'eye',cc:'NZ',pol:'selective',minIx:3,minPni:12,share:.002,up:['ntt','tly'],col:'#E4002B',pops:['akl','chc','syd'],ix:['akl','chc'],blurb:tr('homegrown_eyeballs.new_zealand_s_number_two_renamed')}, + {id:'otn',name:'Ooh-redoo Tunisie',asn:37693,type:'eye',cc:'TN',pol:'open',share:.0012,up:['ord','tly'],col:'#ED1C24',pops:['tun','mrs'],ix:['tun'],blurb:tr('homegrown_eyeballs.ooh_redoo_s_tunisian_network_mint')}, + {id:'pmc',name:'Pal-O-Mine Mobile',asn:58932,type:'eye',cc:'PW',pol:'open',share:.0002,up:['ntt'],col:'#0099CC',pops:['ror'],ix:[],blurb:tr('homegrown_eyeballs.palau_s_mobile_challenger_your_pal')}, + {id:'prm',name:'Paradise Lost Mobile',asn:55159,type:'eye',cc:'BM',pol:'open',share:.0003,up:['lvl'],col:'#00B2A9',pops:['bda'],ix:[],blurb:tr('homegrown_eyeballs.bermuda_s_newest_mobile_network_the')}, + {id:'rob',name:'Robi-n Hood',asn:24432,type:'eye',cc:'BD',pol:'open',share:.002,up:['tat'],col:'#E2231A',pops:['dac'],ix:['dac'],blurb:tr('homegrown_eyeballs.takes_from_the_big_carriers_and')}, + {id:'slt',name:'SLT-and-Pepper',asn:9329,type:'eye',cc:'LK',pol:'selective',minIx:2,minPni:10,share:.0015,up:['tat'],col:'#0070C0',pops:['cbo','sin'],ix:['cbo'],blurb:tr('homegrown_eyeballs.sri_lanka_s_incumbent_adds_a')}, + {id:'smn',name:'Símon Says',asn:215793,type:'eye',cc:'IS',pol:'selective',minIx:1,minPni:8,share:.0006,up:['tly'],col:'#4A2B83',pops:['rek','lon'],ix:[],blurb:tr('homegrown_eyeballs.iceland_s_incumbent_when_simon_says')}, + {id:'sth',name:'StarHubble',asn:4657,type:'eye',cc:'SG',pol:'selective',minIx:4,minPni:15,share:.003,up:['ntt','tat'],col:'#68B030',pops:['sin','hkg'],ix:['sin'],blurb:tr('homegrown_eyeballs.singapore_s_number_two_with_a')}, + {id:'swc',name:'Swiss-Cheese-com',asn:3303,type:'eye',cc:'CH',pol:'selective',minIx:8,minPni:25,share:.004,up:['lvl','tly'],col:'#001155',pops:['zrh','fra'],ix:['zrh'],blurb:tr('homegrown_eyeballs.switzerland_s_incumbent_the_holes_in')}, + {id:'tcg',name:'Tele-Sell Ghana',asn:29614,type:'eye',cc:'GH',pol:'selective',minIx:2,minPni:10,share:.0015,up:['tat','tly'],col:'#E30613',pops:['acc','lag'],ix:['acc'],blurb:tr('homegrown_eyeballs.ghana_s_number_two_a_new')}, + {id:'tdc',name:'YouSee-Me-Now',asn:3292,type:'eye',cc:'DK',pol:'selective',minIx:5,minPni:20,share:.003,up:['tly'],col:'#0B2D71',pops:['cph','ebj','sto','ham'],ix:['cph'],blurb:tr('homegrown_eyeballs.denmark_s_incumbent_you_see_it')}, + {id:'tee',name:'Tell-Ya Eesti',asn:3249,type:'eye',cc:'EE',pol:'selective',minIx:3,minPni:12,share:.001,up:['tly'],col:'#990AE3',pops:['tll','hel','sto'],ix:['tll'],blurb:tr('homegrown_eyeballs.tell_ya_s_estonian_daughter_e')}, + {id:'tel',name:'Tell No One',asn:37204,type:'eye',cc:'ZW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['liq'],col:'#0D4C92',pops:['hre'],ix:['hre'],blurb:tr('homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_what')}, + {id:'tfl',name:'Telecom Fidget',asn:45349,type:'eye',cc:'FJ',pol:'selective',minIx:1,minPni:8,share:.0004,up:['fnt'],col:'#00A3E0',pops:['suv'],ix:['suv'],blurb:tr('homegrown_eyeballs.fiji_s_fixed_line_incumbent_never')}, + {id:'tgd',name:'Tango-Down',asn:48526,type:'eye',cc:'LU',pol:'selective',minIx:2,minPni:8,share:.0005,up:['bgs'],col:'#FF6600',pops:['bet'],ix:['bet'],blurb:tr('homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg')}, + {id:'tlt',name:'Tele-Two-Many',asn:1257,type:'eye',cc:'SE',pol:'selective',minIx:4,minPni:15,share:.003,up:['tly','cog'],col:'#000000',pops:['sto','cph','osl'],ix:['sto'],blurb:tr('homegrown_eyeballs.sweden_s_challenger_that_took_on')}, + {id:'tnm',name:'Tele-Namib',asn:36996,type:'eye',cc:'NA',pol:'open',share:.0004,up:['liq','tat'],col:'#00529B',pops:['wdh'],ix:['wdh'],blurb:tr('homegrown_eyeballs.namibia_s_state_incumbent_wired_across')}, + {id:'utl',name:'Unitel-ly Yours',asn:37119,type:'eye',cc:'AO',pol:'selective',minIx:3,minPni:12,share:.002,up:['agc'],col:'#F28C00',pops:['lad','lis'],ix:['lad'],blurb:tr('homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours')}, + {id:'utp',name:'Unitel T-Plus-Plus',asn:37575,type:'eye',cc:'CV',pol:'open',share:.0003,up:['cvt'],col:'#F28C00',pops:['rai'],ix:['rai'],blurb:tr('homegrown_eyeballs.cape_verde_s_challenger_one_more')}, + {id:'vin',name:'Vini Vidi Vici',asn:9471,type:'eye',cc:'PF',pol:'open',share:.0003,up:['pft'],col:'#E2001A',pops:['ppt'],ix:[],blurb:tr('homegrown_eyeballs.french_polynesia_s_mobile_network_came')}, + {id:'vnp',name:'VNPT (Very Nice Packet Times)',asn:45899,type:'eye',cc:'VN',pol:'selective',minIx:3,minPni:12,share:.004,up:['ntt','tat'],col:'#0066B3',pops:['sgn','hkg','sin'],ix:['sgn'],blurb:tr('homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant')}, + {id:'vvc',name:'Viva la Vidacom',asn:8866,type:'eye',cc:'BG',pol:'selective',minIx:4,minPni:15,share:.002,up:['tly','cog'],col:'#E2001A',pops:['sof','fra'],ix:['sof'],blurb:tr('homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida')}, + {id:'yet',name:'Not Yettel',asn:31042,type:'eye',cc:'RS',pol:'open',share:.0015,up:['tly'],col:'#B4FF00',pops:['beg'],ix:[],blurb:tr('homegrown_eyeballs.the_mobile_network_formerly_known_as')}); diff --git a/src/i18n/en.js b/src/i18n/en.js index 9e5308b..3af0189 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1926,6 +1926,69 @@ "hint.release_to_plan_a_link":"Release to plan a link", "hint.tap_your_city_then_launch_broadband":"Tap your city, then Launch broadband", "hint.tip_drag_from_your_pink_router":"Tip: drag from your pink router to another city to lay fiber", +"homegrown_eyeballs.a_wan_telekom_s_bulgarian_sister":"A-Wan Telekom’s Bulgarian sister: the same WAN, more mountains.", +"homegrown_eyeballs.algeria_s_biggest_mobile_network_easy":"Algeria’s biggest mobile network. Easy does it, the bandwidth is coming.", +"homegrown_eyeballs.algeria_s_state_incumbent_some_days":"Algeria’s state incumbent: some days the internet is so-so, some days it is off for exams.", +"homegrown_eyeballs.american_samoa_s_own_telco_prepaid":"American Samoa’s own telco: prepaid, pay as you go-go.", +"homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours":"Angola’s mobile giant, sincerely yours in every province.", +"homegrown_eyeballs.angola_s_number_two_always_on":"Angola’s number two, always on the move and always selling.", +"homegrown_eyeballs.austria_s_incumbent_first_in_line":"Austria’s incumbent, first in line for every WAN.", +"homegrown_eyeballs.bangladesh_s_biggest_mobile_network_a":"Bangladesh’s biggest mobile network, a hundred million SIMs strong.", +"homegrown_eyeballs.bermuda_s_newest_mobile_network_the":"Bermuda’s newest mobile network. The signal sometimes gets lost in the Triangle.", +"homegrown_eyeballs.bolivia_s_state_telco_thinking_hard":"Bolivia’s state telco, thinking hard at 3,600 metres.", +"homegrown_eyeballs.botswana_s_biggest_mobile_network_with":"Botswana’s biggest mobile network, with a mascot at every tower.", +"homegrown_eyeballs.botswana_s_incumbent_counts_subscribers_like":"Botswana’s incumbent, which counts subscribers like cattle.", +"homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida":"Bulgaria’s incumbent, living la vida broadband.", +"homegrown_eyeballs.cape_verde_s_challenger_one_more":"Cape Verde’s challenger, adding one more island at a time.", +"homegrown_eyeballs.danish_fibre_from_the_power_company":"Danish fibre from the power company: when the lights go out, so does the Wi-Fi.", +"homegrown_eyeballs.denmark_s_incumbent_you_see_it":"Denmark’s incumbent: you see it on every street.", +"homegrown_eyeballs.doitsche_telekomm_s_hungarian_daughter_pink":"Doitsche Telekomm’s Hungarian daughter: pink, and slightly spicy.", +"homegrown_eyeballs.fibre_to_every_tower_block_rung":"Fibre to every tower block, rung in like the trams: ding ding.", +"homegrown_eyeballs.fiji_s_fixed_line_incumbent_never":"Fiji’s fixed-line incumbent, which never sits still.", +"homegrown_eyeballs.finland_s_biggest_mobile_network_unlimited":"Finland’s biggest mobile network, unlimited data played like a piano.", +"homegrown_eyeballs.finnish_broadband_and_mobile_it_s":"Finnish broadband and mobile. It’s in their DNA; test results pending.", +"homegrown_eyeballs.french_polynesia_s_mobile_network_came":"French Polynesia’s mobile network: it came, it saw, it connected the atolls.", +"homegrown_eyeballs.fur_elisa_across_the_gulf_of":"Für Elisa across the Gulf of Finland: the same tune, in Estonian.", +"homegrown_eyeballs.ghana_s_number_two_a_new":"Ghana’s number two: a new name, the same cables, very good salesmen.", +"homegrown_eyeballs.hong_kong_s_incumbent_broadband_full":"Hong Kong’s incumbent broadband, full of vigour and milk tea.", +"homegrown_eyeballs.iceland_s_incumbent_when_simon_says":"Iceland’s incumbent. When Símon says go, every packet takes the cable to Europe.", +"homegrown_eyeballs.iceland_s_mobile_challenger_burning_bright":"Iceland’s mobile challenger, burning bright on geothermal power.", +"homegrown_eyeballs.japan_s_biggest_mobile_network_bows":"Japan’s biggest mobile network, which bows deeply to its big sibling Not That Telecom.", +"homegrown_eyeballs.latvia_s_mobile_leader_let_me":"Latvia’s mobile leader: let me talk, then let me sell you 5G.", +"homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom":"Malaysia’s biggest mobile network: seldom dug up, seldom down.", +"homegrown_eyeballs.mozambique_s_rural_mobile_network_towers":"Mozambique’s rural mobile network, with towers in villages nobody else wired.", +"homegrown_eyeballs.namibia_s_mobile_network_lots_of":"Namibia’s mobile network: lots of desert, not much sea.", +"homegrown_eyeballs.namibia_s_state_incumbent_wired_across":"Namibia’s state incumbent, wired across the Namib one dune at a time.", +"homegrown_eyeballs.new_caledonia_s_cable_operator_can":"New Caledonia’s cable operator: can, will, eventually.", +"homegrown_eyeballs.new_zealand_s_number_two_renamed":"New Zealand’s number two, renamed and rebranded. It won, apparently.", +"homegrown_eyeballs.norwegian_fibre_from_the_power_company":"Norwegian fibre from the power company in Stavanger: you never know what you’re gonna get.", +"homegrown_eyeballs.ooh_redoo_s_maldives_branch_four":"Ooh-redoo’s Maldives branch: four bars on every sandbank.", +"homegrown_eyeballs.ooh_redoo_s_tunisian_network_mint":"Ooh-redoo’s Tunisian network: mint tea first, then megabits.", +"homegrown_eyeballs.pakistan_s_biggest_mobile_network_improvising":"Pakistan’s biggest mobile network, improvising its way through every outage.", +"homegrown_eyeballs.palau_s_mobile_challenger_your_pal":"Palau’s mobile challenger, your pal on every rock island.", +"homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg":"Proxyminus’s dancing brand in Luxembourg: it takes two to tango.", +"homegrown_eyeballs.senegal_s_number_two_freshly_renamed":"Senegal’s number two, freshly renamed and very sure of itself.", +"homegrown_eyeballs.serbia_s_incumbent_at_your_service":"Serbia’s incumbent, at your service.", +"homegrown_eyeballs.singapore_s_number_two_with_a":"Singapore’s number two, with a telescope trained on SingTell.", +"homegrown_eyeballs.sri_lanka_s_biggest_mobile_network_talks":"Sri Lanka’s biggest mobile network: talks to everyone, mostly to itself.", +"homegrown_eyeballs.sri_lanka_s_incumbent_adds_a":"Sri Lanka’s incumbent: adds a pinch of latency to every route.", +"homegrown_eyeballs.sweden_s_challenger_that_took_on":"Sweden’s challenger that took on Tell-Ya. One telco too many, says Tell-Ya.", +"homegrown_eyeballs.switzerland_s_incumbent_the_holes_in":"Switzerland’s incumbent. The holes in the coverage are a design feature.", +"homegrown_eyeballs.taiwan_s_number_three_never_hears":"Taiwan’s number three, which never hears a peering request the first time.", +"homegrown_eyeballs.takes_from_the_big_carriers_and":"Takes from the big carriers and gives cheap data bundles to Dhaka.", +"homegrown_eyeballs.tell_ya_s_estonian_daughter_e":"Tell-Ya’s Estonian daughter, which e-signs every peering request.", +"homegrown_eyeballs.thailand_s_biggest_mobile_network_cool":"Thailand’s biggest mobile network, cool in the Bangkok heat.", +"homegrown_eyeballs.the_challenger_that_made_french_broadband":"The challenger that made French broadband cheap: free as in beer, not as in peering.", +"homegrown_eyeballs.the_dominican_republic_s_other_big":"The Dominican Republic’s other big network. When in doubt, reboot.", +"homegrown_eyeballs.the_dutch_incumbent_peers_for_peanuts":"The Dutch incumbent: peers for peanuts, fibre to every polder.", +"homegrown_eyeballs.the_kingdom_s_challenger_always_mobilising":"The Kingdom’s challenger, always mobilising for the next megaproject.", +"homegrown_eyeballs.the_mobile_network_formerly_known_as":"The mobile network formerly known as something else, and not yet done renaming.", +"homegrown_eyeballs.the_philippines_other_mobile_giant_roaming":"The Philippines’ other mobile giant, roaming the archipelago.", +"homegrown_eyeballs.the_solomon_islands_mobile_challenger_to":"The Solomon Islands’ mobile challenger: to be or not to be online.", +"homegrown_eyeballs.ukraine_s_third_mobile_network_kept":"Ukraine’s third mobile network, kept alive on batteries and stubbornness.", +"homegrown_eyeballs.venezuela_s_state_telco_can_t":"Venezuela’s state telco: can’t fix it, can’t sell it, can’t switch it off.", +"homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant":"Vietnam’s posts and telecoms giant: the packets arrive by moped.", +"homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_what":"Zimbabwe’s fixed-line incumbent. What happens on the line, tell no one.", "hot_ports_and_rank.add_a_lag_member_or_upgrade":"Add a LAG member or upgrade the PNI.", "hot_ports_and_rank.add_a_lag_member_upgrade_the":"Add a LAG member, upgrade the port or buy a second upstream.", "hot_ports_and_rank.and_n_more":"and {n} more", From 94488bf8f70e8be37068c57940f6cb5309b2eb87 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:05:48 +0100 Subject: [PATCH 091/181] Save slots: CHANGELOG and architecture notes --- CHANGELOG.md | 2 ++ docs/ARCHITECTURE.md | 16 +++++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d62391..ba69f5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. +- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside. - 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 d856f63..91b1435 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -78,7 +78,7 @@ Development runs on `npm run dev` (assembles on every request, reloads on save); - **`S`**: the whole saved game (one JSON object). Cash, day, POPs, links, transit, IX ports, PNIs, caches, customers (`biz`), offers, incidents (`inc`), live events - (`ev`), stats, settings. Saved to `localStorage` key `sot-save-v1`. + (`ev`), stats, settings. Saved to `localStorage` key `sot-save-v1:` (one per network, see below). - **`R`**: results of the last `compute()`: per-link load, per-exit use, served and demanded traffic, reach, costs and revenue. Never saved; always rebuilt. - **`UI`**: view state (selection, open tabs, speed, confirmations). Not game state. @@ -146,9 +146,19 @@ Served share per city (`sfOf`) drives eyeball revenue and customer mood. ## Saves, imports and migration -- `save()` writes `S` to localStorage every few seconds and after actions. +- `save()` writes `S` to localStorage every few seconds and after actions, into this window's slot + (`UI.slot`, `src/game/91-slots.js`): `sot-save-v1:`, plain JSON or `gz:`-compressed above a million + characters, with a stamp `sv:{seq,at}` appended. Then the index `sot-slots` (name, ASN, preset, day, tier, + cash, last played, size, seq) is updated; the title screen lists networks from the index alone. +- Each tab keeps its slot in `sessionStorage['sot-slot']`. One window per slot: a Web Lock + (`sot-slot:`) where supported, plus a heartbeat `sot-open:`; BroadcastChannel `sot-slots` asks + another window to hand over, and the `storage` event stops a window whose slot was saved newer elsewhere + (higher seq) or deleted. A window never writes a slot whose index seq is newer than its own. +- The single save of older versions (`sot-save-v1`) is copied to slot `main` and read back before the + index lists it; the old key is removed only by that slot's next successful save. - `boot()` loads the save through `migrate()` → `sanitize()`. If loading throws, the - damaged save is kept under `sot-save-broken` and the player starts fresh. + slot is kept and marked damaged in the index (it can still be exported or deleted). +- Puzzles never write a slot; while one runs, `save()` writes the network set aside (`UI.pzKeep`). - `sanitize(s)` is the gate for all untrusted state (saves and imported files): it drops unknown ids, clamps numbers, repairs references and fills defaults. Every new field in `S` needs a line there. From 7e068fde98069fcf01df6eb3e579c9dd1ddf4fb5 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:08:51 +0100 Subject: [PATCH 092/181] Island eyeballs also buy straight from a Tier 1, like every island network --- src/game/30-networks/32-homegrown-eyeballs.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/game/30-networks/32-homegrown-eyeballs.js b/src/game/30-networks/32-homegrown-eyeballs.js index 6d94cb8..a6d1bc6 100644 --- a/src/game/30-networks/32-homegrown-eyeballs.js +++ b/src/game/30-networks/32-homegrown-eyeballs.js @@ -11,11 +11,11 @@ NETS.push( {id:'ais',name:'AIS-cream',asn:45430,type:'eye',cc:'TH',pol:'selective',minIx:4,minPni:15,share:.006,up:['ntt','tat'],col:'#B5D334',pops:['bkk','sin','hkg'],ix:['bkk'],blurb:tr('homegrown_eyeballs.thailand_s_biggest_mobile_network_cool')}, {id:'alb',name:'Altibox of Chocolates',asn:29695,type:'eye',cc:'NO',pol:'open',share:.002,up:['tly','cog'],col:'#2D2A6E',pops:['osl','svg','krs'],ix:['osl','svg'],blurb:tr('homegrown_eyeballs.norwegian_fibre_from_the_power_company')}, {id:'alt',name:'Alt-Ctrl-Dominicana',asn:28118,type:'eye',cc:'DO',pol:'selective',minIx:2,minPni:10,share:.0015,up:['lvl','cog'],col:'#1A1A1A',pops:['sdq','mia'],ix:[],blurb:tr('homegrown_eyeballs.the_dominican_republic_s_other_big')}, - {id:'ast',name:'Pay-Go Pay-Go Telecom',asn:9751,type:'eye',cc:'AS',pol:'selective',minIx:1,minPni:8,share:.0004,up:['fnt'],col:'#00539B',pops:['ppg'],ix:[],blurb:tr('homegrown_eyeballs.american_samoa_s_own_telco_prepaid')}, + {id:'ast',name:'Pay-Go Pay-Go Telecom',asn:9751,type:'eye',cc:'AS',pol:'selective',minIx:1,minPni:8,share:.0004,up:['fnt','tly'],col:'#00539B',pops:['ppg'],ix:[],blurb:tr('homegrown_eyeballs.american_samoa_s_own_telco_prepaid')}, {id:'bmo',name:'To Be Mobile',asn:132462,type:'eye',cc:'SB',pol:'open',share:.0002,up:['tly'],col:'#E4007C',pops:['hir'],ix:['hir'],blurb:tr('homegrown_eyeballs.the_solomon_islands_mobile_challenger_to')}, {id:'btc',name:'Botswana Tele-cow',asn:14988,type:'eye',cc:'BW',pol:'selective',minIx:1,minPni:8,share:.0006,up:['liq'],col:'#0072BC',pops:['gbe','jnb'],ix:['gbe'],blurb:tr('homegrown_eyeballs.botswana_s_incumbent_counts_subscribers_like')}, {id:'clc',name:'Seldom-Digi',asn:10030,type:'eye',cc:'MY',pol:'selective',minIx:4,minPni:15,share:.003,up:['ntt','tat'],col:'#0019FF',pops:['kul','sin'],ix:['kul'],blurb:tr('homegrown_eyeballs.malaysia_s_biggest_mobile_network_seldom')}, - {id:'cnl',name:'Can’t’L',asn:17480,type:'eye',cc:'NC',pol:'open',share:.0003,up:['pft'],col:'#E30613',pops:['nou'],ix:['nou'],blurb:tr('homegrown_eyeballs.new_caledonia_s_cable_operator_can')}, + {id:'cnl',name:'Can’t’L',asn:17480,type:'eye',cc:'NC',pol:'open',share:.0003,up:['pft','tly'],col:'#E30613',pops:['nou'],ix:['nou'],blurb:tr('homegrown_eyeballs.new_caledonia_s_cable_operator_can')}, {id:'ctv',name:'Can’t-V',asn:8048,type:'eye',cc:'VE',pol:'selective',minIx:2,minPni:10,share:.002,up:['tly','lvl'],col:'#0055A5',pops:['ccs','mia'],ix:['ccs'],blurb:tr('homegrown_eyeballs.venezuela_s_state_telco_can_t')}, {id:'dcm',name:'Docomo Arigato',asn:9605,type:'eye',cc:'JP',pol:'selective',minIx:6,minPni:20,share:.008,up:['ntt'],col:'#CC0033',pops:['tok','osa','fuk'],ix:['tok','osa'],blurb:tr('homegrown_eyeballs.japan_s_biggest_mobile_network_bows')}, {id:'djz',name:'Djezzy Does It',asn:327931,type:'eye',cc:'DZ',pol:'open',share:.002,up:['tly'],col:'#E2001A',pops:['alg'],ix:['alg'],blurb:tr('homegrown_eyeballs.algeria_s_biggest_mobile_network_easy')}, @@ -58,13 +58,13 @@ NETS.push( {id:'tdc',name:'YouSee-Me-Now',asn:3292,type:'eye',cc:'DK',pol:'selective',minIx:5,minPni:20,share:.003,up:['tly'],col:'#0B2D71',pops:['cph','ebj','sto','ham'],ix:['cph'],blurb:tr('homegrown_eyeballs.denmark_s_incumbent_you_see_it')}, {id:'tee',name:'Tell-Ya Eesti',asn:3249,type:'eye',cc:'EE',pol:'selective',minIx:3,minPni:12,share:.001,up:['tly'],col:'#990AE3',pops:['tll','hel','sto'],ix:['tll'],blurb:tr('homegrown_eyeballs.tell_ya_s_estonian_daughter_e')}, {id:'tel',name:'Tell No One',asn:37204,type:'eye',cc:'ZW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['liq'],col:'#0D4C92',pops:['hre'],ix:['hre'],blurb:tr('homegrown_eyeballs.zimbabwe_s_fixed_line_incumbent_what')}, - {id:'tfl',name:'Telecom Fidget',asn:45349,type:'eye',cc:'FJ',pol:'selective',minIx:1,minPni:8,share:.0004,up:['fnt'],col:'#00A3E0',pops:['suv'],ix:['suv'],blurb:tr('homegrown_eyeballs.fiji_s_fixed_line_incumbent_never')}, + {id:'tfl',name:'Telecom Fidget',asn:45349,type:'eye',cc:'FJ',pol:'selective',minIx:1,minPni:8,share:.0004,up:['fnt','ntt'],col:'#00A3E0',pops:['suv'],ix:['suv'],blurb:tr('homegrown_eyeballs.fiji_s_fixed_line_incumbent_never')}, {id:'tgd',name:'Tango-Down',asn:48526,type:'eye',cc:'LU',pol:'selective',minIx:2,minPni:8,share:.0005,up:['bgs'],col:'#FF6600',pops:['bet'],ix:['bet'],blurb:tr('homegrown_eyeballs.proxyminus_s_dancing_brand_in_luxembourg')}, {id:'tlt',name:'Tele-Two-Many',asn:1257,type:'eye',cc:'SE',pol:'selective',minIx:4,minPni:15,share:.003,up:['tly','cog'],col:'#000000',pops:['sto','cph','osl'],ix:['sto'],blurb:tr('homegrown_eyeballs.sweden_s_challenger_that_took_on')}, {id:'tnm',name:'Tele-Namib',asn:36996,type:'eye',cc:'NA',pol:'open',share:.0004,up:['liq','tat'],col:'#00529B',pops:['wdh'],ix:['wdh'],blurb:tr('homegrown_eyeballs.namibia_s_state_incumbent_wired_across')}, {id:'utl',name:'Unitel-ly Yours',asn:37119,type:'eye',cc:'AO',pol:'selective',minIx:3,minPni:12,share:.002,up:['agc'],col:'#F28C00',pops:['lad','lis'],ix:['lad'],blurb:tr('homegrown_eyeballs.angola_s_mobile_giant_sincerely_yours')}, - {id:'utp',name:'Unitel T-Plus-Plus',asn:37575,type:'eye',cc:'CV',pol:'open',share:.0003,up:['cvt'],col:'#F28C00',pops:['rai'],ix:['rai'],blurb:tr('homegrown_eyeballs.cape_verde_s_challenger_one_more')}, - {id:'vin',name:'Vini Vidi Vici',asn:9471,type:'eye',cc:'PF',pol:'open',share:.0003,up:['pft'],col:'#E2001A',pops:['ppt'],ix:[],blurb:tr('homegrown_eyeballs.french_polynesia_s_mobile_network_came')}, + {id:'utp',name:'Unitel T-Plus-Plus',asn:37575,type:'eye',cc:'CV',pol:'open',share:.0003,up:['cvt','tat'],col:'#F28C00',pops:['rai'],ix:['rai'],blurb:tr('homegrown_eyeballs.cape_verde_s_challenger_one_more')}, + {id:'vin',name:'Vini Vidi Vici',asn:9471,type:'eye',cc:'PF',pol:'open',share:.0003,up:['pft','tly'],col:'#E2001A',pops:['ppt'],ix:[],blurb:tr('homegrown_eyeballs.french_polynesia_s_mobile_network_came')}, {id:'vnp',name:'VNPT (Very Nice Packet Times)',asn:45899,type:'eye',cc:'VN',pol:'selective',minIx:3,minPni:12,share:.004,up:['ntt','tat'],col:'#0066B3',pops:['sgn','hkg','sin'],ix:['sgn'],blurb:tr('homegrown_eyeballs.vietnam_s_posts_and_telecoms_giant')}, {id:'vvc',name:'Viva la Vidacom',asn:8866,type:'eye',cc:'BG',pol:'selective',minIx:4,minPni:15,share:.002,up:['tly','cog'],col:'#E2001A',pops:['sof','fra'],ix:['sof'],blurb:tr('homegrown_eyeballs.bulgaria_s_incumbent_living_la_vida')}, {id:'yet',name:'Not Yettel',asn:31042,type:'eye',cc:'RS',pol:'open',share:.0015,up:['tly'],col:'#B4FF00',pops:['beg'],ix:[],blurb:tr('homegrown_eyeballs.the_mobile_network_formerly_known_as')}); From 2b8b64121689c8cfe76121e014862b38b9519f92 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:13:56 +0100 Subject: [PATCH 093/181] Tests for the gameplay rules: world, networks, modes, content, fun and fairness, with documented exceptions; drop exchange ports in cities without an exchange --- src/game/30-networks/10-networks.js | 2 +- .../30-networks/35-glowball-sakura-lager.js | 2 +- tests/gameplay-rules.test.js | 340 ++++++++++++++++++ 3 files changed, 342 insertions(+), 2 deletions(-) create mode 100644 tests/gameplay-rules.test.js diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index 217baa3..46ba3a0 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -57,7 +57,7 @@ NETS.push( {id:'oio',name:'Oi Oi',asn:7739,type:'eye',cc:'BR',pol:'selective',up:['lvl','tly'],minIx:6,minPni:20,share:.008,col:'#FFD000',pops:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],ix:['sao','rio','for','bsb','bhz','cwb','poa','aju','bel','bvb','cac','cpv','cpq','cgr','cau','cgb','cxj','fec','fln','igu','gyn','jpa','ljd','ldb','mcp','mcz','mao','mgf','nat','pmw','pvh','rao','rec','rbr','ssa','ria','sjp','slz','the','vix'],blurb:tr('networks.says_oi_to_every_home_in')}, {id:'tmt',name:'TIM-TIM Mobile',asn:26616,type:'eye',cc:'BR',pol:'selective',up:['skl'],minIx:6,minPni:20,share:.007,col:'#004691',pops:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],ix:['sao','rio','bsb','bhz','cwb','poa','cpq','rec','ssa','for','gyn','bel','mao','vix','fln'],blurb:tr('networks.a_mobile_network_named_after_the')}, {id:'bsn',name:'Brisanada',asn:28127,type:'eye',cc:'BR',pol:'open',up:['lvl'],share:.004,col:'#F7941D',pops:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],ix:['for','nat','jpa','cpv','rec','cau','mcz','aju','ssa','fec','the','slz'],blurb:tr('networks.fiber_across_the_sertao_of_the')}, - {id:'mvs',name:'Moviestar',asn:12957,type:'t2',cc:['AR','CL','CO','EC','MX','PE','UY','VE'],pol:'selective',up:['tly','lvl'],minIx:8,minPni:25,share:.008,price:6,col:'#019DF4',pops:['mex','gua','bog','mde','uio','lim','lpb','scl','bue','cor','mvd','ccs','sao','mia'],ix:['mex','bog','lim','scl','bue','mvd','ccs','sao'],blurb:tr('networks.a_spanish_carrier_starring_in_every')}, + {id:'mvs',name:'Moviestar',asn:12957,type:'t2',cc:['AR','CL','CO','EC','MX','PE','UY','VE'],pol:'selective',up:['tly','lvl'],minIx:8,minPni:25,share:.008,price:6,col:'#019DF4',pops:['mex','gua','bog','mde','uio','lim','lpb','scl','bue','cor','mvd','ccs','sao','mia'],ix:['bog','lim','scl','bue','mvd','ccs','sao'],blurb:tr('networks.a_spanish_carrier_starring_in_every')}, {id:'llt',name:'Liberty Latte America',asn:23521,type:'t2',cc:['BB','BS','CR','CW','JM','PA','PR','TT'],pol:'open',up:['lvl','cog'],share:.005,price:5,col:'#6C2C91',pops:['mia','pan','sjo','gua','bog','mde','ccs','sju','kin','nas','pos','bgi','cur'],ix:['pan','sjo','gua','bog','kin','pos'],blurb:tr('networks.cables_all_around_the_caribbean')}, {id:'ant',name:'Antelope',asn:6058,type:'eye',cc:'UY',pol:'selective',up:['skl','tly'],minIx:3,minPni:15,share:.004,col:'#0072BC',pops:['mvd'],ix:['mvd'],blurb:tr('networks.uruguay_s_state_telco_fast')}, {id:'tgo',name:'Tiger Mobile',asn:27743,type:'eye',cc:['PY','BO','GT','CR','PA','CO'],pol:'selective',up:['lvl'],minIx:4,minPni:15,share:.005,col:'#00377B',pops:['asu','lpb','gua','sjo','pan','bog','mde'],ix:['asu','lpb','gua','sjo','bog'],blurb:tr('networks.prepaid_mobile_from_paraguay_to')}, diff --git a/src/game/30-networks/35-glowball-sakura-lager.js b/src/game/30-networks/35-glowball-sakura-lager.js index d993af0..c45b8de 100644 --- a/src/game/30-networks/35-glowball-sakura-lager.js +++ b/src/game/30-networks/35-glowball-sakura-lager.js @@ -6,7 +6,7 @@ (far), so it never undercuts the locals there. Sits before 40-traffic-shares.js, which indexes NETS. */ const GSL_POPS=['adl','akl','ams','bne','bom','chi','dal','fra','hkg','icn','ist','jkt','lax','lon','mel','mia','mil','mnl','nyc','osa','par','per','phx','sin','syd','tok','waw']; NETS.push( - {id:'gsl',name:'Glowball Sakura Lager',asn:137409,type:'t2',pol:'open',up:['lvl','cog','ntt'],share:.02,price:5,far:{AS:1.6,OC:2},col:'#C94F7C',auIx:['syd','mel','bne','per'],pops:GSL_POPS,ix:GSL_POPS,blurb:tr('glowball_sakura_lager.on_tap_in_the_big_hubs')}); + {id:'gsl',name:'Glowball Sakura Lager',asn:137409,type:'t2',pol:'open',up:['lvl','cog','ntt'],share:.02,price:5,far:{AS:1.6,OC:2},col:'#C94F7C',auIx:['syd','mel','bne','per'],pops:GSL_POPS,ix:GSL_POPS.filter(c=>CITY[c].ix),blurb:tr('glowball_sakura_lager.on_tap_in_the_big_hubs')}); /* Its downstreams: networks that buy their transit from it, so a PNI with it reaches them too. Only where it has PoPs itself, and no Australians: a PNI with it is no back door into Australia. One per line, sorted within each. */ const GSL_DOWN=[ diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js new file mode 100644 index 0000000..3535fb8 --- /dev/null +++ b/tests/gameplay-rules.test.js @@ -0,0 +1,340 @@ +// The game's design rules (.claude/skills/gameplay-rules/SKILL.md): one test per rule id, on the live data. +// A rule may only be broken by an entry in EXCEPTIONS below, with its reason. Never delete a check to make it pass. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const fs = require('node:fs'); +const { execFileSync } = require('node:child_process'); +const { load } = require('./harness'); + +// Every exception names what breaks the rule and why. One per line, sorted within each rule. +const EXCEPTIONS = { + // W2: countries with fewer than two consumer networks of their own, because real life has fewer. + W2: { + CU: 'Cuba has one state operator (ETECSA); Cubacel is its own mobile brand', + DJ: 'Djibouti Telecom is the monopoly for homes and phones', + MH: 'the Marshall Islands have one telco (NTA)', + PN: 'Pitcairn has no network at all: land your own cable (#124)', + SH: 'St Helena has one operator (Sure South Atlantic)', + }, + // W3: cities nobody sells transit in. + W3: { + ivc: 'Invercargill waits for its AI campus; nobody sells transit there yet', + pcn: 'Pitcairn: no cable, no network, land your own (#124)', + prr: 'Prince Rupert is a remote town with no carrier in it', + stg: 'Stuttgart is the Only Spätzle-IX scenario city: peering only, by design (#114)', + }, + // N3: networks in no founding Tier 1's customer cone. Old saves need PNIs with the founding five for Tier 1, + // so anyone outside their cones has to be peered with directly. + N3: { + abb: 'Australians buy only from Australian carriers (#148)', + atl: 'transit-free in India', + bcd: 'transit-free in Canada', + blg: 'Australian, buys from Telstraya (#148)', + btt: 'transit-free incumbent', + cht: 'transit-free in Taiwan', + clr: 'America Movil, transit-free across Latin America', + cmb: 'China (#59): reached through the Chinese carriers', + cmc: 'transit-free incumbent', + cos: 'Greek incumbent, peers for its own reach', + ctc: 'China (#59)', + cun: 'China (#59)', + cxc: 'buys from Spectre-um, which is transit-free', + drz: 'a transit-free Tier 2', + dtk: 'transit-free incumbent', + etc: 'Cuba: buys from Sparkly Seabone, a Tier 1 only for games since 1.12', + ets: 'transit-free in the Gulf', + ftr: 'buys from Very-Zone, which is transit-free', + inp: 'Australian, buys from Toilet Paper Group (#148)', + jio: 'transit-free in India', + kdi: 'transit-free in Japan', + ktt: 'Korea: sender pays, peer with it yourself', + lgu: 'Korea: sender pays', + lnt: 'Australian (#148)', + lpt: 'Australian (#148)', + meo: 'Portuguese incumbent, peers for its own reach', + mgf: 'Russia: buys from Rostelecomedy (#70)', + npt: 'Australian (#148)', + ert: 'Russia: buys from Rostelecomedy (#70)', + opt: 'Australian, buys from SingTell (#148)', + pnt: 'Australian (#148)', + rtc: 'Russia (#70)', + sgt: 'a transit-free Tier 2', + skb: 'Korea: sender pays', + spc: 'transit-free incumbent', + stb: 'satellite: peers for its own reach', + stc: 'transit-free in Saudi Arabia', + teg: 'owns the land crossing; transit-free', + tim: 'buys from Sparkly Seabone, a Tier 1 only for games since 1.12', + tmt: 'buys from Sparkly Seabone, a Tier 1 only for games since 1.12', + tmx: 'transit-free in Mexico', + tmy: 'Malaysian incumbent, peers for its own reach', + tng: 'a transit-free Tier 2', + tpr: 'Australian (#148)', + tsf: 'Indonesian incumbent, peers for its own reach', + tsy: 'Australian, transit-free (#148)', + ttk: 'transit-free in Turkey', + ups: 'European cable group, peers for its own reach', + vdp: 'a transit-free Tier 2', + viv: 'transit-free in Brazil', + vzn: 'transit-free incumbent', + }, + // N7: an exchange port where the network has no PoP. + N7: { + 'spl:hba': 'Speedyloop reaches Hobart’s exchange over its own backhaul but sells no transit there', + }, + // M3: subsystems that annoy the player but read no rule. + M3: { + snub: 'de-peering at exchanges happens in every mode (open question: should Change Freeze stop it?)', + }, +}; + +// The real names the puns are based on. No network, cable, exchange, data center, router or optic may be called one. +const REAL_NAMES = [ + // Tier 1s and carriers + 'AT&T', 'BICS', 'Cogent', 'GTT', 'Hurricane Electric', 'Level 3', 'Level3', 'Liquid', 'Liquid Intelligent Technologies', 'Lumen', 'NTT', 'Orange', 'PCCW', 'Seacom', 'Singtel', 'Sparkle', 'Tata', 'Tata Communications', 'Telia', 'Telxius', 'Vodafone', 'Zayo', + // content and clouds + 'Akamai', 'Alibaba Cloud', 'Amazon', 'Amazon Web Services', 'AWS', 'Baidu', 'ByteDance', 'Cloudflare', 'Facebook', 'Fastly', 'Google', 'Mercado Libre', 'Meta', 'Microsoft', 'Netflix', 'Tencent', 'TikTok', 'VK', 'VKontakte', 'Yandex', + // eyeballs and incumbents + 'A1', 'A1 Telekom Austria', 'AIS', 'Airtel', 'Algérie Télécom', 'Altibox', 'Altice', 'America Movil', 'Angola Cables', 'Antel', 'ASTCA', 'Aussie Broadband', 'Bell', 'Bell Canada', 'Belong', 'Bemobile', 'Brisanet', 'BT', 'BTC', 'Cable & Wireless', 'Cable Bahamas', "CAN'L", 'Canal+', 'CANTV', 'CelcomDigi', 'China Mobile', 'China Telecom', 'China Unicom', 'Chunghwa Telecom', 'Citymesh', 'Claro', 'Comcast', 'Cosmote', 'Cox', 'CV Telecom', 'Deutsche Telekom', 'Dhiraagu', 'Dialog', 'Digi', 'Digicel', 'Djezzy', 'Djibouti Telecom', 'DNA', 'Docomo', 'Docomo Pacific', 'Dodo', 'du', 'Eastlink', 'Elisa', 'Emtel', 'Entel', 'ER-Telecom', 'Etisalat', 'ETECSA', 'Ethio Telecom', 'Exetel', 'Far EasTone', 'Fastweb', 'FINTEL', 'Flow', 'Free', 'Frontier', 'GCI', 'Globe', 'Google Fiber', 'Grameenphone', 'GSL Networks', 'GTA', 'Hawaiian Telcom', 'HKBN', 'HKT', 'iiNet', 'Jazz', 'Jio', 'KDDI', 'KPN', 'KT', 'Kyivstar', 'Launtel', 'Leaptel', 'LG U+', 'Liberty Latin America', 'lifecell', 'LMT', 'Magyar Telekom', 'Maroc Telecom', 'Mascom', 'Mauritius Telecom', 'MegaFon', 'MEO', 'Mobily', 'Movicel', 'Movistar', 'Movitel', 'MTC', 'MTN', 'mts', 'Neptune', 'Netvigator', 'Norlys', 'NOS', 'Nova', 'NTA', 'NTT Docomo', 'Oi', 'Omantel', 'One Communications', 'One NZ', 'Ooredoo', 'OPT', 'Optimum', 'Optus', 'Palau Mobile', 'Paradise Mobile', 'Pentanet', 'PLDT', 'PNCC', 'POST', 'Proximus', 'PTCL', 'Reliance Jio', 'Robi', 'Rogers', 'Rostelecom', 'Safaricom', 'SFR', 'Síminn', 'SK Broadband', 'Sky', 'SLT', 'Sonic', 'Spark', 'Spectrum', 'Spintel', 'Starlink', 'StarHub', 'STC', 'Superloop', 'Sure', 'Swisscom', 'T-Mobile', 'Tango', 'TCC', 'TDC', 'Tele2', 'Telecel', 'Telecom Argentina', 'Telecom Egypt', 'Telecom Fiji', 'Telecom Namibia', 'Telekom Malaysia', 'Telekom Srbija', 'Telenet', 'Telenor', 'Telikom PNG', 'Telkomsel', 'Telma', 'Telmex', 'TelOne', 'Telstra', 'Telus', 'Tet', 'TIM', 'Tigo', 'TPG', 'True', 'True Move', 'TSTT', 'Turk Telekom', 'Unitel', 'UPC', 'Verizon', 'Viettel', 'Vini', 'Virgin Media', 'Vivacom', 'Vivo', 'VNPT', 'Vocus', 'Yas', 'Yettel', 'YouSee', 'Zeop', + // exchanges and data centers + 'AMS-IX', 'Any2', 'BCIX', 'CoreSite', 'DE-CIX', 'Digital Realty', 'Equinix', 'France-IX', 'Interxion', 'IX.br', 'JPIX', 'LINX', 'NAPAfrica', 'NetIX', 'NIX', 'NL-ix', 'SIX', 'Telehouse', + // cables + '2Africa', 'Amitié', 'Dunant', 'EllaLink', 'Equiano', 'Grace Hopper', 'Hibernia Express', 'Jupiter', 'MAREA', 'PEACE', 'SEA-ME-WE 6', + // vendors + 'Arista', 'Ciena', 'Cisco', 'Huawei', 'Infinera', 'Juniper', 'MikroTik', 'Nokia', +]; + +const { ev, errors } = load(); +ev('ACT.start({})'); +const J = (s) => JSON.parse(ev(`JSON.stringify(${s})`)); +const country = (cc) => { try { return new Intl.DisplayNames(['en'], { type: 'region' }).of(cc); } catch (e) { return cc; } }; +const fail = (id, bad, fix) => assert.deepEqual(bad, [], `${id}: ${bad.join('; ')}. ${fix}`); +const ex = (id, k) => Object.prototype.hasOwnProperty.call(EXCEPTIONS[id] || {}, k); + +// ---------- World ---------- + +test('W1: every city has a country code, a region and real coordinates', () => { + const bad = J(`CITIES.filter(c=>!/^[A-Z]{2}$/.test(c.cc||'')||!['AM','SA','EU','AS','OC','AF'].includes(c.reg)||!(Math.abs(c.lat)<=90&&Math.abs(c.lon)<=180&&CITY_LL[c.id])||!c.land).map(c=>c.id+' ('+c.name+')')`); + fail('W1', bad, 'give it cc (ISO 3166-1 alpha-2; territories have their own), reg, land and an entry in CITY_LL'); +}); + +test('W2: every country on the map has at least two consumer networks of its own', () => { + // "Own": the network names the country in its home markets (cc) and has a PoP there. Consumer networks are the + // eyeballs, and the Tier 2 incumbents that sell to homes and phones in their home markets. + const rows = J(`(()=>{const cs={};for(const c of CITIES)if(!c.off)(cs[c.cc]=cs[c.cc]||[]).push(c.id); + return Object.keys(cs).sort().map(cc=>[cc,NETS.filter(n=>(n.type==='eye'||n.type==='t2')&&[].concat(n.cc||[]).includes(cc)&&n.pops.some(p=>CITY[p].cc===cc)).map(n=>n.name)]);})()`); + const bad = rows.filter(([cc, own]) => own.length < 2 && !ex('W2', cc)) + .map(([cc, own]) => `${country(cc)} (${cc}) has ${own.length} own eyeball network${own.length === 1 ? '' : 's'}${own.length ? ': ' + own.join(', ') : ''}`); + fail('W2', bad, 'add a real operator of that country (src/game/30-networks/32-homegrown-eyeballs.js) or list it in EXCEPTIONS with a reason'); + const stale = Object.keys(EXCEPTIONS.W2).filter((cc) => (rows.find((r) => r[0] === cc) || [cc, [1, 2]])[1].length >= 2); + assert.deepEqual(stale, [], 'W2: these exceptions are no longer needed; remove them'); + // a network's home markets are places it really is + const homeless = J(`NETS.filter(n=>n.cc).flatMap(n=>[].concat(n.cc).filter(cc=>!n.pops.some(p=>CITY[p].cc===cc)).map(cc=>n.name+' has no PoP in '+cc))`); + fail('W2', homeless, 'a home market (cc) needs a PoP in that country'); +}); + +test('W3: every city can buy transit from someone, or is a documented exception', () => { + const bad = J(`CITIES.filter(c=>!c.off&&!NETS.some(n=>sellsAt(n,c.id))).map(c=>c.id)`).filter((c) => !ex('W3', c)); + fail('W3', bad, 'give a carrier a PoP there (with a price) or list the city in EXCEPTIONS with a reason'); +}); + +test('W4: cables are consistent: real cities, two distinct ends, a length and unique ids', () => { + const bad = J(`CABLE_PAIRS.filter(p=>!CITY[p.a]||!CITY[p.b]||p.a===p.b||!(p.km>0)||!CAB[p.cid]).map(p=>p.cid+':'+p.a+'-'+p.b)`); + fail('W4', bad, 'fix the cable pair in src/game/20-world/60-cables.js'); + const ids = J('CABLES.map(c=>c.id)'); + assert.equal(new Set(ids).size, ids.length, 'W4: cable ids are unique'); + fail('W4', J("CABLES.filter(c=>!c.name||!c.pairs||!c.pairs.length).map(c=>c.id)"), 'every cable has a name and at least one landing pair'); +}); + +test('W5: every island city can be reached: it shares its land, has a cable, or a beach to land one', () => { + const bad = J(`CITIES.filter(c=>!c.off&&!CITIES.some(o=>o!==c&&!o.off&&(o.land===c.land||o.land2===c.land||c.land2===o.land))&&!landing(c.id)).map(c=>c.id)`); + fail('W5', bad, 'land a cable there or give it beach:true'); +}); + +// ---------- Networks ---------- + +test('N1: network ids and ASNs are unique, ASNs are valid', () => { + const ids = J('NETS.map(n=>n.id)'), asns = J('NETS.map(n=>n.asn)'); + fail('N1', ids.filter((x, i) => ids.indexOf(x) !== i), 'network ids must be unique'); + fail('N1', asns.filter((x, i) => asns.indexOf(x) !== i).map(String), 'ASNs must be unique'); + fail('N1', J("NETS.filter(n=>!Number.isInteger(n.asn)||n.asn<1||n.asn>4294967294||n.asn>=64512&&n.asn<=65534).map(n=>n.id)"), 'use the real, public ASN'); +}); + +test('N2: names are puns: no network, cable, exchange, data center, router or optic carries a real name', () => { + const norm = (s) => String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’`]/g, "'").replace(/\s+/g, ' ').trim(); + const real = new Set(REAL_NAMES.map(norm)); + const names = J(`[...NETS.map(n=>['network',n.name]),...CABLES.map(c=>['cable',c.name]),...XIX.map(x=>['exchange',x.name]), + ...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n])].filter(x=>x[1])`); + fail('N2', names.filter(([, n]) => real.has(norm(n))).map(([k, n]) => `${k} “${n}” is a real name`), 'find a pun'); + fail('N2', names.filter(([, n]) => /-ish\b/i.test(n)).map(([k, n]) => `${k} “${n}”`), 'no lazy -ish names: find a real pun, or keep the plain word'); +}); + +test('N3: every network sits in a founding Tier 1’s customer cone, or is a documented island', () => { + // The founding five (t1Need() of the oldest saves): every save can reach a network in their cones by peering with them. + const out = J(`NETS.filter(n=>n.type!=='t1'&&n.type!=='cdn'&&!['lvl','ntt','tly','cog','tat'].some(t=>CONE_S[t].has(n.id))).map(n=>n.id)`); + fail('N3', out.filter((id) => !ex('N3', id)).map((id) => `${id} (${ev(`NET.${id}.name`)})`), 'give it a realistic upstream (up) in a founding Tier 1’s cone, or list it in EXCEPTIONS with a reason'); + fail('N3', Object.keys(EXCEPTIONS.N3).filter((id) => !out.includes(id)), 'these exceptions are no longer needed; remove them'); + fail('N3', J("NETS.filter(n=>(n.up||[]).some(u=>!NET[u]||NET[u].type==='cdn'||u===n.id)).map(n=>n.id)"), 'an upstream is another network that exists and sells transit, never content'); +}); + +test('N4: no upstream cycles', () => { + const bad = J(`(()=>{const o=[];for(const n of NETS){const seen=new Set(),q=(n.up||[]).slice();while(q.length){const u=q.pop();if(u===n.id){o.push(n.id);break;}if(seen.has(u))continue;seen.add(u);q.push(...((NET[u]||{}).up||[]));}}return o;})()`); + fail('N4', bad, 'a network cannot buy transit from its own customers'); +}); + +test('N5: traffic shares are sane', () => { + fail('N5', J("NETS.filter(n=>!(n.share>0&&n.share<0.2)).map(n=>n.id)"), 'every share is positive and below 20%'); + for (const t of ['NSH', 'NSH_CN', 'NSH_RU', 'NSH_KRX']) { + assert.ok(Math.abs(ev(`Object.values(${t}).reduce((a,b)=>a+b,0)`) - 1) < 1e-9, `N5: ${t} sums to 1`); + fail('N5', J(`Object.entries(${t}).filter(([k,v])=>!NET[k]||!(v>=0)).map(([k])=>k)`), `${t} only holds real networks, never negative`); + } + // the content giants carry the traffic, eyeballs mostly ask for it + assert.ok(ev("NETS.filter(n=>n.type==='cdn').reduce((a,n)=>a+NSH[n.id],0)") > 0.3, 'N5: content is at least 30% of traffic'); +}); + +test('N6: every network has a type, a peering policy and a translated blurb', () => { + fail('N6', J(`NETS.filter(n=>!['t1','t2','cdn','eye'].includes(n.type)||!['open','selective','restrictive','paid'].includes(n.pol)||!n.blurb||!n.col).map(n=>n.id)`), 'set type, pol, col and blurb:tr(...)'); + fail('N6', J("NETS.filter(n=>n.pol==='selective'&&!(n.minIx>=1&&n.minPni>=1)).map(n=>n.id)"), 'selective networks state minIx and minPni'); + fail('N6', J("NETS.filter(n=>n.type==='t1'||n.type==='t2'?!(n.price>0):false).map(n=>n.id)"), 'carriers have a transit price'); +}); + +test('N7: presence is real: PoPs are cities, exchange ports only where the network is', () => { + fail('N7', J("NETS.filter(n=>!n.pops.length||n.pops.some(c=>!CITY[c])||new Set(n.pops).size!==n.pops.length).map(n=>n.id)"), 'PoPs are real, distinct city ids'); + const bad = J(`NETS.filter(n=>Array.isArray(n.ix)).flatMap(n=>n.ix.filter(c=>!XIXM[c]&&(!CITY[c]||!CITY[c].ix||!n.pops.includes(c))).map(c=>n.id+':'+c))`).filter((k) => !ex('N7', k)); + fail('N7', bad, 'an exchange port needs an exchange in that city and a PoP there'); +}); + +// ---------- Modes and rules ---------- + +test('M1: On-call is the classic game: the default rules, and what old saves load as', () => { + assert.deepEqual(J("(({preset,mods,...r})=>r)(makeRules('oncall'))"), J("(({mods,...r})=>r)(RULE_DEF)"), 'M1: On-call is RULE_DEF'); + assert.equal(ev("(()=>{const o=S.rules;delete S.rules;const p=rulePreset();S.rules=o;return p;})()"), 'oncall', 'M1: no rules means On-call'); + // the seeded On-call games are the rest of the suite (tests/game.test.js, tests/rules.test.js); they must stay green +}); + +test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler', () => { + const P = J('PRESETS'), C = J('CHAOS'), lead = { quick: 0, real: 1 }; + assert.ok(C[P.freeze.chaos].m <= C[P.oncall.chaos].m && C[P.oncall.chaos].m <= C[P.bgp.chaos].m, 'M2: chaos'); + assert.ok(lead[P.freeze.lead] <= lead[P.oncall.lead] && lead[P.oncall.lead] <= lead[P.bgp.lead], 'M2: lead times'); + for (const k of ['market', 'inbox']) assert.ok(!P.freeze[k] || P.oncall[k], `M2: ${k}`); + assert.ok(P.bgp.market && P.bgp.inbox && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship'); + // seeded: the same network for a year under each preset + const n = {}; + for (const p of ['freeze', 'oncall', 'bgp']) { + const g = load(); + g.ev(`beginGame('Order','fra',${JSON.stringify({ mode: 'normal', preset: p })});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242);for(let i=0;i<360;i++)dayTick()`); + n[p] = g.ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)'); + assert.deepEqual(g.errors, []); + } + assert.ok(n.freeze <= n.oncall && n.oncall <= n.bgp, `M2: incidents in a year: freeze ${n.freeze}, on-call ${n.oncall}, bgp ${n.bgp}`); +}); + +test('M3: every subsystem that can annoy the player reads a rule', () => { + // [function, what it must read] + const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['inboxDay', "rule('inbox')"], + ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], + ['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"]]; + fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); + // and in play: no chaos, no market, no inbox means a quiet year + const g = load(); + g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false,inbox:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()"); + assert.equal(g.ev('S.inc.length+(S.stats.incidents||0)'), 0, 'M3: nothing breaks without chaos'); + assert.equal(g.ev('S.inbox.items.length+S.inbox.seq'), 0, 'M3: no mail without the inbox'); + assert.equal(g.ev("hwMul('rt')"), 1, 'M3: no hardware inflation without the market'); + assert.equal(g.ev("CITIES.slice(0,40).some(c=>soldOut('fra',c.id,1))"), false, 'M3: no sold-out routes without the market'); + assert.deepEqual(g.errors, []); + assert.ok(Object.keys(EXCEPTIONS.M3).every((f) => ev(`typeof ${f}==='function'`)), 'M3: exceptions name real functions'); +}); + +test('M4: scenarios and the weekly challenge always run On-call', () => { + const g = load(); + const bad = []; + for (const id of g.ev('JSON.stringify(SCN.map(x=>x.id))') && JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))'))) { + g.ev(`beginGame('S','${id}'==='weekly'?'fra':SCN.find(x=>x.id==='${id}').city,{mode:'normal',preset:'bgp',rules:{chaos:'spicy'},scn:SCN.find(x=>x.id==='${id}')});if(UI.pendGame)ACT.pitchSkip()`); + if (g.ev('S.rules.preset') !== 'oncall' || g.ev("rule('chaos')") !== 'normal') bad.push(id); + } + g.ev("ACT.startWeekly({sure:1});if(UI.pendGame)ACT.pitchSkip()"); + if (g.ev('S.scn&&S.scn.id') !== 'weekly' || g.ev('S.rules.preset') !== 'oncall') bad.push('weekly'); + fail('M4', bad, 'beginGame() must give scenarios On-call plus their own S.scn.rules'); + assert.deepEqual(g.errors, []); +}); + +test('M5: Sandbox has no locked feature', () => { + const g = load(); + g.ev("beginGame('Box','fra',{mode:'sandbox'});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(g.ev('gatesOpen()'), true, 'M5: gates open'); + assert.equal(g.ev('lvl()'), g.ev('LEVELS.length'), 'M5: every level unlocked'); + assert.equal(g.ev('cabOpen()'), true, 'M5: own subsea cables'); + assert.equal(g.ev("rule('money')"), 'infinite', 'M5: money'); + assert.deepEqual(g.errors, []); +}); + +// ---------- Content ---------- + +test('C1: every scenario has a goal its card checks, and none is won on day 0', () => { + const g = load(); + const ids = JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))')); + assert.equal(new Set(ids).size, ids.length, 'C1: scenario ids are unique'); + const bad = []; + for (const id of ids) { + g.ev(`ACT.startScn({id:'${id}',sure:1});if(UI.pendGame)ACT.pitchSkip()`); + const def = `SCN.find(x=>x.id==='${id}')`; + if (!g.ev(`!!(${def}.n&&${def}.d&&${def}.goal&&typeof ${def}.ok==='function'&&${def}.days>0&&CITY[${def}.city])`)) bad.push(id + ': incomplete definition'); + if (g.ev(`(()=>{try{return !!${def}.ok();}catch(e){return false;}})()`)) bad.push(id + ': won on day 0'); + if (!g.ev(`typeof SCN_PROG['${id}']==='function'&&scnProg().items.length>0`)) bad.push(id + ': no progress card (SCN_PROG)'); + } + fail('C1', bad, 'give it n, d, goal, ok(), days, a city and a SCN_PROG entry; its goal must need play'); + assert.deepEqual(g.errors, []); +}); + +test('C2: every puzzle has a 1-star and a 3-star reference solution (tests/puzzles.test.js)', () => { + const src = fs.readFileSync(path.join(__dirname, 'puzzles.test.js'), 'utf8'); + const refs = [...src.matchAll(/^\s{2}([a-z0-9]+): \{ one: .*three: /gm)].map((m) => m[1]); + fail('C2', J('PZ.map(p=>p.id)').filter((id) => !refs.includes(id)), 'add its reference solutions to REF in tests/puzzles.test.js (that suite builds and scores them)'); +}); + +test('C3: every player-facing string is translated in every language', () => { + const out = execFileSync(process.execPath, [path.join(__dirname, '..', 'scripts', 'i18n-check.js')], { encoding: 'utf8' }); + assert.match(out, /en\.js: \d+ labels, 0 problems/, 'C3: ' + out); + const langs = out.split('\n').filter((l) => /^[a-z]{2}\.js: \d+ missing/.test(l)); + assert.ok(langs.length >= 5, 'C3: every language is checked'); + fail('C3', langs.filter((l) => !/0 missing, 0 unused, 0 broken/.test(l)), 'run node scripts/i18n-add.js (add-strings skill)'); +}); + +// ---------- Fun and fairness ---------- + +test('F1: new players get a gentle start: nothing breaks for 45 days, no sold-out routes for 90, no hardware inflation for 180', () => { + const g = load(); + g.ev("beginGame('New','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip()"); + assert.ok(g.ev('S.nextFail') >= 45 && g.ev('S.nextEvent') >= 40, 'F1: first outage after day 45, first event after day 40'); + // the first events are only good news or harmless (a viral hit, a price change, a grant) + const opts = JSON.parse(g.ev(`(()=>{let o=null;const f=eval('('+fireEvent.toString().replace('const e=pick(opts);','o=opts.slice();return;')+')');S.day=45;f();return JSON.stringify(o);})()`)); + fail('F1', opts.filter((e) => !['viral', 'price', 'grant'].includes(e)), 'no bad events before day 50'); + assert.equal(g.ev("(()=>{for(let d=0;d<90;d++){S.day=d;if(CITIES.some(c=>soldOut('fra',c.id,1)))return true;}return false;})()"), false, 'F1: nothing sold out in the first 90 days'); + assert.equal(g.ev("(()=>{S.day=180;return hwMul('rt');})()"), 1, 'F1: hardware prices hold for 180 days'); + // customers get 15 days before a bad day costs them mood + g.ev("S.day=10;S.biz=[{id:'b1',city:'fra',city2:null,reqs:[],name:'X',type:'host',bw:5,rate:100,mood:80,since:5}];compute();dayTick()"); + assert.ok(g.ev("(S.biz[0]||{mood:0}).mood") >= 80, 'F1: no mood loss in a customer’s first 15 days'); + assert.deepEqual(g.errors, []); +}); + +test('F2: a simple build in a start city makes money within three months on On-call', () => { + // Reference build: launch broadband, the cheapest 100G transit in town, and a port with a route server where there is an exchange. + const bad = []; + for (const city of ['fra', 'nyc', 'sin', 'jnb']) { + const g = load(); + g.ev(`beginGame('Ref','${city}',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip()`); + g.ev(`(()=>{const c='${city}',n=NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0]; + ACT.launchBB({city:c});ACT.buyTransit({city:c,net:n.id,tier:1});if(ixName(c)){ACT.buyIx({city:c,tier:1,signed:true});ACT.rs({city:c});}})()`); + let month = 0; + for (let m = 1; m <= 3 && !month; m++) { g.ev('for(let i=0;i<30;i++)dayTick()'); if (g.ev('R.revMo-R.costMo') > 0) month = m; } + if (!month || g.ev('S.lost')) bad.push(`${city}: still losing money after 3 months (${Math.round(g.ev('R.revMo-R.costMo'))}/mo)`); + assert.deepEqual(g.errors, []); + } + fail('F2', bad, 'a balance change made the start too hard; fix the balance, or argue for a new N in the gameplay-rules skill'); +}); + +test('no page errors while checking the rules', () => { + assert.deepEqual(errors, []); +}); From 06da3f7456a3e13bcccbbf853fc61853e9f87a69 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:15:32 +0100 Subject: [PATCH 094/181] Gameplay rules skill, pointer in CLAUDE.md, CHANGELOG for homegrown eyeballs --- .claude/skills/gameplay-rules/SKILL.md | 64 ++++++++++++++++++++++++++ CHANGELOG.md | 2 + CLAUDE.md | 2 + 3 files changed, 68 insertions(+) create mode 100644 .claude/skills/gameplay-rules/SKILL.md diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md new file mode 100644 index 0000000..98de506 --- /dev/null +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -0,0 +1,64 @@ +--- +name: gameplay-rules +description: The design rules of Series of Tubes, each with an id and the test that enforces it. Use whenever you add or change cities, countries, networks (NETS, upstreams, traffic shares, presence), cables, exchanges, data centers, customers, scenarios, puzzles, presets or rules, balance numbers or progression, and before committing any such change. +--- + +# Gameplay rules + +These are what the game promises, held up by `tests/gameplay-rules.test.js` (one `test()` per id, on the live +`CITIES`, `NETS`, `CABLES`, `SCN`, `PZ`, `PRESETS`…). Each rule is true of the intended design. + +## Procedure + +1. Changing anything above? Run `npm test -- tests/gameplay-rules.test.js` (under a minute) before committing. +2. A failure names what breaks the rule and how to fix it. Fix the data or the code. +3. Only when real life really is different, add an entry to `EXCEPTIONS` in the test (keyed by rule id, sorted, with + its reason in plain words). Never delete or loosen a check to make it pass. A stale exception fails too. +4. A new rule gets an id in the right section here, one line, a why, and its own `test('ID: …')`. + +## World + +| Id | Rule | Why | +| --- | --- | --- | +| W1 | Every city has a country code (`cc`, ISO 3166-1 alpha-2; territories have their own: PR, GU, RE, MQ, CW…), a region, a landmass and coordinates. | Borders, prices and the eyeball rule all hang off the country. | +| W2 | Every country on the map has at least two consumer networks of its own: an eyeball network, or a Tier 2 incumbent that sells to homes, whose home markets (`cc` on the network) include that country and which has a PoP there. | Real countries have competing local ISPs, and peering locally is half the game. Add real operators in `src/game/30-networks/32-homegrown-eyeballs.js`. | +| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. | +| W4 | Cable pairs join two distinct real cities, have a length, and cable ids are unique. | Broken landings break routing and the own-cable planner. | +| W5 | A city alone on its landmass has a cable or a beach to land one. | Islands are reachable. | + +## Networks + +| Id | Rule | Why | +| --- | --- | --- | +| N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. | +| N2 | Names are puns: no network, cable, exchange, data center, router or optic is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. | +| N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. | +| N4 | No upstream cycles. | Cones must be trees, not loops. | +| N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. | +| N6 | Every network has a type, a peering policy (selective ones state `minIx`/`minPni`), a colour and a translated blurb; carriers have a price. | Panels and the peering rules read them. | +| N7 | PoPs are real, distinct cities; exchange ports only where the city has an exchange and the network has a PoP. | Presence follows PeeringDB-style reality. | + +## Modes and rules + +| Id | Rule | Why | +| --- | --- | --- | +| M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. | +| M2 | Presets are ordered: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market, inbox; and a seeded year of incidents). | The names promise it. | +| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, the peering inbox, sold-out routes and hardware prices (`market`), lead times (`lead`), the clock. A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. Open question: de-peering ignores the rules (exception). | +| M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. | +| M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. | + +## Content + +| Id | Rule | Why | +| --- | --- | --- | +| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0. | A goal must need play. | +| C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. | +| C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. | + +## Fun and fairness + +| Id | Rule | Why | +| --- | --- | --- | +| F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. | New players learn before they get punished. | +| F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. | diff --git a/CHANGELOG.md b/CHANGELOG.md index f13ceb4..e4abd57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,8 @@ All notable changes to this project are documented here. The project follows - 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). +- Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days. +- Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. ## [1.36.0] — 2026-10-28 diff --git a/CLAUDE.md b/CLAUDE.md index bf2ab35..94dd082 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,6 +13,8 @@ Read these before larger changes: - `docs/adr/`: decisions that are settled (GitHub Pages only; one page assembled at build). - `.claude/skills/`: step-by-step procedures (`edit-the-game`, `github-pages`, release, translations, tests, performance). +- `.claude/skills/gameplay-rules/`: the game's design rules (W1, N3, F2…), each enforced by + `tests/gameplay-rules.test.js`; run it before changing cities, networks, cables, modes or balance. ## Commands From 31e44440e8045f1199201cb12c2506c38611a300 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:17:08 +0100 Subject: [PATCH 095/181] Flood Season escalates again, and empty POPs no longer hold floods for free Every flood was 700G or more from day 1, so the scenario no longer built up. Sizes are 1.36's again (a third terabit monsters, the rest ordinary floods sized to the city), growing by the year as #153 had it. Floods go for POPs that serve someone, and a city with nobody to serve only holds a flood its tools soak up. Seeded runs over a year: no defence or one 1T center cannot win; one 1T center with full Flowspec and clean pipe wins around day 100 (main needed two centers, day 164). --- CHANGELOG.md | 1 + .../85-incidents/10-incidents-and-ddos.js | 3 ++- src/game/85-incidents/20-failures.js | 25 +++++++++++-------- tests/ddos-floods.test.js | 19 ++++++++++++++ tests/game.test.js | 17 ++++++------- 5 files changed, 44 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebd3011..9e50d6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ All notable changes to this project are documented here. The project follows - Live attacks now show how much traffic Flowspec actually drops. Routers without TCAM no longer claim to filter attacks, and Flowspec drops are counted separately from other edge filters (#153). - Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec and require dedicated mitigation (#153). - Flood Season keeps sending ever larger attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off (#153). +- Flood Season escalates again: ordinary floods mixed with terabit monsters, all growing through the year, and floods go for the POPs that serve customers, so empty POPs no longer hold them for free. - Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through (#153). - 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 (#153). - Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation (#153). diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js index a7a9624..a28a5dc 100644 --- a/src/game/85-incidents/10-incidents-and-ddos.js +++ b/src/game/85-incidents/10-incidents-and-ddos.js @@ -30,7 +30,8 @@ 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);}} // An attack is held or lost at its victim: the junk lands there, and other POPs' bad days are not the attacker's doing. -const ddosSf=a=>sfOf(R,a.city); +// A city with nobody to serve holds only if its tools soak up the flood (or there is nothing to judge but that). +const ddosSf=a=>((R.cityDem||{})[a.city]||0)>1e-6||!a.gbps?sfOf(R,a.city):clamp(1-ddosReport(a).leak/a.gbps,0,1); function ddosReport(a){return (R.ddos||[]).find(m=>m.attack===a)||ddosMitigation(a);} // Where the junk comes in: one of the city's live uplinks, or just "the edge" if it has none yet. function ddosEntry(c){const o=[]; diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index 33d4843..c7eaebf 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -120,18 +120,21 @@ const ddosVectors=()=>Object.keys(DDOS_VEC).filter(k=>!DDOS_VEC[k].gaming||gamin // 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); +// Normalize the vector mix so smaller gaming-only floods do not lower the advertised overall mean (Flood Season sizes its own). +function ddosSizeMean(){const stage=Math.max(1,S.lvl||1)/LEVELS.length,games=gamingCount(); + const base=Math.max(10,(R.demand||0)*4/3*stage); // 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);} +const ddosSizeMax=()=>ddosSizeMean()*12/1.278; +/* Flood Season (as in 1.36): a third are terabit monsters, the rest ordinary floods sized to the city; all of it grows + through the year, and on after it. One draw picks both, so fixed draws give fixed sizes. */ +function ddosSize(vec,c){const fl=scnRule('ddos'),r=Math.random(); + if(fl){const games=gamingCount(),grow=(1+S.day/365)*(1+0.2*games/(games+10))*(DDOS_VEC[vec].gaming?1/3:1); + const raw=r<1/3?800+2600*r*3:2+(r-1/3)*1.5*Math.max(18,((R.cityDem||{})[c]||0)*0.9);return Math.max(2,Math.floor(raw*grow));} + const roll=(r<.98?.2+1.8*r/.98:8+4*(r-.98)/.02)/12,raw=ddosSizeMax()*(DDOS_VEC[vec].gaming?1/3:1)*roll; + return Math.max(0.001,Math.floor(raw*1000)/1000);} // Calm (Change Freeze) and no chaos at all mean no attacks, gamers or not. const ddosOff=()=>{const c=rule('chaos');return c==='calm'||c==='none';}; // More frequent attacks are opt-in: the spicy chaos setting, or hosting gamers (who attract them in real life). @@ -145,8 +148,10 @@ function ddosTick(){if(ddosOff()&&!scnRule('ddos'))return;if(scnRule('ddos')){le // Size, duration and starts are randomized independently; overlapping floods never replace each other. function ddosAttack(recompute=true){const type='ddos',fl=scnRule('ddos');ddosExpire(); S.ddosStarts=(S.ddosStarts||[]).filter(d=>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); + // Flood Season goes for the POPs that serve someone, so empty ones cannot soak up floods for a free win. + const all=Object.keys(S.pops),served=fl?all.filter(x=>(R.cityDem||{})[x]>1e-6):[]; + const c=pick(served.length?served:all),vec=pick(ddosVectors()),V=DDOS_VEC[vec]; + const gbps=ddosSize(vec,c); const dur=1+Math.floor(Math.random()*(1+6*ddosPressure())),entry=ddosEntry(c); const a={id:uid(),city:c,vec,gbps,until:S.day+dur,entry,bh:false,start:S.day}; if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a); diff --git a/tests/ddos-floods.test.js b/tests/ddos-floods.test.js index 4415ad9..dfabb02 100644 --- a/tests/ddos-floods.test.js +++ b/tests/ddos-floods.test.js @@ -134,3 +134,22 @@ test('the China licence arrives in a tenth of the time with quick lead times, an assert.deepEqual(errors, []); } }); + +test('Flood Season escalates from ordinary floods to monsters, and empty POPs or no customers do not hold floods for free', () => { + const { ev, errors } = load({ seed: 5 }); + ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'ams'});ACT.buyTransit({city:'ams',net:NETS.find(n=>sellsAt(n,'ams')).id,tier:1});compute()"); + const sizes = JSON.parse(ev("const o=[];for(let i=0;i<60;i++){dayTick();for(const a of ddosAll())if(a.start===S.day)o.push(a.gbps);}JSON.stringify(o)")); + assert.ok(sizes.some(g => g < 100), `some ordinary floods early on (${sizes.join(' ')})`); + assert.ok(sizes.some(g => g >= 1000), 'and some terabit monsters'); + // Ten empty POPs: floods still go for Amsterdam, where the customers are. + ev("for(const c of ['lon','par','fra','mad','mil','vie','waw','sto','osl','hel'])ACT.buildPop({city:c});compute();S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[]"); + ev("for(let i=0;i<10;i++){S.ddosStarts=[];ddosAttack(false);}"); + assert.deepEqual(JSON.parse(ev('JSON.stringify([...new Set(ddosAll().map(a=>a.city))])')), ['ams']); + // A flood on a city with nobody to serve only holds if the tools soak it up. + ev("S.ev.ddosMore=[];S.ev.ddos={id:'e',city:'lon',vec:'http',gbps:500,start:S.day,until:S.day+2,entry:{k:'edge',lab:''}};compute()"); + assert.equal(ev("R.cityDem.lon||0"), 0); + assert.ok(ev('ddosSf(S.ev.ddos)') < 0.97, 'unmitigated: not held'); + ev("S.scrubs=[{city:'lon',tier:1}];S.scrubMode='always';compute()"); + assert.equal(ev('ddosSf(S.ev.ddos)'), 1, 'scrubbed: held'); + assert.deepEqual(errors, []); +}); diff --git a/tests/game.test.js b/tests/game.test.js index 5102de3..13e085a 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -806,11 +806,7 @@ test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood 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'); + ev('R.demand=300000'); assert.equal(ev('ddosSizeMean()'), 40000, 'larger networks can draw still larger attacks'); ev('S.lvl=1'); const early = ev('ddosSizeMax()'); @@ -1034,13 +1030,14 @@ test('normal attack sizes cover a broad ordinary range and a two-percent large t assert.deepEqual(errors, []); }); -test('Flood Season retains its existing size quantiles and escalation when normal attacks gain rare spikes', () => { +test('Flood Season mixes terabit monsters with ordinary floods, and all of it grows through the year and after', () => { 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("ACT.start({});S.scn={id:'flood',rules:{ddos:true}};S.lvl=3;S.biz=[];R.cityDem={fra:100}"); + // One draw: below a third a monster (800 to 3,400G), above it an ordinary flood up to 90% of the city's traffic. + for (const [day,expected] of [[0,[800,3399,2,91]],[365,[1600,6799,4,183]],[730,[2400,10199,6,275]]]) { 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); + const actual = JSON.parse(ev("const old=Math.random;let sizes;try{sizes=[0,1/3-1e-9,1/3,0.999999].map(r=>{Math.random=()=>r;return ddosSize('syn','fra')})}finally{Math.random=old}JSON.stringify(sizes)")); + assert.deepEqual(actual, expected, `day ${day}`); } assert.deepEqual(errors, []); }); From c5142046ed2a2a04a2e3f8d7b98ca8df23341acf Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:17:15 +0100 Subject: [PATCH 096/181] CHANGELOG: China licence lead time, locked rules and attacker names in saves --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e50d6c..dcb95df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,8 @@ All notable changes to this project are documented here. The project follows - Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec and require dedicated mitigation (#153). - Flood Season keeps sending ever larger attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off (#153). - Flood Season escalates again: ordinary floods mixed with terabit monsters, all growing through the year, and floods go for the POPs that serve customers, so empty POPs no longer hold them for free. +- The China licence follows quick lead times: about 5 days instead of 45 under Change Freeze and in Sandbox. +- Imported saves can no longer change a network's rules or slip HTML into a Flood Season attacker's name. - Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through (#153). - 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 (#153). - Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation (#153). From 08e88d53a82a27ed6d315b679f8b839897fb38b0 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:40:14 +0100 Subject: [PATCH 097/181] Save slots: reuse the parsed index between autosaves --- src/game/91-slots.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/game/91-slots.js b/src/game/91-slots.js index 4a5f77b..d3b1e30 100644 --- a/src/game/91-slots.js +++ b/src/game/91-slots.js @@ -29,6 +29,8 @@ function slotFromKey(id){const raw=slotRaw(id)||'';if(raw.startsWith(GZ))return /* The list of networks. scan also looks at the keys themselves (cheap: no save is read unless its entry is missing): a save whose index write failed is added back, an entry whose save is gone is dropped. A damaged index is rebuilt. */ function slotIdx(scan){const raw=lsGet(SLOT_IX);let list=null; + // The same text as last time (every autosave): no need to parse and check it again. + if(!scan&&raw!=null&&raw===SLOT.ixRaw)return SLOT.ixList.map(e=>({...e})); if(raw!=null)try{const j=JSON.parse(raw);if(j&&Array.isArray(j.slots))list=j.slots.map(slotClean).filter(Boolean);}catch(e){} const bad=raw!=null&&!list;if(!list)list=[];{const seen=new Set();list=list.filter(e=>!seen.has(e.id)&&seen.add(e.id));} if(scan||bad){const ks=slotKeys(),keys=new Set(ks);let ch=bad;const n=list.length; @@ -36,8 +38,9 @@ function slotIdx(scan){const raw=lsGet(SLOT_IX);let list=null; list=list.filter(e=>keys.has(e.id));if(list.length!==n)ch=true; for(const id of keys)if(!list.some(e=>e.id===id)){list.push(slotFromKey(id));ch=true;} if(ch)slotIdxPut(list);if(list.some(e=>e.gz&&!e.name&&!e.broken))slotFix(list);} + else if(raw!=null&&list.length){SLOT.ixRaw=raw;SLOT.ixList=list.map(e=>({...e}));} return list;} -function slotIdxPut(list){try{localStorage.setItem(SLOT_IX,JSON.stringify({v:1,slots:list}));return true;}catch(e){return false;}} +function slotIdxPut(list){const t=JSON.stringify({v:1,slots:list});try{localStorage.setItem(SLOT_IX,t);SLOT.ixRaw=t;SLOT.ixList=list.map(e=>({...e}));return true;}catch(e){SLOT.ixRaw=null;return false;}} function slotFix(list){for(const e of list)if(e.gz&&!e.name&&!e.broken&&!SLOT['fix'+e.id]){SLOT['fix'+e.id]=1;const raw=slotRaw(e.id); gunzip(raw).then(t=>{const s=JSON.parse(t);return s&&s.v===1?slotMeta(s,null):null;},()=>null).then(m=>{const l=slotIdx(),x=l.find(y=>y.id===e.id);if(!x)return; if(m)Object.assign(x,slotClean({...x,...m}));else x.broken=true;slotIdxPut(l);slotRefresh();});}} From 9b7b1c150ccebb16ec751954c05652cd8b9540e4 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 07:57:21 +0100 Subject: [PATCH 098/181] Series of Tubes 2.0.0: one game, four doors --- CHANGELOG.md | 23 ++++++++++++----------- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43896a9..4933538 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,18 +6,22 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. -- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside. -- 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. -- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner. -- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. +## [2.0.0] — 2026-10-29 + - 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. +- 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. +- 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. +- 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). +- 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. - 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 (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. -- 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). +- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. - 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. +- Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days. +- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside. +- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner. +- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. +- 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). - 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 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. @@ -37,10 +41,7 @@ All notable changes to this project are documented here. The project follows - 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 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. 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, 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). -- Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days. - Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. - 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). diff --git a/package-lock.json b/package-lock.json index a378772..19b7dea 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "1.37.0", + "version": "2.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "1.37.0", + "version": "2.0.0", "license": "MIT", "devDependencies": { "jsdom": "24.1.3", diff --git a/package.json b/package.json index 55062b1..62b1c37 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "1.37.0", + "version": "2.0.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", From e17ddc247bff6ee82e8d50e4bb3734a57fff28ae Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 09:55:35 +0100 Subject: [PATCH 099/181] Change Freeze stops de-peering at exchanges Snubs (refused and torn-down sessions at exchanges) are part of the market rule now, so Change Freeze and puzzles have none; On-call is unchanged. --- .claude/skills/gameplay-rules/SKILL.md | 2 +- CHANGELOG.md | 2 +- 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/40-progress/30-rules.js | 2 +- src/game/70-rules/50-peering-policy.js | 5 +++-- src/i18n/en.js | 2 +- tests/gameplay-rules.test.js | 6 ++---- tests/peering.test.js | 20 ++++++++++++++++++++ 12 files changed, 34 insertions(+), 15 deletions(-) diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 98de506..092aa0f 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -44,7 +44,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | --- | --- | --- | | M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. | | M2 | Presets are ordered: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market, inbox; and a seeded year of incidents). | The names promise it. | -| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, the peering inbox, sold-out routes and hardware prices (`market`), lead times (`lead`), the clock. A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. Open question: de-peering ignores the rules (exception). | +| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, the peering inbox, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock. A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | | M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. | | M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 4933538..f681b9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ All notable changes to this project are documented here. The project follows - 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. - 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). - 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. -- 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. +- 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, sold-out routes and de-peering at exchanges. 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. - Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. - 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. diff --git a/site/i18n/de.js b/site/i18n/de.js index 711b9e0..bd56b10 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3243,6 +3243,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Steck zuerst etwas aus.
{used} Ports sind belegt, und mit einem Router weniger gibt es nur {max}.", "rules.a_billion_dollars_every_unlock_your":"Eine Milliarde Dollar, alles freigeschaltet, dein eigenes Seekabel.", "rules.a_cut_now_and_then":"Ab und zu ein Bagger.", +"rules.a_third_of_the_outages_no_ddos":"Ein Drittel der Ausfälle, kein DDoS. PNIs und Bauten in Tagen. Kein Postfach, keine Lieferengpässe, keine ausverkauften Routen, kein De-Peering.", "rules.bgp_at_3_a_m":"BGP um 3 Uhr nachts", "rules.change_freeze":"Change Freeze", "rules.chaos_calm":"Ruhig", @@ -3250,7 +3251,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Scharf", "rules.everything_is_on_fire_and_it":"Alles brennt, und du hast Bereitschaft.", -"rules.fewer_outages_pnis_and_builds_in":"Ein Drittel der Ausfälle, kein DDoS. PNIs und Bauten in Tagen. Kein Postfach, keine Lieferengpässe, keine ausverkauften Routen.", "rules.infinite_money_everything_unlocked_quick":"Endlos Geld, alles freigeschaltet, kurze Lieferzeiten. Keine Abzeichen.", "rules.like_the_real_game":"Wie im echten Spiel.", "rules.more_and_longer_outages_more_ddos":"Fast doppelt so viele Ausfälle, anderthalbmal so lang, doppelt so viel DDoS. Alles an.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 21a7058..3f3a819 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3241,6 +3241,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Desconecta algo primero.
Hay {used} puertos en uso, y con un router menos solo hay {max}.", "rules.a_billion_dollars_every_unlock_your":"Mil millones de dólares, todo desbloqueado, tu propio cable submarino.", "rules.a_cut_now_and_then":"Algún corte de vez en cuando.", +"rules.a_third_of_the_outages_no_ddos":"Un tercio de las caídas, sin DDoS. PNI y obras en días. Sin bandeja de entrada, sin escasez, sin rutas agotadas, sin de-peering.", "rules.bgp_at_3_a_m":"BGP a las 3 de la mañana", "rules.change_freeze":"Congelación de cambios", "rules.chaos_calm":"Tranquilo", @@ -3248,7 +3249,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Picante", "rules.everything_is_on_fire_and_it":"Todo está ardiendo, y te toca a ti.", -"rules.fewer_outages_pnis_and_builds_in":"Un tercio de las caídas, sin DDoS. PNI y obras en días. Sin bandeja de entrada, sin escasez, sin rutas agotadas.", "rules.infinite_money_everything_unlocked_quick":"Dinero sin fin, todo desbloqueado, plazos cortos. Sin insignias.", "rules.like_the_real_game":"Como el juego de verdad.", "rules.more_and_longer_outages_more_ddos":"Casi el doble de caídas, la mitad más largas, el doble de DDoS. Todo activado.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index ec80dc5..acdf746 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3241,6 +3241,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Débranche d’abord quelque chose.
{used} ports sont utilisés, et avec un routeur de moins tu n’en aurais que {max}.", "rules.a_billion_dollars_every_unlock_your":"Un milliard de dollars, tout débloqué, ton propre câble sous-marin.", "rules.a_cut_now_and_then":"Une coupure de temps en temps.", +"rules.a_third_of_the_outages_no_ddos":"Un tiers des pannes, pas de DDoS. PNI et chantiers en quelques jours. Pas de boîte de réception, pas de pénurie, pas de routes épuisées, pas de dépeering.", "rules.bgp_at_3_a_m":"BGP à 3 h du matin", "rules.change_freeze":"Gel des changements", "rules.chaos_calm":"Calme", @@ -3248,7 +3249,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Épicé", "rules.everything_is_on_fire_and_it":"Tout brûle, et c’est ton tour d’astreinte.", -"rules.fewer_outages_pnis_and_builds_in":"Un tiers des pannes, pas de DDoS. PNI et chantiers en quelques jours. Pas de boîte de réception, pas de pénurie, pas de routes épuisées.", "rules.infinite_money_everything_unlocked_quick":"Argent infini, tout débloqué, délais courts. Pas de badges.", "rules.like_the_real_game":"Comme le vrai jeu.", "rules.more_and_longer_outages_more_ddos":"Presque deux fois plus de pannes, moitié plus longues, deux fois plus de DDoS. Tout activé.", diff --git a/site/i18n/it.js b/site/i18n/it.js index f6250c9..f959550 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3241,6 +3241,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Prima stacca qualcosa.
Ci sono {used} porte in uso, e con un router in meno ne avresti solo {max}.", "rules.a_billion_dollars_every_unlock_your":"Un miliardo di dollari, tutto sbloccato, il tuo cavo sottomarino.", "rules.a_cut_now_and_then":"Un taglio ogni tanto.", +"rules.a_third_of_the_outages_no_ddos":"Un terzo dei guasti, niente DDoS. PNI e cantieri in pochi giorni. Niente posta, niente carenze, niente rotte esaurite, niente de-peering.", "rules.bgp_at_3_a_m":"BGP alle 3 di notte", "rules.change_freeze":"Change freeze", "rules.chaos_calm":"Calmo", @@ -3248,7 +3249,6 @@ "rules.chaos_normal":"Normale", "rules.chaos_spicy":"Piccante", "rules.everything_is_on_fire_and_it":"Va tutto a fuoco, e tocca a te.", -"rules.fewer_outages_pnis_and_builds_in":"Un terzo dei guasti, niente DDoS. PNI e cantieri in pochi giorni. Niente posta, niente carenze, niente rotte esaurite.", "rules.infinite_money_everything_unlocked_quick":"Soldi infiniti, tutto sbloccato, consegne rapide. Niente medaglie.", "rules.like_the_real_game":"Come il gioco vero.", "rules.more_and_longer_outages_more_ddos":"Quasi il doppio dei guasti, lunghi una volta e mezza, il doppio dei DDoS. Tutto acceso.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 4308d56..1f7e31c 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3241,6 +3241,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Desconecte algo primeiro.
Há {used} portas em uso, e com um router a menos só teria {max}.", "rules.a_billion_dollars_every_unlock_your":"Um bilhão de dólares, tudo desbloqueado, o seu próprio cabo submarino.", "rules.a_cut_now_and_then":"Um corte de vez em quando.", +"rules.a_third_of_the_outages_no_ddos":"Um terço das falhas, sem DDoS. PNIs e obras em dias. Sem caixa de entrada, sem escassez, sem rotas esgotadas, sem de-peering.", "rules.bgp_at_3_a_m":"BGP às 3 da manhã", "rules.change_freeze":"Congelamento de mudanças", "rules.chaos_calm":"Calmo", @@ -3248,7 +3249,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Apimentado", "rules.everything_is_on_fire_and_it":"Está tudo pegando fogo, e o plantão é seu.", -"rules.fewer_outages_pnis_and_builds_in":"Um terço das falhas, sem DDoS. PNIs e obras em dias. Sem caixa de entrada, sem escassez, sem rotas esgotadas.", "rules.infinite_money_everything_unlocked_quick":"Dinheiro sem fim, tudo desbloqueado, prazos curtos. Sem medalhas.", "rules.like_the_real_game":"Como o jogo de verdade.", "rules.more_and_longer_outages_more_ddos":"Quase o dobro de falhas, metade mais longas, o dobro de DDoS. Tudo ligado.", diff --git a/src/game/40-progress/30-rules.js b/src/game/40-progress/30-rules.js index c61421b..656677e 100644 --- a/src/game/40-progress/30-rules.js +++ b/src/game/40-progress/30-rules.js @@ -7,7 +7,7 @@ const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,inbox:true,mon const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],inbox:[true,false],money:['normal','infinite'],gates:['ladder','open']}; // i: icon, n: name, d: the one-line joke, x: what is different, in small print. const PRESETS={ - freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.fewer_outages_pnis_and_builds_in'),clock:true,chaos:'calm',lead:'quick',market:false,inbox:false,money:'normal',gates:'ladder'}, + freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos'),clock:true,chaos:'calm',lead:'quick',market:false,inbox:false,money:'normal',gates:'ladder'}, oncall:{i:'📟',n:tr('rules.on_call'),d:tr('rules.the_real_thing_your_pager_has'),x:tr('rules.real_lead_times_real_outages_a'),clock:true,chaos:'normal',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder'}, bgp:{i:'🔥',n:tr('rules.bgp_at_3_a_m'),d:tr('rules.everything_is_on_fire_and_it'),x:tr('rules.more_and_longer_outages_more_ddos'),clock:true,chaos:'spicy',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder'}, sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,inbox:true,money:'infinite',gates:'open'}, diff --git a/src/game/70-rules/50-peering-policy.js b/src/game/70-rules/50-peering-policy.js index 48edcd3..93e1913 100644 --- a/src/game/70-rules/50-peering-policy.js +++ b/src/game/70-rules/50-peering-policy.js @@ -1,12 +1,13 @@ /* Big networks sometimes refuse to peer in a particular city, for a while. Each (network, city) - pair gets a stable verdict per window, derived from a hash, so asking again does not reroll it. */ + pair gets a stable verdict per window, derived from a hash, so asking again does not reroll it. + It is part of the market: without one (Change Freeze, puzzles), nobody refuses or drops a session. */ const SNUB_WIN=150,SNUB_P=0.22; const SNUB_IX=[tr('peering_policy.only_peers_over_pnis_in_this'),tr('peering_policy.their_ix_port_here_is_full'),tr('peering_policy.moved_everything_in_this_city_to'),tr('peering_policy.the_peering_coordinator_for_this'),tr('peering_policy.their_policy_here_says_ix_peering')]; const SNUB_ALL=[tr('peering_policy.not_accepting_new_peers_in_this'),tr('peering_policy.region_frozen_while_they_renegotiate'),tr('peering_policy.their_routers_in_this_city_are'),tr('peering_policy.already_reach_you_through_your'),tr('peering_policy.their_lawyers_are_reviewing_every'),tr('peering_policy.a_new_vp_wants_to_monetise')]; function hstr(t){let h=2166136261;for(let i=0;i>>0;} function bigPeer(n){return !!n&&n.pol==='selective'&&n.share>=0.03;} function snub(id,c){ - const n=NET[id];if(!c||!bigPeer(n)||!S||S.myIx[c])return null; + const n=NET[id];if(!c||!bigPeer(n)||!S||S.myIx[c]||!rule('market'))return null; const off=hstr(id+c)%SNUB_WIN,ep=Math.floor((S.day+off)/SNUB_WIN),h=hstr(S.asn+'|'+id+'|'+c+'|'+ep); if(h%1000>=SNUB_P*1000)return null; const all=(h>>>10)%5<2,list=all?SNUB_ALL:SNUB_IX; diff --git a/src/i18n/en.js b/src/i18n/en.js index c8236d6..193d061 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3242,6 +3242,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Unplug something first.
{used} ports are in use, and one router fewer only has {max}.", "rules.a_billion_dollars_every_unlock_your":"A billion dollars, every unlock, your own subsea cable.", "rules.a_cut_now_and_then":"A cut now and then.", +"rules.a_third_of_the_outages_no_ddos":"A third of the outages, no DDoS. PNIs and builds in days. No inbox, no shortages, no sold-out routes, no de-peering.", "rules.bgp_at_3_a_m":"BGP at 3 a.m.", "rules.change_freeze":"Change Freeze", "rules.chaos_calm":"Calm", @@ -3249,7 +3250,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Spicy", "rules.everything_is_on_fire_and_it":"Everything is on fire, and it's your turn.", -"rules.fewer_outages_pnis_and_builds_in":"A third of the outages, no DDoS. PNIs and builds in days. No inbox, no shortages, no sold-out routes.", "rules.infinite_money_everything_unlocked_quick":"Endless money, everything unlocked, quick lead times. No badges.", "rules.like_the_real_game":"Like the real game.", "rules.more_and_longer_outages_more_ddos":"Almost twice the outages, half as long again, twice the DDoS. Everything on.", diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 3535fb8..3c2c1f7 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -84,9 +84,7 @@ const EXCEPTIONS = { 'spl:hba': 'Speedyloop reaches Hobart’s exchange over its own backhaul but sells no transit there', }, // M3: subsystems that annoy the player but read no rule. - M3: { - snub: 'de-peering at exchanges happens in every mode (open question: should Change Freeze stop it?)', - }, + M3: {}, }; // The real names the puns are based on. No network, cable, exchange, data center, router or optic may be called one. @@ -234,7 +232,7 @@ test('M3: every subsystem that can annoy the player reads a rule', () => { // [function, what it must read] const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['inboxDay', "rule('inbox')"], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], - ['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"]]; + ['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"], ['snub', "rule('market')"]]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); // and in play: no chaos, no market, no inbox means a quiet year const g = load(); diff --git a/tests/peering.test.js b/tests/peering.test.js index 4b51227..4e1d185 100644 --- a/tests/peering.test.js +++ b/tests/peering.test.js @@ -99,6 +99,26 @@ test('a snubbing peer tears down an existing session and the Request button expl assert.deepEqual(errors, []); }); +test('Change Freeze never refuses or tears down a session at an exchange; On-call does', () => { + const { ev, errors } = load(); + setup(ev); + const k = ev(`(()=>{const ok=['fra','ams','lon','par','nyc','ash','sjc','sin','tok','hkg']; + for(let d=0;d<600;d++)for(const n of NETS)for(const c of ok){if(!ixMembers(c).includes(n.id))continue; + S.day=d;const a=snub(n.id,c);S.day=d+1;const b=snub(n.id,c);S.day=0;if(!a&&b)return n.id+'@'+c+'@'+d;}})()`); + assert.ok(k, 'found a snub starting at an IX'); + const [id, c, d] = k.split('@'); + ev(`S.rules=makeRules('freeze');S.day=${d}`); + ev(`ACT.buildPop({city:'${c}'});ACT.buyIx({city:'${c}',tier:1,signed:true});S.peers['${id}@${c}']=true;compute()`); + ev('dayTick()'); + assert.equal(ev(`!!S.peers['${id}@${c}']`), true, 'the session survives the freeze'); + assert.equal(ev(`snub('${id}','${c}')`), null, 'and nobody refuses a new one'); + assert.equal(ev(`ixSessions('${c}').has('${id}')`), true); + assert.equal(ev('S.stats.depeered||0'), 0); + ev(`S.rules=makeRules('oncall');S.day=${+d + 1}`); + assert.ok(ev(`!!snub('${id}','${c}')`), 'On-call still snubs the same pair'); + assert.deepEqual(errors, []); +}); + test('remote peering is offered but costs more, gives less and gets refused more', () => { const { ev, errors } = load(); setup(ev); From 77ec31d1a08774315abdebecefe89c53d90a8b30 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 09:58:01 +0100 Subject: [PATCH 100/181] Give Palau's and the Marshall Islands' networks their real ASNs PNC-See had AS9534 (Maxis, Malaysia) and Never Too Atoll AS21581 (a US host); the real operators are AS17893 (PNCC) and AS24439 (NTA). Saves key on network ids, so nothing stored changes. The fudged numbers of the big carriers and the African/Latin American incumbents are deliberate and stay. --- CHANGELOG.md | 1 + src/game/30-networks/30-long-tail.js | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f681b9b..0c71bd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ All notable changes to this project are documented here. The project follows - 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). - Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. - 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). +- Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. ## [1.37.0] — 2026-10-28 diff --git a/src/game/30-networks/30-long-tail.js b/src/game/30-networks/30-long-tail.js index fd83534..1304fb8 100644 --- a/src/game/30-networks/30-long-tail.js +++ b/src/game/30-networks/30-long-tail.js @@ -93,8 +93,8 @@ NETS.push( {id:'otk',name:'Ours-Truly Telekom',asn:45891,type:'eye',cc:'SB',pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#00843D',pops:['hir'],ix:['hir'],blurb:tr('long_tail.the_solomon_islands_incumbent_yours')}, {id:'tcc',name:'Tongue-in-Cheek Comms',asn:38201,type:'eye',cc:'TO',pol:'selective',minIx:1,minPni:8,share:.001,up:['ntt'],col:'#C10230',pops:['tbu'],ix:[],blurb:tr('long_tail.tonga_s_own_telco_lived_through')}, {id:'bsk',name:'Blue-Sky-Pie Samoa',asn:17993,type:'eye',cc:['WS','AS'],pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#0096D6',pops:['apw','ppg'],ix:[],blurb:tr('long_tail.samoa_s_broadband_promised_with_a')}, - {id:'pnc',name:'PNC-See',asn:9534,type:'eye',cc:'PW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#1B75BB',pops:['ror'],ix:[],blurb:tr('long_tail.palau_s_telco_snorkel_down_and')}, - {id:'nta',name:'Never Too Atoll',asn:21581,type:'eye',cc:'MH',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#2E8B57',pops:['maj'],ix:[],blurb:tr('long_tail.the_marshall_islands_telco_two')}); + {id:'pnc',name:'PNC-See',asn:17893,type:'eye',cc:'PW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#1B75BB',pops:['ror'],ix:[],blurb:tr('long_tail.palau_s_telco_snorkel_down_and')}, + {id:'nta',name:'Never Too Atoll',asn:24439,type:'eye',cc:'MH',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#2E8B57',pops:['maj'],ix:[],blurb:tr('long_tail.the_marshall_islands_telco_two')}); NETS.push( {id:'onc',name:'One Commotion',asn:3855,type:'eye',cc:'BM',pol:'selective',minIx:1,minPni:8,share:.001,up:['lvl','tly'],col:'#E4007C',pops:['bda'],ix:[],blurb:tr('long_tail.bermuda_s_phones_tv_and_internet')}, {id:'cvt',name:'Curriculum Vitae Telecom',asn:37517,type:'t2',cc:'CV',pol:'open',share:.002,price:8,up:['tat','tly'],col:'#004B87',pops:['rai','lis','for','dkr'],ix:['rai'],blurb:tr('long_tail.cape_verde_s_incumbent_and_the')}, From 7cbe0ec09b4d8949a8f789a83d8890bd7f5e52a1 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 10:03:20 +0100 Subject: [PATCH 101/181] Regenerate published weekly puzzles when a release's prices break them --check now re-solves every week not over yet and, when its budget no longer verifies, regenerates it deterministically: the same puzzle with a new budget if that works, else a fresh one for the key. A regenerated file carries rev 2, 3...; the game keeps stars per revision, so only that week's stars reset. Past weeks are left alone unless the game rejects them. release.yml runs it before the tests on every deploy, weekly-puzzle.yml before making the new week; either fails only if a week cannot be regenerated. --- .claude/skills/github-pages/SKILL.md | 3 +- .claude/skills/release/SKILL.md | 7 +++ .github/workflows/release.yml | 14 ++++-- .github/workflows/weekly-puzzle.yml | 3 ++ CHANGELOG.md | 1 + scripts/weekly-puzzle.js | 60 ++++++++++++++++++++--- src/game/60-features/92-puzzles.js | 10 ++-- src/game/60-features/93-puzzles-weekly.js | 8 +-- src/game/95-modals/95-puzzles.js | 2 +- tests/weekly-puzzle.test.js | 50 ++++++++++++++++++- 10 files changed, 135 insertions(+), 23 deletions(-) diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index f57d959..69d4a49 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -45,7 +45,8 @@ steps. 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 +`main`, so a release never drops a published week, and regenerates (in the build, deterministically) any week +not over yet that the release's prices no longer fit. 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 diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 0378f48..99f8b4d 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -21,6 +21,13 @@ version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly `gh workflow run release.yml --ref -f tag= -f weekly=true`). A release includes every weekly file on `main` when it builds. +**Prices change, weeks follow.** `--check` re-solves every week not over yet with the game it runs; a week whose +budget no longer verifies is regenerated deterministically (the same puzzle with a new budget if that works, else a +fresh one for the same key) with `rev` + 1, which resets players' stars for that week only. Past weeks are left alone +unless the game rejects them. `release.yml` runs it before the tests on every deploy and fails only if a week cannot be +regenerated. A change to prices, cables or cities fails `npm test` until you run `node scripts/weekly-puzzle.js --check` +and commit the regenerated files with it. + ## Only release when Frederic says so Never bump the version on your own. Finished work is committed and pushed with its diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 801aee4..fe2070b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -80,16 +80,20 @@ jobs: 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 }} + # This release's prices may no longer fit a week already published: --check regenerates every week not over + # yet whose budget no longer verifies (deterministically, so main's next weekly run commits the same files), + # and fails the deploy only if that fails. Before the tests, which check the weeks too. + - name: Fit the weekly puzzles to this release 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 + - run: npm test + if: ${{ !inputs.weekly }} + - name: Test the weekly puzzles against this release + if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }} + run: 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 diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml index 09cf814..0629330 100644 --- a/.github/workflows/weekly-puzzle.yml +++ b/.github/workflows/weekly-puzzle.yml @@ -45,6 +45,9 @@ jobs: node-version: 24 cache: npm - run: npm ci + # Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current. + - name: Fit the published weeks to main + run: node scripts/weekly-puzzle.js --check - name: Make the puzzle run: | set -euo pipefail diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c71bd6..e56d08c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ All notable changes to this project are documented here. The project follows - Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. - 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). - Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. +- When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. ## [1.37.0] — 2026-10-28 diff --git a/scripts/weekly-puzzle.js b/scripts/weekly-puzzle.js index 93b6edd..11c654f 100644 --- a/scripts/weekly-puzzle.js +++ b/scripts/weekly-puzzle.js @@ -7,7 +7,8 @@ // 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) +// node scripts/weekly-puzzle.js --check regenerate weeks not over yet whose budget this game no longer verifies +// (see refresh()), then validate every file; fails only if that fails // --page FILE play another build of the game (the live release), see the workflow // --dir DIR where the files live (default site/puzzles/weekly) // @@ -250,6 +251,7 @@ function play(ev, def, links) { ev('closeModal()'); return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))')); } +// A first edition has no rev; refresh() adds rev 2, 3… when it regenerates a week. 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 } }); @@ -267,6 +269,14 @@ function verify(g, W, j, key) { return { ok: true, sol, s1, s3 }; } +// 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. +function budgetOf(sol) { + 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); + return budget; +} + function generate(g, key, dir) { const { ev } = g, W = world(ev); if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`); @@ -281,11 +291,7 @@ function generate(g, key, dir) { 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 budget = budgetOf(sol), 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) }); } @@ -315,16 +321,54 @@ function check(g, dir, now = Date.now()) { } return bad; } +/* --check, first part: a release can change prices, cables or cities under weeks that are already published. Every + week not over yet is re-solved with this game; when its budget no longer verifies it is regenerated, deterministically: + the same puzzle (theme, cities, twist, name) with a new budget when that still works, else a fresh puzzle for the + same key. Its rev goes up, so players' stars for that week (and only that week) start again; new references alone + keep the rev. Past weeks can no longer be played, so they keep their stars and are only replaced when the game + rejects them outright. Returns what changed and what could not be fixed. */ +function refresh(g, dir, now = Date.now()) { + const { ev } = g, W = world(ev), fixed = [], bad = []; + for (const k of list(dir)) { + const f = path.join(dir, k + '.json'); + let j = null; try { j = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { /* regenerated below */ } + const valid = !!j && ev(`!!pzWkValid(${JSON.stringify(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now; + if (valid && !live) continue; + const v = valid ? verify(g, W, j, k) : null; + if (v && v.ok) { + if (j.ref && j.ref.one === v.sol.one.cost && j.ref.three === v.sol.three.cost) continue; + j.ref = { one: v.sol.one.cost, three: v.sol.three.cost }; writeWeek(dir, j); fixed.push(`${k}: new references`); continue; + } + const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1; + let n = null; + if (valid) { + const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${k}'))`)); + const sol = solve(W, { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: def.lat }); + if (sol.one && sol.three) { + const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev }); + if (verify(g, W, c, k).ok) n = c; + } + } + if (!n) { try { n = Object.assign(generate(g, k, dir), { rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; } } + writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}${n.theme === (j && j.theme) && JSON.stringify(n.cities) === JSON.stringify(j.cities) ? ', same puzzle, new budget ' + n.budget : ', a new ' + n.theme + ' puzzle'}`); + } + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ } + if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); } + return { fixed, 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 }; +module.exports = { game, generate, check, refresh, 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); + // Fix what a release's new prices broke, then check everything; only what could not be fixed fails. + const r = refresh(g, dir); + for (const x of r.fixed) console.log(`fixed: ${x}`); + const bad = [...r.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); diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index fff7bb3..232a4cf 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -10,11 +10,13 @@ const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key' 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; - const rec=r=>r&&typeof r==='object'?{st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)}:null; + const rec=r=>{if(!r||typeof r!=='object')return null;const o={st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)},rv=int(r.rv,1,999,1);if(rv>1)o.rv=rv;return o;}; if(j.s&&typeof j.s==='object')for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;} if(j.wk&&typeof j.wk==='object')for(const k of Object.keys(j.wk)){const r=rec(j.wk[k]);if(/^\d{4}-W\d{2}$/.test(k)&&r)o.wk[k]=r;} const st=j.streak;if(st&&typeof st==='object'){o.streak.last=typeof st.last==='string'&&/^\d{4}-W\d{2}$/.test(st.last)?st.last:null;o.streak.n=int(st.n,0,9999,0);o.streak.best=int(st.best,0,9999,0);} return o;} +// A weekly's stars belong to the revision they were earned on: a week regenerated for new prices starts again. +const pzWkRec=(p,d)=>{const r=p.wk[d.key];return r&&(r.rv||1)===(d.rev||1)?r:null;}; function pzLoad(){try{return pzClean(JSON.parse(localStorage.getItem(PZ_KEY)||'{}'));}catch(e){return pzClean(null);}} function pzStore(p){try{localStorage.setItem(PZ_KEY,JSON.stringify(p));}catch(e){}} const pzStarsTotal=p=>PZ.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0); @@ -86,7 +88,7 @@ const pzToastsClear=()=>{$('toasts').textContent='';}; function pzFlush(){save(true);UI.pzKeep=S;} 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,wn:def.wn||null,wj:def.wj||null,theme:def.theme||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,rev:def.rev||1}; 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();pzToastsClear();document.body.classList.add('pz'); compute();pzCam();renderAll();track('puzzle_'+def.id); @@ -114,8 +116,8 @@ function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI // 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}; +function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null}; if(e.stars1)r.rv=P.rev;else delete r.rv;bag[k]=r;if(P.id==='weekly')pzStreak(p,P.key);pzStore(p);} // The next puzzle in the list whose pack is open. function pzNextDef(){const p=pzLoad(),i=PZ.findIndex(x=>x.id===S.pz.id);for(let j=i+1;j0&&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']; +// rev: the file's revision, from 2 when a release's new prices made the week regenerate (scripts/weekly-puzzle.js). +const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref','rev']; 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(j.rev!==undefined&&!(Number.isInteger(j.rev)&&j.rev>=2&&j.rev<=999))return null; + const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null,rev:j.rev||1}; 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;} @@ -72,4 +74,4 @@ function pzWkRefresh(){const el=$('pzWk');if(el)el.outerHTML=pzWkRow();} 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;}} +function pzWkNew(){try{const k=pzWeekKey(new Date()),w=UI.pzWk;return !pzWkRec(pzLoad(),w&&w.key===k&&w.def?w.def:{key:k});}catch(e){return false;}} diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index dc45fdf..1a1f639 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -75,7 +75,7 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);} // ---------- the list ---------- // 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); +function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=pzWkRec(p,w),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)}):''}
diff --git a/tests/weekly-puzzle.test.js b/tests/weekly-puzzle.test.js index f8107f5..e41c26e 100644 --- a/tests/weekly-puzzle.test.js +++ b/tests/weekly-puzzle.test.js @@ -96,7 +96,8 @@ 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(); - // Weeks still to come are re-solved; past ones are checked the way the game reads them. + // Weeks still to come are re-solved; past ones are checked the way the game reads them. check() only reports; + // refresh() (the first half of --check) is what fixes. assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify'); const bad = (edit, why) => { const d = tmp(); @@ -117,6 +118,53 @@ test('--check passes on the committed files and rejects tampered ones', () => { bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks'); }); +test('--check regenerates a published week when new prices break its budget, and only then', () => { + const g = G.game(), d = tmp(); + for (const k of G.list(DIR)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json')); + G.writeIndex(d); + const read = (k) => JSON.parse(fs.readFileSync(path.join(d, k + '.json'), 'utf8')), [k0, k1] = G.list(d).slice(-2); + assert.deepEqual(G.refresh(g, d, 0), { fixed: [], bad: [] }, 'the committed weeks still verify: nothing changes'); + // Prices went up: the old budget no longer buys the N-1 build. The same puzzle comes back with a budget that does. + const old = read(k0), j = read(k0); j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1; + fs.writeFileSync(path.join(d, k0 + '.json'), JSON.stringify(j)); + const r = G.refresh(g, d, 0); + assert.deepEqual(r.bad, []); + assert.equal(r.fixed.length, 1, r.fixed.join('; ')); + const n = read(k0); + assert.equal(n.rev, 2, 'a new revision'); + assert.deepEqual([n.theme, n.cities, n.via, n.avoid, n.twist, n.name, n.joke], [old.theme, old.cities, old.via, old.avoid, old.twist, old.name, old.joke], 'the same puzzle'); + assert.ok(n.budget >= n.ref.three && n.ref.three > j.budget); + assert.deepEqual(G.check(g, d, 0), [], 'and it verifies'); + assert.deepEqual(G.refresh(g, d, 0), { fixed: [], bad: [] }, 'deterministic and settled: a second run changes nothing'); + // A week the game rejects (a city that is gone) gets a fresh puzzle under the same key. + const b = read(k1); b.cities[0] = 'xxx'; fs.writeFileSync(path.join(d, k1 + '.json'), JSON.stringify(b)); + assert.equal(G.refresh(g, d, 0).fixed.length, 1); + assert.equal(read(k1).key, k1); + assert.equal(read(k1).rev, 2); + assert.deepEqual(G.check(g, d, 0), []); + // Weeks that are over cannot be played again: their stars stay, so a broken budget there is left alone. + const e = read(k0); e.budget = 50000; fs.writeFileSync(path.join(d, k0 + '.json'), JSON.stringify(e)); + assert.deepEqual(G.refresh(g, d, 8.64e15), { fixed: [], bad: [] }); +}); + +test('stars belong to the revision of the week they were earned on', () => { + const { ev, errors } = load(); + const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`); + assert.equal(ev(`pzWkValid(${JSON.stringify(j)},'${k}').rev`), 1, 'a first edition is rev 1'); + assert.ok(ok({ ...j, rev: 2 })); + for (const rev of [1, 0, '2', 2.5, 1000]) assert.equal(ok({ ...j, rev }), false, `rev ${rev}`); + ev(`localStorage.setItem('sot-puzzles',JSON.stringify({wk:{'${k}':{st:3,sp:1},'2026-W01':{st:2,sp:5}}}))`); + assert.equal(ev(`pzWkRec(pzLoad(),pzWkValid(${JSON.stringify(j)},'${k}')).st`), 3, 'same week, same revision: the stars stand'); + const d2 = `pzWkValid(${JSON.stringify({ ...j, rev: 2 })},'${k}')`; + assert.equal(ev(`pzWkRec(pzLoad(),${d2})`), null, 'regenerated: that week starts again'); + ev(`pzBegin(${d2});pzRecord({stars:1,spend:9})`); + const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); + assert.deepEqual(p.wk[k], { st: 1, sp: 9, rv: 2 }, 'a lower score on the new revision replaces the old one'); + assert.deepEqual(p.wk['2026-W01'], { st: 2, sp: 5 }, 'other weeks keep theirs'); + assert.equal(ev(`pzWkRec(pzLoad(),${d2}).st`), 1); + assert.deepEqual(errors, []); +}); + 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()})}"); From cc89a266f3fe4bbbb30012c1d31bc480c99d8cd0 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 10:33:12 +0100 Subject: [PATCH 102/181] Lighter NOC traffic table: fewer elements and inline styles per network row The traffic tab lists every network with traffic, now 63 more, each with a Peer on all POPs button. Rows drop empty traffic-mix segments, the button's wrapper div and two inline styles (now classes), with the same look. On the big fixture the tab has 16% fewer elements; NOC dashboard tabs 390 -> 331 ms against the previous commit (p=0.014). --- src/game/94-dashboard/60-dashboard.js | 2 +- src/styles/40-modal.css | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index f2c1bf7..269f689 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -20,7 +20,7 @@ function renderDash(){checkLayer(); if(DT==='conn')h+=connSection(); 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)):'—'}
`; + ${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 pall'):''}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${t?['c','p','ix','t'].filter(k=>e[k]>0).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/styles/40-modal.css b/src/styles/40-modal.css index cfe106c..9853087 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -97,6 +97,8 @@ label.f+select.pick{width:100%} .tbl td.r,.tbl th.r{text-align:right} .mix{display:flex;height:10px;width:100px;border:1.5px solid var(--ink);border-radius:5px;overflow:hidden;background:var(--paper)} .mix i{display:block;height:100%} +/* The NOC's traffic table has a row per network: classes, not inline styles, keep its hundreds of rows cheap to parse. */ +.nmc{display:inline-flex;align-items:center;gap:6px}.dlost{color:var(--bad)}.b.pall{display:block;margin-top:5px} .tscroll{overflow-x:auto} #modal{position:fixed;inset:0;background:rgba(30,38,64,.45);display:grid;place-items:center;z-index:20;padding:16px max(16px,env(safe-area-inset-right,0px)) 16px max(16px,env(safe-area-inset-left,0px))} #modal .card{width:min(560px,100%);max-height:calc(100% - 20px);overflow:auto;padding:20px 22px} From e90f5f675ea24b58d5b4d6e2cfd5b789284e81b4 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 10:35:28 +0100 Subject: [PATCH 103/181] Puzzles: real traffic routed by the game, routers, link sizes and paths Every puzzle now carries demand (eyeballs pulling from a content origin, circuits with latency caps, best-effort flows) routed by compute(). Stars: delivered, within budget, N-1 under load. Routers, ports, metrics, standby and the redundancy check work in puzzles; the whole world is open. Weekly schema 2 carries the demand; scripts/lib/puzzle-solver.js sizes and searches builds. --- scripts/lib/puzzle-solver.js | 89 ++++++++++++++++ scripts/weekly-puzzle.js | 81 +++++++++----- site/i18n/de.js | 101 ++++++++++++------ site/i18n/es.js | 101 ++++++++++++------ site/i18n/fr.js | 101 ++++++++++++------ site/i18n/it.js | 101 ++++++++++++------ site/i18n/pt.js | 101 ++++++++++++------ src/game/10-catalog/40-ports.js | 5 +- src/game/60-features/90-puzzles-data.js | 55 +++++----- src/game/60-features/92-puzzles.js | 123 ++++++++++++++-------- src/game/60-features/93-puzzles-weekly.js | 27 +++-- src/game/90-actions/90-action-helpers.js | 2 +- src/game/90-actions/95-puzzles.js | 54 +++++++--- src/game/95-modals/95-puzzles.js | 115 +++++++++++++------- src/game/96-map/60-draw.js | 4 +- src/game/96-map/85-puzzle-cities.js | 14 ++- src/i18n/en.js | 101 ++++++++++++------ src/styles/70-puzzles.css | 6 ++ 18 files changed, 817 insertions(+), 364 deletions(-) create mode 100644 scripts/lib/puzzle-solver.js diff --git a/scripts/lib/puzzle-solver.js b/scripts/lib/puzzle-solver.js new file mode 100644 index 0000000..a225744 --- /dev/null +++ b/scripts/lib/puzzle-solver.js @@ -0,0 +1,89 @@ +// Puzzle tools (the weekly generator, the puzzle tests): build a puzzle network straight into a headless game, judge +// it with the game's own star code, and search for the cheapest build that earns three stars. +// +// A build is a list of links [a, b, via, tier, same]: via is 'land' or a cable id, tier an index into LT, and `same` +// (k > 0) puts an overland link in the k-th trench already on that pair (otherwise a further one takes a diverse +// route, +40%). Routers +// are not part of the search: each POP gets the cheapest models that carry its busiest moment (across every single +// cut), its ports and its biggest wave, which is what any sensible player would buy for that build. + +// Runs inside the page. +function page() { + window.pzsReset = () => { S.pops = {}; S.links = []; S.pairMet = {}; for (const b of S.biz) b.route = 'normal'; UI.pzEv = null; }; + window.pzsLink = (a, b, via, tier, same) => { + const r = pzRoutes(a, b).find((x) => x.via === via); if (!r) throw new Error(`no route ${via} for ${a}-${b}`); + for (const c of [a, b]) if (!S.pops[c]) S.pops[c] = pzNewPop(c); + // `same` k > 0: in the k-th overland trench on this pair; 0: a trench of its own (diverse, unless it is the first). + const tr = !r.sub ? [...new Set(S.links.filter((l) => edgeKey(l) === edgeKey({ a, b }) && !l.cable).map((l) => l.trench))] : [], sm = same && tr[same - 1], div = !!(tr.length && sm !== tr[0]), id = uid(); + S.links.push({ id, a, b, kind: 'wave', border: false, premium: false, tier, km: r.km, sub: r.sub, cable: r.cab, mo: pzMo(r, tier, div), mult: r.f * (div ? DIVERSE : 1), trench: r.cab ? 'cab:' + r.cab : sm || id, cut: 0, day: 0 }); + }; + // The cheapest routers for POP c: enough ports, a model that lights its biggest wave, and capacity for its peak. + window.pzsRouters = (c, peak) => { + const used = portsUsed(c), lt = Math.max(0, ...S.links.filter((l) => l.a === c || l.b === c).map((l) => l.tier)); let best = null; + for (const g of PZ_RG) for (let rt = 1; rt <= 6; rt++) { const M = RG[g]; if (M.maxLT < lt || M.ports * rt < used - 1e-9 || M.cap * rt < peak - 1e-6) continue; + const cost = pzRtCost(g, rt); if (!best || cost < best.cost) best = { g, rt, cost }; } + return best; + }; + // Judge the build on routers big enough for anything, then price the routers it really needs. With those, routing + // is the same (no router is ever full), so the stars are too. + window.pzsJudge = () => { + const BIG = RG.findIndex((r) => r.n === 'Arrrhipster 7800R'), keep = {}; + for (const c in S.pops) { keep[c] = [S.pops[c].rgen, S.pops[c].routers]; S.pops[c].rgen = BIG; S.pops[c].routers = 1; } + UI.pzEv = null; const b0 = S.pz.budget; S.pz.budget = 0; const e = pzEval(); S.pz.budget = b0; UI.pzEv = null; + const rt = {}; let spend = 0, bad = false; + for (const c in S.pops) { const r = pzsRouters(c, e.peak[c] || 0); if (!r) { bad = true; continue; } rt[c] = [r.g, r.rt]; spend += r.cost + pzPopCost(c); S.pops[c].rgen = keep[c][0]; S.pops[c].routers = keep[c][1]; } + for (const l of S.links) spend += l.mo * PZ_YEAR; + return { one: e.goal && !bad, three: e.goal && e.n1 && !bad, spend, rt }; + }; + window.pzsApplyRt = (rt) => { for (const c in rt) { S.pops[c].rgen = rt[c][0]; S.pops[c].routers = rt[c][1]; } UI.pzEv = null; }; +} +const install = (ev) => { if (ev("typeof pzsJudge!=='function'")) ev(`(${page.toString()})()`); }; + +const key = (L) => JSON.stringify(L); +// Steps that are not links set what a player sets in the panels: ['@route', flow, 'fast'] a circuit's path, +// ['@met', a, b, 'avoid'] a pair's metric. The search keeps them as they are. +const step = ([a, b, v, t, s]) => a === '@route' ? `S.biz.find(x=>x.id===pzFlowId(${b})).route='${v}';` : a === '@met' ? `(S.pairMet=S.pairMet||{})[edgeKey({a:'${b}',b:'${v}'})]='${t}';` + : `pzsLink('${a}','${b}','${v}',${t},${s || 0});`; +function judge(ev, L) { + return JSON.parse(ev(`pzsReset();${L.map(step).join('')}JSON.stringify(pzsJudge())`)); +} +// Every link option between the given cities: each route, at tiers up to maxTier. +function options(ev, cities, maxTier, noSub) { + const out = []; + for (let i = 0; i < cities.length; i++) for (let j = i + 1; j < cities.length; j++) { + const [a, b] = [cities[i], cities[j]]; + const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').map(r=>({via:r.via,sub:r.sub,ok:[0,1,2,3].map(t=>!subWaveWhy(t,r.km,r.sub))})))`)); + for (const r of rs) { if (noSub && r.sub) continue; for (let t = 0; t <= maxTier; t++) if (r.ok[t]) { out.push([a, b, r.via, t, 0]); if (!r.sub) { out.push([a, b, r.via, t, 1]); out.push([a, b, r.via, t, 2]); } } } + } + return out; +} +// Local search from a 3-star build: drop a link, shrink one, move one to another route, put it in the first trench +// or out of it, or swap one link for another option, while it is cheaper and still three stars. +function improve(ev, start, opts = {}) { + const memo = new Map(), J = (L) => { const k = key(L); if (!memo.has(k)) memo.set(k, judge(ev, L)); return memo.get(k); }; + let cur = start.map((x) => x.slice()), cj = J(cur); + if (!cj.three) throw new Error('the starting build does not earn three stars'); + const routes = {}, via = (a, b) => { const k = a < b ? a + '|' + b : b + '|' + a; if (!routes[k]) routes[k] = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').map(r=>r.via))`)); return routes[k]; }; + const opt = opts.options || []; + for (let round = 0; round < 60; round++) { + const nb = []; + for (let i = 0; i < cur.length; i++) { + const w = (x) => { const L = cur.slice(); L[i] = x; return L; }, [a, b, v, t, s] = cur[i]; + if (a[0] === '@') continue; + nb.push(cur.filter((_, k) => k !== i)); + if (t > 0) nb.push(w([a, b, v, t - 1, s])); + for (const v2 of via(a, b)) if (v2 !== v) nb.push(w([a, b, v2, t, 0])); + if (v === 'land') for (const s2 of [0, 1, 2]) if (s2 !== (s || 0)) nb.push(w([a, b, v, t, s2])); + } + if (opts.swap) for (const o of opt) for (let i = 0; i < cur.length; i++) { if (cur[i][0][0] === '@') continue; const L = cur.slice(); L[i] = o; nb.push(L); } + let best = null; + for (const L of nb) { const j = J(L); if (j.three && j.spend < cj.spend - 1 && (!best || j.spend < best.j.spend)) best = { L, j }; } + if (!best && opts.add) for (const o of opt) for (let i = 0; i < cur.length; i++) for (let k = i + 1; k < cur.length; k++) { + if (cur[i][0][0] === '@' || cur[k][0][0] === '@') continue; + const L = [...cur.filter((_, x) => x !== i && x !== k), o], j = J(L); if (j.three && j.spend < cj.spend - 1 && (!best || j.spend < best.j.spend)) best = { L, j }; } + if (!best) break; + cur = best.L; cj = best.j; + } + return { links: cur, ...cj }; +} +module.exports = { install, judge, options, improve }; diff --git a/scripts/weekly-puzzle.js b/scripts/weekly-puzzle.js index 93b6edd..17c2364 100644 --- a/scripts/weekly-puzzle.js +++ b/scripts/weekly-puzzle.js @@ -12,15 +12,18 @@ // --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. +// cities) and the traffic they carry (content in the first city, eyeballs in the others; a latency sprint adds a +// circuit with a latency cap). Search for the cheapest topology that connects them and the cheapest one that survives +// any single cut (a whole cable or a trench), then size each with the game's own routing (scripts/lib/puzzle-solver.js): +// links and routers big enough for every flow, after any single cut too, then as small as they can be. The budget is +// that N-1 build plus a little. Both reference builds are judged by the game's own star code 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 SV = require('./lib/puzzle-solver'); +const SCHEMA = 2, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6; const THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint']; // ---------- the game, headless ---------- @@ -31,6 +34,7 @@ function game(file) { console.warn(`warning: ${file} has no published weekly puzzles yet; using src/ instead`); g = load(); } + SV.install(g.ev); // 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; @@ -219,6 +223,12 @@ function draft(W, theme, r, banned) { } 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; + // The traffic: content in the first city, eyeballs in the others (less across an ocean, where waves are dear), and + // for a sprint a circuit between its two cities under the latency cap. + const far = theme === 'ocean' || theme === 'islands', sizes = far ? [5, 8, 10, 15] : [10, 20, 30, 40, 60]; + P.src = [P.cities[0]]; + P.dem = P.cities.slice(1).map((c) => ({ t: 'eye', a: c, g: pick(r, sizes) })); + if (P.lat) P.dem.unshift({ t: 'l2', a: P.lat[0], b: P.lat[1], g: 10, ms: P.lat[2] }); return P; } @@ -240,29 +250,45 @@ function history(dir, key) { } 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})`); +// A topology's links, sized for the traffic: every wave at the smallest size that carries it all (after any single cut +// too, for the N-1 build), as the game routes it, with the cheapest routers that fit. +const TIER_G = [10, 100, 400]; +function size(ev, def, links, n1) { + ev(`pzBegin(${JSON.stringify(def)})`); + const tot = def.dem.reduce((a, f) => a + f.g, 0), t0 = Math.max(0, TIER_G.findIndex((g) => g >= tot)); + for (let t = t0; t < TIER_G.length; t++) { + const L = [...links.map((l) => [l.a, l.b, l.via, t, 0]), ...def.dem.map((f, i) => f.ms ? ['@route', i, 'fast'] : null).filter(Boolean)], j = SV.judge(ev, L); + if (n1 ? j.three : j.one) { const r = n1 ? SV.improve(ev, L) : { links: L, ...j }; return r; } } - ev('closeModal()'); + return null; +} +// Plays a sized build (links and routers) in the game and returns the stars it earns. +function play(ev, def, b) { + ev(`localStorage.removeItem('sot-puzzles');pzBegin(${JSON.stringify(def)})`); + SV.judge(ev, b.links); ev(`pzsApplyRt(${JSON.stringify(b.rt)})`); 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 } : {}), +const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, src: P.src, dem: P.dem, via: P.via, avoid: P.avoid, budget, + twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}), name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } }); +// The topology search reads a sprint's latency cap from its circuit. +const shape = (def) => { const l2 = def.dem.find((f) => f.t === 'l2' && f.ms); return { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: l2 ? [l2.a, l2.b, l2.ms] : null }; }; +// Topology, then sizes: the 1-star and 3-star references with their prices. +function sized(g, W, P, def) { + const sol = solve(W, P); if (!sol.one || !sol.three) return null; + const one = size(g.ev, def, sol.one.links, false), three = size(g.ev, def, sol.three.links, true); + if (!one || !three) return null; + return { one: { cost: Math.round(one.spend), b: one }, three: { cost: Math.round(three.spend), b: three } }; +} // The game's own validator decides what a puzzle is; then both references must earn their stars. -function verify(g, W, j, key) { +function verify(g, W, j, key, known) { 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' }; + const P = shape(def), sol = known || sized(g, W, P, def); + if (!sol) return { ok: false, why: 'no build delivers the traffic 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` }; + const s1 = play(ev, def, sol.one.b), s3 = play(ev, def, sol.three.b); + if (s1.stars < 1) 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 }; } @@ -281,17 +307,18 @@ function generate(g, key, dir) { 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; + // Prefer puzzles where surviving a cut takes real thought: the obvious "double everything" costs a lot more. + const smart = sol.naive ? sol.naive.cost / sol.three.cost : 1.05, slack = sol.three.cost / 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.push({ P, 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); + // Sized with the traffic: the budget sits just above the cheapest N-1 build found. + const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(fileOf(key, c.P, 1e6, c.w, { one: { cost: 0 }, three: { cost: 0 } }))},'${key}'))`)); + const sol = def && sized(g, W, c.P, def); + if (!sol) { console.warn(`${key}: rejected a ${theme} puzzle: no build carries its traffic`); continue; } + const j = fileOf(key, c.P, Math.max(50000, ceil10k(sol.three.cost * 1.05)), c.w, sol), v = verify(g, W, j, key, sol); if (v.ok) return j; console.warn(`${key}: rejected a ${theme} puzzle: ${v.why}`); } diff --git a/site/i18n/de.js b/site/i18n/de.js index 711b9e0..975168e 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2908,56 +2908,79 @@ "progress.your_score_peak_traffic":"Dein Ergebnis: Spitzen-Traffic", "progress.your_traffic_to_and_from_asia":"Dein Traffic von und nach Asien", "puzzles.a_backhoe_walks_into_your_network":"Kommt ein Bagger in dein Netz. Nichts passiert.", +"puzzles.a_bigger_boat":"Wir brauchen ein größeres Boot", +"puzzles.a_cut_on_where_drops_g":"Ein Schnitt bei {where} kostet {g}", +"puzzles.a_different_route":"Eine andere Route", +"puzzles.a_diverse_route":"Eine diverse Route (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"Ein POP kostet {setup} Einrichtung, dann {mo}/Monat. Puzzles rechnen die Einrichtung und ein Jahr Miete.", -"puzzles.a_tiny_island_where_half_the":"Eine winzige Insel, auf der die halbe Pazifik-Verkabelung Kaffeepause macht.", -"puzzles.a_to_b_under_ms":"{a} → {b} unter {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} unter {ms} ms (jetzt {now} ms)", -"puzzles.aloha_latency":"Aloha Latenz", +"puzzles.add_a_router_cost":"Router dazu {cost}/Jahr", +"puzzles.add_another_link_here":"Noch einen Link auf diesem Paar", +"puzzles.all_of_europe_s_cat_videos":"Alle Katzenvideos Europas wohnen in London, und jedes einzelne geht durch deinen Router.", +"puzzles.already_here_list":"Schon auf diesem Paar: {list}", +"puzzles.another_wave_on_this_cable":"Noch eine Wave auf diesem Kabel", "puzzles.avoid_list":"ohne {list}", "puzzles.back_to_my_network":"Zurück zu meinem Netz", "puzzles.back_to_the_title":"Zurück zum Startbildschirm", -"puzzles.beat_the_clock_light_in_glass":"Licht in Glasfaser schafft 200 km pro Millisekunde. Wähl deine Kabel, als ob es darauf ankäme.", +"puzzles.baltic_shortcut":"Baltische Abkürzung", "puzzles.belt_and_braces":"Gürtel und Hosenträger", +"puzzles.best_effort":"Best Effort", "puzzles.best_x":"Bestwert {x}", +"puzzles.biggest_wave":"Größte Wave", "puzzles.budget":"Budget", "puzzles.budget_x":"Budget {x}", -"puzzles.connect_list":"Verbinde {list}.", -"puzzles.connected":"Verbunden", +"puzzles.capacity_first_every_link_has_a":"Erst die Kapazität: Jeder Link hat eine Größe, und der Traffic muss reinpassen. Großzügige Budgets, die ersten zwei gehen aufs Haus.", +"puzzles.carry_list":"Zu transportieren: {list}.", +"puzzles.carrying":"Transportiert", +"puzzles.carrying_on_this_pair":"Transportiert (alle {n} Links dieses Paars)", +"puzzles.content_lives_in_list":"Die Inhalte liegen in {list}: Privatkunden ziehen vom nächsten.", "puzzles.copied_paste_it_anywhere":"Kopiert! Füg es irgendwo ein:
{t}", "puzzles.de_kicks_sales_has_your_number":"Der DE-KICKS-Vertrieb hat deine Nummer. Verbinde Deutschland ohne Frankfurt.", +"puzzles.delivered":"Geliefert", "puzzles.diverse_route_40_survives_a_backhoe":"Getrennte Trasse (+40 %, übersteht einen Bagger)", "puzzles.down_under_up_and_running":"Down Under, up and running", "puzzles.drag_from_a_pink_pop_to":"Zieh von einem pinken POP zu einer anderen Stadt, um eine Wave zu mieten", "puzzles.drag_from_this_pop_onto_another":"Zieh von diesem POP auf eine andere Puzzle-Stadt oder wähl eine hier.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro-Trip", +"puzzles.every_bit_arrives":"jedes Bit kommt an", "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.everything_at_once_across_oceans":"Alles auf einmal, über Ozeane. Knappe Budgets.", +"puzzles.fat_pipes":"Dicke Rohre", +"puzzles.five_small_cities_one_small_router":"Fünf Städte, je ein paar Gigabit, und ein Router mit acht Ports. Erst zählen, dann graben.", +"puzzles.fjord_focus":"Fjord im Fokus", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Für Architekten, die die Baggersaison verschlafen.", -"puzzles.four_capitals_one_very_long_winter":"Vier Hauptstädte, ein sehr langer Winter, null Ausreden für Ausfälle.", +"puzzles.flow_circuit_a_b":"Leitung {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Privatkunden in {city}", "puzzles.four_cities_four_cables_one_ring":"Vier Städte, ein Ring. Tolkien wäre begeistert, dein NOC sowieso.", "puzzles.four_cities_one_continent_and_a":"Vier Städte, ein Kontinent und dazwischen sehr viel Mais.", +"puzzles.framed_n_stars_from_the_old":"Gerahmt an der Wand: {n} ⭐ aus den alten Puzzles", "puzzles.frankfurt_to_singapore_the_short_way":"Frankfurt nach Singapur auf dem kurzen Weg. Der lange führt über Land, und das merkt man.", "puzzles.free":"Gratis", -"puzzles.goal":"Ziel", "puzzles.goal_city":"Zielstadt", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Hallo, Welt", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: der malerischste Regenerator-Standort der Welt.", +"puzzles.hub_cap":"Radkappe", "puzzles.includes_a_new_pop_in_city":"Mit neuem POP in {city} ({price} für ein Jahr).", +"puzzles.installed":"verbaut", "puzzles.it_works_finance_and_the_backhoe":"Läuft! Die Buchhaltung und der Bagger hätten da noch Fragen.", "puzzles.keep_building":"Weiterbauen", "puzzles.kiwi_fruit_salad":"Kiwi-Obstsalat", +"puzzles.latency":"Latenz", +"puzzles.latency_caps":"Latenzgrenzen", "puzzles.lease_a_wave_to":"Wave mieten nach", "puzzles.loading_this_week_s_puzzle":"Lade das Puzzle dieser Woche…", +"puzzles.london_wants_half_a_terabit_your":"London will ein halbes Terabit, und deine Router sind von eBuy.", +"puzzles.model_facts":"{cap} · {ports} Ports · Waves bis {wave}", "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_1_deliver_everything_first":"N-1: erst alles liefern", +"puzzles.n_circuits":{"one":"{n} Leitung","other":"{n} Leitungen"}, +"puzzles.n_g_of_eyeballs":"{n} Privatkunden", +"puzzles.n_links_on_this_pair":"{n} Links auf diesem Paar: {what}", "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.needs_what":"braucht {what}", "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}⭐", @@ -2967,26 +2990,31 @@ "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.", -"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_clock_no_bills_real_traffic":"Keine Uhr, keine Rechnungen, nichts geht kaputt. Echter Traffic, geroutet wie im echten Spiel: Liefere jeden Flow, bleib im Budget, und halt alles am Laufen, wenn irgendein Graben oder Kabel gekappt wird.", +"puzzles.no_free_ports_in_list":"Keine freien Router-Ports in {list}: erst einen Router oder ein größeres Modell dazu.", "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.", +"puzzles.no_traffic_starts_or_ends_here":"Hier fängt kein Traffic an und keiner hört auf. Bauen darfst du trotzdem, wenn es dich weiterbringt.", +"puzzles.not_a_city_you_can_build_in":"In dieser Stadt kannst du nicht bauen.", +"puzzles.not_in_the_plan":"Nicht im Plan", "puzzles.not_this_one_find_a_way_around":"Die nicht. Such dir einen Weg drumherum.", "puzzles.not_through_frankfurt":"Nicht über Frankfurt", "puzzles.off_limits":"Tabu", "puzzles.on_the_house":"Aufs Haus", "puzzles.one_backhoe_away_from_a_very":"Ein Bagger trennt dich von einer sehr langen Nacht. Ein zweiter Weg gibt ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Ein Schnitt trennt es", -"puzzles.one_cut_splits_it_where":"Ein Schnitt trennt es: {where}", "puzzles.one_ring_through_every_pop":"Ein Ring durch jeden POP", "puzzles.one_very_big_island_and_a":"Eine sehr große Insel und sehr viel sehr leere Glasfaser.", "puzzles.open_a_pop_cost":"POP eröffnen · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping-Pong nach Tokio", +"puzzles.or_drag_to_any_city_on_the_map":"Oder zieh zu irgendeiner Stadt auf der Karte: Die ganze Welt ist offen.", +"puzzles.paris_wants_150g_one_100g_wave":"Paris will 150G. Eine 100G-Wave ist ein Gartenschlauch.", +"puzzles.port_authority":"Hafenbehörde", +"puzzles.ports":"Ports", "puzzles.price_per_year":"{price}/Jahr", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle gelöst", "puzzles.puzzles":"Puzzles", +"puzzles.puzzles_got_traffic_note":"Die Puzzles haben jetzt Traffic! Jedes Puzzle transportiert echte Flows, deshalb fangen die Sterne neu an. Deine alten {n} ⭐ hängen gerahmt an der Wand.", +"puzzles.remove_a_router":"Einen Router weg", "puzzles.remove_this_link":"Diesen Link entfernen", "puzzles.remove_this_pop":"Diesen POP entfernen", "puzzles.reset":"Zurücksetzen", @@ -2994,41 +3022,48 @@ "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.router_load":"Router-Last", +"puzzles.router_model":"Router-Modell", +"puzzles.router_rodeo":"Router-Rodeo", +"puzzles.routers_have_ports_and_a_limit":"Router haben Ports und ein Limit. Ist einer voll, bleibt der Traffic vor der Tür.", "puzzles.rule_not_via_list":"Regel: nicht über {list}", "puzzles.samba_sprint":"Samba-Sprint", +"puzzles.same_cable_same_anchor":"Dasselbe Kabel wie ein Link, den du schon hast: Ein Anker erwischt beide.", "puzzles.same_puzzle_for_everyone_this_week":"Diese Woche für alle dasselbe Puzzle", +"puzzles.same_trench_cheaper":"Gleicher Graben (günstiger)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Gleicher Graben (billiger, ein Bagger kappt beide)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo nach Miami, bevor der Caipirinha warm wird.", "puzzles.sea_to_shining_sea":"Von Küste zu Küste", -"puzzles.seattle_to_singapore_with_a_stop":"Seattle nach Singapur, mit Zwischenstopp für Sushi und Dim Sum.", "puzzles.share_line":"Series of Tubes Puzzle {what} {stars} {spend} · seriesoftub.es", "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.small_networks_real_traffic":"Kleine Netze, echter Traffic", "puzzles.spent_x":"Ausgegeben {x}", "puzzles.spent_x_of_y":"Ausgegeben {x} / {y}", "puzzles.stepping_stone_optional":"Trittstein (optional)", "puzzles.suez_you_later":"Suez bald", -"puzzles.survives_any_single_cut":"Übersteht jeden einzelnen Schnitt", +"puzzles.survive_any_single_cut_with_the":"Überleb jeden einzelnen Schnitt, und der Traffic fließt weiter. Verbunden sein reicht nicht.", +"puzzles.survives_any_single_cut_under_load":"Übersteht jeden einzelnen Schnitt, unter Last", "puzzles.tap_a_goal_city_to_open":"Tipp auf eine leuchtende Stadt für deinen ersten POP", -"puzzles.that_city_is_not_part_of":"Diese Stadt gehört nicht zu diesem Puzzle.", -"puzzles.the_pacific_is_big_light_is":"Der Pazifik ist groß. Licht ist schnell. Dein Budget ist beides nicht.", -"puzzles.the_pacific_rim_where_every_hop":"Der Pazifikrand, wo jeder Hop ein Ozean ist.", +"puzzles.the_content_origin_lives_here":"Hier liegen die Inhalte. Privatkunden anderswo ziehen von hier.", +"puzzles.the_oil_rigs_want_their_numbers":"Die Bohrinseln wollen ihre Zahlen schnell. Der kürzeste Weg nach Stavanger ist nicht der schnellste.", +"puzzles.the_road_to_tallinn_is_short":"Der Weg nach Tallinn ist kurz. Das Licht über Helsinki ist kürzer.", "puzzles.the_shark_tank":"Das Haifischbecken", "puzzles.the_sharks_have_been_biting_again":"Die Haie haben wieder zugebissen. Bleib auf dem Trockenen.", "puzzles.the_sharks_say_no":"Die Haie sagen nein.", +"puzzles.this_link":"Dieser Link", "puzzles.three_cities_two_currencies_one_very":"Drei Städte, zwei Währungen, ein sehr kurzer Tunnel unter dem Meer.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Trader haben Millionen bezahlt, um hier Millisekunden zu sparen. Du schaffst es billiger.", +"puzzles.traffic_cops":"Verkehrspolizei", +"puzzles.trench_n":"Graben {n}", "puzzles.two_cables_across_the_atlantic_because":"Zwei Kabel über den Atlantik, denn eins ist eine Hoffnung, kein Plan.", -"puzzles.under_n_ms":"unter {n} ms", +"puzzles.u_of_m_used":"{u} von {m} belegt", "puzzles.undo":"Rückgängig", "puzzles.unlocks_at_n_stars":"Ab {n}⭐", "puzzles.weekly_puzzle":"Wochenpuzzle", "puzzles.weekly_puzzle_key":"Wochenpuzzle {key}", "puzzles.with_the_pop_price":"mit POP: {price}", -"puzzles.your_first_tubes_roomy_budgets":"Deine ersten Röhren. Großzügige Budgets, und die ersten zwei gehen aufs Haus.", +"puzzles.your_pop":"Dein POP", +"puzzles.your_routers_pick_the_path":"Deine Router wählen den Weg. Sag ihnen welchen: Metriken, niedrigste Latenz, Best Effort.", "puzzles.your_stars":"Deine Sterne", "puzzles_weekly.detour":"Umleitung", "puzzles_weekly.island_hopping":"Inselhüpfen", diff --git a/site/i18n/es.js b/site/i18n/es.js index 21a7058..f7032d9 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2906,56 +2906,79 @@ "progress.your_score_peak_traffic":"Tu puntuación: tráfico pico", "progress.your_traffic_to_and_from_asia":"Tu tráfico desde y hacia Asia", "puzzles.a_backhoe_walks_into_your_network":"Una retroexcavadora entra en tu red. No pasa nada.", +"puzzles.a_bigger_boat":"Necesitaremos un barco más grande", +"puzzles.a_cut_on_where_drops_g":"Un corte en {where} tira {g}", +"puzzles.a_different_route":"Otra ruta", +"puzzles.a_diverse_route":"Una ruta diversa (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"Un POP cuesta {setup} de instalación y luego {mo}/mes. Los puzles cuentan la instalación y un año de alquiler.", -"puzzles.a_tiny_island_where_half_the":"Una isla diminuta donde medio Pacífico de cables para a tomar café.", -"puzzles.a_to_b_under_ms":"{a} → {b} en menos de {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} en menos de {ms} ms (ahora {now} ms)", -"puzzles.aloha_latency":"Aloha, latencia", +"puzzles.add_a_router_cost":"Añadir un router {cost}/año", +"puzzles.add_another_link_here":"Añadir otro enlace en este par", +"puzzles.all_of_europe_s_cat_videos":"Todos los vídeos de gatos de Europa viven en Londres, y todos pasan por tu router.", +"puzzles.already_here_list":"Ya en este par: {list}", +"puzzles.another_wave_on_this_cable":"Otra wave en este cable", "puzzles.avoid_list":"sin {list}", "puzzles.back_to_my_network":"Volver a mi red", "puzzles.back_to_the_title":"Volver a la pantalla de inicio", -"puzzles.beat_the_clock_light_in_glass":"La luz en la fibra hace 200 km por milisegundo. Elige tus cables como si importara.", +"puzzles.baltic_shortcut":"Atajo báltico", "puzzles.belt_and_braces":"Cinturón y tirantes", +"puzzles.best_effort":"best effort", "puzzles.best_x":"mejor {x}", +"puzzles.biggest_wave":"Wave más grande", "puzzles.budget":"Presupuesto", "puzzles.budget_x":"presupuesto {x}", -"puzzles.connect_list":"Conecta {list}.", -"puzzles.connected":"Conectado", +"puzzles.capacity_first_every_link_has_a":"Primero la capacidad: cada enlace tiene un tamaño y el tráfico tiene que caber. Presupuestos holgados, y los dos primeros invita la casa.", +"puzzles.carry_list":"A transportar: {list}.", +"puzzles.carrying":"Transporta", +"puzzles.carrying_on_this_pair":"Transporta (los {n} enlaces de este par)", +"puzzles.content_lives_in_list":"El contenido vive en {list}: los usuarios tiran del más cercano.", "puzzles.copied_paste_it_anywhere":"¡Copiado! Pégalo donde quieras:
{t}", "puzzles.de_kicks_sales_has_your_number":"Ventas de DE-KICKS tiene tu número. Conecta Alemania sin pasar por Fráncfort.", +"puzzles.delivered":"Entregado", "puzzles.diverse_route_40_survives_a_backhoe":"Ruta diversa (+40 %, sobrevive a una retroexcavadora)", "puzzles.down_under_up_and_running":"Down Under, en marcha", "puzzles.drag_from_a_pink_pop_to":"Arrastra desde un POP rosa a otra ciudad para alquilar una onda", "puzzles.drag_from_this_pop_onto_another":"Arrastra desde este POP a otra ciudad del puzle, o elige una aquí.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"cada bit llega", "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.everything_at_once_across_oceans":"Todo a la vez, cruzando océanos. Presupuestos ajustados.", +"puzzles.fat_pipes":"Tubos gordos", +"puzzles.five_small_cities_one_small_router":"Cinco ciudades, pocos gigas cada una, y un router con ocho puertos. Cuenta antes de cavar.", +"puzzles.fjord_focus":"Rumbo al fiordo", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Para arquitectos que duermen tranquilos en temporada de retroexcavadoras.", -"puzzles.four_capitals_one_very_long_winter":"Cuatro capitales, un invierno larguísimo y cero excusas para caerse.", +"puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Usuarios en {city}", "puzzles.four_cities_four_cables_one_ring":"Cuatro ciudades, un anillo. Tolkien lo aprobaría; tu NOC, seguro.", "puzzles.four_cities_one_continent_and_a":"Cuatro ciudades, un continente y mucho maíz entre medias.", +"puzzles.framed_n_stars_from_the_old":"Enmarcadas en la pared: {n} ⭐ de los puzles antiguos", "puzzles.frankfurt_to_singapore_the_short_way":"De Fráncfort a Singapur por el camino corto. El largo va por tierra, y se nota.", "puzzles.free":"Gratis", -"puzzles.goal":"Objetivo", "puzzles.goal_city":"Ciudad objetivo", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Hola, mundo", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: el sitio de regeneración más bonito del mundo.", +"puzzles.hub_cap":"Tapacubos", "puzzles.includes_a_new_pop_in_city":"Incluye un POP nuevo en {city} ({price} por un año).", +"puzzles.installed":"instalado", "puzzles.it_works_finance_and_the_backhoe":"¡Funciona! Finanzas y la retroexcavadora quieren hablar contigo.", "puzzles.keep_building":"Seguir construyendo", "puzzles.kiwi_fruit_salad":"Macedonia de kiwi", +"puzzles.latency":"Latencia", +"puzzles.latency_caps":"límites de latencia", "puzzles.lease_a_wave_to":"Alquilar una onda hasta", "puzzles.loading_this_week_s_puzzle":"Cargando el puzle de esta semana…", +"puzzles.london_wants_half_a_terabit_your":"Londres quiere medio terabit, y tus routers salieron de eBuy.", +"puzzles.model_facts":"{cap} · {ports} puertos · waves hasta {wave}", "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_1_deliver_everything_first":"N-1: primero entrégalo todo", +"puzzles.n_circuits":{"one":"{n} circuito","other":"{n} circuitos"}, +"puzzles.n_g_of_eyeballs":"{n} de usuarios", +"puzzles.n_links_on_this_pair":"{n} enlaces en este par: {what}", "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.needs_what":"necesita {what}", "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}⭐", @@ -2965,26 +2988,31 @@ "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.", -"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_clock_no_bills_real_traffic":"Sin reloj, sin facturas, nada se rompe. Tráfico de verdad, enrutado como en el juego de verdad: entrega cada flujo, no te pases del presupuesto y mantenlo todo en marcha cuando se corte cualquier zanja o cable.", +"puzzles.no_free_ports_in_list":"No quedan puertos libres en el router de {list}: añade un router o un modelo más grande antes.", "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.", +"puzzles.no_traffic_starts_or_ends_here":"Aquí no empieza ni termina tráfico. Puedes construir igual, si te lleva a alguna parte.", +"puzzles.not_a_city_you_can_build_in":"No puedes construir en esa ciudad.", +"puzzles.not_in_the_plan":"Fuera del plan", "puzzles.not_this_one_find_a_way_around":"Esta no. Busca otro camino.", "puzzles.not_through_frankfurt":"Sin pasar por Fráncfort", "puzzles.off_limits":"Prohibida", "puzzles.on_the_house":"Invita la casa", "puzzles.one_backhoe_away_from_a_very":"A una retroexcavadora de una noche muy larga. Añade un segundo camino para ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Un corte la parte en dos", -"puzzles.one_cut_splits_it_where":"Un corte la parte en dos: {where}", "puzzles.one_ring_through_every_pop":"Un anillo por todos los POP", "puzzles.one_very_big_island_and_a":"Una isla enorme y muchísima fibra vacía.", "puzzles.open_a_pop_cost":"Abrir un POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping-pong a Tokio", +"puzzles.or_drag_to_any_city_on_the_map":"O arrastra a cualquier ciudad del mapa: el mundo entero está abierto.", +"puzzles.paris_wants_150g_one_100g_wave":"París quiere 150G. Una wave de 100G es una manguera de jardín.", +"puzzles.port_authority":"Autoridad portuaria", +"puzzles.ports":"Puertos", "puzzles.price_per_year":"{price}/año", "puzzles.puzzle":"Puzle", "puzzles.puzzle_solved":"Puzle resuelto", "puzzles.puzzles":"Puzles", +"puzzles.puzzles_got_traffic_note":"¡Los puzles tienen tráfico! Cada puzle transporta ahora flujos de verdad, así que las estrellas empiezan de nuevo. Tus {n} ⭐ antiguas están enmarcadas en la pared.", +"puzzles.remove_a_router":"Quitar un router", "puzzles.remove_this_link":"Quitar este enlace", "puzzles.remove_this_pop":"Quitar este POP", "puzzles.reset":"Reiniciar", @@ -2992,41 +3020,48 @@ "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.router_load":"Carga del router", +"puzzles.router_model":"Modelo de router", +"puzzles.router_rodeo":"Rodeo de routers", +"puzzles.routers_have_ports_and_a_limit":"Los routers tienen puertos y un límite. Llena uno y el tráfico se queda en la puerta.", "puzzles.rule_not_via_list":"Regla: sin pasar por {list}", "puzzles.samba_sprint":"Sprint de samba", +"puzzles.same_cable_same_anchor":"Mismo cable que un enlace que ya tienes: un ancla se lleva los dos.", "puzzles.same_puzzle_for_everyone_this_week":"El mismo puzle para todos esta semana", +"puzzles.same_trench_cheaper":"Misma zanja (más barato)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Misma zanja (más barata, una retroexcavadora corta las dos)", "puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes de que se caliente la caipiriña.", "puzzles.sea_to_shining_sea":"De costa a costa", -"puzzles.seattle_to_singapore_with_a_stop":"De Seattle a Singapur, con parada para sushi y dim sum.", "puzzles.share_line":"Series of Tubes puzle {what} {stars} {spend} · seriesoftub.es", "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.small_networks_real_traffic":"Redes pequeñas, tráfico de verdad", "puzzles.spent_x":"Gastado {x}", "puzzles.spent_x_of_y":"Gastado {x} / {y}", "puzzles.stepping_stone_optional":"Escala (opcional)", "puzzles.suez_you_later":"Suez luego", -"puzzles.survives_any_single_cut":"Sobrevive a cualquier corte", +"puzzles.survive_any_single_cut_with_the":"Sobrevive a cualquier corte, con el tráfico todavía fluyendo. Estar conectado no basta.", +"puzzles.survives_any_single_cut_under_load":"Aguanta cualquier corte, con carga", "puzzles.tap_a_goal_city_to_open":"Toca una ciudad brillante para abrir tu primer POP", -"puzzles.that_city_is_not_part_of":"Esa ciudad no forma parte de este puzle.", -"puzzles.the_pacific_is_big_light_is":"El Pacífico es grande. La luz es rápida. Tu presupuesto no es ninguna de las dos cosas.", -"puzzles.the_pacific_rim_where_every_hop":"El borde del Pacífico, donde cada salto es un océano.", +"puzzles.the_content_origin_lives_here":"Aquí vive el contenido. Los usuarios de otros sitios tiran de aquí.", +"puzzles.the_oil_rigs_want_their_numbers":"Las plataformas quieren sus números rápido. El camino más corto a Stavanger no es el más rápido.", +"puzzles.the_road_to_tallinn_is_short":"El camino a Tallin es corto. La luz por Helsinki, más.", "puzzles.the_shark_tank":"La pecera de tiburones", "puzzles.the_sharks_have_been_biting_again":"Los tiburones vuelven a morder. Quédate en tierra firme.", "puzzles.the_sharks_say_no":"Los tiburones dicen que no.", +"puzzles.this_link":"Este enlace", "puzzles.three_cities_two_currencies_one_very":"Tres ciudades, dos monedas y un túnel muy corto bajo el mar.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Los traders pagaron millones por arañar milisegundos a esta ruta. Tú lo harás por menos.", +"puzzles.traffic_cops":"Guardias de tráfico", +"puzzles.trench_n":"zanja {n}", "puzzles.two_cables_across_the_atlantic_because":"Dos cables cruzando el Atlántico, porque uno es una esperanza, no un plan.", -"puzzles.under_n_ms":"menos de {n} ms", +"puzzles.u_of_m_used":"{u} de {m} en uso", "puzzles.undo":"Deshacer", "puzzles.unlocks_at_n_stars":"Se desbloquea con {n}⭐", "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_roomy_budgets":"Tus primeros tubos. Presupuestos holgados, y los dos primeros invita la casa.", +"puzzles.your_pop":"Tu POP", +"puzzles.your_routers_pick_the_path":"Tus routers eligen el camino. Diles cuál: métricas, menor latencia, best effort.", "puzzles.your_stars":"Tus estrellas", "puzzles_weekly.detour":"Desvío", "puzzles_weekly.island_hopping":"De isla en isla", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index ec80dc5..63bdb66 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2906,56 +2906,79 @@ "progress.your_score_peak_traffic":"Ton score : pic de trafic", "progress.your_traffic_to_and_from_asia":"Ton trafic vers et depuis l’Asie", "puzzles.a_backhoe_walks_into_your_network":"C’est une pelleteuse qui entre dans ton réseau. Il ne se passe rien.", +"puzzles.a_bigger_boat":"Il nous faut un plus gros bateau", +"puzzles.a_cut_on_where_drops_g":"Une coupure sur {where} fait tomber {g}", +"puzzles.a_different_route":"Une autre route", +"puzzles.a_diverse_route":"Une route diverse (+40 %)", "puzzles.a_pop_costs_setup_plus_a_year":"Un POP coûte {setup} à installer, puis {mo}/mois. Les puzzles comptent l’installation et un an de loyer.", -"puzzles.a_tiny_island_where_half_the":"Une île minuscule où la moitié des câbles du Pacifique s’arrêtent pour un café.", -"puzzles.a_to_b_under_ms":"{a} → {b} en moins de {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} en moins de {ms} ms (actuellement {now} ms)", -"puzzles.aloha_latency":"Aloha la latence", +"puzzles.add_a_router_cost":"Ajouter un routeur {cost}/an", +"puzzles.add_another_link_here":"Ajouter un autre lien sur cette paire", +"puzzles.all_of_europe_s_cat_videos":"Toutes les vidéos de chats d'Europe vivent à Londres, et toutes passent par ton routeur.", +"puzzles.already_here_list":"Déjà sur cette paire : {list}", +"puzzles.another_wave_on_this_cable":"Une autre wave sur ce câble", "puzzles.avoid_list":"sans {list}", "puzzles.back_to_my_network":"Retour à mon réseau", "puzzles.back_to_the_title":"Retour à l’écran titre", -"puzzles.beat_the_clock_light_in_glass":"La lumière dans la fibre fait 200 km par milliseconde. Choisis tes câbles comme si ça comptait.", +"puzzles.baltic_shortcut":"Raccourci balte", "puzzles.belt_and_braces":"Ceinture et bretelles", +"puzzles.best_effort":"best effort", "puzzles.best_x":"record {x}", +"puzzles.biggest_wave":"Plus grosse wave", "puzzles.budget":"Budget", "puzzles.budget_x":"budget {x}", -"puzzles.connect_list":"Relie {list}.", -"puzzles.connected":"Relié", +"puzzles.capacity_first_every_link_has_a":"La capacité d'abord : chaque lien a une taille, et le trafic doit y tenir. Budgets confortables, et les deux premiers sont offerts.", +"puzzles.carry_list":"À transporter : {list}.", +"puzzles.carrying":"Transporte", +"puzzles.carrying_on_this_pair":"Transporte (les {n} liens de cette paire)", +"puzzles.content_lives_in_list":"Le contenu vit à {list} : les internautes tirent du plus proche.", "puzzles.copied_paste_it_anywhere":"Copié ! Colle-le où tu veux :
{t}", "puzzles.de_kicks_sales_has_your_number":"Les commerciaux de DE-KICKS ont ton numéro. Relie l’Allemagne sans passer par Francfort.", +"puzzles.delivered":"Livré", "puzzles.diverse_route_40_survives_a_backhoe":"Route diverse (+40 %, survit à une pelleteuse)", "puzzles.down_under_up_and_running":"Down Under, ça tourne", "puzzles.drag_from_a_pink_pop_to":"Glisse depuis un POP rose vers une autre ville pour louer une longueur d’onde", "puzzles.drag_from_this_pop_onto_another":"Glisse depuis ce POP vers une autre ville du puzzle, ou choisis-en une ici.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"chaque bit arrive", "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.everything_at_once_across_oceans":"Tout à la fois, par-delà les océans. Budgets serrés.", +"puzzles.fat_pipes":"Gros tuyaux", +"puzzles.five_small_cities_one_small_router":"Cinq villes, quelques gigas chacune, et un routeur à huit ports. Compte avant de creuser.", +"puzzles.fjord_focus":"Cap sur le fjord", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Pour les architectes qui dorment pendant la saison des pelleteuses.", -"puzzles.four_capitals_one_very_long_winter":"Quatre capitales, un très long hiver, zéro excuse pour une panne.", +"puzzles.flow_circuit_a_b":"Circuit {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Internautes à {city}", "puzzles.four_cities_four_cables_one_ring":"Quatre villes, un anneau. Tolkien approuverait ; ton NOC, à coup sûr.", "puzzles.four_cities_one_continent_and_a":"Quatre villes, un continent et beaucoup de maïs entre les deux.", +"puzzles.framed_n_stars_from_the_old":"Encadrées au mur : {n} ⭐ des anciens puzzles", "puzzles.frankfurt_to_singapore_the_short_way":"Francfort–Singapour par le chemin court. Le long passe par la terre, et ça se voit.", "puzzles.free":"Gratuit", -"puzzles.goal":"Objectif", "puzzles.goal_city":"Ville objectif", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Hello, World", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu : le site de régénération le plus pittoresque du monde.", +"puzzles.hub_cap":"Enjoliveur", "puzzles.includes_a_new_pop_in_city":"Inclut un nouveau POP à {city} ({price} pour un an).", +"puzzles.installed":"installé", "puzzles.it_works_finance_and_the_backhoe":"Ça marche ! La compta et la pelleteuse aimeraient te dire un mot.", "puzzles.keep_building":"Continuer à construire", "puzzles.kiwi_fruit_salad":"Salade de kiwis", +"puzzles.latency":"Latence", +"puzzles.latency_caps":"plafonds de latence", "puzzles.lease_a_wave_to":"Louer une longueur d’onde vers", "puzzles.loading_this_week_s_puzzle":"Chargement du puzzle de la semaine…", +"puzzles.london_wants_half_a_terabit_your":"Londres veut un demi-térabit, et tes routeurs viennent d'eBuy.", +"puzzles.model_facts":"{cap} · {ports} ports · waves jusqu'à {wave}", "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_1_deliver_everything_first":"N-1 : livre tout d'abord", +"puzzles.n_circuits":{"one":"{n} circuit","other":"{n} circuits"}, +"puzzles.n_g_of_eyeballs":"{n} d'internautes", +"puzzles.n_links_on_this_pair":"{n} liens sur cette paire : {what}", "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.needs_what":"il faut {what}", "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}⭐", @@ -2965,26 +2988,31 @@ "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.", -"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_clock_no_bills_real_traffic":"Pas d'horloge, pas de factures, rien ne casse. Du vrai trafic, routé comme dans le vrai jeu : livre chaque flux, reste dans le budget, et garde tout en marche quand une tranchée ou un câble est coupé.", +"puzzles.no_free_ports_in_list":"Plus de port libre sur le routeur à {list} : ajoute un routeur ou un plus gros modèle d'abord.", "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.", +"puzzles.no_traffic_starts_or_ends_here":"Aucun trafic ne part ni n'arrive ici. Tu peux quand même construire, si ça te mène quelque part.", +"puzzles.not_a_city_you_can_build_in":"Impossible de construire dans cette ville.", +"puzzles.not_in_the_plan":"Hors du plan", "puzzles.not_this_one_find_a_way_around":"Pas celle-là. Trouve un détour.", "puzzles.not_through_frankfurt":"Pas par Francfort", "puzzles.off_limits":"Interdite", "puzzles.on_the_house":"Offert par la maison", "puzzles.one_backhoe_away_from_a_very":"À une pelleteuse d’une très longue nuit. Ajoute un deuxième chemin pour ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Une coupure le divise", -"puzzles.one_cut_splits_it_where":"Une coupure le divise : {where}", "puzzles.one_ring_through_every_pop":"Un anneau qui passe par chaque POP", "puzzles.one_very_big_island_and_a":"Une très grande île, et beaucoup de fibre très vide.", "puzzles.open_a_pop_cost":"Ouvrir un POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping-pong jusqu’à Tokyo", +"puzzles.or_drag_to_any_city_on_the_map":"Ou glisse vers n'importe quelle ville de la carte : le monde entier est ouvert.", +"puzzles.paris_wants_150g_one_100g_wave":"Paris veut 150G. Une wave de 100G, c'est un tuyau d'arrosage.", +"puzzles.port_authority":"Autorité portuaire", +"puzzles.ports":"Ports", "puzzles.price_per_year":"{price}/an", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle résolu", "puzzles.puzzles":"Puzzles", +"puzzles.puzzles_got_traffic_note":"Les puzzles ont du trafic ! Chaque puzzle transporte maintenant de vrais flux, alors les étoiles repartent de zéro. Tes {n} ⭐ d'avant sont encadrées au mur.", +"puzzles.remove_a_router":"Retirer un routeur", "puzzles.remove_this_link":"Supprimer ce lien", "puzzles.remove_this_pop":"Supprimer ce POP", "puzzles.reset":"Recommencer", @@ -2992,41 +3020,48 @@ "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.router_load":"Charge du routeur", +"puzzles.router_model":"Modèle de routeur", +"puzzles.router_rodeo":"Rodéo des routeurs", +"puzzles.routers_have_ports_and_a_limit":"Les routeurs ont des ports et une limite. Remplis-en un et le trafic s'arrête à la porte.", "puzzles.rule_not_via_list":"Règle : pas par {list}", "puzzles.samba_sprint":"Sprint samba", +"puzzles.same_cable_same_anchor":"Même câble qu'un lien que tu as : une ancre emporte les deux.", "puzzles.same_puzzle_for_everyone_this_week":"Le même puzzle pour tout le monde cette semaine", +"puzzles.same_trench_cheaper":"Même tranchée (moins cher)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Même tranchée (moins cher, une pelleteuse coupe les deux)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo–Miami avant que la caïpirinha ne tiédisse.", "puzzles.sea_to_shining_sea":"D’une côte à l’autre", -"puzzles.seattle_to_singapore_with_a_stop":"Seattle–Singapour, avec une escale sushis et dim sum.", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", "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.small_networks_real_traffic":"Petits réseaux, vrai trafic", "puzzles.spent_x":"Dépensé {x}", "puzzles.spent_x_of_y":"Dépensé {x} / {y}", "puzzles.stepping_stone_optional":"Escale (facultative)", "puzzles.suez_you_later":"Suez la prochaine", -"puzzles.survives_any_single_cut":"Survit à n’importe quelle coupure", +"puzzles.survive_any_single_cut_with_the":"Survis à n'importe quelle coupure, avec le trafic qui passe toujours. Être connecté ne suffit pas.", +"puzzles.survives_any_single_cut_under_load":"Tient n'importe quelle coupure, en charge", "puzzles.tap_a_goal_city_to_open":"Touche une ville lumineuse pour ouvrir ton premier POP", -"puzzles.that_city_is_not_part_of":"Cette ville ne fait pas partie de ce puzzle.", -"puzzles.the_pacific_is_big_light_is":"Le Pacifique est grand. La lumière est rapide. Ton budget n’est ni l’un ni l’autre.", -"puzzles.the_pacific_rim_where_every_hop":"Le pourtour du Pacifique, où chaque saut est un océan.", +"puzzles.the_content_origin_lives_here":"Le contenu vit ici. Les internautes d'ailleurs tirent d'ici.", +"puzzles.the_oil_rigs_want_their_numbers":"Les plateformes veulent leurs chiffres vite. La route la plus courte vers Stavanger n'est pas la plus rapide.", +"puzzles.the_road_to_tallinn_is_short":"La route vers Tallinn est courte. La lumière via Helsinki l'est encore plus.", "puzzles.the_shark_tank":"L’aquarium à requins", "puzzles.the_sharks_have_been_biting_again":"Les requins ont encore mordu. Reste sur la terre ferme.", "puzzles.the_sharks_say_no":"Les requins disent non.", +"puzzles.this_link":"Ce lien", "puzzles.three_cities_two_currencies_one_very":"Trois villes, deux monnaies, un tout petit tunnel sous la mer.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Des traders ont payé des millions pour gratter des millisecondes sur cette route. Toi, tu le fais pour moins cher.", +"puzzles.traffic_cops":"Agents de la circulation", +"puzzles.trench_n":"tranchée {n}", "puzzles.two_cables_across_the_atlantic_because":"Deux câbles à travers l’Atlantique, parce qu’un seul, c’est un espoir, pas un plan.", -"puzzles.under_n_ms":"moins de {n} ms", +"puzzles.u_of_m_used":"{u} sur {m} utilisés", "puzzles.undo":"Annuler", "puzzles.unlocks_at_n_stars":"À partir de {n}⭐", "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_roomy_budgets":"Tes premiers tubes. Des budgets confortables, et les deux premiers sont offerts par la maison.", +"puzzles.your_pop":"Ton POP", +"puzzles.your_routers_pick_the_path":"Tes routeurs choisissent le chemin. Dis-leur lequel : métriques, latence minimale, best effort.", "puzzles.your_stars":"Tes étoiles", "puzzles_weekly.detour":"Détour", "puzzles_weekly.island_hopping":"Saut d’île en île", diff --git a/site/i18n/it.js b/site/i18n/it.js index f6250c9..fd69c3d 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2906,56 +2906,79 @@ "progress.your_score_peak_traffic":"Il tuo punteggio: picco di traffico", "progress.your_traffic_to_and_from_asia":"Il tuo traffico da e per l’Asia", "puzzles.a_backhoe_walks_into_your_network":"Una ruspa entra nella tua rete. Non succede niente.", +"puzzles.a_bigger_boat":"Ci serve una barca più grande", +"puzzles.a_cut_on_where_drops_g":"Un taglio su {where} perde {g}", +"puzzles.a_different_route":"Un altro percorso", +"puzzles.a_diverse_route":"Un percorso diverso (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"Un POP costa {setup} di attivazione, poi {mo}/mese. I puzzle contano l’attivazione e un anno di canone.", -"puzzles.a_tiny_island_where_half_the":"Un’isoletta dove metà dei cavi del Pacifico si ferma per un caffè.", -"puzzles.a_to_b_under_ms":"{a} → {b} sotto i {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} sotto i {ms} ms (ora {now} ms)", -"puzzles.aloha_latency":"Aloha latenza", +"puzzles.add_a_router_cost":"Aggiungi un router {cost}/anno", +"puzzles.add_another_link_here":"Aggiungi un altro link su questa coppia", +"puzzles.all_of_europe_s_cat_videos":"Tutti i video di gatti d'Europa vivono a Londra, e passano tutti dal tuo router.", +"puzzles.already_here_list":"Già su questa coppia: {list}", +"puzzles.another_wave_on_this_cable":"Un'altra wave su questo cavo", "puzzles.avoid_list":"senza {list}", "puzzles.back_to_my_network":"Torna alla mia rete", "puzzles.back_to_the_title":"Torna alla schermata iniziale", -"puzzles.beat_the_clock_light_in_glass":"La luce nella fibra fa 200 km al millisecondo. Scegli i cavi come se contasse.", +"puzzles.baltic_shortcut":"Scorciatoia baltica", "puzzles.belt_and_braces":"Cintura e bretelle", +"puzzles.best_effort":"best effort", "puzzles.best_x":"record {x}", +"puzzles.biggest_wave":"Wave più grande", "puzzles.budget":"Budget", "puzzles.budget_x":"budget {x}", -"puzzles.connect_list":"Collega {list}.", -"puzzles.connected":"Collegato", +"puzzles.capacity_first_every_link_has_a":"Prima la capacità: ogni link ha una taglia, e il traffico deve starci. Budget comodi, e i primi due li offre la casa.", +"puzzles.carry_list":"Da trasportare: {list}.", +"puzzles.carrying":"Trasporta", +"puzzles.carrying_on_this_pair":"Trasporta (tutti i {n} link di questa coppia)", +"puzzles.content_lives_in_list":"I contenuti vivono a {list}: gli utenti pescano dal più vicino.", "puzzles.copied_paste_it_anywhere":"Copiato! Incollalo dove vuoi:
{t}", "puzzles.de_kicks_sales_has_your_number":"Il commerciale di DE-KICKS ha il tuo numero. Collega la Germania senza passare da Francoforte.", +"puzzles.delivered":"Consegnato", "puzzles.diverse_route_40_survives_a_backhoe":"Percorso diverso (+40%, sopravvive a una ruspa)", "puzzles.down_under_up_and_running":"Down Under, operativi", "puzzles.drag_from_a_pink_pop_to":"Trascina da un POP rosa a un’altra città per noleggiare una wave", "puzzles.drag_from_this_pop_onto_another":"Trascina da questo POP su un’altra città del puzzle, o scegline una qui.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"ogni bit arriva", "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.everything_at_once_across_oceans":"Tutto insieme, oltre gli oceani. Budget stretti.", +"puzzles.fat_pipes":"Tubi grossi", +"puzzles.five_small_cities_one_small_router":"Cinque città, pochi giga ciascuna, e un router con otto porte. Conta prima di scavare.", +"puzzles.fjord_focus":"Fuoco sul fiordo", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Per architetti che dormono sonni tranquilli nella stagione delle ruspe.", -"puzzles.four_capitals_one_very_long_winter":"Quattro capitali, un inverno lunghissimo, zero scuse per i disservizi.", +"puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Utenti a {city}", "puzzles.four_cities_four_cables_one_ring":"Quattro città, un anello. Tolkien approverebbe; il tuo NOC di sicuro.", "puzzles.four_cities_one_continent_and_a":"Quattro città, un continente e tantissimo mais in mezzo.", +"puzzles.framed_n_stars_from_the_old":"Incorniciate sul muro: {n} ⭐ dei vecchi puzzle", "puzzles.frankfurt_to_singapore_the_short_way":"Da Francoforte a Singapore per la via corta. Quella lunga è via terra, e si vede.", "puzzles.free":"Gratis", -"puzzles.goal":"Obiettivo", "puzzles.goal_city":"Città obiettivo", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Ciao, mondo", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: il sito di rigenerazione più panoramico del mondo.", +"puzzles.hub_cap":"Coprimozzo", "puzzles.includes_a_new_pop_in_city":"Include un nuovo POP a {city} ({price} per un anno).", +"puzzles.installed":"installato", "puzzles.it_works_finance_and_the_backhoe":"Funziona! L’amministrazione e la ruspa vorrebbero parlarti.", "puzzles.keep_building":"Continua a costruire", "puzzles.kiwi_fruit_salad":"Macedonia di kiwi", +"puzzles.latency":"Latenza", +"puzzles.latency_caps":"limiti di latenza", "puzzles.lease_a_wave_to":"Noleggia una wave verso", "puzzles.loading_this_week_s_puzzle":"Carico il puzzle della settimana…", +"puzzles.london_wants_half_a_terabit_your":"Londra vuole mezzo terabit, e i tuoi router vengono da eBuy.", +"puzzles.model_facts":"{cap} · {ports} porte · wave fino a {wave}", "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_1_deliver_everything_first":"N-1: prima consegna tutto", +"puzzles.n_circuits":{"one":"{n} circuito","other":"{n} circuiti"}, +"puzzles.n_g_of_eyeballs":"{n} di utenti", +"puzzles.n_links_on_this_pair":"{n} link su questa coppia: {what}", "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.needs_what":"servono {what}", "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}⭐", @@ -2965,26 +2988,31 @@ "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.", -"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_clock_no_bills_real_traffic":"Niente orologio, niente bollette, non si rompe niente. Traffico vero, instradato come nel gioco vero: consegna ogni flusso, resta nel budget, e tieni tutto in piedi quando si taglia una qualsiasi trincea o cavo.", +"puzzles.no_free_ports_in_list":"Nessuna porta libera sul router a {list}: aggiungi un router o un modello più grande.", "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.", +"puzzles.no_traffic_starts_or_ends_here":"Qui non parte né arriva traffico. Puoi costruire lo stesso, se ti porta da qualche parte.", +"puzzles.not_a_city_you_can_build_in":"In quella città non puoi costruire.", +"puzzles.not_in_the_plan":"Fuori dal piano", "puzzles.not_this_one_find_a_way_around":"Questa no. Trova un altro giro.", "puzzles.not_through_frankfurt":"Non da Francoforte", "puzzles.off_limits":"Vietata", "puzzles.on_the_house":"Offre la casa", "puzzles.one_backhoe_away_from_a_very":"A una ruspa da una nottata lunghissima. Aggiungi un secondo percorso per ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Un taglio la divide", -"puzzles.one_cut_splits_it_where":"Un taglio la divide: {where}", "puzzles.one_ring_through_every_pop":"Un anello che passa per ogni POP", "puzzles.one_very_big_island_and_a":"Un’isola enorme e tantissima fibra vuota.", "puzzles.open_a_pop_cost":"Apri un POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping pong fino a Tokyo", +"puzzles.or_drag_to_any_city_on_the_map":"Oppure trascina su qualsiasi città della mappa: il mondo intero è aperto.", +"puzzles.paris_wants_150g_one_100g_wave":"Parigi vuole 150G. Una wave da 100G è un tubo da giardino.", +"puzzles.port_authority":"Autorità portuale", +"puzzles.ports":"Porte", "puzzles.price_per_year":"{price}/anno", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle risolto", "puzzles.puzzles":"Puzzle", +"puzzles.puzzles_got_traffic_note":"I puzzle hanno il traffico! Ogni puzzle ora trasporta flussi veri, quindi le stelle ripartono da zero. Le tue vecchie {n} ⭐ sono incorniciate sul muro.", +"puzzles.remove_a_router":"Togli un router", "puzzles.remove_this_link":"Rimuovi questo link", "puzzles.remove_this_pop":"Rimuovi questo POP", "puzzles.reset":"Ricomincia", @@ -2992,41 +3020,48 @@ "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.router_load":"Carico del router", +"puzzles.router_model":"Modello di router", +"puzzles.router_rodeo":"Rodeo dei router", +"puzzles.routers_have_ports_and_a_limit":"I router hanno porte e un limite. Riempine uno e il traffico si ferma alla porta.", "puzzles.rule_not_via_list":"Regola: niente passaggi da {list}", "puzzles.samba_sprint":"Sprint di samba", +"puzzles.same_cable_same_anchor":"Stesso cavo di un link che hai già: un'ancora li prende tutti e due.", "puzzles.same_puzzle_for_everyone_this_week":"Lo stesso puzzle per tutti questa settimana", +"puzzles.same_trench_cheaper":"Stessa trincea (costa meno)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Stesso scavo (più economico, una ruspa li taglia tutti e due)", "puzzles.sao_paulo_to_miami_before_the":"Da São Paulo a Miami prima che la caipirinha si scaldi.", "puzzles.sea_to_shining_sea":"Da costa a costa", -"puzzles.seattle_to_singapore_with_a_stop":"Da Seattle a Singapore, con una sosta per sushi e dim sum.", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", "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.small_networks_real_traffic":"Reti piccole, traffico vero", "puzzles.spent_x":"Speso {x}", "puzzles.spent_x_of_y":"Speso {x} / {y}", "puzzles.stepping_stone_optional":"Tappa (facoltativa)", "puzzles.suez_you_later":"Suez la prossima", -"puzzles.survives_any_single_cut":"Sopravvive a qualsiasi taglio", +"puzzles.survive_any_single_cut_with_the":"Sopravvivi a qualsiasi taglio, con il traffico che scorre ancora. Essere collegati non basta.", +"puzzles.survives_any_single_cut_under_load":"Regge qualsiasi taglio, sotto carico", "puzzles.tap_a_goal_city_to_open":"Tocca una città illuminata per aprire il tuo primo POP", -"puzzles.that_city_is_not_part_of":"Quella città non fa parte di questo puzzle.", -"puzzles.the_pacific_is_big_light_is":"Il Pacifico è grande. La luce è veloce. Il tuo budget non è né l’uno né l’altro.", -"puzzles.the_pacific_rim_where_every_hop":"Il bordo del Pacifico, dove ogni hop è un oceano.", +"puzzles.the_content_origin_lives_here":"Qui vivono i contenuti. Gli utenti altrove pescano da qui.", +"puzzles.the_oil_rigs_want_their_numbers":"Le piattaforme vogliono i numeri in fretta. La strada più corta per Stavanger non è la più veloce.", +"puzzles.the_road_to_tallinn_is_short":"La strada per Tallinn è corta. La luce via Helsinki è più corta.", "puzzles.the_shark_tank":"La vasca degli squali", "puzzles.the_sharks_have_been_biting_again":"Gli squali hanno ricominciato a mordere. Resta sulla terraferma.", "puzzles.the_sharks_say_no":"Gli squali dicono di no.", +"puzzles.this_link":"Questo link", "puzzles.three_cities_two_currencies_one_very":"Tre città, due valute, un tunnel cortissimo sotto il mare.", "puzzles.traders_paid_millions_to_shave_milliseconds":"I trader hanno pagato milioni per limare millisecondi su questa rotta. Tu ci riesci spendendo meno.", +"puzzles.traffic_cops":"Vigili del traffico", +"puzzles.trench_n":"trincea {n}", "puzzles.two_cables_across_the_atlantic_because":"Due cavi attraverso l’Atlantico, perché uno solo è una speranza, non un piano.", -"puzzles.under_n_ms":"sotto i {n} ms", +"puzzles.u_of_m_used":"{u} di {m} in uso", "puzzles.undo":"Annulla", "puzzles.unlocks_at_n_stars":"Si sblocca a {n}⭐", "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_roomy_budgets":"I tuoi primi tubi. Budget comodi, e i primi due li offre la casa.", +"puzzles.your_pop":"Il tuo POP", +"puzzles.your_routers_pick_the_path":"I tuoi router scelgono il percorso. Digli quale: metriche, latenza minima, best effort.", "puzzles.your_stars":"Le tue stelle", "puzzles_weekly.detour":"Deviazione", "puzzles_weekly.island_hopping":"Di isola in isola", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 4308d56..df59333 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2906,56 +2906,79 @@ "progress.your_score_peak_traffic":"Sua pontuação: pico de tráfego", "progress.your_traffic_to_and_from_asia":"Seu tráfego de e para a Ásia", "puzzles.a_backhoe_walks_into_your_network":"Uma retroescavadeira entra na sua rede. Nada acontece.", +"puzzles.a_bigger_boat":"Vamos precisar de um barco maior", +"puzzles.a_cut_on_where_drops_g":"Um corte em {where} derruba {g}", +"puzzles.a_different_route":"Outra rota", +"puzzles.a_diverse_route":"Uma rota diversa (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"Um POP custa {setup} de instalação e depois {mo}/mês. Os puzzles contam a instalação e um ano de aluguel.", -"puzzles.a_tiny_island_where_half_the":"Uma ilhota onde metade dos cabos do Pacífico para pra tomar um café.", -"puzzles.a_to_b_under_ms":"{a} → {b} abaixo de {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} abaixo de {ms} ms (agora {now} ms)", -"puzzles.aloha_latency":"Aloha, latência", +"puzzles.add_a_router_cost":"Adicionar um router {cost}/ano", +"puzzles.add_another_link_here":"Adicionar outro link neste par", +"puzzles.all_of_europe_s_cat_videos":"Todos os vídeos de gatos da Europa moram em Londres, e todos passam pelo seu router.", +"puzzles.already_here_list":"Já neste par: {list}", +"puzzles.another_wave_on_this_cable":"Outra wave neste cabo", "puzzles.avoid_list":"sem {list}", "puzzles.back_to_my_network":"Voltar à minha rede", "puzzles.back_to_the_title":"Voltar à tela inicial", -"puzzles.beat_the_clock_light_in_glass":"A luz na fibra faz 200 km por milissegundo. Escolha seus cabos como se isso importasse.", +"puzzles.baltic_shortcut":"Atalho báltico", "puzzles.belt_and_braces":"Cinto e suspensórios", +"puzzles.best_effort":"best effort", "puzzles.best_x":"recorde {x}", +"puzzles.biggest_wave":"Maior wave", "puzzles.budget":"Orçamento", "puzzles.budget_x":"orçamento {x}", -"puzzles.connect_list":"Conecte {list}.", -"puzzles.connected":"Conectado", +"puzzles.capacity_first_every_link_has_a":"Capacidade primeiro: cada link tem um tamanho, e o tráfego tem que caber. Orçamentos folgados, e os dois primeiros são por conta da casa.", +"puzzles.carry_list":"Transporte: {list}.", +"puzzles.carrying":"Transportando", +"puzzles.carrying_on_this_pair":"Transportando (todos os {n} links deste par)", +"puzzles.content_lives_in_list":"O conteúdo mora em {list}: os usuários puxam do mais próximo.", "puzzles.copied_paste_it_anywhere":"Copiado! Cole onde quiser:
{t}", "puzzles.de_kicks_sales_has_your_number":"O comercial da DE-KICKS tem seu número. Conecte a Alemanha sem passar por Frankfurt.", +"puzzles.delivered":"Entregue", "puzzles.diverse_route_40_survives_a_backhoe":"Rota diversa (+40%, sobrevive a uma retroescavadeira)", "puzzles.down_under_up_and_running":"Down Under, no ar", "puzzles.drag_from_a_pink_pop_to":"Arraste de um POP rosa até outra cidade para alugar uma wave", "puzzles.drag_from_this_pop_onto_another":"Arraste deste POP até outra cidade do puzzle, ou escolha uma aqui.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"cada bit chega", "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.everything_at_once_across_oceans":"Tudo de uma vez, atravessando oceanos. Orçamentos apertados.", +"puzzles.fat_pipes":"Canos grossos", +"puzzles.five_small_cities_one_small_router":"Cinco cidades, poucos gigas cada, e um router com oito portas. Conte antes de cavar.", +"puzzles.fjord_focus":"Foco no fiorde", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"Para arquitetos que dormem tranquilos na temporada das retroescavadeiras.", -"puzzles.four_capitals_one_very_long_winter":"Quatro capitais, um inverno longuíssimo, zero desculpas para cair.", +"puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", +"puzzles.flow_eyeballs_in_city":"Usuários em {city}", "puzzles.four_cities_four_cables_one_ring":"Quatro cidades, um anel. Tolkien aprovaria; seu NOC, com certeza.", "puzzles.four_cities_one_continent_and_a":"Quatro cidades, um continente e muito milho no meio.", +"puzzles.framed_n_stars_from_the_old":"Emolduradas na parede: {n} ⭐ dos puzzles antigos", "puzzles.frankfurt_to_singapore_the_short_way":"De Frankfurt a Singapura pelo caminho curto. O longo vai por terra, e dá pra notar.", "puzzles.free":"Grátis", -"puzzles.goal":"Objetivo", "puzzles.goal_city":"Cidade objetivo", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Olá, mundo", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: o ponto de regeneração mais bonito do mundo.", +"puzzles.hub_cap":"Calota", "puzzles.includes_a_new_pop_in_city":"Inclui um POP novo em {city} ({price} por um ano).", +"puzzles.installed":"instalado", "puzzles.it_works_finance_and_the_backhoe":"Funciona! O financeiro e a retroescavadeira querem uma palavrinha.", "puzzles.keep_building":"Continuar construindo", "puzzles.kiwi_fruit_salad":"Salada de kiwi", +"puzzles.latency":"Latência", +"puzzles.latency_caps":"limites de latência", "puzzles.lease_a_wave_to":"Alugar uma wave até", "puzzles.loading_this_week_s_puzzle":"Carregando o puzzle da semana…", +"puzzles.london_wants_half_a_terabit_your":"Londres quer meio terabit, e seus routers vieram do eBuy.", +"puzzles.model_facts":"{cap} · {ports} portas · waves até {wave}", "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_1_deliver_everything_first":"N-1: entregue tudo primeiro", +"puzzles.n_circuits":{"one":"{n} circuito","other":"{n} circuitos"}, +"puzzles.n_g_of_eyeballs":"{n} de usuários", +"puzzles.n_links_on_this_pair":"{n} links neste par: {what}", "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.needs_what":"precisa de {what}", "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}⭐", @@ -2965,26 +2988,31 @@ "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.", -"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_clock_no_bills_real_traffic":"Sem relógio, sem contas, nada quebra. Tráfego de verdade, roteado como no jogo de verdade: entregue cada fluxo, fique no orçamento e mantenha tudo fluindo quando qualquer vala ou cabo for cortado.", +"puzzles.no_free_ports_in_list":"Sem portas livres no router em {list}: adicione um router ou um modelo maior antes.", "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.", +"puzzles.no_traffic_starts_or_ends_here":"Nenhum tráfego começa ou termina aqui. Ainda dá para construir, se isso te levar a algum lugar.", +"puzzles.not_a_city_you_can_build_in":"Não dá para construir nessa cidade.", +"puzzles.not_in_the_plan":"Fora do plano", "puzzles.not_this_one_find_a_way_around":"Essa não. Dê a volta.", "puzzles.not_through_frankfurt":"Sem passar por Frankfurt", "puzzles.off_limits":"Proibida", "puzzles.on_the_house":"Por conta da casa", "puzzles.one_backhoe_away_from_a_very":"A uma retroescavadeira de uma noite muito longa. Adicione um segundo caminho para ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"Um corte divide a rede", -"puzzles.one_cut_splits_it_where":"Um corte divide a rede: {where}", "puzzles.one_ring_through_every_pop":"Um anel passando por todos os POPs", "puzzles.one_very_big_island_and_a":"Uma ilha enorme e muita fibra vazia.", "puzzles.open_a_pop_cost":"Abrir um POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Pingue-pongue até Tóquio", +"puzzles.or_drag_to_any_city_on_the_map":"Ou arraste para qualquer cidade do mapa: o mundo todo está aberto.", +"puzzles.paris_wants_150g_one_100g_wave":"Paris quer 150G. Uma wave de 100G é uma mangueira de jardim.", +"puzzles.port_authority":"Autoridade portuária", +"puzzles.ports":"Portas", "puzzles.price_per_year":"{price}/ano", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle resolvido", "puzzles.puzzles":"Puzzles", +"puzzles.puzzles_got_traffic_note":"Os puzzles ganharam tráfego! Cada puzzle agora transporta fluxos de verdade, então as estrelas recomeçam. Suas {n} ⭐ antigas estão emolduradas na parede.", +"puzzles.remove_a_router":"Remover um router", "puzzles.remove_this_link":"Remover este link", "puzzles.remove_this_pop":"Remover este POP", "puzzles.reset":"Recomeçar", @@ -2992,41 +3020,48 @@ "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.router_load":"Carga do router", +"puzzles.router_model":"Modelo de router", +"puzzles.router_rodeo":"Rodeio dos routers", +"puzzles.routers_have_ports_and_a_limit":"Routers têm portas e um limite. Encha um e o tráfego para na porta.", "puzzles.rule_not_via_list":"Regra: sem passar por {list}", "puzzles.samba_sprint":"Corrida de samba", +"puzzles.same_cable_same_anchor":"Mesmo cabo de um link que você já tem: uma âncora leva os dois.", "puzzles.same_puzzle_for_everyone_this_week":"O mesmo puzzle para todo mundo nesta semana", +"puzzles.same_trench_cheaper":"Mesma vala (mais barato)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Mesma vala (mais barata, uma retroescavadeira corta as duas)", "puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes que a caipirinha esquente.", "puzzles.sea_to_shining_sea":"De costa a costa", -"puzzles.seattle_to_singapore_with_a_stop":"De Seattle a Singapura, com parada para sushi e dim sum.", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", "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.small_networks_real_traffic":"Redes pequenas, tráfego de verdade", "puzzles.spent_x":"Gasto {x}", "puzzles.spent_x_of_y":"Gasto {x} / {y}", "puzzles.stepping_stone_optional":"Escala (opcional)", "puzzles.suez_you_later":"Suez mais tarde", -"puzzles.survives_any_single_cut":"Sobrevive a qualquer corte", +"puzzles.survive_any_single_cut_with_the":"Sobreviva a qualquer corte, com o tráfego ainda fluindo. Estar conectado não basta.", +"puzzles.survives_any_single_cut_under_load":"Aguenta qualquer corte, sob carga", "puzzles.tap_a_goal_city_to_open":"Toque numa cidade brilhante para abrir seu primeiro POP", -"puzzles.that_city_is_not_part_of":"Essa cidade não faz parte deste puzzle.", -"puzzles.the_pacific_is_big_light_is":"O Pacífico é grande. A luz é rápida. Seu orçamento não é nenhum dos dois.", -"puzzles.the_pacific_rim_where_every_hop":"A borda do Pacífico, onde cada salto é um oceano.", +"puzzles.the_content_origin_lives_here":"O conteúdo mora aqui. Usuários de outros lugares puxam daqui.", +"puzzles.the_oil_rigs_want_their_numbers":"As plataformas querem os números rápido. A estrada mais curta para Stavanger não é a mais rápida.", +"puzzles.the_road_to_tallinn_is_short":"A estrada para Tallinn é curta. A luz via Helsinque é mais curta.", "puzzles.the_shark_tank":"O aquário dos tubarões", "puzzles.the_sharks_have_been_biting_again":"Os tubarões voltaram a morder. Fique em terra firme.", "puzzles.the_sharks_say_no":"Os tubarões dizem não.", +"puzzles.this_link":"Este link", "puzzles.three_cities_two_currencies_one_very":"Três cidades, duas moedas e um túnel bem curtinho debaixo do mar.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Traders pagaram milhões para tirar milissegundos desta rota. Você faz por menos.", +"puzzles.traffic_cops":"Guardas de trânsito", +"puzzles.trench_n":"vala {n}", "puzzles.two_cables_across_the_atlantic_because":"Dois cabos atravessando o Atlântico, porque um só é esperança, não plano.", -"puzzles.under_n_ms":"abaixo de {n} ms", +"puzzles.u_of_m_used":"{u} de {m} em uso", "puzzles.undo":"Desfazer", "puzzles.unlocks_at_n_stars":"Abre com {n}⭐", "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_roomy_budgets":"Seus primeiros tubos. Orçamentos folgados, e os dois primeiros são por conta da casa.", +"puzzles.your_pop":"Seu POP", +"puzzles.your_routers_pick_the_path":"Seus routers escolhem o caminho. Diga qual: métricas, menor latência, best effort.", "puzzles.your_stars":"Suas estrelas", "puzzles_weekly.detour":"Desvio", "puzzles_weekly.island_hopping":"De ilha em ilha", diff --git a/src/game/10-catalog/40-ports.js b/src/game/10-catalog/40-ports.js index 6dbccc1..435cd37 100644 --- a/src/game/10-catalog/40-ports.js +++ b/src/game/10-catalog/40-ports.js @@ -3,7 +3,8 @@ const PORT_SLOT=i=>i===0?0.25:1; function portsUsed(c){let u=0; for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;u+=l.kind==='df'?(l.ch||[]).length:1;} - for(const t of S.transit)if(t.city===c)u+=PORT_SLOT(t.tier)*(t.n||1); + // A puzzle's content origin (t.pz) hands off on a port of its own: it takes none of yours. + for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1); for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1); for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1); if(S.myIx[c])u+=1; @@ -17,6 +18,6 @@ const popIdle=c=>{const p=S.pops[c];return !!p&&!p.bb&&portsUsed(c)===0&&!S.biz. const fmtPorts=u=>Number.isInteger(u)?String(u):u.toFixed(2).replace(/0+$/,''); function modelFits(c,g){const G=RG[g],p=S.pops[c];if(!p)return ''; if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='wave'&&l.tier>G.maxLT))return tr('ports.a_wave_here_is_faster_than',{pn:G.pn}); - if([...S.transit,...S.pni].some(t=>t.city===c&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn}); + if([...S.transit,...S.pni].some(t=>t.city===c&&!t.pz&&t.tier>G.maxP)||ixIdsIn(c).some(x=>S.ixp[x]!==undefined&&!S.myIx[x]&&S.ixp[x]>G.maxP))return tr('ports.a_port_here_is_bigger_than',{pn:G.pn}); if(S.links.some(l=>(l.a===c||l.b===c)&&l.kind==='df'&&(l.ch||[]).some(o=>OPT[o]&&OPT[o].rg>G.cls)))return tr('ports.a_fibre_here_uses_optics_this'); if(portsUsed(c)>portsMax(c,g))return tr('ports.you_use_u_ports_here_and',{u:fmtPorts(portsUsed(c)),r:p.routers||1,model:G.n,max:portsMax(c,g)});return '';} diff --git a/src/game/60-features/90-puzzles-data.js b/src/game/60-features/90-puzzles-data.js index a6b7bba..1d64d54 100644 --- a/src/game/60-features/90-puzzles-data.js +++ b/src/game/60-features/90-puzzles-data.js @@ -1,33 +1,36 @@ /* Puzzles: one entry per line, in play order. A puzzle is data: - id, pack, n (name), j (one-line joke), cities (all must end up connected), via (optional stepping stones), - budget (setup + a year of monthly, 0 = no budget star to chase: it is given), and at most a twist or two: - 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). */ + id, pack, n (name), j (one-line joke), src (the content origins: eyeballs pull from the nearest), dem (the traffic: + {t:'eye',a,g} eyeballs in city a want g Gbps; {t:'l2',a,b,g,ms} a circuit of g Gbps between a and b, under ms + milliseconds one way; be:1 marks a flow best effort, which may drop when something is cut), via (suggested stepping + stones), budget (setup + a year of monthly, 0 = no budget star to chase: it is given), and at most a twist: + noSub (no subsea cables), ring (one ring through every POP), avoid (cities you may not build in). + Each pack teaches one idea; the budgets sit a little above the cheapest 3-star build found (tests/puzzles.test.js). */ const PZ_PACKS=[ - {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}, + {id:'hello',n:tr('puzzles.fat_pipes'),d:tr('puzzles.capacity_first_every_link_has_a'),need:0}, + {id:'rodeo',n:tr('puzzles.router_rodeo'),d:tr('puzzles.routers_have_ports_and_a_limit'),need:10}, + {id:'cops',n:tr('puzzles.traffic_cops'),d:tr('puzzles.your_routers_pick_the_path'),need:18}, + {id:'n1',n:tr('puzzles.n_1_club'),d:tr('puzzles.survive_any_single_cut_with_the'),need:26}, + {id:'final',n:tr('puzzles.grand_tour'),d:tr('puzzles.everything_at_once_across_oceans'),need:36}, ]; 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: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: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}, + {id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),src:['nyc'],dem:[{t:'eye',a:'lon',g:8}],budget:0}, + {id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),src:['ams'],dem:[{t:'eye',a:'lon',g:30},{t:'eye',a:'fra',g:60}],budget:0}, + {id:'bigboat',pack:'hello',n:tr('puzzles.a_bigger_boat'),j:tr('puzzles.paris_wants_150g_one_100g_wave'),src:['fra'],dem:[{t:'eye',a:'par',g:150}],budget:1}, + {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),src:['nyc'],dem:[{t:'eye',a:'chi',g:40},{t:'eye',a:'dal',g:30},{t:'eye',a:'sjc',g:60}],budget:1}, + {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),src:['syd'],dem:[{t:'eye',a:'mel',g:50},{t:'eye',a:'bne',g:30},{t:'eye',a:'adl',g:20}],budget:1}, + {id:'edgelord',pack:'rodeo',n:tr('puzzles.edge_lord'),j:tr('puzzles.london_wants_half_a_terabit_your'),src:['ams'],dem:[{t:'eye',a:'lon',g:500}],budget:1}, + {id:'hubcap',pack:'rodeo',n:tr('puzzles.hub_cap'),j:tr('puzzles.all_of_europe_s_cat_videos'),src:['lon'],dem:[{t:'eye',a:'ams',g:150},{t:'eye',a:'par',g:150},{t:'eye',a:'fra',g:120}],budget:1}, + {id:'ports',pack:'rodeo',n:tr('puzzles.port_authority'),j:tr('puzzles.five_small_cities_one_small_router'),src:['zrh'],dem:[{t:'eye',a:'mil',g:8},{t:'eye',a:'muc',g:8},{t:'eye',a:'fra',g:8},{t:'eye',a:'par',g:8},{t:'eye',a:'vie',g:8}],budget:1}, + {id:'flash',pack:'cops',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),src:['nyc'],dem:[{t:'l2',a:'nyc',b:'lon',g:10,ms:26},{t:'eye',a:'lon',g:80,be:1}],budget:1}, + {id:'baltic',pack:'cops',n:tr('puzzles.baltic_shortcut'),j:tr('puzzles.the_road_to_tallinn_is_short'),src:['fra'],dem:[{t:'eye',a:'tll',g:60},{t:'l2',a:'fra',b:'tll',g:10,ms:8.8}],via:['hel'],budget:1}, + {id:'fjord',pack:'cops',n:tr('puzzles.fjord_focus'),j:tr('puzzles.the_oil_rigs_want_their_numbers'),src:['par'],dem:[{t:'eye',a:'svg',g:30},{t:'l2',a:'par',b:'svg',g:10,ms:7.2}],via:['lon'],budget:1}, + {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),src:['nyc'],dem:[{t:'eye',a:'lon',g:60},{t:'eye',a:'dub',g:40}],budget:1}, + {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),src:['lis'],dem:[{t:'eye',a:'mad',g:40},{t:'eye',a:'par',g:60},{t:'eye',a:'mil',g:30}],via:['bcn','mrs'],noSub:true,budget:1}, + {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),src:['ams'],dem:[{t:'eye',a:'ber',g:50},{t:'eye',a:'muc',g:50},{t:'eye',a:'zrh',g:40}],via:['ham','dus'],avoid:['fra'],budget:1}, + {id:'fire',pack:'n1',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),src:['tok'],dem:[{t:'eye',a:'hkg',g:20},{t:'eye',a:'sin',g:20},{t:'eye',a:'syd',g:10}],ring:true,budget:1}, + {id:'suez',pack:'final',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),src:['fra'],dem:[{t:'l2',a:'fra',b:'sin',g:10,ms:68},{t:'eye',a:'sin',g:30,be:1}],via:['mrs','bom'],budget:1}, + {id:'kiwi',pack:'final',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),src:['sea'],dem:[{t:'eye',a:'akl',g:20},{t:'eye',a:'syd',g:40}],via:['hnl','suv','lax'],budget:1}, + {id:'samba',pack:'final',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),src:['mia'],dem:[{t:'l2',a:'sao',b:'mia',g:10,ms:45},{t:'eye',a:'sao',g:40},{t:'eye',a:'rio',g:20,be:1}],via:['for'],budget:1}, ]; // 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/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index fff7bb3..c0b6be5 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -1,17 +1,30 @@ /* ================= PUZZLES (#190) ================= - Small, calm builds: connect a few cities, earn up to three stars. A puzzle runs as its own S (S.mode='puzzle'): - no clock, no bills, no incidents, links up at once. That S is never saved. Only progress (stars and best spend per - puzzle, weekly results and the weekly streak) is kept, under its own key, so the main save is never touched. */ -const PZ_KEY='sot-puzzles',PZ_YEAR=12; + Small, calm builds that carry real traffic: every puzzle has demand (eyeballs pulling from a content origin, circuits + between two cities with a latency cap), and the game's own compute() routes it: metrics, standby, LAGs, router + capacity and ports all behave as in the main game. A puzzle runs as its own S (S.mode='puzzle'): no clock, no bills, + no incidents, links up at once. The demand is ordinary game state, so compute() needs no puzzle cases: an origin is a + transit port (t.pz, which takes no router port), a circuit is an L2VPN customer, eyeballs are broadband with a fixed + demand. That S is never saved. Only progress (stars and best spend per puzzle, weekly results and the weekly streak) + is kept, under its own key, so the main save is never touched. */ +const PZ_KEY='sot-puzzles',PZ_YEAR=12,PZ_SET=2; 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; +// goal: a city the traffic starts or ends in; via: a suggested stepping stone; avoid: off limits; off: any other city +// (the whole world is open, it just is not part of the plan). +const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':pzCityOk(c)?'off':null; 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); +// Every city a puzzle's traffic touches, origins first. +const pzCities=d=>[...new Set([...(d.src||[]),...d.dem.flatMap(f=>f.t==='l2'?[f.a,f.b]:[f.a])])]; // ---------- 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; +// `set` is the puzzle set the stars belong to: the set with traffic (2) started again, and the stars won before hang +// framed on the wall (`old`), with a note shown once (`noted`). Weekly results and the streak carry on. +function pzClean(j){const o={set:PZ_SET,s:{},wk:{},streak:{last:null,n:0,best:0},old:null,noted:1};if(!j||typeof j!=='object')return o; const rec=r=>r&&typeof r==='object'?{st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)}:null; - if(j.s&&typeof j.s==='object')for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;} + const cur=j.set===PZ_SET; + if(j.s&&typeof j.s==='object'){if(cur){for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;}} + else{let n=0;for(const k of Object.keys(j.s).slice(0,200)){const r=rec(j.s[k]);if(r&&/^[a-z0-9]{1,20}$/.test(k))n+=r.st;}if(n){o.old=n;o.noted=0;}}} + if(cur){o.old=j.old==null?null:int(j.old,0,9999,0)||null;o.noted=j.noted?1:0;if(o.old==null)o.noted=1;} if(j.wk&&typeof j.wk==='object')for(const k of Object.keys(j.wk)){const r=rec(j.wk[k]);if(/^\d{4}-W\d{2}$/.test(k)&&r)o.wk[k]=r;} const st=j.streak;if(st&&typeof st==='object'){o.streak.last=typeof st.last==='string'&&/^\d{4}-W\d{2}$/.test(st.last)?st.last:null;o.streak.n=int(st.n,0,9999,0);o.streak.best=int(st.best,0,9999,0);} return o;} @@ -19,7 +32,7 @@ function pzLoad(){try{return pzClean(JSON.parse(localStorage.getItem(PZ_KEY)||'{ function pzStore(p){try{localStorage.setItem(PZ_KEY,JSON.stringify(p));}catch(e){}} const pzStarsTotal=p=>PZ.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0); const pzPackOpen=(k,p)=>{const P=PZ_PACKS.find(x=>x.id===k);return !!P&&pzStarsTotal(p||pzLoad())>=P.need;}; -// ---------- prices: the real game's waves, on day 0, for a year ---------- +// ---------- prices: the real game's waves and routers, on day 0, for a year ---------- const pzMood=(a,b,sub)=>{const k=waveMarket(a,b,sub);return k.m/k.ero;}; // Overland (when the two cities share a landmass) and every cable between them, each with its price factor and latency. function pzRoutes(a,b){const out=[],sub=isSub(a,b); @@ -29,53 +42,72 @@ function pzRoutes(a,b){const out=[],sub=isSub(a,b); 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*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;} +// 10G to 800G: an 800G wave needs an 800G router at both ends, as in the main game. +const PZ_TIERS=[0,1,2,3]; +// Router models on offer: the main game's catalogue up to its level-3 gear, cheapest class first. +const PZ_RG=RG.map((r,i)=>i).filter(i=>RG[i].lvl<=3).sort((a,b)=>RG[a].cls-RG[b].cls||RG[a].cost-RG[b].cost); +// A POP's routers for a year: the chassis (the first Rusty Router is free), each extra one as the main game prices it +// (#157 cages included), and their rent. +function pzRtCost(g,rt){let s=Math.round(RG[g].cost*hwMul('rt'));for(let k=1;k{const p=S.pops[c];return p?pzRtCost(p.rgen||0,p.routers||1):0;}; +function pzSpend(){let s=0;for(const c in S.pops)s+=pzPopCost(c)+pzRouterCost(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 // as a whole, as in the main game's diversity checks). const pzUnit=l=>l.cable?'cab:'+l.cable:String(l.trench||l.id); +// ---------- the traffic ---------- +// Origins are transit ports the size of a content farm; circuits are L2VPN customers; eyeballs come with their POP. +const PZ_NET='lvl',PZ_ORIG=5; +const pzFlowId=i=>'pzf'+i; +const pzFlowName=f=>f.t==='l2'?tr('puzzles.flow_circuit_a_b',{a:CITY[f.a].name,b:CITY[f.b].name}):tr('puzzles.flow_eyeballs_in_city',{city:CITY[f.a].name}); +function pzDemand(){const P=S.pz;S.transit=P.src.map((c,i)=>({id:'pzo'+i,city:c,net:PZ_NET,tier:PZ_ORIG,n:1,pz:1,pref:'normal',hist:[]})); + S.biz=P.dem.map((f,i)=>f.t==='l2'?{id:pzFlowId(i),type:'l2vpn',name:pzFlowName(f),city:f.a,city2:f.b,bw:f.g,rate:0,route:'normal',reqs:[],day:0}:null).filter(Boolean);} +const pzEye=c=>{const f=pzOn()&&S.pz.dem.find(x=>x.t==='eye'&&x.a===c);return f?f.g:0;}; +const pzNewPop=c=>{const g=pzEye(c);return {day:0,bb:g?{d:g}:null,boost:0,down:0,routers:1,gen:false};}; +// What each flow gets from the last compute(): Gbps delivered, and a circuit's latency. +// Eyeball traffic to networks behind the Great Firewall loses a fifth at the border, as in the main game; that is not +// the player's doing, so a puzzle counts what crosses the border as delivered (pzGfw: the share that arrives). +let PZ_GFW=null;const pzGfw=()=>PZ_GFW||(PZ_GFW=1-0.2*NETS.filter(n=>n.cn).reduce((a,n)=>a+(NSH[n.id]||0),0)); +function pzGot(){return S.pz.dem.map((f,i)=>f.t==='l2'?{g:R.l2[pzFlowId(i)]||0,ms:isFinite(R.l2lat[pzFlowId(i)])?R.l2lat[pzFlowId(i)]:null}:{g:S.pops[f.a]?(R.citySrv[f.a]||0)/pzGfw():0,ms:null});} +const pzFull=(f,x)=>x.g>=f.g*0.999-1e-6; +const pzFast=(f,x)=>!f.ms||(x.ms!=null&&x.ms<=f.ms+1e-9); // ---------- 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;} function pzRingOk(ls){const nb={};for(const l of ls){(nb[l.a]=nb[l.a]||new Set()).add(l.b);(nb[l.b]=nb[l.b]||new Set()).add(l.a);} const ns=Object.keys(nb);if(ns.length<3||!S.pz.cities.every(c=>nb[c])||!Object.keys(S.pops).every(c=>nb[c])||!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 cur===ns[0]&&n===ns.length;} -function pzEval(){const P=S.pz,ls=S.links,cs=P.cities,spend=pzSpend(); - // The checklist ticks the goal cities that are already joined up: the group holding the most of them. - let best=new Set();for(const c of cs){if(!S.pops[c]||best.has(c))continue;const g=pzComp(ls,null,c);if(cs.filter(x=>g.has(x)).length>cs.filter(x=>best.has(x)).length)best=g;} - const joined=cs.filter(c=>best.has(c)).length>=2?best:new Set(); - const marks=cs.map(c=>({c,st:joined.has(c)?2:S.pops[c]?1:0})); - const conn=cs.every(c=>joined.has(c)); +// The same build always gets the same answer, so pzEval() keeps the last one (it routes once, then once per cut). +const pzSig=()=>JSON.stringify([S.pops,S.links,S.pairMet||null,S.biz.map(b=>b.route),S.pz.budget]); +/* ⭐ every flow delivered in full (circuits within their latency cap), and the twists; ⭐⭐ the year's spend within + budget; ⭐⭐⭐ N-1 under load: whichever single trench or cable is cut, every priority flow still gets all of its traffic + (best-effort flows may drop). The cut is routed by compute() like the real thing. */ +function pzEval(){const sig=pzSig(),c0=UI.pzEv;if(c0&&c0.sig===sig)return c0.e; + const P=S.pz,hot=UI.hotMap;compute();const R0=R,got=pzGot(),spend=pzSpend(),peak={},pk=()=>{for(const c in R.nodeLoad)peak[c]=Math.max(peak[c]||0,R.nodeLoad[c]);};pk(); + const flows=P.dem.map((f,i)=>({f,i,g:got[i].g,ms:got[i].ms,full:pzFull(f,got[i]),fast:pzFast(f,got[i])})); const tw=[];if(P.noSub)tw.push({k:'sub',ok:!S.links.some(l=>l.sub)}); - if(P.ring)tw.push({k:'ring',ok:pzRingOk(ls)}); - if(P.lat){const ms=S.pops[P.lat[0]]&&S.pops[P.lat[1]]?bestLat(P.lat[0],P.lat[1]):Infinity;tw.push({k:'lat',ok:ms<=P.lat[2],ms});} - if(P.minG)tw.push({k:'g',ok:ls.every(l=>LT[l.tier].g>=P.minG)}); + if(P.ring)tw.push({k:'ring',ok:pzRingOk(S.links)}); 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 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};} -// 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;} + const del=flows.every(x=>x.full&&x.fast),goal=del&&tw.every(t=>t.ok),units=[...new Set(S.links.map(pzUnit))],cuts=[]; + if(goal)try{for(const u of units){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1; + try{compute();pk();const g=pzGot(),lost=[];P.dem.forEach((f,i)=>{if(!f.be&&!pzFull(f,g[i]))lost.push({i,g:Math.max(0,f.g-g[i].g)});});if(lost.length)cuts.push({u,lost,g:lost.reduce((a,x)=>a+x.g,0)});} + finally{for(const l of ls)l.cut=0;}}} + finally{R=R0;UI.hotMap=hot;} + cuts.sort((a,b)=>b.g-a.g); + const n1=goal&&units.length>0&&!cuts.length,cheap=!P.budget||spend<=P.budget; + const e={flows,del,tw,goal,spend,cheap,n1,weak:cuts.map(x=>x.u),worst:cuts[0]||null,peak,stars:goal?1+(cheap?1:0)+(n1?1:0):0}; + UI.pzEv={sig,e};return e;} // ---------- 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.lengthkmBetween(u,a)-kmBetween(u,b));ring.push(left.shift());} 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};} + const g=Math.floor(9/(n-1)),dem=cities.slice(1).map(c=>({t:'eye',a:c,g})); + return {id:'weekly',key,cities,src:[cities[0]],dem,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 ---------- @@ -85,16 +117,18 @@ const pzToastsClear=()=>{$('toasts').textContent='';}; // (leaving the page mid-puzzle), and leaving the puzzle picks it up again. function pzFlush(){save(true);UI.pzKeep=S;} function pzBegin(def){if(!def)return; - 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,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; + const go=()=>{const cs=pzCities(def);newGame(pzName(def),cs[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null; + S.pz={id:def.id,key:def.key||null,cities:cs,src:(def.src||[]).slice(),dem:def.dem.map(f=>({t:f.t,a:f.a,b:f.t==='l2'?f.b:null,g:f.g,ms:f.ms||0,be:!!f.be})), + via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null}; + pzDemand(); + UI.pzHist=[];UI.pzTop=0;UI.pzEv=null;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();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');}; + toast(`${esc(pzName(def))}
${tr('puzzles.carry_list',{list:S.pz.dem.map(f=>`${esc(pzFlowName(f))} ${fmtG(f.g)}`).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;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; +function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null; if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} // It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told. @@ -106,8 +140,7 @@ function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0]. const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();} // ---------- building ---------- -function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links}));if(h.length>60)h.shift();} -const pzNewPop=()=>({day:0,bb:null,boost:0,down:0,routers:1,gen:false}); +function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();} function 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. diff --git a/src/game/60-features/93-puzzles-weekly.js b/src/game/60-features/93-puzzles-weekly.js index b262164..6b580e6 100644 --- a/src/game/60-features/93-puzzles-weekly.js +++ b/src/game/60-features/93-puzzles-weekly.js @@ -41,18 +41,29 @@ function pzWkTxt(o,list){if(!pzObj(o)||typeof o.l!=='string'||!list.includes(o.l 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 PZ_WK_FIELDS=['v','key','theme','cities','src','dem','via','avoid','budget','twist','name','joke','ref']; +// Schema 2 (puzzles with traffic): `src` the content origins, `dem` the flows ({t:'eye',a,g} eyeballs in a; {t:'l2',a,b,g,ms} +// a circuit, ms its latency cap; be:true best effort), `cities` exactly the cities they touch. Older files are refused. +const PZ_WK_V=2; +function pzWkDem(a){if(!Array.isArray(a)||a.length<1||a.length>6)return null;const out=[],eye=new Set(); + for(const f of a){if(!pzObj(f)||Object.keys(f).some(k=>!['t','a','b','g','ms','be'].includes(k))||!pzCityOk(f.a)||!Number.isInteger(f.g)||f.g<1||f.g>2000)return null; + if(own(f,'be')&&f.be!==true)return null; + if(f.t==='eye'){if(own(f,'b')||own(f,'ms')||eye.has(f.a))return null;eye.add(f.a);out.push({t:'eye',a:f.a,g:f.g,be:!!f.be});} + else if(f.t==='l2'){if(!pzCityOk(f.b)||f.b===f.a||(own(f,'ms')&&!(typeof f.ms==='number'&&isFinite(f.ms)&&f.ms>=1&&f.ms<=500)))return null;out.push({t:'l2',a:f.a,b:f.b,g:f.g,ms:f.ms||0,be:!!f.be});} + else return null;} + return out;} +function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==PZ_WK_V||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 cities=ids(j.cities,2,6),src=ids(j.src==null?[]:j.src,0,3),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2),dem=pzWkDem(j.dem);if(!cities||!src||!via||!avoid||!dem)return null; + // Eyeballs need somewhere to pull from; an origin is not also a city of eyeballs. + if(dem.some(f=>f.t==='eye')&&!src.length||dem.some(f=>f.t==='eye'&&src.includes(f.a)))return null; + const d0={src,dem},cs=pzCities(d0);if(cs.length!==cities.length||!cs.every(c=>cities.includes(c)))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(!Number.isInteger(j.budget)||j.budget<50000||j.budget>2e7)return null; + const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['ring','noSub'].includes(k)))return null; + const d={id:'weekly',key,theme:j.theme,cities,src,dem,via,avoid,budget:j.budget,noSub:false,ring:false}; 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 ---------- diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 0efe713..32e9458 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/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index 26f158e..a874829 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -1,3 +1,7 @@ +// Can a wave of this size be lit between a and b here? Router ports and models as in the main game; a city without a +// POP yet will get a Rusty Router. +function pzWaveWhy(a,b,tier,r){if(r&&subWaveWhy(tier,r.km,r.sub))return tr('common.too_far_for_this_cable');if(!waveOk(a,b,tier))return tr('puzzles.needs_what',{what:waveNeed(tier)});return '';} +const pzPortsFree=c=>!S.pops[c]||portsUsed(c)+1<=portsMax(c)+1e-9; Object.assign(ACT,{ // The puzzle list. The ruleset's title-screen door calls this. puzzleMenu:()=>{if(S&&UI.started&&!pzOn())UI.nm=S.name;pzMenu();}, @@ -5,27 +9,47 @@ Object.assign(ACT,{ 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();}, + pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via','off'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop(city);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);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, pzLinkTo:({a,b})=>{if(!pzOn()||!S.pops[a]||a===b)return;pzLinkModal(a,b);}, pzVia:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzVia=v;pzLinkModal(p.a,p.b,true);}, pzDiv:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzDiv=!!+v;pzLinkModal(p.a,p.b,true);}, - pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!PZ_TIERS.includes(tier))return;const {a,b}=p;if(!S.pops[a]||!['goal','via'].includes(pzKind(b)))return; - const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))return; - const same=!r.sub&&UI.pzDiv===false?S.links.find(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):null,div=!r.sub&&!same&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable); - pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop();const id=uid(),f=r.f*(div?DIVERSE:1); - S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:same?(same.trench||same.id):id,cut:0,day:0}); + pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!PZ_TIERS.includes(tier))return;const {a,b}=p,kb=pzKind(b);if(!S.pops[a]||!['goal','via','off'].includes(kb))return; + const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub))return; + const why=pzWaveWhy(a,b,tier,r);if(why){toast(esc(why),'bad');sfx('err');return;} + if(!portGate(a,1)||(S.pops[b]&&!portGate(b,1)))return; + // Overland: the same trench as a link already on the pair (the one picked from, or the first), or a diverse route + // of its own. Every trench but the first runs the long way round and costs 40% more. + const lands=pzOn()&&!r.sub?S.links.filter(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):[],t0=lands.length?pzUnit(lands[0]):null; + const same=UI.pzDiv===false&&lands.length?(lands.find(l=>pzUnit(l)===UI.pzTrench)||lands[0]):null,trench=same?pzUnit(same):null,div=!!t0&&trench!==t0; + pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop(b);const id=uid(),f=r.f*(div?DIVERSE:1); + S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:trench||id,cut:0,day:0}); closeModal();sfx('build');haptic(12);floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');UI.sel=null;pzAfter();}, - pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!PZ_TIERS.includes(tier)||l.tier===tier||subWaveWhy(tier,l.km,l.sub))return;pzSnap();l.tier=tier;l.mo=pzMo({km:l.km,sub:l.sub,f:l.mult||1},tier,false);sfx('build');pzAfter();}, - pzRmLink:({id})=>{if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();S.links=S.links.filter(l=>l.id!==id);sfx('click');UI.sel=null;pzAfter();}, - pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;sfx('click');pzAfter();}, - pzReset:()=>{if(!pzOn())return;pzSnap();S.pops={};S.links=[];UI.sel=null;sfx('click');pzAfter();}, + // Another link next to this one: the picker opens on the same pair, on the same route, in the same trench or a diverse one. + pzAddPar:({id,div})=>{const l=pzOn()&&S.links.find(x=>x.id===id);if(!l)return;UI.pzVia=l.cable||'land';UI.pzDiv=!!+div;UI.pzTrench=l.cable?null:pzUnit(l); + if(+div&&l.cable){const o=pzRoutes(l.a,l.b).find(x=>x.via!==l.cable&&!(S.pz.noSub&&x.sub));if(o)UI.pzVia=o.via;} + pzLinkModal(l.a,l.b,true);}, + pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!PZ_TIERS.includes(tier)||l.tier===tier)return;const why=pzWaveWhy(l.a,l.b,tier,{km:l.km,sub:l.sub});if(why){toast(esc(why),'bad');sfx('err');return;} + pzSnap();l.tier=tier;l.mo=pzMo({km:l.km,sub:l.sub,f:l.mult||1},tier,false);sfx('build');pzAfter();}, + pzRmLink:({id})=>{if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();S.links=S.links.filter(l=>l.id!==id);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, + // Routers: one more of the same model, one fewer, or every router in the POP swapped for another model. + pzRtAdd:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;pzSnap();p.routers=(p.routers||1)+1;sfx('build');floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');pzAfter();}, + pzRtRm:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;} + pzSnap();p.routers--;sfx('click');pzAfter();}, + pzRtModel:({city,g})=>{g=+g;const p=pzOn()&&S.pops[city];if(!p||!PZ_RG.includes(g)||g===(p.rgen||0))return;const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;} + pzSnap();p.rgen=g;sfx('build');floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');pzAfter();}, + // A circuit follows the metrics (the IGP's shortest path) or takes the lowest-latency path, as customers can in the main game. + pzRoute:({i,m})=>{const b=pzOn()&&S.biz.find(x=>x.id===pzFlowId(+i));if(!b||!['normal','fast'].includes(m)||b.route===m)return;pzSnap();b.route=m;sfx('click');pzAfter();}, + pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};(o.r||[]).forEach((m,i)=>{if(S.biz[i])S.biz[i].route=m;});sfx('click');pzAfter();}, + pzReset:()=>{if(!pzOn())return;pzSnap();S.pops={};S.links=[];S.pairMet={};for(const b of S.biz)b.route='normal';UI.sel=null;sfx('click');pzAfter();}, pzShare:()=>{if(!pzOn())return;const t=pzShareText(pzEval()); 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);} +// open anything in it. Everything but these and the pz* actions does nothing while a puzzle is on. The main game's +// routing controls (metric, standby, the redundancy check) work in a puzzle too, and their changes can be undone. +// 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','linkCheck','menu','metricMode','metricSet','mute','prefSet','puzzleDoor','puzzleMenu','selLink','setMetric','setStandby','settings','settingsClose','soundSet','speed','updateLater','updateNow','vpSet','whatsNewShow']); +const PZ_UNDO=new Set(['metricMode','metricSet','setMetric','setStandby']); +for(const k of Object.keys(ACT)){const f=ACT[k];if(PZ_UNDO.has(k))ACT[k]=a=>{if(pzOn())pzSnap();return f(a);};else if(!PZ_ACTS.has(k)&&!/^pz[A-Z]/.test(k))ACT[k]=a=>pzOn()?undefined:f(a);} diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index dc45fdf..037c77d 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -1,62 +1,103 @@ /* ---------- puzzles: the card, the panels, the link picker, the results and the list ---------- */ -const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫'}; -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}); - 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&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} +const PZ_ICON={goal:'🎯',via:'🪨',avoid:'🚫',off:'📍'}; +function pzTwistTxt(t){if(t.k==='sub')return tr('puzzles.no_subsea_cables');return tr('puzzles.one_ring_through_every_pop');} +// The short version, for the puzzle list: what has to be carried, and the twists. +function pzDemTag(d){const t=[];const eye=d.dem.filter(f=>f.t==='eye'),l2=d.dem.filter(f=>f.t==='l2'); + if(eye.length)t.push(tr('puzzles.n_g_of_eyeballs',{n:fmtG(eye.reduce((a,f)=>a+f.g,0))}));if(l2.length)t.push(trn('puzzles.n_circuits',l2.length)); + if(d.dem.some(f=>f.ms))t.push(tr('puzzles.latency_caps'));if(d.noSub)t.push(tr('puzzles.no_subsea'));if(d.ring)t.push(tr('puzzles.ring'));if(d.avoid&&d.avoid.length)t.push(tr('puzzles.avoid_list',{list:d.avoid.map(c=>CITY[c].name).join(', ')}));return t;} // 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)+')':''}`;}; +// Each flow on the card: what it is, how much of it arrives, and a circuit's latency against its cap. +function pzFlowRow(x){const f=x.f,ok=x.full&&x.fast,u=f.g?Math.min(1,x.g/f.g):0; + const lat=f.ms?` · ${x.ms==null?tr('common.no_path'):x.ms.toFixed(1)+' ms'} / ${f.ms} ms`:''; + return `
${f.t==='l2'?'🔗':'👀'} ${esc(pzFlowName(f))}${f.be?` ${tr('puzzles.best_effort')}`:''}${fmtG(x.g)} / ${fmtG(f.g)}
${lat?`
${tr('puzzles.latency')}${lat}
`:''}${f.t==='l2'?pzRouteCtl(x.i):''}
`;} +// A circuit's path: the metrics, or the lowest latency. +function pzRouteCtl(i){const b=S.biz.find(x=>x.id===pzFlowId(i));if(!b)return '';return `
${['normal','fast'].map(m=>btn(RT[m],'pzRoute',{i,m},b.route===m?'pink sm':'ghost sm')).join('')}
`;} 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):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')}
`; - // ○ 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('')}
`; + h+=`
${star(e.goal,tr('puzzles.delivered'))}${star(e.goal&&e.cheap,P.budget?tr('puzzles.budget'):tr('puzzles.free'))}${star(e.goal&&e.n1,'N-1')}
`; + if(P.src.length)h+=`
🗄️ ${tr('puzzles.content_lives_in_list',{list:P.src.map(c=>esc(CITY[c].name)).join(', ')})}
`; + h+=`
${e.flows.map(pzFlowRow).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); 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])})}${pzOneMore(e)?`
${tr('puzzles.so_close_one_more_link_and')}`:''}
`; + const w=e.worst; + h+=!e.goal?`
🛡 ${tr('puzzles.n_1_deliver_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut_under_load')}
` + :`
⚠️ ${tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(w.u),g:fmtG(w.g)})}
${w.lost.map(x=>esc(pzFlowName(P.dem[x.i]))).join(', ')}
`; 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);}} +// Trenches on a pair get numbers, cables their names, so parallel links say where they run. +function pzTrench(l){if(l.cable)return esc(CAB[l.cable].name);const us=[...new Set(pairLinks(l.a,l.b).filter(x=>!x.cable).map(pzUnit))];return tr('puzzles.trench_n',{n:us.indexOf(pzUnit(l))+1});} +const pzLoadTxt=l=>`${fmtG(R.load[l.id]||0)} / ${fmtG(capOf(l))}`; +function pzPopSection(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1,G=RG[g],cap=nodeCap(c),ld=R.nodeLoad[c]||0,u=cap?ld/cap:0,pu=portsUsed(c),pm=portsMax(c),cur=pzRtCost(g,rt); + const dl=v=>(v>=0?'+':'−')+fmt$(Math.abs(v)); + let h=`

${tr('puzzles.your_pop')}

${rt>1?rt+' × ':''}${esc(G.n)}${tr('puzzles.price_per_year',{price:fmt$(cur)})}
+
${tr('puzzles.router_load')}${fmtG(ld)} / ${fmtG(cap)}
+
${tr('puzzles.ports')}${tr('puzzles.u_of_m_used',{u:fmtPorts(pu),m:pm})}
${tr('puzzles.biggest_wave')}${LT[G.maxLT].n}
+
${btn(tr('puzzles.add_a_router_cost',{cost:dl(pzRtCost(g,rt+1)-cur)}),'pzRtAdd',{city:c},'sm',rt>=RMAX)}${rt>1?btn(tr('puzzles.remove_a_router'),'pzRtRm',{city:c},'ghost sm'):''}
+

${tr('puzzles.router_model')}

`; + h+=PZ_RG.map(i=>{const M=RG[i],why=i===g?'':modelFits(c,i);return `
${esc(M.n)}${i===g?` ${tr('puzzles.installed')}`:''}
${tr('puzzles.model_facts',{cap:fmtG(M.cap),ports:M.ports,wave:LT[M.maxLT].n})}
${why?`
${esc(why)}
`:''}
${i===g?'':btn(dl(pzRtCost(i,rt)-cur),'pzRtModel',{city:c,g:i},'ghost sm',!!why)}
`;}).join(''); + return h;} function pzPanel(sel){const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; - if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c];if(!k)return ''; - const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):tr('puzzles.off_limits'); + if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c],P=S.pz;if(!k)return ''; + const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):k==='off'?tr('puzzles.not_in_the_plan'):tr('puzzles.off_limits'); let h=head(`${PZ_ICON[k]} ${eb}`,esc(C.name),p?`${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$(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(''); - h+=`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`;} + // What this city sends or asks for. + const fl=P.dem.map((f,i)=>({f,i})).filter(({f})=>f.a===c||f.b===c),ev=pzEval(); + if(P.src.includes(c))h+=`

🗄️ ${tr('puzzles.the_content_origin_lives_here')}

`; + if(fl.length)h+=`
${fl.map(({i})=>pzFlowRow(ev.flows[i])).join('')}
`; + if(k==='off'&&!p)h+=`

${tr('puzzles.no_traffic_starts_or_ends_here')}

`; + if(!p)return 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')}
`; + h+=pzPopSection(c); + // Every pair this POP has links on, with what each member carries, so a second link is never a guess. + const nb=[...new Set(S.links.filter(l=>l.a===c||l.b===c).map(l=>l.a===c?l.b:l.a))]; + h+=`

${tr('common.links')}

`; + if(!nb.length)h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

`; + for(const x of nb){const ls=pairLinks(c,x),ld=ls.reduce((a,l)=>a+(R.load[l.id]||0),0),cp=ls.filter(l=>!linkDown(l)).reduce((a,l)=>a+capOf(l),0); + h+=`
${esc(CITY[x].name)} · ${groupLabel(ls,ls)}${fmtG(ld)} / ${fmtG(cp)}
${ls.map(l=>`
${capName(l)} · ${pzTrench(l)}${l.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(l)} · ${linkLat(l).toFixed(1)} ms
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`).join('')}
`;} + const others=[...P.cities,...P.via].filter(x=>x!==c); + h+=`

${tr('puzzles.lease_a_wave_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}

${tr('puzzles.or_drag_to_any_city_on_the_map')}

`; + h+=`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`; return h+'
';} - const l=S.links.find(x=>x.id===sel.id);if(!l)return ''; + const l=S.links.find(x=>x.id===sel.id);if(!l)return '';const pl=pairLinks(l.a,l.b); let h=head(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`${capName(l)}${l.km.toLocaleString()} km${linkLat(l).toFixed(1)} ms${tr('puzzles.price_per_year',{price:fmt$(l.mo*PZ_YEAR)})}`)+'
'; - h+=`

${tr('puzzles.size')}

${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=subWaveWhy(i,l.km,l.sub);return btn(`${LT[i].n} ${tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
`; + // What it carries now: each circuit by name, the eyeball traffic by where it is going. + {const rec=R.ef[edgeKey(l)],u=capOf(l)?(R.load[l.id]||0)/capOf(l):0;h+=`
${tr('puzzles.this_link')}${pzLoadTxt(l)}
`; + if(rec){const rows=[];let l2=0;S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){rows.push([pzFlowName(f),v]);}}); + const byc={};for(const k in rec.dst)byc[k]=rec.dst[k];S.pz.dem.forEach((f,i)=>{const v=rec.eg['l2:'+pzFlowId(i)];if(v>0.01){byc[f.b]=(byc[f.b]||0)-v;l2+=v;}}); + for(const k in byc)if(byc[k]>0.01)rows.push([tr('puzzles.flow_eyeballs_in_city',{city:CITY[k].name}),byc[k]]); + if(rows.length)h+=`

${pl.length>1?tr('puzzles.carrying_on_this_pair',{n:pl.length}):tr('puzzles.carrying')}

`+rows.map(([n,v])=>`
${esc(n)}${fmtG(v)}
`).join('');void l2;}} + if(pl.length>1)h+=`

${tr('puzzles.n_links_on_this_pair',{n:pl.length,what:groupLabel(pl,pl)})}

`+pl.map(x=>`
${capName(x)} · ${pzTrench(x)}${x.standby?' · '+tr('common.standby'):''} · ${pzLoadTxt(x)}
${x===l?'':btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join(''); + h+=`

${tr('puzzles.size')}

${PZ_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=pzWaveWhy(l.a,l.b,i,r);return btn(`${LT[i].n} ${why?esc(why):tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
`; + h+=`

${tr('puzzles.add_another_link_here')}

${btn(l.cable?tr('puzzles.another_wave_on_this_cable'):tr('puzzles.same_trench_cheaper'),'pzAddPar',{id:l.id,div:0},'sm')}${btn(l.cable?tr('puzzles.a_different_route'):tr('puzzles.a_diverse_route'),'pzAddPar',{id:l.id,div:1},'pink sm')}
`; + h+=metricSection(l)+linkCheckControl(l); return h+`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} // The link picker: overland or one of the real cables between the two cities, and a size. Prices are for a year. function pzLinkModal(a,b,keep){const kb=pzKind(b); - if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.that_city_is_not_part_of'),'bad');sfx('err');return;} - if(!keep){UI.pzVia=null;UI.pzDiv=true;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz; + if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.not_a_city_you_can_build_in'),'bad');sfx('err');return;} + if(!keep){UI.pzVia=null;UI.pzDiv=true;UI.pzTrench=null;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz; const head=`
${kmBetween(a,b).toLocaleString()} km

${esc(CITY[a].name)} → ${esc(CITY[b].name)}

`; if(!rs.length){openModal(head+`

${tr('puzzles.no_cable_lands_in_both_try',{a:esc(CITY[a].name),b:esc(CITY[b].name)})}

`);return;} const r=rs.find(x=>x.via===UI.pzVia)||rs.find(x=>!(P.noSub&&x.sub))||rs[0];UI.pzVia=r.via; - const land=!r.sub&&S.links.some(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b); - let h=head+`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${x.cab&&CAB[x.cab].age==='old'?'':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}
`; + const pl=pairLinks(a,b),land=!r.sub&&pl.some(l=>!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b); + let h=head; + if(pl.length)h+=`

${tr('puzzles.already_here_list',{list:groupLabel(pl,pl)+' · '+[...new Set(pl.map(pzTrench))].join(', ')})}

`; + h+=`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}
`; if(P.noSub&&r.sub)h+=`

${tr('puzzles.the_sharks_say_no')}

`; - if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}

`; + if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}

`; if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; - h+=`
${PZ_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),c=pzLinkCost(r,i,div)+pop;return ``;}).join('')}
`; + const full=[a,b].filter(c=>!pzPortsFree(c));if(full.length)h+=`

${tr('puzzles.no_free_ports_in_list',{list:full.map(c=>esc(CITY[c].name)).join(', ')})}

`; + h+=`
${PZ_TIERS.map(i=>{const why=pzWaveWhy(a,b,i,r),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?(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');} +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');} // 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=''; @@ -67,7 +108,7 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left 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)}

${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'))} + ${row(true,tr('puzzles.delivered'),tr('puzzles.every_bit_arrives'))}${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_under_load'):tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(e.worst.u),g:fmtG(e.worst.g)}))}
${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(_){}} @@ -75,19 +116,21 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);} // ---------- the list ---------- // 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); +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=pzDemTag(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)}):''}
+
${pzCities(w).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)})}
`:''}
`; + let h=`
${tr('puzzles.puzzles')}

${tr('puzzles.small_networks_real_traffic')}

+

${tr('puzzles.no_clock_no_bills_real_traffic')}

`; + // Once, after the puzzles got traffic: the old stars are kept on the wall, the new set starts at zero. + if(p.old&&!p.noted){h+=`
🖼️ ${tr('puzzles.puzzles_got_traffic_note',{n:p.old})}
`;p.noted=1;pzStore(p);} + h+=`
${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}${p.old?`
🖼️ ${tr('puzzles.framed_n_stars_from_the_old',{n:p.old})}
`:''}
`; 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+=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); - h+=`
${esc(d.n)} ${pzStarStr(r?r.st:0)}
${esc(d.j)}
${d.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · '+tg.join(' · ')+'':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}
${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}
`;}} + for(const d of PZ.filter(x=>x.pack===pk.id)){const r=p.s[d.id],tg=pzDemTag(d); + h+=`
${esc(d.n)} ${pzStarStr(r?r.st:0)}
${esc(d.j)}
${pzCities(d).map(c=>esc(CITY[c].name)).join(' · ')} · ${d.budget?tr('puzzles.budget_x',{x:fmt$(d.budget)}):tr('puzzles.no_budget')}${tg.length?' · '+tg.join(' · ')+'':''}${r&&r.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(r.sp)}):''}
${btn(tr('common.play'),'pzStart',{id:d.id},r&&r.st>=3?'ghost':'',!open)}
`;}} openModal(h);} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index de49bd3..f82dee0 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -28,7 +28,7 @@ function drawFrame(now){ const far=lodFar(),PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),busy=linesOnScreen(GM,ks)>MAP_BUSY; for(let gi=0;gi1,up=many?grp.filter(x=>!linkDown(x)):null; const gm=GM[gi],cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); - const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id);let lab=null; + const pz=pzOn(),sel=(UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id))||(pz&&pzLinkHot(grp));let lab=null; const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1),np=gm.pts.length; if(SX.length0.9&&!busy)){const t=lab||(lab=many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} + else if(sel||pz||(z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} } } // drag preview diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js index 3c2a0f0..954a64a 100644 --- a/src/game/96-map/85-puzzle-cities.js +++ b/src/game/96-map/85-puzzle-cities.js @@ -1,10 +1,16 @@ -/* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring, stepping stones with a dashed one, cities to - avoid crossed out); every other city stays on the map, faded and untappable. */ +/* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring and a badge for what they send or ask for, + stepping stones with a dashed one, cities to avoid crossed out); every other city is on the map as usual, open to + build in but not emphasised. */ +function pzBadge(c){const P=S.pz;return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';} function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); - if(!k){ctx.save();ctx.globalAlpha=0.3;drawCity(v.C,v.sx,v.sy,sc,now,null);ctx.restore();return;} + if(!k||k==='off'){drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);return;} const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc),p=S.pops[v.C.id]; ctx.save();ctx.lineWidth=3; if(k==='avoid'){ctx.strokeStyle='#FF4D5E';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.moveTo(v.sx-r*.7,y-r*.7);ctx.lineTo(v.sx+r*.7,y+r*.7);ctx.stroke();} else{const a=animOn()?.55+.35*Math.sin(now/300):.8;ctx.strokeStyle=k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(k==='via')ctx.setLineDash([5,5]); ctx.fillStyle=k==='goal'&&!p?'rgba(255,210,63,.35)':'rgba(255,255,255,.25)';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.fill();ctx.stroke();ctx.setLineDash([]);} - ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);} + ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly); + const b=k==='goal'&&!CM.far?pzBadge(v.C.id):'';if(b){ctx.font=`${Math.round(15*sc)}px sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(b,v.sx+r*.75,y-r*.75);}} +// In a puzzle every line says what it is ("2×100G · 70%"), and a selected POP lights up every pair it has links on. +function pzLinkLab(grp,up,load,cap){return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');} +const pzLinkHot=grp=>!!(UI.sel&&UI.sel.type==='city'&&grp.some(x=>x.a===UI.sel.id||x.b===UI.sel.id)); diff --git a/src/i18n/en.js b/src/i18n/en.js index c8236d6..ac08026 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2907,56 +2907,79 @@ "progress.your_score_peak_traffic":"Your score: peak traffic", "progress.your_traffic_to_and_from_asia":"Your traffic to and from Asia", "puzzles.a_backhoe_walks_into_your_network":"A backhoe walks into your network. Nothing happens.", +"puzzles.a_bigger_boat":"A Bigger Boat", +"puzzles.a_cut_on_where_drops_g":"A cut on {where} drops {g}", +"puzzles.a_different_route":"A different route", +"puzzles.a_diverse_route":"A diverse route (+40%)", "puzzles.a_pop_costs_setup_plus_a_year":"A POP costs {setup} to set up, then {mo}/mo. Puzzles count the setup and a year of rent.", -"puzzles.a_tiny_island_where_half_the":"A tiny island where half the Pacific's cables stop for coffee.", -"puzzles.a_to_b_under_ms":"{a} → {b} under {ms} ms", -"puzzles.a_to_b_under_ms_now":"{a} → {b} under {ms} ms (now {now} ms)", -"puzzles.aloha_latency":"Aloha Latency", +"puzzles.add_a_router_cost":"Add a router {cost}/yr", +"puzzles.add_another_link_here":"Add another link on this pair", +"puzzles.all_of_europe_s_cat_videos":"All of Europe's cat videos live in London, and every one of them goes through your router.", +"puzzles.already_here_list":"Already on this pair: {list}", +"puzzles.another_wave_on_this_cable":"Another wave on this cable", "puzzles.avoid_list":"avoid {list}", "puzzles.back_to_my_network":"Back to my network", "puzzles.back_to_the_title":"Back to the title screen", -"puzzles.beat_the_clock_light_in_glass":"Light in glass does 200 km per millisecond. Pick your cables like it matters.", +"puzzles.baltic_shortcut":"Baltic Shortcut", "puzzles.belt_and_braces":"Belt and Braces", +"puzzles.best_effort":"best effort", "puzzles.best_x":"best {x}", +"puzzles.biggest_wave":"Biggest wave", "puzzles.budget":"Budget", "puzzles.budget_x":"budget {x}", -"puzzles.connect_list":"Connect {list}.", -"puzzles.connected":"Connected", +"puzzles.capacity_first_every_link_has_a":"Capacity first: every link has a size, and the traffic has to fit. Roomy budgets, and the first two are on the house.", +"puzzles.carry_list":"Carry: {list}.", +"puzzles.carrying":"Carrying", +"puzzles.carrying_on_this_pair":"Carrying (all {n} links on this pair)", +"puzzles.content_lives_in_list":"Content lives in {list}: eyeballs pull from the nearest.", "puzzles.copied_paste_it_anywhere":"Copied! Paste it anywhere:
{t}", "puzzles.de_kicks_sales_has_your_number":"DE-KICKS sales has your number. Connect Germany without Frankfurt.", +"puzzles.delivered":"Delivered", "puzzles.diverse_route_40_survives_a_backhoe":"Diverse route (+40%, survives a backhoe)", "puzzles.down_under_up_and_running":"Down Under, Up and Running", "puzzles.drag_from_a_pink_pop_to":"Drag from a pink POP to another city to lease a wave", "puzzles.drag_from_this_pop_onto_another":"Drag from this POP onto another puzzle city, or pick one here.", +"puzzles.edge_lord":"Edge Lord", "puzzles.euro_trip":"Euro Trip", +"puzzles.every_bit_arrives":"every bit arrives", "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.everything_at_once_across_oceans":"Everything at once, across oceans. Tight budgets.", +"puzzles.fat_pipes":"Fat Pipes", +"puzzles.five_small_cities_one_small_router":"Five cities, a few gigs each, and a router with eight ports. Count before you dig.", +"puzzles.fjord_focus":"Fjord Focus", "puzzles.flash_boys":"Flash Boys", -"puzzles.for_architects_who_sleep_through_backhoes":"For architects who sleep through backhoe season.", -"puzzles.four_capitals_one_very_long_winter":"Four capitals, one very long winter, zero excuses for downtime.", +"puzzles.flow_circuit_a_b":"{a} ⇄ {b} circuit", +"puzzles.flow_eyeballs_in_city":"Eyeballs in {city}", "puzzles.four_cities_four_cables_one_ring":"Four cities, one ring. Tolkien would approve; your NOC definitely does.", "puzzles.four_cities_one_continent_and_a":"Four cities, one continent and a lot of corn between them.", +"puzzles.framed_n_stars_from_the_old":"Framed on the wall: {n} ⭐ from the old puzzles", "puzzles.frankfurt_to_singapore_the_short_way":"Frankfurt to Singapore the short way. The long way is overland, and it shows.", "puzzles.free":"Free", -"puzzles.goal":"Goal", "puzzles.goal_city":"Goal city", -"puzzles.guam_slam":"Guam Slam", +"puzzles.grand_tour":"Grand Tour", "puzzles.hello_world":"Hello, World", -"puzzles.honolulu_the_world_s_most_scenic":"Honolulu: the world's most scenic regeneration site.", +"puzzles.hub_cap":"Hub Cap", "puzzles.includes_a_new_pop_in_city":"Includes a new POP in {city} ({price} for a year).", +"puzzles.installed":"installed", "puzzles.it_works_finance_and_the_backhoe":"It works! Finance and the backhoe would like a word.", "puzzles.keep_building":"Keep building", "puzzles.kiwi_fruit_salad":"Kiwi Fruit Salad", +"puzzles.latency":"Latency", +"puzzles.latency_caps":"latency caps", "puzzles.lease_a_wave_to":"Lease a wave to", "puzzles.loading_this_week_s_puzzle":"Loading this week's puzzle…", +"puzzles.london_wants_half_a_terabit_your":"London wants half a terabit, and your routers came off eBuy.", +"puzzles.model_facts":"{cap} · {ports} ports · waves up to {wave}", "puzzles.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_1_deliver_everything_first":"N-1: deliver everything first", +"puzzles.n_circuits":{"one":"{n} circuit","other":"{n} circuits"}, +"puzzles.n_g_of_eyeballs":"{n} of eyeballs", +"puzzles.n_links_on_this_pair":"{n} links on this pair: {what}", "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.needs_what":"needs {what}", "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}⭐", @@ -2966,26 +2989,31 @@ "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.", -"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_clock_no_bills_real_traffic":"No clock, no bills, nothing breaks. Real traffic, routed like the real game: deliver every flow, stay under budget, and keep it all flowing when any one trench or cable is cut.", +"puzzles.no_free_ports_in_list":"No free router ports in {list}: add a router or a bigger model first.", "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.", +"puzzles.no_traffic_starts_or_ends_here":"No traffic starts or ends here. You can still build here, if it gets you somewhere.", +"puzzles.not_a_city_you_can_build_in":"You can't build in that city.", +"puzzles.not_in_the_plan":"Not in the plan", "puzzles.not_this_one_find_a_way_around":"Not this one. Find a way around.", "puzzles.not_through_frankfurt":"Not Through Frankfurt", "puzzles.off_limits":"Off limits", "puzzles.on_the_house":"On the house", "puzzles.one_backhoe_away_from_a_very":"One backhoe away from a very long night. Add a second path for ⭐⭐⭐.", -"puzzles.one_cut_splits_it":"One cut splits it", -"puzzles.one_cut_splits_it_where":"One cut splits it: {where}", "puzzles.one_ring_through_every_pop":"One ring through every POP", "puzzles.one_very_big_island_and_a":"One very big island, and a lot of very empty fiber.", "puzzles.open_a_pop_cost":"Open a POP · {cost}", -"puzzles.pacific_rim_shot":"Pacific Rim Shot", -"puzzles.ping_pong_to_tokyo":"Ping Pong to Tokyo", +"puzzles.or_drag_to_any_city_on_the_map":"Or drag to any city on the map: the whole world is open.", +"puzzles.paris_wants_150g_one_100g_wave":"Paris wants 150G. One 100G wave is a garden hose.", +"puzzles.port_authority":"Port Authority", +"puzzles.ports":"Ports", "puzzles.price_per_year":"{price}/yr", "puzzles.puzzle":"Puzzle", "puzzles.puzzle_solved":"Puzzle solved", "puzzles.puzzles":"Puzzles", +"puzzles.puzzles_got_traffic_note":"Puzzles got traffic! Every puzzle now carries real flows, so the stars start again. Your old {n} ⭐ are framed on the wall.", +"puzzles.remove_a_router":"Remove a router", "puzzles.remove_this_link":"Remove this link", "puzzles.remove_this_pop":"Remove this POP", "puzzles.reset":"Reset", @@ -2993,41 +3021,48 @@ "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.router_load":"Router load", +"puzzles.router_model":"Router model", +"puzzles.router_rodeo":"Router Rodeo", +"puzzles.routers_have_ports_and_a_limit":"Routers have ports and a limit. Fill one and the traffic stops at the door.", "puzzles.rule_not_via_list":"Rule: not via {list}", "puzzles.samba_sprint":"Samba Sprint", +"puzzles.same_cable_same_anchor":"Same cable as a link you have: one anchor takes both.", "puzzles.same_puzzle_for_everyone_this_week":"Same puzzle for everyone this week", +"puzzles.same_trench_cheaper":"Same trench (cheaper)", "puzzles.same_trench_cheaper_one_backhoe_cuts":"Same trench (cheaper, one backhoe cuts both)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo to Miami before the caipirinha gets warm.", "puzzles.sea_to_shining_sea":"Sea to Shining Sea", -"puzzles.seattle_to_singapore_with_a_stop":"Seattle to Singapore, with a stop for sushi and dim sum.", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", "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.small_networks_real_traffic":"Small networks, real traffic", "puzzles.spent_x":"Spent {x}", "puzzles.spent_x_of_y":"Spent {x} / {y}", "puzzles.stepping_stone_optional":"Stepping stone (optional)", "puzzles.suez_you_later":"Suez You Later", -"puzzles.survives_any_single_cut":"Survives any single cut", +"puzzles.survive_any_single_cut_with_the":"Survive any single cut, with the traffic still flowing. Connected is not enough.", +"puzzles.survives_any_single_cut_under_load":"Survives any single cut, under load", "puzzles.tap_a_goal_city_to_open":"Tap a glowing city to open your first POP", -"puzzles.that_city_is_not_part_of":"That city is not part of this puzzle.", -"puzzles.the_pacific_is_big_light_is":"The Pacific is big. Light is fast. Your budget is neither.", -"puzzles.the_pacific_rim_where_every_hop":"The Pacific rim, where every hop is an ocean.", +"puzzles.the_content_origin_lives_here":"The content lives here. Eyeballs elsewhere pull from it.", +"puzzles.the_oil_rigs_want_their_numbers":"The oil rigs want their numbers fast. The shortest road to Stavanger is not the quickest.", +"puzzles.the_road_to_tallinn_is_short":"The road to Tallinn is short. The light through Helsinki is shorter.", "puzzles.the_shark_tank":"The Shark Tank", "puzzles.the_sharks_have_been_biting_again":"The sharks have been biting again. Keep it on dry land.", "puzzles.the_sharks_say_no":"The sharks say no.", +"puzzles.this_link":"This link", "puzzles.three_cities_two_currencies_one_very":"Three cities, two currencies, one very short tunnel under the sea.", "puzzles.traders_paid_millions_to_shave_milliseconds":"Traders paid millions to shave milliseconds off this route. You get to do it for less.", +"puzzles.traffic_cops":"Traffic Cops", +"puzzles.trench_n":"trench {n}", "puzzles.two_cables_across_the_atlantic_because":"Two cables across the Atlantic, because one is a hope, not a plan.", -"puzzles.under_n_ms":"under {n} ms", +"puzzles.u_of_m_used":"{u} of {m} used", "puzzles.undo":"Undo", "puzzles.unlocks_at_n_stars":"Unlocks at {n}⭐", "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_roomy_budgets":"Your first tubes. Roomy budgets, and the first two are on the house.", +"puzzles.your_pop":"Your POP", +"puzzles.your_routers_pick_the_path":"Your routers pick the path. Tell them which: metrics, lowest latency, best effort.", "puzzles.your_stars":"Your stars", "puzzles_weekly.detour":"Detour", "puzzles_weekly.island_hopping":"Island hopping", diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css index e879143..a126f60 100644 --- a/src/styles/70-puzzles.css +++ b/src/styles/70-puzzles.css @@ -8,6 +8,12 @@ body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteB .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} +.pzsrc{font-size:12px;font-weight:800;color:var(--ink2);margin:4px 0} +.pzfl{margin:4px 0 6px}.pzf{margin:4px 0;padding:3px 6px;border:2px solid var(--line);border-radius:10px}.pzf.ok{border-color:var(--ok)} +.pzf .kv{font-size:12px;gap:6px}.pzf .bar{margin:2px 0}.pzf .meta .bad{color:var(--bad);font-weight:900}.pzf .seg.pzrt{margin-top:3px} +.pzpair{border-top:2px dashed var(--line);padding-top:4px;margin-top:4px}.pzhave{font-size:13px;font-weight:800;margin:6px 0;padding:4px 8px;border-radius:10px;background:#FFF4D6} +.pznote{font-weight:800;font-size:13.5px;margin:8px 0;padding:8px 10px;border:2.5px solid var(--ink);border-radius:12px;background:#FFF3C4} +.row.on{background:#FFE3F0;border-radius:10px} .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)} From 12ef18f9e62baa91c110031e928ec627fd43b991 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 10:48:24 +0100 Subject: [PATCH 104/181] Puzzles: eighteen puzzles in five packs with traffic, and their tests Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. Every puzzle has 1-star and 3-star references played through the player's actions; budgets sit over the cheapest 3-star build the solver found, and the tests check that no single change keeps three stars for less. --- 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 +- site/puzzles/weekly/2026-W44.json | 2 +- site/puzzles/weekly/2026-W45.json | 2 +- site/puzzles/weekly/2026-W46.json | 2 +- site/puzzles/weekly/index.json | 2 +- src/game/60-features/90-puzzles-data.js | 32 +- src/i18n/en.js | 2 +- tests/puzzles.test.js | 675 +++++++++++++----------- 12 files changed, 403 insertions(+), 324 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index f7a33b8..7fd624d 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2947,7 +2947,6 @@ "puzzles.every_star_in_this_pack_is":"Alle Sterne in diesem Paket gehören dir.", "puzzles.everything_at_once_across_oceans":"Alles auf einmal, über Ozeane. Knappe Budgets.", "puzzles.fat_pipes":"Dicke Rohre", -"puzzles.five_small_cities_one_small_router":"Fünf Städte, je ein paar Gigabit, und ein Router mit acht Ports. Erst zählen, dann graben.", "puzzles.fjord_focus":"Fjord im Fokus", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Leitung {a} ⇄ {b}", @@ -3035,6 +3034,7 @@ "puzzles.sao_paulo_to_miami_before_the":"São Paulo nach Miami, bevor der Caipirinha warm wird.", "puzzles.sea_to_shining_sea":"Von Küste zu Küste", "puzzles.share_line":"Series of Tubes Puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Sechs Städte, je ein paar Gigabit, und ein Router mit acht Ports. Erst zählen, dann graben.", "puzzles.size":"Größe", "puzzles.small_networks_real_traffic":"Kleine Netze, echter Traffic", "puzzles.spent_x":"Ausgegeben {x}", diff --git a/site/i18n/es.js b/site/i18n/es.js index a8b6476..d300f54 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2945,7 +2945,6 @@ "puzzles.every_star_in_this_pack_is":"Todas las estrellas de este paquete son tuyas.", "puzzles.everything_at_once_across_oceans":"Todo a la vez, cruzando océanos. Presupuestos ajustados.", "puzzles.fat_pipes":"Tubos gordos", -"puzzles.five_small_cities_one_small_router":"Cinco ciudades, pocos gigas cada una, y un router con ocho puertos. Cuenta antes de cavar.", "puzzles.fjord_focus":"Rumbo al fiordo", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", @@ -3033,6 +3032,7 @@ "puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes de que se caliente la caipiriña.", "puzzles.sea_to_shining_sea":"De costa a costa", "puzzles.share_line":"Series of Tubes puzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Seis ciudades, pocos gigas cada una, y un router con ocho puertos. Cuenta antes de cavar.", "puzzles.size":"Tamaño", "puzzles.small_networks_real_traffic":"Redes pequeñas, tráfico de verdad", "puzzles.spent_x":"Gastado {x}", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index b4c714b..b84b1a5 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2945,7 +2945,6 @@ "puzzles.every_star_in_this_pack_is":"Toutes les étoiles de ce pack sont à toi.", "puzzles.everything_at_once_across_oceans":"Tout à la fois, par-delà les océans. Budgets serrés.", "puzzles.fat_pipes":"Gros tuyaux", -"puzzles.five_small_cities_one_small_router":"Cinq villes, quelques gigas chacune, et un routeur à huit ports. Compte avant de creuser.", "puzzles.fjord_focus":"Cap sur le fjord", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Circuit {a} ⇄ {b}", @@ -3033,6 +3032,7 @@ "puzzles.sao_paulo_to_miami_before_the":"São Paulo–Miami avant que la caïpirinha ne tiédisse.", "puzzles.sea_to_shining_sea":"D’une côte à l’autre", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Six villes, quelques gigas chacune, et un routeur à huit ports. Compte avant de creuser.", "puzzles.size":"Taille", "puzzles.small_networks_real_traffic":"Petits réseaux, vrai trafic", "puzzles.spent_x":"Dépensé {x}", diff --git a/site/i18n/it.js b/site/i18n/it.js index 1a0e9a1..94f2d17 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2945,7 +2945,6 @@ "puzzles.every_star_in_this_pack_is":"Tutte le stelle di questo pacchetto sono tue.", "puzzles.everything_at_once_across_oceans":"Tutto insieme, oltre gli oceani. Budget stretti.", "puzzles.fat_pipes":"Tubi grossi", -"puzzles.five_small_cities_one_small_router":"Cinque città, pochi giga ciascuna, e un router con otto porte. Conta prima di scavare.", "puzzles.fjord_focus":"Fuoco sul fiordo", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", @@ -3033,6 +3032,7 @@ "puzzles.sao_paulo_to_miami_before_the":"Da São Paulo a Miami prima che la caipirinha si scaldi.", "puzzles.sea_to_shining_sea":"Da costa a costa", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Sei città, pochi giga ciascuna, e un router con otto porte. Conta prima di scavare.", "puzzles.size":"Taglia", "puzzles.small_networks_real_traffic":"Reti piccole, traffico vero", "puzzles.spent_x":"Speso {x}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index c65ace3..38ee4f2 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2945,7 +2945,6 @@ "puzzles.every_star_in_this_pack_is":"Todas as estrelas deste pacote são suas.", "puzzles.everything_at_once_across_oceans":"Tudo de uma vez, atravessando oceanos. Orçamentos apertados.", "puzzles.fat_pipes":"Canos grossos", -"puzzles.five_small_cities_one_small_router":"Cinco cidades, poucos gigas cada, e um router com oito portas. Conte antes de cavar.", "puzzles.fjord_focus":"Foco no fiorde", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", @@ -3033,6 +3032,7 @@ "puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes que a caipirinha esquente.", "puzzles.sea_to_shining_sea":"De costa a costa", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Seis cidades, poucos gigas cada, e um router com oito portas. Conte antes de cavar.", "puzzles.size":"Tamanho", "puzzles.small_networks_real_traffic":"Redes pequenas, tráfego de verdade", "puzzles.spent_x":"Gasto {x}", diff --git a/site/puzzles/weekly/2026-W44.json b/site/puzzles/weekly/2026-W44.json index 128937c..be7a930 100644 --- a/site/puzzles/weekly/2026-W44.json +++ b/site/puzzles/weekly/2026-W44.json @@ -1 +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}} +{"v":2,"key":"2026-W44","theme":"ring","cities":["ham","fra","bru","dus"],"src":["ham"],"dem":[{"t":"eye","a":"fra","g":30},{"t":"eye","a":"bru","g":60},{"t":"eye","a":"dus","g":60}],"via":[],"avoid":[],"budget":360000,"twist":{"ring":true},"name":{"l":"puzzles_weekly.name_one_ring_to_rule_reg","p":{"reg":"EU"}},"joke":{"l":"puzzles_weekly.joke_a_ring_survives_one_cut","p":{}},"ref":{"one":341708,"three":341708}} diff --git a/site/puzzles/weekly/2026-W45.json b/site/puzzles/weekly/2026-W45.json index 413d8ac..fc475a5 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":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}} +{"v":2,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"src":["abj"],"dem":[{"t":"eye","a":"fih","g":20},{"t":"eye","a":"acc","g":10},{"t":"eye","a":"dkr","g":30}],"via":["lag"],"avoid":[],"budget":1750000,"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":989200,"three":1657240}} diff --git a/site/puzzles/weekly/2026-W46.json b/site/puzzles/weekly/2026-W46.json index d7b9f26..11a7fbf 100644 --- a/site/puzzles/weekly/2026-W46.json +++ b/site/puzzles/weekly/2026-W46.json @@ -1 +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}} +{"v":2,"key":"2026-W46","theme":"ocean","cities":["for","ssa","lad","lun"],"src":["for"],"dem":[{"t":"eye","a":"ssa","g":8},{"t":"eye","a":"lad","g":5},{"t":"eye","a":"lun","g":8}],"via":["sao","dla"],"avoid":[],"budget":4520000,"twist":{},"name":{"l":"puzzles_weekly.name_sea_you_in_b","p":{"b":"lad"}},"joke":{"l":"puzzles_weekly.joke_somewhere_between_a_and_b","p":{"a":"for","b":"lad"}},"ref":{"one":2368700,"three":4296628}} diff --git a/site/puzzles/weekly/index.json b/site/puzzles/weekly/index.json index 8955841..e112cc1 100644 --- a/site/puzzles/weekly/index.json +++ b/site/puzzles/weekly/index.json @@ -1 +1 @@ -{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]} +{"v":2,"weeks":["2026-W44","2026-W45","2026-W46"]} diff --git a/src/game/60-features/90-puzzles-data.js b/src/game/60-features/90-puzzles-data.js index 1d64d54..b9c611e 100644 --- a/src/game/60-features/90-puzzles-data.js +++ b/src/game/60-features/90-puzzles-data.js @@ -15,22 +15,22 @@ const PZ_PACKS=[ const PZ=[ {id:'hello',pack:'hello',n:tr('puzzles.hello_world'),j:tr('puzzles.every_internet_starts_with_one_tube'),src:['nyc'],dem:[{t:'eye',a:'lon',g:8}],budget:0}, {id:'eurotrip',pack:'hello',n:tr('puzzles.euro_trip'),j:tr('puzzles.three_cities_two_currencies_one_very'),src:['ams'],dem:[{t:'eye',a:'lon',g:30},{t:'eye',a:'fra',g:60}],budget:0}, - {id:'bigboat',pack:'hello',n:tr('puzzles.a_bigger_boat'),j:tr('puzzles.paris_wants_150g_one_100g_wave'),src:['fra'],dem:[{t:'eye',a:'par',g:150}],budget:1}, - {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),src:['nyc'],dem:[{t:'eye',a:'chi',g:40},{t:'eye',a:'dal',g:30},{t:'eye',a:'sjc',g:60}],budget:1}, - {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),src:['syd'],dem:[{t:'eye',a:'mel',g:50},{t:'eye',a:'bne',g:30},{t:'eye',a:'adl',g:20}],budget:1}, - {id:'edgelord',pack:'rodeo',n:tr('puzzles.edge_lord'),j:tr('puzzles.london_wants_half_a_terabit_your'),src:['ams'],dem:[{t:'eye',a:'lon',g:500}],budget:1}, - {id:'hubcap',pack:'rodeo',n:tr('puzzles.hub_cap'),j:tr('puzzles.all_of_europe_s_cat_videos'),src:['lon'],dem:[{t:'eye',a:'ams',g:150},{t:'eye',a:'par',g:150},{t:'eye',a:'fra',g:120}],budget:1}, - {id:'ports',pack:'rodeo',n:tr('puzzles.port_authority'),j:tr('puzzles.five_small_cities_one_small_router'),src:['zrh'],dem:[{t:'eye',a:'mil',g:8},{t:'eye',a:'muc',g:8},{t:'eye',a:'fra',g:8},{t:'eye',a:'par',g:8},{t:'eye',a:'vie',g:8}],budget:1}, - {id:'flash',pack:'cops',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),src:['nyc'],dem:[{t:'l2',a:'nyc',b:'lon',g:10,ms:26},{t:'eye',a:'lon',g:80,be:1}],budget:1}, - {id:'baltic',pack:'cops',n:tr('puzzles.baltic_shortcut'),j:tr('puzzles.the_road_to_tallinn_is_short'),src:['fra'],dem:[{t:'eye',a:'tll',g:60},{t:'l2',a:'fra',b:'tll',g:10,ms:8.8}],via:['hel'],budget:1}, - {id:'fjord',pack:'cops',n:tr('puzzles.fjord_focus'),j:tr('puzzles.the_oil_rigs_want_their_numbers'),src:['par'],dem:[{t:'eye',a:'svg',g:30},{t:'l2',a:'par',b:'svg',g:10,ms:7.2}],via:['lon'],budget:1}, - {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),src:['nyc'],dem:[{t:'eye',a:'lon',g:60},{t:'eye',a:'dub',g:40}],budget:1}, - {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),src:['lis'],dem:[{t:'eye',a:'mad',g:40},{t:'eye',a:'par',g:60},{t:'eye',a:'mil',g:30}],via:['bcn','mrs'],noSub:true,budget:1}, - {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),src:['ams'],dem:[{t:'eye',a:'ber',g:50},{t:'eye',a:'muc',g:50},{t:'eye',a:'zrh',g:40}],via:['ham','dus'],avoid:['fra'],budget:1}, - {id:'fire',pack:'n1',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),src:['tok'],dem:[{t:'eye',a:'hkg',g:20},{t:'eye',a:'sin',g:20},{t:'eye',a:'syd',g:10}],ring:true,budget:1}, - {id:'suez',pack:'final',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),src:['fra'],dem:[{t:'l2',a:'fra',b:'sin',g:10,ms:68},{t:'eye',a:'sin',g:30,be:1}],via:['mrs','bom'],budget:1}, - {id:'kiwi',pack:'final',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),src:['sea'],dem:[{t:'eye',a:'akl',g:20},{t:'eye',a:'syd',g:40}],via:['hnl','suv','lax'],budget:1}, - {id:'samba',pack:'final',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),src:['mia'],dem:[{t:'l2',a:'sao',b:'mia',g:10,ms:45},{t:'eye',a:'sao',g:40},{t:'eye',a:'rio',g:20,be:1}],via:['for'],budget:1}, + {id:'bigboat',pack:'hello',n:tr('puzzles.a_bigger_boat'),j:tr('puzzles.paris_wants_150g_one_100g_wave'),src:['fra'],dem:[{t:'eye',a:'par',g:150}],budget:175000}, + {id:'shining',pack:'hello',n:tr('puzzles.sea_to_shining_sea'),j:tr('puzzles.four_cities_one_continent_and_a'),src:['nyc'],dem:[{t:'eye',a:'chi',g:40},{t:'eye',a:'dal',g:30},{t:'eye',a:'sjc',g:60}],budget:715000}, + {id:'downunder',pack:'hello',n:tr('puzzles.down_under_up_and_running'),j:tr('puzzles.one_very_big_island_and_a'),src:['syd'],dem:[{t:'eye',a:'mel',g:50},{t:'eye',a:'bne',g:30},{t:'eye',a:'adl',g:20}],budget:585000}, + {id:'edgelord',pack:'rodeo',n:tr('puzzles.edge_lord'),j:tr('puzzles.london_wants_half_a_terabit_your'),src:['ams'],dem:[{t:'eye',a:'lon',g:500}],budget:240000}, + {id:'hubcap',pack:'rodeo',n:tr('puzzles.hub_cap'),j:tr('puzzles.all_of_europe_s_cat_videos'),src:['lon'],dem:[{t:'eye',a:'ams',g:150},{t:'eye',a:'par',g:150},{t:'eye',a:'fra',g:120}],budget:455000}, + {id:'ports',pack:'rodeo',n:tr('puzzles.port_authority'),j:tr('puzzles.six_cities_a_few_gigs_each'),src:['zrh'],dem:[{t:'eye',a:'mil',g:12},{t:'eye',a:'muc',g:12},{t:'eye',a:'fra',g:12},{t:'eye',a:'par',g:12},{t:'eye',a:'vie',g:12},{t:'eye',a:'prg',g:12}],budget:470000}, + {id:'flash',pack:'cops',n:tr('puzzles.flash_boys'),j:tr('puzzles.traders_paid_millions_to_shave_milliseconds'),src:['nyc'],dem:[{t:'l2',a:'nyc',b:'lon',g:10,ms:26},{t:'eye',a:'lon',g:80,be:1}],budget:660000}, + {id:'baltic',pack:'cops',n:tr('puzzles.baltic_shortcut'),j:tr('puzzles.the_road_to_tallinn_is_short'),src:['fra'],dem:[{t:'eye',a:'tll',g:60},{t:'l2',a:'fra',b:'tll',g:10,ms:8.8}],via:['hel'],budget:285000}, + {id:'fjord',pack:'cops',n:tr('puzzles.fjord_focus'),j:tr('puzzles.the_oil_rigs_want_their_numbers'),src:['par'],dem:[{t:'eye',a:'svg',g:30},{t:'l2',a:'par',b:'svg',g:10,ms:7.2}],via:['lon'],budget:265000}, + {id:'braces',pack:'n1',n:tr('puzzles.belt_and_braces'),j:tr('puzzles.two_cables_across_the_atlantic_because'),src:['nyc'],dem:[{t:'eye',a:'lon',g:60},{t:'eye',a:'dub',g:40}],budget:840000}, + {id:'sharks',pack:'n1',n:tr('puzzles.the_shark_tank'),j:tr('puzzles.the_sharks_have_been_biting_again'),src:['lis'],dem:[{t:'eye',a:'mad',g:40},{t:'eye',a:'par',g:60},{t:'eye',a:'mil',g:30}],via:['bcn','mrs'],noSub:true,budget:450000}, + {id:'nofra',pack:'n1',n:tr('puzzles.not_through_frankfurt'),j:tr('puzzles.de_kicks_sales_has_your_number'),src:['ams'],dem:[{t:'eye',a:'ber',g:50},{t:'eye',a:'muc',g:50},{t:'eye',a:'zrh',g:40}],via:['ham','dus'],avoid:['fra'],budget:390000}, + {id:'fire',pack:'n1',n:tr('puzzles.ring_of_fire'),j:tr('puzzles.four_cities_four_cables_one_ring'),src:['tok'],dem:[{t:'eye',a:'hkg',g:20},{t:'eye',a:'sin',g:20},{t:'eye',a:'syd',g:10}],ring:true,budget:4070000}, + {id:'suez',pack:'final',n:tr('puzzles.suez_you_later'),j:tr('puzzles.frankfurt_to_singapore_the_short_way'),src:['fra'],dem:[{t:'l2',a:'fra',b:'sin',g:10,ms:68},{t:'eye',a:'sin',g:30,be:1}],via:['mrs','bom'],budget:1790000}, + {id:'kiwi',pack:'final',n:tr('puzzles.kiwi_fruit_salad'),j:tr('puzzles.new_zealand_is_far_from_everything'),src:['sea'],dem:[{t:'eye',a:'akl',g:20},{t:'eye',a:'syd',g:40}],via:['hnl','suv','lax'],budget:4200000}, + {id:'samba',pack:'final',n:tr('puzzles.samba_sprint'),j:tr('puzzles.sao_paulo_to_miami_before_the'),src:['mia'],dem:[{t:'l2',a:'sao',b:'mia',g:10,ms:45},{t:'eye',a:'sao',g:40},{t:'eye',a:'rio',g:20,be:1}],via:['for'],budget:2655000}, ]; // 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 8ab1e1d..a0e51dc 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2946,7 +2946,6 @@ "puzzles.every_star_in_this_pack_is":"Every star in this pack is yours.", "puzzles.everything_at_once_across_oceans":"Everything at once, across oceans. Tight budgets.", "puzzles.fat_pipes":"Fat Pipes", -"puzzles.five_small_cities_one_small_router":"Five cities, a few gigs each, and a router with eight ports. Count before you dig.", "puzzles.fjord_focus":"Fjord Focus", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"{a} ⇄ {b} circuit", @@ -3034,6 +3033,7 @@ "puzzles.sao_paulo_to_miami_before_the":"São Paulo to Miami before the caipirinha gets warm.", "puzzles.sea_to_shining_sea":"Sea to Shining Sea", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", +"puzzles.six_cities_a_few_gigs_each":"Six cities, a few gigs each, and a router with eight ports. Count before you dig.", "puzzles.size":"Size", "puzzles.small_networks_real_traffic":"Small networks, real traffic", "puzzles.spent_x":"Spent {x}", diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 9290a77..8e1db0d 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -1,99 +1,94 @@ -// Puzzle mode (#190): small builds with stars, no clock, and a main save that is never touched. +// Puzzle mode (#190), with traffic: small builds that carry real flows, routed by the game's own compute(), with stars, +// no clock, and a main save that is never touched. const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); +const SV = require('../scripts/lib/puzzle-solver'); -// Reference solutions: [a, b, route ('land' or a cable id), tier (0 = 10G, 1 = 100G)]. -// `one` earns the goal star, `three` earns all three. A second land link on the same pair is a diverse route. +/* Reference solutions, played through the player's own actions. A link is [a, b, route ('land' or a cable id), tier + (0 = 10G, 1 = 100G, 2 = 400G), same]: a further overland link on a pair takes a diverse route, or with same = k + goes into the k-th trench already there (added from the link panel). ['@rt', city, model, count] sets a POP's + routers (RG index), ['@route', flow, 'fast'] sends a circuit the lowest-latency way. `one` earns the delivery star, + `three` all three: the three-star ones are the cheapest builds the solver (scripts/lib/puzzle-solver.js) found. */ const REF = { - hello: { one: [['lon', 'nyc', 'grace']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'amitie']] }, - 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'], ['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'], ['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]] }, + hello: { one: [['nyc', 'lon', 'grace', 0]], three: [['nyc', 'lon', 'grace', 0], ['nyc', 'lon', 'amitie', 0]] }, + eurotrip: { one: [['ams', 'lon', 'nshuttle', 1], ['ams', 'fra', 'land', 1]], three: [['ams', 'lon', 'concerto', 1], ['ams', 'lon', 'nshuttle', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1]] }, + bigboat: { one: [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1]], three: [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1]] }, + shining: { one: [['nyc', 'chi', 'land', 1], ['dal', 'sjc', 'land', 1], ['nyc', 'dal', 'land', 1]], three: [['nyc', 'chi', 'land', 1], ['nyc', 'chi', 'land', 1], ['chi', 'sjc', 'land', 1], ['dal', 'sjc', 'land', 1], ['nyc', 'dal', 'land', 1]] }, + downunder: { one: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1]], three: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1], ['bne', 'adl', 'land', 1]] }, + edgelord: { one: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]], three: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'concerto', 2], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]] }, + hubcap: { one: [['@rt', 'lon', 5, 1], ['lon', 'par', 'pasdc', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1]], three: [['@rt', 'lon', 5, 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'uly', 1]] }, + flash: { one: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]] }, + baltic: { one: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['@route', 1, 'fast']], three: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['fra', 'tll', 'land', 1], ['@route', 1, 'fast']] }, + fjord: { one: [['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']], three: [['par', 'svg', 'land', 1], ['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']] }, + braces: { one: [['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]] }, + sharks: { one: [['lis', 'mad', 'land', 1], ['lis', 'bcn', 'land', 1], ['par', 'mil', 'land', 1], ['par', 'mrs', 'land', 1], ['bcn', 'mrs', 'land', 1]], three: [['lis', 'mad', 'land', 1], ['lis', 'mad', 'land', 1], ['lis', 'bcn', 'land', 1], ['mad', 'bcn', 'land', 1], ['par', 'mil', 'land', 1], ['par', 'mrs', 'land', 1], ['mil', 'bcn', 'land', 1], ['bcn', 'mrs', 'land', 1]] }, + nofra: { one: [['ams', 'dus', 'land', 1], ['ams', 'dus', 'land', 1], ['ber', 'ham', 'land', 1], ['muc', 'zrh', 'land', 1], ['muc', 'dus', 'land', 1], ['ham', 'dus', 'land', 1]], three: [['ams', 'ham', 'land', 1], ['ams', 'dus', 'land', 1], ['ams', 'dus', 'land', 1], ['ber', 'ham', 'land', 1], ['ber', 'ham', 'land', 1], ['muc', 'zrh', 'land', 1], ['muc', 'dus', 'land', 1], ['zrh', 'dus', 'land', 1], ['ham', 'dus', 'land', 1]] }, + fire: { one: [['tok', 'hkg', 'adc', 1], ['hkg', 'sin', 'land', 1], ['sin', 'syd', 'indigo', 1], ['syd', 'tok', 'guam', 1]], three: [['tok', 'hkg', 'adc', 1], ['hkg', 'sin', 'land', 1], ['sin', 'syd', 'indigo', 1], ['syd', 'tok', 'guam', 1]] }, + suez: { one: [['fra', 'mrs', 'land', 1], ['sin', 'mrs', 'peace', 1]], three: [['fra', 'mrs', 'land', 1], ['fra', 'mrs', 'land', 0], ['sin', 'mrs', 'peace', 1], ['sin', 'bom', 'land', 0], ['mrs', 'bom', 'twoaf', 0]] }, + kiwi: { one: [['sea', 'lax', 'land', 1], ['akl', 'syd', 'tasman', 1], ['akl', 'hnl', 'hwk', 1], ['hnl', 'lax', 'seaus', 1]], three: [['sea', 'hnl', 'hwk', 1], ['sea', 'lax', 'land', 1], ['akl', 'syd', 'scx', 1], ['akl', 'syd', 'tasman', 1], ['akl', 'hnl', 'hwk', 1], ['akl', 'suv', 'scx', 1], ['hnl', 'suv', 'scx', 1], ['hnl', 'lax', 'seaus', 1]] }, + samba: { one: [['mia', 'for', 'monet', 1], ['sao', 'rio', 'land', 1], ['sao', 'for', 'land', 1]], three: [['mia', 'for', 'monet', 1], ['mia', 'for', 'sam1', 1], ['sao', 'rio', 'land', 1], ['sao', 'for', 'land', 1], ['rio', 'for', 'land', 1]] }, + ports: { one: [['@rt', 'zrh', 4, 1], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0]], three: [['@rt', 'zrh', 5, 1], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'mil', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'muc', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'fra', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'par', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'vie', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0], ['zrh', 'prg', 'land', 0]] }, }; -// Builds links the way a player does: POP at the first city, then the link picker for each hop. -function build(ev, links) { - for (const [a, b, via, tier] of links) { +function build(ev, steps) { + for (const s of steps) { + if (s[0] === '@rt') { const [, c, g, n] = s; if (!ev(`!!S.pops['${c}']`)) ev(`ACT.pzPop({city:'${c}'})`); if (g) ev(`ACT.pzRtModel({city:'${c}',g:${g}})`); for (let i = 1; i < n; i++) ev(`ACT.pzRtAdd({city:'${c}'})`); continue; } + if (s[0] === '@route') { ev(`ACT.pzRoute({i:${s[1]},m:'${s[2]}'})`); continue; } + const [a, b, via, tier, same] = s; if (!ev(`!!S.pops['${a}']`)) ev(`ACT.pzPop({city:'${a}'})`); - ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:${tier || 0}})`); + if (same) ev(`(()=>{const ls=S.links.filter(l=>edgeKey(l)===edgeKey({a:'${a}',b:'${b}'})&&!l.cable),ts=[...new Set(ls.map(pzUnit))],l=ls.find(x=>pzUnit(x)===ts[${same - 1}]);ACT.pzAddPar({id:l.id,div:0});ACT.pzLink({tier:${tier}})})()`); + else ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:${tier || 0}})`); } ev('closeModal()'); } const evalP = (ev) => JSON.parse(ev('JSON.stringify(pzEval())')); +const links = (steps) => steps.filter((s) => s[0] !== '@rt'); -test('puzzle data: every puzzle is valid, solvable, and its 3-star reference earns three stars', () => { +test('puzzle data: every puzzle is valid, carries traffic, and its references earn their stars through the real routing', () => { const { ev, errors } = load(); const ids = JSON.parse(ev('JSON.stringify(PZ.map(p=>p.id))')); - assert.ok(ids.length >= 16, 'at least 16 puzzles'); + assert.ok(ids.length >= 16 && ids.length <= 20, '16 to 20 puzzles'); assert.equal(new Set(ids).size, ids.length, 'ids are unique'); assert.deepEqual(Object.keys(REF).sort(), ids.slice().sort(), 'every puzzle has a reference solution'); - assert.ok(ev("PZ.every(p=>PZ_PACKS.some(k=>k.id===p.pack)&&p.n&&p.j&&p.cities.length>=2&&p.cities.length<=6&&[...p.cities,...(p.via||[]),...(p.avoid||[])].every(c=>isCity(c)&&!CITY[c].off&&!CITY[c].cn))"), 'cities exist and are playable'); + assert.ok(ev("PZ.every(p=>PZ_PACKS.some(k=>k.id===p.pack)&&p.n&&p.j&&p.dem.length>=1&&pzCities(p).length>=2&&pzCities(p).length<=7&&[...pzCities(p),...(p.via||[]),...(p.avoid||[])].every(pzCityOk))"), 'cities exist and are playable'); + assert.ok(ev("PZ.every(p=>p.dem.every(f=>f.g>0&&(f.t==='eye'?(p.src||[]).length>0&&!p.src.includes(f.a):f.t==='l2'&&f.a!==f.b)))"), 'eyeballs have an origin, circuits two ends'); assert.ok(ev("PZ.every(p=>!p.budget||(p.budget>=100000&&p.budget<=5e6))"), 'budgets are sane'); assert.ok(ev("PZ_PACKS[0].need===0&&PZ_PACKS.every((k,i)=>!i||k.need>PZ_PACKS[i-1].need)"), 'packs unlock in order'); + assert.ok(ev("PZ_PACKS.every(k=>PZ.filter(p=>p.pack===k.id).length>=3)"), 'every pack has at least three puzzles'); assert.ok(ev("PZ.filter(p=>p.pack==='hello'&&!p.budget).length>=2"), 'the first puzzles give the budget star away'); for (const id of ids) { ev(`pzBegin(pzDef('${id}'))`); build(ev, REF[id].one); let e = evalP(ev); - assert.ok(e.goal, `${id}: the one-star reference reaches the goal`); - assert.ok(e.stars >= 1, `${id}: one star`); + assert.ok(e.goal, `${id}: the one-star reference delivers everything (${JSON.stringify(e.flows.map((x) => [x.g, x.ms]))})`); ev('ACT.pzReset({})'); assert.equal(evalP(ev).stars, 0, `${id}: reset clears it`); build(ev, REF[id].three); e = evalP(ev); - assert.equal(e.stars, 3, `${id}: three stars (spend ${e.spend} of ${ev('S.pz.budget')}, n1 ${e.n1}, twists ${JSON.stringify(e.tw)})`); + assert.equal(e.stars, 3, `${id}: three stars (spend ${e.spend} of ${ev('S.pz.budget')}, n1 ${e.n1}, worst cut ${JSON.stringify(e.worst)})`); } 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', () => { +test('budgets follow the teaching curve, and each 3-star reference is the cheapest build nearby', () => { 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] }; + SV.install(ev); + // Slack over the cheapest 3-star build found: roomy first, tight at the end. Traffic Cops is tight on purpose: the + // routing trick (a circuit on the lowest-latency path) is what brings it under budget. + const SLACK = { hello: [0.15, 0.22], rodeo: [0.09, 0.13], cops: [0.03, 0.06], n1: [0.05, 0.08], final: [0.04, 0.07] }; 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`); + // The routers in the reference are the cheapest that carry it: the solver prices the same build the same. + const L = links(REF[id].three), j = SV.judge(ev, L); + assert.ok(j.three && Math.abs(j.spend - e.spend) < 1, `${id}: solver ${j.spend} vs game ${e.spend}`); + // No single change (drop a link, shrink one, move it to another route or trench) keeps three stars for less. + const r = SV.improve(ev, L); + assert.ok(r.spend >= e.spend - 1, `${id}: ${JSON.stringify(r.links)} is cheaper (${r.spend})`); 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}%`); } @@ -101,58 +96,331 @@ test('budgets follow the difficulty curve: roomy first pack, ~10% in the middle, assert.deepEqual(errors, []); }); -test('stars: goal, budget, N-1 and twists each count', () => { +test('stars come from traffic: capacity, latency caps, best effort and N-1 under load', () => { const { ev, errors } = load(); - ev("pzBegin(pzDef('braces'))"); - build(ev, REF.braces.one); + // Connected is not delivered: a 10G wave for 30G of London eyeballs gets 10G there. + ev("pzBegin(pzDef('eurotrip'))"); + build(ev, [['ams', 'lon', 'nshuttle', 0], ['ams', 'fra', 'land', 1]]); let e = evalP(ev); - assert.equal(e.stars, 2, 'connected and under budget, but one cut splits it'); - assert.ok(!e.n1 && e.weak.length > 0); - build(ev, [['dub', 'nyc', 'havf']]); + assert.ok(!e.goal && Math.abs(e.flows[0].g - 10) < 0.1, `10G of 30G (${e.flows[0].g})`); + assert.match(ev("document.getElementById('pzBox').textContent"), /Eyeballs in London(9\.\d|10\.0) Gbps \/ 30\.0 Gbps/); + ev("ACT.pzTier({id:S.links[0].id,tier:1})"); + assert.ok(evalP(ev).goal, 'a 100G wave carries it'); + // N-1 under load: two trenches into Paris are connected after a cut, but one 100G wave cannot carry 150G. + ev("pzBegin(pzDef('bigboat'))"); + build(ev, [['fra', 'par', 'land', 1], ['fra', 'par', 'land', 1, 1], ['fra', 'par', 'land', 1]]); + e = evalP(ev); + assert.ok(e.goal && !e.n1, 'still connected after a cut, but short'); + assert.equal(Math.round(e.worst.g), 50, 'cutting the trench with two waves leaves 100G for 150G: 50G drop'); + assert.match(ev("document.getElementById('pzBox').textContent"), /A cut on Frankfurt ⇄ Paris drops 50\.\d Gbps/); + build(ev, [['fra', 'par', 'land', 1, 2]]); + assert.ok(evalP(ev).n1, 'two waves in each trench: either one carries Paris alone'); + // A latency cap: Grace Hopscotch is too slow for the traders; the eyeballs are best effort and may drop on a cut. + ev("pzBegin(pzDef('flash'))"); + build(ev, [['nyc', 'lon', 'grace', 1]]); + e = evalP(ev); + assert.ok(!e.goal && e.flows[0].full && !e.flows[0].fast, 'all of the circuit, but at 29 ms'); + build(ev, [['nyc', 'lon', 'hibx', 0]]); + e = evalP(ev); + assert.equal(e.stars, 3, 'the fast cable for the circuit; when the big one is cut, only best effort drops'); + // A circuit follows the metrics unless told otherwise: the road to Tallinn is shorter, the light via Helsinki faster. + ev("pzBegin(pzDef('baltic'))"); + build(ev, links(REF.baltic.three).filter((s) => s[0] !== '@route')); + e = evalP(ev); + assert.ok(!e.goal && e.flows[1].ms > 8.8, `the metric path is too slow (${e.flows[1].ms})`); + assert.ok(ev("!!document.querySelector('#pzBox [data-act=pzRoute]')"), 'the card has the circuit\'s route switch'); + ev("document.querySelector('#pzBox [data-act=pzRoute][data-args*=fast]').click()"); + e = evalP(ev); + assert.ok(e.goal && e.flows[1].ms <= 8.8, 'lowest latency goes via Helsinki'); + ev('ACT.pzUndo({})'); + assert.equal(ev("S.biz[0].route"), 'normal', 'undo takes the route back'); + // The main game's metric control works in a puzzle and moves the traffic: Backup only on the road pushes the + // eyeballs through Helsinki too. + ev("ACT.pzRoute({i:1,m:'fast'});ACT.selLink({id:S.links.find(l=>edgeKey(l)==='fra|tll').id})"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Routing metric/); + ev("ACT.setMetric({id:S.links.find(l=>edgeKey(l)==='fra|tll').id,v:'backup'})"); + assert.ok(ev("(R.load[S.links.find(l=>edgeKey(l)==='fra|tll').id]||0)<0.01"), 'nothing on a backup-only link while the others are up'); + ev('ACT.pzUndo({})'); + assert.ok(ev("!S.pairMet['fra|tll']"), 'undo takes the metric back'); + // Over budget loses the second star only. + ev("pzBegin(pzDef('braces'))");build(ev, REF.braces.three); assert.equal(evalP(ev).stars, 3); ev('S.pz.budget=1000'); - assert.equal(evalP(ev).stars, 2, 'over budget loses the second star'); - // Two waves in the same trench are one backhoe away from nothing. - ev("pzBegin(pzDef('shining'))"); - 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); - ev("pzBegin(pzDef('fire'))");build(ev, REF.fire.one);ev("ACT.pzRmLink({id:S.links[3].id})"); - e = evalP(ev); - assert.ok(e.conn && !e.goal, 'a line is not a ring'); - ev('ACT.pzUndo({})'); - assert.ok(evalP(ev).goal, 'undo puts the ring back'); - ev("pzBegin(pzDef('flash'))");build(ev, [['nyc', 'lon', 'grace']]); - e = evalP(ev); - assert.ok(e.conn && !e.goal, 'Grace Hopscotch is too slow for the traders'); - ev("pzBegin(pzDef('fatpipes'))");build(ev, REF.fatpipes.one.map(([a, b, v]) => [a, b, v, 0])); - assert.ok(!evalP(ev).goal, '10G is too thin'); - ev("ACT.pzTier({id:S.links[0].id,tier:1});ACT.pzTier({id:S.links[1].id,tier:1});ACT.pzTier({id:S.links[2].id,tier:1})"); - assert.ok(evalP(ev).goal, 'upgraded in place'); - ev("pzBegin(pzDef('nofra'))"); - ev("ACT.pzPop({city:'fra'})"); - assert.equal(ev("!!S.pops.fra"), false, 'no POP in a city to avoid'); - assert.equal(ev("pzKind('lon')"), null, 'cities outside the puzzle are inert'); - ev("ACT.pzPop({city:'lon'})"); - assert.equal(ev("Object.keys(S.pops).length"), 0); - // Subsea is greyed out in the shark tank. - ev("pzBegin(pzDef('sharks'));ACT.pzPop({city:'lis'});ACT.pzLinkTo({a:'lis',b:'bcn'});ACT.pzVia({v:'medusa'});ACT.pzLink({tier:0})"); - assert.equal(ev('S.links.length'), 0); + assert.equal(evalP(ev).stars, 2); + // A cable fails as a whole: two waves on one cable are one cut. + ev("pzBegin(pzDef('kiwi'))"); + build(ev, [['akl', 'syd', 'scx', 1], ['akl', 'suv', 'scx', 1]]); + assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 1, 'one cable, one failure unit'); assert.deepEqual(errors, []); }); +test('parallel links say how many they are and where they run; diversity from the link panel', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('bigboat'))"); + build(ev, [['fra', 'par', 'land', 1]]); + const id = ev('S.links[0].id'); + ev(`ACT.selLink({id:'${id}'})`); + let panel = ev("document.getElementById('panelBody').textContent"); + assert.match(panel, /Add another link on this pair/); + // Same trench from the panel: no surcharge, one failure unit, one line on the map labelled 2×100G. + ev(`ACT.pzAddPar({id:'${id}',div:0})`); + assert.match(ev("document.getElementById('modalCard').textContent"), /Already on this pair: 1×100G · trench 1/); + ev('ACT.pzLink({tier:1})'); + assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 1); + assert.equal(ev('S.links[1].mo'), ev('S.links[0].mo')); + assert.equal(ev("pzLinkLab(S.links,S.links,R.load[S.links[0].id]+R.load[S.links[1].id],200)"), '2×100G · 75%'); + assert.equal(ev("groupLabel(linkGroups()[0],linkGroups()[0])"), '2×100G', 'the map draws one line for the trench, labelled with its count'); + // A diverse one from the panel: its own trench, 40% dearer, its own line. + ev(`ACT.pzAddPar({id:'${id}',div:1});ACT.pzLink({tier:1})`); + assert.equal(ev("new Set(S.links.map(pzUnit)).size"), 2); + assert.equal(ev('S.links[2].mo'), ev('Math.round(S.links[0].mo*DIVERSE)')); + assert.equal(ev('linkGroups().length'), 2); + ev(`ACT.selLink({id:'${id}'})`); + panel = ev("document.getElementById('panelBody').textContent"); + assert.match(panel, /3 links on this pair: 3×100G/); + assert.match(panel, /trench 1/); + assert.match(panel, /trench 2/); + // Selecting a city lights up every pair it has links on, and its panel lists them with their loads. + ev("selectCity('par')"); + assert.ok(ev('pzLinkHot(S.links)')); + panel = ev("document.getElementById('panelBody').textContent"); + assert.match(panel, /Frankfurt · 3×100G150 Gbps \/ 300 Gbps/); + // A subsea link: "a different route" picks another cable. + ev("pzBegin(pzDef('hello'))");build(ev, [['nyc', 'lon', 'grace', 0]]); + ev("ACT.pzAddPar({id:S.links[0].id,div:1})"); + assert.notEqual(ev('UI.pzVia'), 'grace'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Already on this pair: 1×10G/); + assert.deepEqual(errors, []); +}); + +test('routers in a puzzle: ports, wave sizes and capacity as in the main game, priced into the budget', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('edgelord'))"); + build(ev, [['ams', 'lon', 'nshuttle', 0]]); + // A Rusty Router lights 100G at most. + ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'concerto'})"); + assert.match(ev("document.querySelector('#modalCard .tierbtn[data-args*=\"2\"]').textContent"), /needs 400G routers/); + assert.equal(ev("document.querySelector('#modalCard .tierbtn[data-args*=\"2\"]').disabled"), true); + ev('closeModal()'); + // Eight ports: the ninth wave is refused, a second router makes room, and it is in the bill. + for (let i = 0; i < 7; i++) ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})"); + assert.equal(ev('S.links.length'), 8); + ev("ACT.pzLinkTo({a:'ams',b:'lon'})"); + assert.match(ev("document.getElementById('modalCard').textContent"), /No free router ports in Amsterdam, London/); + ev("ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})"); + assert.equal(ev('S.links.length'), 8, 'no port, no wave'); + const sp0 = evalP(ev).spend; + ev("ACT.pzRtAdd({city:'ams'});ACT.pzRtAdd({city:'lon'})"); + assert.equal(evalP(ev).spend - sp0, ev('2*pzRtCost(0,2)'), 'two second routers, priced as the main game prices them'); + ev("ACT.pzLinkTo({a:'ams',b:'lon'});ACT.pzVia({v:'nshuttle'});ACT.pzLink({tier:0})"); + assert.equal(ev('S.links.length'), 9); + ev("ACT.pzRtRm({city:'ams'})"); + assert.equal(ev('S.pops.ams.routers'), 2, 'cannot drop a router whose ports are in use'); + // The city panel shows the POP: model, load against capacity, ports. + ev("selectCity('lon')"); + const panel = ev("document.getElementById('panelBody').textContent"); + assert.match(panel, /2 × Rusty Router 9000/); + assert.match(panel, /Ports9 of 16 used/); + assert.match(panel, /Router load90\.0 Gbps \/ 800 Gbps/); + // Capacity: a Rusty Router moves 400G. Three 400G waves on Sonic routers bring 1.2T, but a Rusty-sized POP would + // stop at 400G of the 500G London wants. + ev("pzBegin(pzDef('edgelord'))"); + build(ev, [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'concerto', 2], ['ams', 'lon', 'nshuttle', 2]]); + assert.equal(Math.round(evalP(ev).flows[0].g), 500); + ev("ACT.pzRtModel({city:'lon',g:0})"); + assert.equal(ev('S.pops.lon.rgen'), 5, 'a Rusty Router cannot take a 400G wave: the swap is refused'); + ev("S.pops.lon.rgen=4;UI.pzEv=null");// a Mikrowtik moves 300G (set directly: it refuses 400G waves too) + assert.ok(Math.abs(evalP(ev).flows[0].g - 300) < 5, 'the router is the bottleneck'); + assert.deepEqual(errors, []); +}); + +test('the whole world is open: an off-plan city can get a POP and links, and it counts in the budget', () => { + const { ev, errors } = load(); + ev("pzBegin(pzDef('bigboat'))"); + assert.equal(ev("pzKind('bru')"), 'off'); + ev("selectCity('bru')"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Not in the plan/); + ev("ACT.pzPop({city:'bru'})"); + assert.ok(ev('!!S.pops.bru')); + const sp = evalP(ev).spend; + assert.equal(sp, ev("pzPopCost('bru')")); + ev("ACT.pzLinkTo({a:'bru',b:'par'});ACT.pzVia({v:'land'});ACT.pzLink({tier:1})"); + ev("ACT.pzLinkTo({a:'bru',b:'fra'});ACT.pzVia({v:'land'});ACT.pzLink({tier:1})"); + const e = evalP(ev); + assert.ok(e.spend > sp && Math.round(e.flows[0].g) === 100, 'Paris gets 100G through Brussels'); + assert.equal(ev("pzKind('pek')"), null, 'cities that need a licence stay out'); + ev("pzBegin(pzDef('nofra'));ACT.pzPop({city:'fra'})"); + assert.equal(ev('!!S.pops.fra'), false, 'a city to avoid stays off limits'); + assert.deepEqual(errors, []); +}); + +test('determinism and speed: the same build always gets the same stars, fast enough on the biggest puzzle', () => { + const { ev, errors } = load(); + const run = (id) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, REF[id].three); ev('UI.pzEv=null'); const a = ev('JSON.stringify(pzEval())'); ev('UI.pzEv=null'); return [a, ev('JSON.stringify(pzEval())')]; }; + const [a, b] = run('kiwi'), [c] = run('kiwi'); + assert.equal(a, b, 'twice in a row'); + assert.equal(a, c, 'and from scratch'); + // The biggest puzzle by failure units: one full evaluation (routing plus every single cut). + const big = ev("PZ.map(p=>p.id).sort()[0]") && JSON.parse(ev('JSON.stringify(PZ.map(p=>p.id))')).map((id) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, REF[id].three); return [id, ev('new Set(S.links.map(pzUnit)).size')]; }).sort((x, y) => y[1] - x[1])[0]; + ev(`pzBegin(pzDef('${big[0]}'))`); build(ev, REF[big[0]].three); + for (let i = 0; i < 3; i++) ev('UI.pzEv=null;pzEval()'); + const ms = ev('(()=>{const t=performance.now();for(let i=0;i<5;i++){UI.pzEv=null;pzEval();}return (performance.now()-t)/5})()'); + console.log(`# star evaluation on ${big[0]} (${big[1]} failure units): ${ms.toFixed(1)} ms`); + assert.ok(ms < 150, `${big[0]}: ${ms.toFixed(1)} ms`); + assert.deepEqual(errors, []); +}); + +test('progress: the puzzle set with traffic starts the stars again once, with the old ones framed', () => { + const { ev, errors } = load(); + ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:3,sp:1},eurotrip:{st:2},gone:{st:3}},wk:{'2026-W40':{st:3,sp:9}},streak:{last:'2026-W40',n:2,best:4}}))"); + let p = JSON.parse(ev('JSON.stringify(pzLoad())')); + assert.deepEqual(p.s, {}, 'old stars do not count in the new set'); + assert.equal(p.old, 8); + assert.deepEqual(p.wk, { '2026-W40': { st: 3, sp: 9 } }, 'weekly results stay'); + assert.equal(p.streak.best, 4, 'and so does the streak'); + ev('ACT.puzzleMenu({})'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Puzzles got traffic!.*Your old 8 ⭐ are framed on the wall/); + ev('closeModal();ACT.puzzleMenu({})'); + assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /Puzzles got traffic!/, 'the note shows once'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Framed on the wall: 8 ⭐/); + // New stars are kept under the new set. + ev("pzBegin(pzDef('hello'))");build(ev, REF.hello.three); + p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); + assert.equal(p.set, 2); + assert.equal(p.s.hello.st, 3); + assert.equal(JSON.parse(ev('JSON.stringify(pzLoad())')).old, 8); + // Bad data is ignored. + ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:{hello:{st:99,sp:'x'},nope:{st:3}},old:'',wk:{bad:{st:3}},streak:{n:-4,last:''}}))"); + p = JSON.parse(ev('JSON.stringify(pzLoad())')); + assert.deepEqual(p.s, { hello: { st: 3, sp: null } }); + assert.equal(p.old, null); + assert.deepEqual(p.wk, {}); + assert.deepEqual(p.streak, { last: null, n: 0, best: 0 }); + ev("localStorage.setItem('sot-puzzles','{nope')"); + assert.equal(ev('pzStarsTotal(pzLoad())'), 0); + // Packs unlock by the new stars. + ev("localStorage.removeItem('sot-puzzles')"); + assert.equal(ev("pzPackOpen('rodeo')"), false); + ev("ACT.pzStart({id:'edgelord'})"); + assert.notEqual(ev('S.pz.id'), 'edgelord', 'a locked puzzle does not start'); + ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:{hello:{st:3},eurotrip:{st:3},bigboat:{st:2},shining:{st:2}}}))"); + assert.equal(ev("pzPackOpen('rodeo')"), true, '10 stars open pack 2'); + ev('ACT.puzzleMenu({})'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Next pack, Traffic Cops, unlocks at 18/); + assert.deepEqual(errors, []); +}); + +test('results card: stars, the next puzzle, a retry, a share line and stars left in the pack', () => { + const { ev, errors } = load(); + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('eurotrip'))"); + build(ev, REF.eurotrip.one); + let card = ev("document.getElementById('modalCard').textContent"); + assert.match(card, /Puzzle solved/); + assert.equal(evalP(ev).stars, 2, 'delivered, and the budget star is on the house'); + assert.match(card, /One backhoe away/); + assert.match(card, /13 ⭐ left in this pack/); + assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')")); + build(ev, [['ams', 'lon', 'concerto', 1], ['ams', 'fra', 'land', 1]]); + card = ev("document.getElementById('modalCard').textContent"); + assert.match(card, /A backhoe walks into your network/); + assert.equal(ev("document.querySelectorAll('#modalCard .pzbig.on').length"), 3); + assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')")); + assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/); + assert.equal(ev("document.querySelector('#modalCard [data-act=pzRetry]')"), null, 'no retry after three stars'); + assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle Euro Trip ⭐⭐⭐ \$[\d.]+[kM] · seriesoftub\.es$/); + // The last puzzle points back to the list. + ev("localStorage.setItem('sot-puzzles',JSON.stringify({set:2,s:Object.fromEntries(PZ.map(p=>[p.id,{st:3}]))}));pzBegin(pzDef('samba'))"); + build(ev, REF.samba.three); + assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /More puzzles/); + assert.match(ev("document.getElementById('modalCard').textContent"), /Every star in this pack is yours/); + assert.deepEqual(errors, []); +}); + +test('best spend: kept for the best star count, and a cheaper build at the same stars counts', () => { + 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.three); + const three = evalP(ev); + assert.deepEqual(rec(), { st: 3, sp: three.spend }); + ev('S.pz.budget=1e7;ACT.pzTier({id:S.links[0].id,tier:2})'); + assert.equal(ev('S.links[0].tier'), 1, 'a 400G wave needs 400G routers: refused'); + ev("ACT.pzRtAdd({city:'nyc'})"); + assert.equal(evalP(ev).stars, 3); + assert.deepEqual(rec(), { st: 3, sp: three.spend }, 'a dearer 3-star build does not replace it'); + ev("ACT.pzRmLink({id:S.links[0].id})"); + assert.deepEqual(rec(), { st: 3, sp: three.spend }, 'fewer stars never overwrite more'); + ev('ACT.puzzleMenu({})'); + assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`))); + assert.deepEqual(errors, []); +}); + +test('weekly puzzle (seeded stand-in): stable per week, carries traffic, its reference ring earns three stars, streak', () => { + const { ev, errors } = load(); + const a = ev("JSON.stringify(pzWeekly(new Date(2026,9,28)))"), b = ev("JSON.stringify(pzWeekly(new Date(2026,10,1)))"), c = ev("JSON.stringify(pzWeekly(new Date(2026,10,2)))"); + assert.equal(a, b, 'same week, same puzzle'); + assert.notEqual(a, c, 'next week, a new one'); + const w = JSON.parse(a); + assert.equal(w.key, '2026-W44'); + assert.ok(w.cities.length >= 4 && w.dem.length === w.cities.length - 1 && w.src[0] === w.cities[0]); + for (let i = 0; i < 400; i += 28) { + const wi = JSON.parse(ev(`JSON.stringify(pzWeekly(new Date(2026,0,1+${i})))`)); + ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`); + build(ev, wi.ref.map((x, j) => [x, wi.ref[(j + 1) % wi.ref.length], wi.refVia[j], 0])); + assert.equal(evalP(ev).stars, 3, `week +${i}`); + } + ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))"); + build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j], 0])); + assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle 2026-W44 ⭐⭐⭐ \$[\d.]+[kM] · seriesoftub\.es$/); + assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).streak.n"), 1); + ev("const p=pzLoad();pzStreak(p,'2026-W45');pzStreak(p,'2026-W45');pzStreak(p,'2026-W46');window.__p=p"); + assert.equal(ev('__p.streak.n'), 3); + ev("pzStreak(__p,'2026-W49')"); + assert.equal(ev('__p.streak.n'), 1); + assert.equal(ev('__p.streak.best'), 3); + assert.deepEqual(errors, []); +}); + +test('puzzle HUD and panels fit a 360 px phone, portrait and landscape', () => { + const { ev, errors } = load(); + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'))"); + ev("pzBegin(pzDef('baltic'))"); + assert.equal(ev("document.getElementById('tabbar').hidden"), true); + assert.equal(ev("document.getElementById('pzBox').hidden"), false); + const box = ev("document.getElementById('pzBox').textContent"); + assert.match(box, /Eyeballs in Tallinn/); + assert.match(box, /Frankfurt ⇄ Tallinn circuit/); + assert.match(box, /Content lives in Frankfurt/); + ev("selectCity('fra')"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Open a POP/); + ev("document.querySelector('#panelBody [data-act=pzPop]').click()"); + assert.match(ev("document.getElementById('panelBody').textContent"), /Your POP[\s\S]*Router load[\s\S]*Ports[\s\S]*Router model/); + ev("pzLinkModal('fra','tll')"); + assert.equal(ev("document.querySelectorAll('#modalCard .tierbtn').length"), 4, 'four sizes'); + ev("closeModal();innerWidth=740;innerHeight=360;dispatchEvent(new Event('resize'));renderAll()"); + assert.equal(ev("document.getElementById('pzBox').hidden"), false, 'landscape too'); + // jsdom has no layout: the phone rules keep 40 px targets and pin the action row. + 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'),pos:r.style.getPropertyValue('position')})))`)); + assert.ok(rules.some((r) => /#pzBox \.btns \.b/.test(r.sel) && parseFloat(r.mh) >= 40), 'touch targets'); + assert.ok(rules.some((r) => /^#pzBox ?> ?\.btns$/.test(r.sel) && r.pos === 'sticky'), 'pinned actions'); + 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('puzzles in every language', () => { + for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { + const { ev, errors } = load({ lang }); + ev("ACT.puzzleMenu({});pzBegin(pzDef('baltic'))"); + build(ev, REF.baltic.three); + ev("selectCity('hel');renderAll()"); + const seen = ev("['pzBox','modalCard','hud','panelBody'].map(id=>document.getElementById(id).textContent).join(' ')"); + assert.ok(!/puzzles\./.test(seen), `${lang}: no raw labels`); + assert.match(seen, /⭐/); + assert.deepEqual(errors, [], lang); + } +}); + test('no clock in a puzzle: days never pass, nothing breaks, no bills', () => { const { ev, errors } = load(); ev("pzBegin(pzDef('hello'))"); @@ -205,152 +473,6 @@ test('leaving a puzzle with no game goes back to the title screen', () => { assert.deepEqual(errors, []); }); -test('results card pops the stars, offers the next puzzle, a retry and a share line', () => { - const { ev, errors } = load(); - ev("pzBegin(pzDef('eurotrip'))"); - build(ev, REF.eurotrip.one); - let card = ev("document.getElementById('modalCard').textContent"); - assert.match(card, /Puzzle solved/); - assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')")); - assert.match(ev("document.querySelector('#modalCard [data-act=pzStart]').dataset.args"), /shining/); - build(ev, [['lon', 'ams', 'concerto'], ['ams', 'fra', 'land']]); - card = ev("document.getElementById('modalCard').textContent"); - assert.match(card, /A backhoe walks into your network/); - assert.equal(ev("document.querySelectorAll('#modalCard .pzbig.on').length"), 3); - const line = ev('pzShareText(pzEval())'); - assert.match(line, /^Series of Tubes puzzle Euro Trip ⭐⭐⭐ \$\d+k · seriesoftub\.es$/); - assert.deepEqual(errors, []); -}); - -test('weekly puzzle: stable seed per ISO week, solvable, share string and streak', () => { - const { ev, errors } = load(); - const a = ev("JSON.stringify(pzWeekly(new Date(2026,9,28)))"), b = ev("JSON.stringify(pzWeekly(new Date(2026,10,1)))"), c = ev("JSON.stringify(pzWeekly(new Date(2026,10,2)))"); - assert.equal(a, b, 'same week, same puzzle'); - assert.notEqual(a, c, 'next week, a new one'); - const w = JSON.parse(a); - 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 < 400; i += 7) { - ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`); - 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)))"); - 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. - ev("const p=pzLoad();pzStreak(p,'2026-W45');pzStreak(p,'2026-W45');pzStreak(p,'2026-W46');window.__p=p"); - assert.equal(ev('__p.streak.n'), 3); - ev("pzStreak(__p,'2026-W49')"); - assert.equal(ev('__p.streak.n'), 1); - assert.equal(ev('__p.streak.best'), 3); - assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53'); - assert.equal(ev("pzPrevKey('2026-W01')"), '2025-W52'); - assert.deepEqual(errors, []); -}); - -test('pack unlocking follows the stars, and bad progress data is ignored', () => { - const { ev, errors } = load(); - ev("localStorage.removeItem('sot-puzzles')"); - assert.equal(ev("pzPackOpen('hello')"), true); - assert.equal(ev("pzPackOpen('fire')"), false); - ev("ACT.pzStart({id:'aloha'})"); - assert.notEqual(ev('S&&S.mode'), 'puzzle', 'a locked puzzle does not start'); - ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:3},eurotrip:{st:3}}}))"); - assert.equal(ev("pzPackOpen('fire')"), true, '6 stars open pack 2'); - ev('ACT.puzzleMenu({})'); - assert.match(ev("document.getElementById('modalCard').textContent"), /Next pack, Speed Runs, unlocks at 14/); - ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{hello:{st:99,sp:'x'},nope:{st:3},__proto__:{st:3}},wk:{bad:{st:3}},streak:{n:-4,last:''}}))"); - const p = JSON.parse(ev('JSON.stringify(pzLoad())')); - assert.deepEqual(p.s, { hello: { st: 3, sp: null } }); - assert.deepEqual(p.wk, {}); - assert.deepEqual(p.streak, { last: null, n: 0, best: 0 }); - ev("localStorage.setItem('sot-puzzles','{nope')"); - assert.equal(ev('pzStarsTotal(pzLoad())'), 0); - assert.deepEqual(errors, []); -}); - -test('puzzle HUD fits a 360 px phone: bottom sheet, no tab bar, panels work', () => { - const { dom, ev, errors } = load(); - ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'))"); - ev("pzBegin(pzDef('hello'))"); - assert.equal(ev("document.getElementById('tabbar').hidden"), true); - assert.equal(ev("document.getElementById('pzBox').hidden"), false); - ev("selectCity('lon')"); - assert.match(ev("document.getElementById('panelBody').textContent"), /Open a POP/); - ev("document.querySelector('#panelBody [data-act=pzPop]').click()"); - assert.ok(ev('!!S.pops.lon')); - ev("selectCity('par')"); - assert.equal(ev("document.getElementById('panel').hidden"), true, 'other cities do nothing'); - ev("pzLinkModal('lon','nyc')"); - assert.ok(ev("document.querySelectorAll('#modalCard .tierbtn').length") === 3, 'three sizes'); - assert.deepEqual(errors, []); - void dom; -}); - -test('puzzles in every language', () => { - for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { - const { ev, errors } = load({ lang }); - ev("ACT.puzzleMenu({});pzBegin(pzDef('braces'))"); - build(ev, REF.braces.three); - const seen = ev("['pzBox','modalCard','hud'].map(id=>document.getElementById(id).textContent).join(' ')"); - assert.ok(!/puzzles\./.test(seen), `${lang}: no raw labels`); - assert.match(seen, /⭐/); - 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, []); -}); - -test('best spend: kept for the best star count, and a cheaper build at the same stars counts', () => { - 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, []); -}); - 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)"); @@ -394,56 +516,13 @@ test('a city to avoid reads as a rule, not a goal that can fail', () => { assert.deepEqual(errors, []); }); -test('phone sheet: 40 px touch targets, pinned actions, and goal chips with a clear mark', () => { +test('a POP in a thin market costs its higher monthly rent too, and the panel says so', () => { 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, []); -}); - -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/); + 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 b640ab98148c93a279b91ee6a8171c62b903ef31 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 10:50:04 +0100 Subject: [PATCH 105/181] Weekly puzzle: schema 2 with traffic, sized references, regenerated weeks The generator gives every week content in its first city and eyeballs in the others (a latency sprint adds a circuit with a cap), sizes both references with the game's routing, and keeps the per-week rev refresh working with it. --- scripts/weekly-puzzle.js | 6 ++++-- tests/weekly-puzzle.test.js | 27 ++++++++++++++++++--------- 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/scripts/weekly-puzzle.js b/scripts/weekly-puzzle.js index 64092ae..5a9a0a1 100644 --- a/scripts/weekly-puzzle.js +++ b/scripts/weekly-puzzle.js @@ -279,7 +279,9 @@ function sized(g, W, P, def) { const sol = solve(W, P); if (!sol.one || !sol.three) return null; const one = size(g.ev, def, sol.one.links, false), three = size(g.ev, def, sol.three.links, true); if (!one || !three) return null; - return { one: { cost: Math.round(one.spend), b: one }, three: { cost: Math.round(three.spend), b: three } }; + // The three-star build delivers too: when it is the cheaper one (a ring, sized down), it is the one-star reference. + const o = one.spend <= three.spend ? one : three; + return { one: { cost: Math.round(o.spend), b: o }, three: { cost: Math.round(three.spend), b: three } }; } // The game's own validator decides what a puzzle is; then both references must earn their stars. function verify(g, W, j, key, known) { @@ -384,7 +386,7 @@ function refresh(g, dir, now = Date.now()) { 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, refresh, solve, world, writeWeek, writeIndex, list }; +module.exports = { game, generate, check, refresh, solve, sized, shape, 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; }; diff --git a/tests/weekly-puzzle.test.js b/tests/weekly-puzzle.test.js index e41c26e..8c3c118 100644 --- a/tests/weekly-puzzle.test.js +++ b/tests/weekly-puzzle.test.js @@ -88,8 +88,9 @@ test('generator: a quarter of weeks, all verified, varied, small and in the sche 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.ok(JSON.stringify(j).length < 900, 'small file'); + assert.ok(j.dem.length >= 2 && j.src.length === 1 && j.dem.every((f) => f.g > 0), `${j.key}: it carries traffic`); + assert.deepEqual(Object.keys(j), ['v', 'key', 'theme', 'cities', 'src', 'dem', '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)); }); @@ -113,7 +114,8 @@ test('--check passes on the committed files and rejects tampered ones', () => { 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((j) => { j.dem.push({ t: 'l2', a: j.cities[0], b: j.cities[1], g: 10, ms: 1 }); }, 'an impossible latency target'); + bad((j) => { j.dem[0].g = 5000; }, 'more traffic than a puzzle carries'); bad(() => '{nope', 'not JSON'); bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks'); }); @@ -221,11 +223,12 @@ test('the published puzzle is played when it is good, the seeded one when it is 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})`); - } + // The generator's sized 3-star reference, played into this puzzle (links, routers, routes). + const SV = require('../scripts/lib/puzzle-solver');SV.install(ev); + const def = JSON.parse(ev('JSON.stringify(pzWkDef())')), sol = G.sized({ ev }, G.world(ev), G.shape(def), def).three.b; + ev('pzBegin(pzWkDef())'); + SV.judge(ev, sol.links); + ev(`pzsApplyRt(${JSON.stringify(sol.rt)});pzAfter()`); 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')")); @@ -242,7 +245,13 @@ test('the file is checked field by field', () => { 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.v = 3; }, 'a newer schema'); + no((o) => { o.v = 1; }, 'an old file without traffic'); + no((o) => { o.dem = []; }, 'no traffic'); + no((o) => { o.dem = [{ t: 'warp', a: o.cities[0], g: 1 }]; }, 'an unknown kind of flow'); + no((o) => { o.dem = [{ ...o.dem[0], g: 1.5 }, ...o.dem.slice(1)]; }, 'fractional gigabits'); + no((o) => { o.src = []; }, 'eyeballs with nowhere to pull from'); + no((o) => { o.cities = o.cities.slice(0, -1); }, 'cities that do not match the traffic'); 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'); From 0ad1ef64350ebb9faa17d6f5496310aff2385c56 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 10:51:00 +0100 Subject: [PATCH 106/181] Changelog and architecture notes: puzzles with traffic --- CHANGELOG.md | 4 ++-- docs/ARCHITECTURE.md | 14 ++++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e56d08c..0dafde6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,8 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 - 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. -- 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. -- 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. +- Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. +- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, 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. - 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). - 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. - 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, sold-out routes and de-peering at exchanges. 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. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f990db4..ecdacda 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -157,12 +157,14 @@ its Monday (the week starting Sunday 1 November 2026 is `2026-W45`); `pzWeekKey( 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"}`). +latency sprint) and cities the last four weeks did not use, gives them traffic (content in the first city, eyeballs +in the others, a circuit with a latency cap for a sprint), searches for the cheapest topology that connects them and +the cheapest one that survives any single cut (a whole cable, or a trench), then sizes both with the game's own +routing (`scripts/lib/puzzle-solver.js`: links and routers big enough for every flow, after any cut too, then as +small as they go). The budget sits just above that N-1 build. Both references are judged by the game's own star +code 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":2,"key","theme","cities","src","dem","via","avoid","budget","twist","name":{"l","p"},"joke":{"l","p"},"ref","rev"?}`). `--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 From e880dc69c1d6966162aad46649f21843fcdbf4fd Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 11:13:59 +0100 Subject: [PATCH 107/181] The Networks list shows 100 networks at a time --- CHANGELOG.md | 1 + 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/90-actions/10-interface.js | 2 +- src/game/90-actions/70-dashboard-lists.js | 2 +- src/game/93-ui/40-hud-and-panels.js | 5 ++++- src/i18n/en.js | 1 + tests/networks-list.test.js | 18 ++++++++++++++++++ 11 files changed, 31 insertions(+), 3 deletions(-) create mode 100644 tests/networks-list.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dafde6..3f7204b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,7 @@ All notable changes to this project are documented here. The project follows - 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). - Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. - When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. +- The Networks list shows 100 networks at a time, with a button for the rest, so it opens quickly now that every country has its own networks. ## [1.37.0] — 2026-10-28 diff --git a/site/i18n/de.js b/site/i18n/de.js index 7fd624d..e9e57f3 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2014,6 +2014,7 @@ "hud_and_panels.lv_n":"Lv {n}", "hud_and_panels.n_incident":{"one":"{n} Störung","other":"{n} Störungen"}, "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} Nachricht wartet auf eine Antwort.","other":"{n} Nachrichten warten auf eine Antwort."}, +"hud_and_panels.n_more_networks":{"one":"+{n} weiteres Netz","other":"+{n} weitere Netze"}, "hud_and_panels.n_networks_d_days_left":"{n} Netze · noch {d} Tage", "hud_and_panels.n_new_notification":{"one":"{n} neue Benachrichtigung","other":"{n} neue Benachrichtigungen"}, "hud_and_panels.n_rules_live":"{n} Regeln aktiv", diff --git a/site/i18n/es.js b/site/i18n/es.js index d300f54..8fa80cc 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2012,6 +2012,7 @@ "hud_and_panels.lv_n":"Nv {n}", "hud_and_panels.n_incident":{"one":"{n} incidente","other":"{n} incidentes"}, "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} mensaje esperando respuesta.","other":"{n} mensajes esperando respuesta."}, +"hud_and_panels.n_more_networks":{"one":"+{n} red más","other":"+{n} redes más"}, "hud_and_panels.n_networks_d_days_left":"{n} redes · quedan {d} días", "hud_and_panels.n_new_notification":{"one":"{n} notificación nueva","other":"{n} notificaciones nuevas"}, "hud_and_panels.n_rules_live":"{n} reglas activas", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index b84b1a5..f10dcd5 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2012,6 +2012,7 @@ "hud_and_panels.lv_n":"Niv. {n}", "hud_and_panels.n_incident":{"one":"{n} incident","other":"{n} incidents"}, "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} message attend une réponse.","other":"{n} messages attendent une réponse."}, +"hud_and_panels.n_more_networks":{"one":"+{n} autre réseau","other":"+{n} autres réseaux"}, "hud_and_panels.n_networks_d_days_left":"{n} réseaux · {d} j restants", "hud_and_panels.n_new_notification":{"one":"{n} nouvelle notification","other":"{n} nouvelles notifications"}, "hud_and_panels.n_rules_live":"{n} règles actives", diff --git a/site/i18n/it.js b/site/i18n/it.js index 94f2d17..3f3f7d3 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2012,6 +2012,7 @@ "hud_and_panels.lv_n":"Liv. {n}", "hud_and_panels.n_incident":{"one":"{n} incidente","other":"{n} incidenti"}, "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} messaggio aspetta una risposta.","other":"{n} messaggi aspettano una risposta."}, +"hud_and_panels.n_more_networks":{"one":"+{n} altra rete","other":"+{n} altre reti"}, "hud_and_panels.n_networks_d_days_left":"{n} reti · {d} giorni rimasti", "hud_and_panels.n_new_notification":{"one":"{n} nuova notifica","other":"{n} nuove notifiche"}, "hud_and_panels.n_rules_live":"{n} regole attive", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 38ee4f2..634078f 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2012,6 +2012,7 @@ "hud_and_panels.lv_n":"Nv {n}", "hud_and_panels.n_incident":{"one":"{n} incidente","other":"{n} incidentes"}, "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} mensagem esperando resposta.","other":"{n} mensagens esperando resposta."}, +"hud_and_panels.n_more_networks":{"one":"+{n} rede a mais","other":"+{n} redes a mais"}, "hud_and_panels.n_networks_d_days_left":"{n} redes · faltam {d} dias", "hud_and_panels.n_new_notification":{"one":"{n} notificação nova","other":"{n} notificações novas"}, "hud_and_panels.n_rules_live":"{n} regras ativas", diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 70dc725..2efcb05 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -30,7 +30,7 @@ const ACT={ tab:({t})=>{UI.tab=t;UI.confirm=null;renderPanel();}, leftTab:({t})=>{UI.left=t;UI.leftOpen=true;renderLeft();}, netFocus:({id})=>{if(!NET[id])return;$('dash').hidden=true;UI.netFocus=id;UI.nf='all';UI.left='nets';UI.leftOpen=true;UI.sel=null;renderPanel();renderLeft();const b=$('leftBody');if(b)b.scrollTop=0;}, - netFilter:({f})=>{UI.nf=f==='out'?'out':'all';UI.netFocus=null;$('dash').hidden=true;UI.left='nets';UI.leftOpen=true;UI.sel=null;renderPanel();renderLeft();const b=$('leftBody');if(b)b.scrollTop=0;}, + netFilter:({f})=>{UI.nf=f==='out'?'out':'all';listReset('nets');UI.netFocus=null;$('dash').hidden=true;UI.left='nets';UI.leftOpen=true;UI.sel=null;renderPanel();renderLeft();const b=$('leftBody');if(b)b.scrollTop=0;}, meetGo:({city})=>{if(!isCity(city))return;$('dash').hidden=true;ACT.focusCity({city});if(S.pops[city]){UI.tab='peer';renderPanel();}}, toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;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();}, diff --git a/src/game/90-actions/70-dashboard-lists.js b/src/game/90-actions/70-dashboard-lists.js index 41d9ff6..3bb414b 100644 --- a/src/game/90-actions/70-dashboard-lists.js +++ b/src/game/90-actions/70-dashboard-lists.js @@ -1,6 +1,6 @@ Object.assign(ACT,{ 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();}, + listMore:({k})=>{if(k!=='conn'&&k!=='cust'&&k!=='nets')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;if(k==='nets'){renderLeft();return;}renderDash();}, custF:({v})=>{UI.kf=UI.kf||{};UI.kf.f=v==='sad'?'sad':'';listReset('cust');renderDash();}, custCity:({v})=>{UI.kf=UI.kf||{};UI.kf.city=isCity(v)?v:'';listReset('cust');renderDash();}, custSort:({k})=>{if(!['mood','mo','name','city'].includes(k))return;listReset('cust');if(UI.custSort===k)UI.custDir=-(UI.custDir||1);else{UI.custSort=k;UI.custDir=k==='mo'?-1:1;}renderDash();}, diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 90ccb82..8991ade 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -79,8 +79,11 @@ function renderLeft(){checkLayer(); const foc=UI.netFocus&&NET[UI.netFocus]?NET[UI.netFocus]:null,out=!foc&&UI.nf==='out',lostN=ntLost().length; 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; + // Shown 100 at a time like the dashboard lists: every country's own eyeballs made this list long (2.0). + const nl=(foc?[foc]:out?ntLost():NETS).filter(n=>!n.tail||UI.tailOpen||foc||out); + for(const n of nl.slice(0,listN('nets'))){ 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):''}
`;} + h+=listMore('nets',nl.length,n=>trn('hud_and_panels.n_more_networks',n)); 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/src/i18n/en.js b/src/i18n/en.js index a0e51dc..ba42357 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2013,6 +2013,7 @@ "hud_and_panels.lv_n":"Lv {n}", "hud_and_panels.n_incident":{"one":"{n} incident","other":"{n} incidents"}, "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} message waiting for an answer.","other":"{n} messages waiting for an answer."}, +"hud_and_panels.n_more_networks":{"one":"+{n} more network","other":"+{n} more networks"}, "hud_and_panels.n_networks_d_days_left":"{n} networks · {d} days left", "hud_and_panels.n_new_notification":{"one":"{n} new notification","other":"{n} new notifications"}, "hud_and_panels.n_rules_live":"{n} rules live", diff --git a/tests/networks-list.test.js b/tests/networks-list.test.js new file mode 100644 index 0000000..307bfbf --- /dev/null +++ b/tests/networks-list.test.js @@ -0,0 +1,18 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('the Networks list shows 100 networks at a time, with a button for the rest', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();UI.left='nets';UI.leftOpen=true;UI.tailOpen=false;ACT.netFilter({f:'all'})"); + const total = ev("NETS.filter(n=>!n.tail).length"); + assert.ok(total > 100, 'enough networks to page'); + const rows = () => ev("[...document.querySelectorAll('#left .row .nm .meta')].filter(e=>/^AS\\d/.test(e.textContent)).length"); + assert.equal(rows(), 100); + assert.ok(ev("!!document.querySelector('#left [data-act=listMore]')")); + ev("document.querySelector('#left [data-act=listMore]').click()"); + assert.equal(rows(), Math.min(total, 200)); + ev("ACT.netFilter({f:'all'})"); + assert.equal(rows(), 100, 'a new filter starts at the first page again'); + assert.deepEqual(errors, []); +}); From 2eb22d1df34b93fc9b1471b521a4271ff8e21755 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 11:31:46 +0100 Subject: [PATCH 108/181] Title screen: language first, name on top, compact presets, one home-city drawer --- CHANGELOG.md | 1 + site/i18n/de.js | 4 +-- site/i18n/es.js | 4 +-- site/i18n/fr.js | 4 +-- site/i18n/it.js | 4 +-- site/i18n/pt.js | 4 +-- src/game/90-actions/89-game-and-settings.js | 4 +-- src/game/95-modals/40-title.js | 26 +++++++++-------- src/i18n/en.js | 4 +-- src/styles/40-modal.css | 7 ++++- src/styles/60-phone.css | 7 ++--- tests/any-home-city.test.js | 31 +++++++++++---------- tests/regions.test.js | 2 +- 13 files changed, 49 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f7204b..bf31011 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,7 @@ All notable changes to this project are documented here. The project follows - Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. - When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. - The Networks list shows 100 networks at a time, with a button for the rest, so it opens quickly now that every country has its own networks. +- A tidier start screen: language first, then your network's name, the doors, three compact difficulty buttons with the chosen one explained below, and one drop-down for your home city with the five suggested homes at the top. ## [1.37.0] — 2026-10-28 diff --git a/site/i18n/de.js b/site/i18n/de.js index e9e57f3..3e92480 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3517,14 +3517,12 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · noch {n} Tage", "supply_chain.your_price_lock_covers_you_until":"Deine Preisgarantie gilt bis {date}.", "title.a_billion_dollars_and_every_toy":"Eine Milliarde Dollar und jedes Spielzeug im Laden.", -"title.anywhere_else":"Irgendwo anders", "title.asia_hub_great_peering_far_from":"Asien-Drehkreuz. Tolles Peering, weit weg von zu Hause.", "title.back_to_my_network":"Zurück zu meinem Netz", "title.big_hungry_market_few_providers":"Großer, hungriger Markt, wenige Anbieter.", "title.build_an_internet_lay_fiber_between":"Baue deinen eigenen ISP auf. Verlege Glasfaser zwischen Städten, kauf Transit, peere an Exchanges, gewinne Geschäftskunden und halte deine Privatkunden bei Laune, während Bagger, Haie und Route Leaks alles tun, um dich aufzuhalten.", "title.chaos_in_your_sandbox":"Chaos in deinem Sandkasten", "title.chat_on_signal":"Chat auf Signal", -"title.choose":"Auswählen …", "title.continue_name_date":"{name} fortsetzen · {date}", "title.cookieless_stats_no_tracking":"Statistik ohne Cookies, kein Tracking", "title.crossroads_of_europe_de_kicks_ix":"Drehkreuz Europas. DE-KICKS IX, günstiger Transit.", @@ -3532,7 +3530,6 @@ "title.hard_mode_pricey_everything":"Schwerer Modus. Alles teuer, und die Tierwelt will dich tot sehen.", "title.how_much_trouble":"Wie viel Ärger darf’s sein?", "title.huge_eyeball_market_pricey":"Riesiger Privatkundenmarkt. Teure Nachbarn.", -"title.n_more_cities_with_transit":{"one":"{n} weitere Stadt mit Transit zum Kaufen","other":"{n} weitere Städte mit Transit zum Kaufen"}, "title.name_your_network":"Gib deinem Netz einen Namen", "title.new_in_series_of_tubes_v":"Neu in Series of Tubes {v}", "title.one_network_one_knot_no_clock":"Ein Netz, ein Knoten zum Entwirren. Keine Uhr.", @@ -3543,6 +3540,7 @@ "title.rules_are_picked_once_and_locked":"Die Regeln wählst du einmal, danach sind sie für dieses Netz festgelegt. Kein Nachverhandeln mitten im Spiel.", "title.scenarios_amp_weekly":"Szenarien & Woche", "title.source_on_github":"Quellcode auf GitHub", +"title.suggested":"Empfohlen", "title.the_real_game_climb_from_tier":"Das echte Spiel: von Tier 3 hoch zu Tier 1.", "title.your_network_name_was_saved_and":"Dein Netz {name} wurde gespeichert und wartet auf dich.", "traceroute.a_peer_s_customers_come_after":"die Kunden eines Peers kommen nach direkten Peers und vor Transit", diff --git a/site/i18n/es.js b/site/i18n/es.js index 8fa80cc..fa2aec2 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3515,14 +3515,12 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · quedan {n} días", "supply_chain.your_price_lock_covers_you_until":"Tu precio fijo te cubre hasta {date}.", "title.a_billion_dollars_and_every_toy":"Mil millones de dólares y todos los juguetes de la tienda.", -"title.anywhere_else":"En otro lugar", "title.asia_hub_great_peering_far_from":"Hub de Asia. Gran peering, lejos de casa.", "title.back_to_my_network":"Volver a mi red", "title.big_hungry_market_few_providers":"Mercado enorme y hambriento, pocos proveedores.", "title.build_an_internet_lay_fiber_between":"Construye un internet. Tiende fibra entre ciudades, compra tránsito, haz peering en intercambios, firma con empresas y mantén contentos a los eyeballs mientras retroexcavadoras, tiburones y fugas de rutas hacen lo posible por detenerte.", "title.chaos_in_your_sandbox":"Caos en tu sandbox", "title.chat_on_signal":"Chatea en Signal", -"title.choose":"Elegir…", "title.continue_name_date":"Continuar {name} · {date}", "title.cookieless_stats_no_tracking":"Estadísticas sin cookies, sin rastreo", "title.crossroads_of_europe_de_kicks_ix":"La encrucijada de Europa. DE-KICKS IX, tránsito barato.", @@ -3530,7 +3528,6 @@ "title.hard_mode_pricey_everything":"Modo difícil. Todo carísimo, y la fauna te quiere muerto.", "title.how_much_trouble":"¿Cuántos problemas quieres?", "title.huge_eyeball_market_pricey":"Mercado enorme de eyeballs. Vecinos caros.", -"title.n_more_cities_with_transit":{"one":"{n} ciudad más con tránsito a la venta","other":"{n} ciudades más con tránsito a la venta"}, "title.name_your_network":"Ponle nombre a tu red", "title.new_in_series_of_tubes_v":"Novedades de Series of Tubes {v}", "title.one_network_one_knot_no_clock":"Una red, un nudo que deshacer. Sin reloj.", @@ -3541,6 +3538,7 @@ "title.rules_are_picked_once_and_locked":"Las reglas se eligen una vez y quedan fijadas para esta red. Nada de cambiar el trato a mitad de partida.", "title.scenarios_amp_weekly":"Escenarios y semanal", "title.source_on_github":"Código en GitHub", +"title.suggested":"Sugeridas", "title.the_real_game_climb_from_tier":"El juego de verdad: sube de Tier 3 a Tier 1.", "title.your_network_name_was_saved_and":"Tu red {name} se guardó y te está esperando.", "traceroute.a_peer_s_customers_come_after":"los clientes de un peer van después de los peers directos y antes del tránsito", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f10dcd5..030f85f 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3515,14 +3515,12 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · encore {n} jours", "supply_chain.your_price_lock_covers_you_until":"Votre blocage des prix vous couvre jusqu’au {date}.", "title.a_billion_dollars_and_every_toy":"Un milliard de dollars et tous les jouets du magasin.", -"title.anywhere_else":"Ailleurs", "title.asia_hub_great_peering_far_from":"Hub de l’Asie. Super peering, loin de chez soi.", "title.back_to_my_network":"Retour à mon réseau", "title.big_hungry_market_few_providers":"Gros marché affamé, peu d’opérateurs.", "title.build_an_internet_lay_fiber_between":"Construis un Internet. Pose de la fibre entre les villes, achète du transit, fais du peering aux IX, signe des entreprises et garde les eyeballs contents pendant que pelleteuses, requins et fuites de routes font tout pour t’arrêter.", "title.chaos_in_your_sandbox":"Du chaos dans ton bac à sable", "title.chat_on_signal":"Discuter sur Signal", -"title.choose":"Choisir…", "title.continue_name_date":"Continuer {name} · {date}", "title.cookieless_stats_no_tracking":"Stats sans cookies, sans pistage", "title.crossroads_of_europe_de_kicks_ix":"Carrefour de l’Europe. IX DE-KICKS, transit pas cher.", @@ -3530,7 +3528,6 @@ "title.hard_mode_pricey_everything":"Mode difficile. Tout coûte cher, et la faune veut ta peau.", "title.how_much_trouble":"Combien d’ennuis ?", "title.huge_eyeball_market_pricey":"Énorme marché d’eyeballs. Voisins chers.", -"title.n_more_cities_with_transit":{"one":"{n} autre ville où acheter du transit","other":"{n} autres villes où acheter du transit"}, "title.name_your_network":"Nomme ton réseau", "title.new_in_series_of_tubes_v":"Nouveautés de Series of Tubes {v}", "title.one_network_one_knot_no_clock":"Un réseau, un nœud à défaire. Pas d’horloge.", @@ -3541,6 +3538,7 @@ "title.rules_are_picked_once_and_locked":"Les règles se choisissent une fois et restent verrouillées pour ce réseau. Pas de renégociation en pleine partie.", "title.scenarios_amp_weekly":"Scénarios & hebdo", "title.source_on_github":"Code source sur GitHub", +"title.suggested":"Suggérées", "title.the_real_game_climb_from_tier":"Le vrai jeu : grimpe de Tier 3 à Tier 1.", "title.your_network_name_was_saved_and":"Ton réseau {name} a été sauvegardé et t’attend.", "traceroute.a_peer_s_customers_come_after":"les clients d’un peer passent après les peers directs, avant le transit", diff --git a/site/i18n/it.js b/site/i18n/it.js index 3f3f7d3..09c5feb 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3515,14 +3515,12 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · {n} giorni rimasti", "supply_chain.your_price_lock_covers_you_until":"Il tuo blocco dei prezzi ti copre fino al {date}.", "title.a_billion_dollars_and_every_toy":"Un miliardo di dollari e tutti i giocattoli del negozio.", -"title.anywhere_else":"Altrove", "title.asia_hub_great_peering_far_from":"Hub dell’Asia. Ottimo peering, lontano da casa.", "title.back_to_my_network":"Torna alla mia rete", "title.big_hungry_market_few_providers":"Mercato grande e affamato, pochi provider.", "title.build_an_internet_lay_fiber_between":"Costruisci un internet. Posa fibra tra le città, compra transit, fai peering agli exchange, metti sotto contratto le aziende e tieni contenti gli eyeball, mentre ruspe, squali e route leak fanno di tutto per fermarti.", "title.chaos_in_your_sandbox":"Caos nella tua sandbox", "title.chat_on_signal":"Chat su Signal", -"title.choose":"Scegli…", "title.continue_name_date":"Continua {name} · {date}", "title.cookieless_stats_no_tracking":"Statistiche senza cookie, nessun tracciamento", "title.crossroads_of_europe_de_kicks_ix":"Crocevia d’Europa. IX DE-KICKS, transit economico.", @@ -3530,7 +3528,6 @@ "title.hard_mode_pricey_everything":"Modalità difficile. Tutto carissimo, e la fauna ti vuole morto.", "title.how_much_trouble":"Quanti guai vuoi?", "title.huge_eyeball_market_pricey":"Enorme mercato di eyeball. Vicini costosi.", -"title.n_more_cities_with_transit":{"one":"Ancora {n} città dove comprare transit","other":"Altre {n} città dove comprare transit"}, "title.name_your_network":"Dai un nome alla tua rete", "title.new_in_series_of_tubes_v":"Novità di Series of Tubes {v}", "title.one_network_one_knot_no_clock":"Una rete, un nodo da sciogliere. Niente orologio.", @@ -3541,6 +3538,7 @@ "title.rules_are_picked_once_and_locked":"Le regole si scelgono una volta e restano bloccate per questa rete. Niente cambi di accordo a metà partita.", "title.scenarios_amp_weekly":"Scenari e sfida settimanale", "title.source_on_github":"Codice su GitHub", +"title.suggested":"Consigliate", "title.the_real_game_climb_from_tier":"Il gioco vero: sali da Tier 3 a Tier 1.", "title.your_network_name_was_saved_and":"La tua rete {name} è stata salvata e ti sta aspettando.", "traceroute.a_peer_s_customers_come_after":"i clienti di un peer vengono dopo i peer diretti e prima del transit", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 634078f..32d8965 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3515,14 +3515,12 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · faltam {n} dias", "supply_chain.your_price_lock_covers_you_until":"Seu congelamento de preços te cobre até {date}.", "title.a_billion_dollars_and_every_toy":"Um bilhão de dólares e todos os brinquedos da loja.", -"title.anywhere_else":"Outro lugar", "title.asia_hub_great_peering_far_from":"Hub da Ásia. Ótimo peering, longe de casa.", "title.back_to_my_network":"Voltar para minha rede", "title.big_hungry_market_few_providers":"Mercado grande e faminto, poucos provedores.", "title.build_an_internet_lay_fiber_between":"Construa uma internet. Lance fibra entre cidades, compre transit, faça peering nos exchanges, feche contratos com empresas e mantenha os eyeballs felizes enquanto retroescavadeiras, tubarões e route leaks fazem de tudo para te parar.", "title.chaos_in_your_sandbox":"Caos na sua sandbox", "title.chat_on_signal":"Chat no Signal", -"title.choose":"Escolha…", "title.continue_name_date":"Continuar {name} · {date}", "title.cookieless_stats_no_tracking":"Estatísticas sem cookies, sem rastreamento", "title.crossroads_of_europe_de_kicks_ix":"Encruzilhada da Europa. IX DE-KICKS, transit barato.", @@ -3530,7 +3528,6 @@ "title.hard_mode_pricey_everything":"Modo difícil. Tudo caro, e a fauna quer te ver morto.", "title.how_much_trouble":"Quanta encrenca?", "title.huge_eyeball_market_pricey":"Mercado enorme de eyeballs. Vizinhos caros.", -"title.n_more_cities_with_transit":{"one":"Mais {n} cidade com transit à venda","other":"Mais {n} cidades com transit à venda"}, "title.name_your_network":"Dê um nome à sua rede", "title.new_in_series_of_tubes_v":"Novidades no Series of Tubes {v}", "title.one_network_one_knot_no_clock":"Uma rede, um nó para desatar. Sem relógio.", @@ -3541,6 +3538,7 @@ "title.rules_are_picked_once_and_locked":"As regras são escolhidas uma vez e ficam travadas para esta rede. Nada de mudar o combinado no meio do jogo.", "title.scenarios_amp_weekly":"Cenários e semanal", "title.source_on_github":"Código no GitHub", +"title.suggested":"Sugeridas", "title.the_real_game_climb_from_tier":"O jogo de verdade: suba de Tier 3 a Tier 1.", "title.your_network_name_was_saved_and":"Sua rede {name} foi salva e está te esperando.", "traceroute.a_peer_s_customers_come_after":"os clientes de um peer vêm depois dos peers diretos e antes do transit", diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 2cf2360..d81413e 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -4,14 +4,14 @@ Object.assign(ACT,{ beginGame(nm,homeOk(UI.startCity)?UI.startCity:'fra',sb?{mode:'sandbox',rules:{chaos:own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'}}:{mode:'normal',preset:NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall'});}, // Title-screen doors and their options toggle in place, so the name being typed and the city stay as they are. modeSet:({m})=>{if(m!=='sandbox'&&m!=='normal')return;UI.mode=m;document.querySelectorAll('.door').forEach(b=>b.classList.toggle('on',b.dataset.door===m));const n=$('doorNormal'),x=$('doorSandbox');if(n)n.hidden=m!=='normal';if(x)x.hidden=m!=='sandbox';}, - presetSet:({p})=>{if(!NORMAL_PRESETS.includes(p))return;UI.preset=p;ACT.modeSet({m:'normal'});document.querySelectorAll('.preset').forEach(b=>b.classList.toggle('on',b.dataset.preset===p));}, + presetSet:({p})=>{if(!NORMAL_PRESETS.includes(p))return;UI.preset=p;ACT.modeSet({m:'normal'});document.querySelectorAll('.preset').forEach(b=>{b.classList.toggle('on',b.dataset.preset===p);b.setAttribute('aria-pressed',b.dataset.preset===p);});const w=$('presetWhat');if(w)w.innerHTML=presetWhat(p);}, chaosSet:({c})=>{if(!own(CHAOS,c))return;UI.sbChaos=c;ACT.modeSet({m:'sandbox'});document.querySelectorAll('.chs').forEach(b=>b.classList.toggle('on',b.dataset.chaos===c));}, // Puzzles live in their own module; until it ships, the door says so. puzzleDoor:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||randomNetworkName()).slice(0,24);if(typeof ACT.puzzleMenu==='function')ACT.puzzleMenu();else toast(tr('title.puzzles_are_coming_soon'),'goal');}, scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();}, startScn:({id})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});}, startWeekly:()=>{const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, - pickStart:({city})=>{if(!homeOk(city))return;UI.startCity=city;document.querySelectorAll('.start').forEach(b=>b.classList.toggle('on',b.dataset.city===city||(b.classList.contains('own')&&!START5.includes(city))));const s=$('homeSel');if(s&&START5.includes(city))s.value='';const w=$('homeWhat');if(w)w.innerHTML=homeWhat();}, + pickStart:({city})=>{if(!homeOk(city))return;UI.startCity=city;const s=$('homeSel');if(s)s.value=city;const w=$('homeWhat');if(w)w.innerHTML=homeWhat();}, pickHome:({v})=>{if(v)ACT.pickStart({city:v});else ACT.pickStart({city:'fra'});}, // Delete this window's network and go back to the title (the other networks stay). newgame:()=>{if(pzOn())pzLeave();const id=UI.slot;if(id){slotDrop(id);slotFree(id);}gameClear();showTitle();}, diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index ec9a0f9..ef1dc02 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -2,24 +2,24 @@ // a license first) can't be a home, and neither can a city where nobody sells transit: you'd start cut off. const homeOk=c=>own(CITY,c)&&!CITY[c].off&&!CITY[c].cn&&NETS.some(n=>sellsAt(n,c)); const START5=['fra','nyc','sin','sao','syd']; -function homePick(){const cs=Object.keys(CITY).filter(homeOk),cur=START5.includes(UI.startCity)?'':UI.startCity; - return ``;} -// A dropdown can't wrap, so long names (Yuzhno-Sakhalinsk) get cut on phones: the line above it says the whole name. -const homeWhat=()=>START5.includes(UI.startCity)?trn('title.n_more_cities_with_transit',Object.keys(CITY).filter(c=>homeOk(c)&&!START5.includes(c)).length):`${esc(CITY[UI.startCity].name)} · ${esc(REG[CITY[UI.startCity].reg])}`; +// One drawer for the home city: the five suggested homes first, then every city with transit by continent. +const START_D=()=>({fra:tr('title.crossroads_of_europe_de_kicks_ix'),nyc:tr('title.huge_eyeball_market_pricey'),sin:tr('title.asia_hub_great_peering_far_from'),sao:tr('title.big_hungry_market_few_providers'),syd:tr('title.hard_mode_pricey_everything')}); +function homePick(){const cs=Object.keys(CITY).filter(c=>homeOk(c)&&!START5.includes(c)),cur=UI.startCity,opt=c=>``; + return ``;} +// The line under the drawer: what the suggested home is like, or which continent another city is on. +const homeWhat=()=>START5.includes(UI.startCity)?esc(START_D()[UI.startCity]):`${esc(CITY[UI.startCity].name)} · ${esc(REG[CITY[UI.startCity].reg])}`; function showTitle(){ const list=slotIdx(true),top=slotTop(list),many=list.length>1||(list.length===1&&list[0]!==top); if(UI.nm==null)UI.nm=randomNetworkName(); - const starts=[['fra',tr('title.crossroads_of_europe_de_kicks_ix')],['nyc',tr('title.huge_eyeball_market_pricey')],['sin',tr('title.asia_hub_great_peering_far_from')],['sao',tr('title.big_hungry_market_few_providers')],['syd',tr('title.hard_mode_pricey_everything')]]; - openModal(`
+ openModal(`
${langPick('langTitle')}

Series
of Tubes

-

${tr('title.build_an_internet_lay_fiber_between')}

${plugHtml(false)}${isPhone()?installRow():''} +

${tr('title.build_an_internet_lay_fiber_between')}

${isPhone()?installRow():''} ${top?`
${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}
`:''} ${many?slotsHtml():''} - ${doorsHtml()}
${btn(tr('common.another_one'),'randomName',{},'ghost sm')}
-
${starts.map(([c,d])=>``).join('')}
- ${langPick('langTitle')} + ${doorsHtml()} + ${homePick()}

${homeWhat()}

${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); $('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;}); } @@ -37,8 +37,10 @@ function whatsNew(returning,force){ screen (presets / chaos below), Puzzles and Scenarios open their own lists. Choices toggle in place (no re-render). */ 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'}; +// The chosen preset in one line: its joke, then what actually changes. +const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)}`; 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('')}
-
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}
+
${NORMAL_PRESETS.map(k=>{const P=PRESETS[k];return ``;}).join('')}

${presetWhat(pr)}

${Object.entries(CHAOS).map(([k,C])=>``).join('')}

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

`;} diff --git a/src/i18n/en.js b/src/i18n/en.js index ba42357..eec9b80 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3516,14 +3516,12 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · {n} days left", "supply_chain.your_price_lock_covers_you_until":"Your price lock covers you until {date}.", "title.a_billion_dollars_and_every_toy":"A billion dollars and every toy in the shop.", -"title.anywhere_else":"Anywhere else", "title.asia_hub_great_peering_far_from":"Asia hub. Great peering, far from home.", "title.back_to_my_network":"Back to my network", "title.big_hungry_market_few_providers":"Big hungry market, few providers.", "title.build_an_internet_lay_fiber_between":"Build an internet. Lay fiber between cities, buy transit, peer at exchanges, sign up businesses, and keep the eyeballs happy while backhoes, sharks and route leaks do their best to stop you.", "title.chaos_in_your_sandbox":"Chaos in your sandbox", "title.chat_on_signal":"Chat on Signal", -"title.choose":"Choose…", "title.continue_name_date":"Continue {name} · {date}", "title.cookieless_stats_no_tracking":"Cookieless stats, no tracking", "title.crossroads_of_europe_de_kicks_ix":"Crossroads of Europe. DE-KICKS IX, cheap transit.", @@ -3531,7 +3529,6 @@ "title.hard_mode_pricey_everything":"Hard mode. Pricey everything, and the wildlife wants you dead.", "title.how_much_trouble":"How much trouble?", "title.huge_eyeball_market_pricey":"Huge eyeball market. Pricey neighbours.", -"title.n_more_cities_with_transit":{"one":"{n} more city with transit to buy","other":"{n} more cities with transit to buy"}, "title.name_your_network":"Name your network", "title.new_in_series_of_tubes_v":"New in Series of Tubes {v}", "title.one_network_one_knot_no_clock":"One network, one knot to untie. No clock.", @@ -3542,6 +3539,7 @@ "title.rules_are_picked_once_and_locked":"The rules are picked once and locked for this network. No changing the deal mid-game.", "title.scenarios_amp_weekly":"Scenarios & weekly", "title.source_on_github":"Source on GitHub", +"title.suggested":"Suggested", "title.the_real_game_climb_from_tier":"The real game: climb from Tier 3 to Tier 1.", "title.your_network_name_was_saved_and":"Your network {name} was saved and is waiting for you.", "traceroute.a_peer_s_customers_come_after":"a peer’s customers come after direct peers, before transit", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 9853087..01c2101 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -107,7 +107,7 @@ label.f+select.pick{width:100%} .title-art h1 span{color:var(--me)} .tagline{color:var(--ink2);font-size:14.5px;line-height:1.45;margin:10px 0 14px} label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink2);margin:12px 0 5px} -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)} +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);color:var(--ink);-webkit-text-fill-color:var(--ink)} .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} @@ -177,3 +177,8 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .slot-go:focus-visible,.slot-more:focus-visible{outline:3px solid #FF4F9A;outline-offset:-3px} .ibx.space{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.ibx.space .btns{margin:0} h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} +/* Title: language first, compact presets, one drawer for the home city (2.0) */ +.tlang{display:flex;justify-content:flex-end;margin:-4px 0 4px}.tlang .pick{width:auto;max-width:60%} +.presets .preset{flex-direction:row;align-items:center;gap:6px;padding:6px 10px 5px}.presets .preset i{font-size:20px}.presets .preset b{font-size:15px} +.presets .preset.on::after{display:none}#presetWhat{margin:6px 0 0} +.homepick{width:100%} diff --git a/src/styles/60-phone.css b/src/styles/60-phone.css index ae2a0b8..6bccadf 100644 --- a/src/styles/60-phone.css +++ b/src/styles/60-phone.css @@ -60,10 +60,9 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar .tagline{font-size:13.5px;margin:8px 0 10px} .slots{max-height:38vh}.slot-go{padding:7px 4px 7px 9px;gap:8px}.slot-go>i{font-size:22px}.slot .sn b{font-size:16px}.slot .sm em{font-size:13.5px}.slot .sn small,.slot .sm small{font-size:11.5px} .door{padding:7px 9px 6px}.door i{font-size:22px}.door b{font-size:16px}.door span{font-size:11.5px} - .presets{grid-template-columns:1fr;gap:6px} - .preset{display:grid;grid-template-columns:auto 1fr;column-gap:9px;align-items:center;padding:6px 10px} - .preset i{grid-row:1/4;font-size:24px}.preset b{font-size:16px}.preset span,.preset small{grid-column:2} - .preset small{border-top:0;padding-top:0;margin-top:1px} + .presets{grid-template-columns:repeat(3,minmax(0,1fr));gap:6px} + .presets .preset{flex-direction:column;align-items:center;text-align:center;padding:6px 4px;gap:0} + .presets .preset i{font-size:20px}.presets .preset b{font-size:13.5px} .chaos{grid-template-columns:repeat(2,minmax(0,1fr))} #modal .card{box-sizing:border-box;width:100%;max-height:calc(100% - env(safe-area-inset-top,0px) - 24px);border-radius:22px 22px 0 0;padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px));border-bottom:0} #dash{padding:calc(env(safe-area-inset-top,0px) + 6px) 0 0} diff --git a/tests/any-home-city.test.js b/tests/any-home-city.test.js index 9044b9c..0330cb7 100644 --- a/tests/any-home-city.test.js +++ b/tests/any-home-city.test.js @@ -3,31 +3,29 @@ const assert = require('node:assert/strict'); const { load } = require('./harness'); const choose = (ev, v) => ev(`(()=>{const s=document.getElementById('homeSel');s.value=${JSON.stringify(v)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`); -const onTiles = ev => JSON.parse(ev("JSON.stringify([...document.querySelectorAll('.starts .start.on')].map(b=>b.dataset.city||'own'))")); - -test('the title screen offers five homes and a sixth tile for any city, grouped by continent', () => { +test('the title screen has one drawer for the home city: the five suggested first, then every city by continent', () => { const { ev, errors } = load(); assert.equal(ev('S'), null, 'before any game exists'); - assert.equal(ev("document.querySelectorAll('.starts .start').length"), 6); - const opts = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#homeSel option')].map(o=>o.value).filter(Boolean))")); + const opts = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#homeSel option')].map(o=>o.value))")); + assert.deepEqual(opts.slice(0, 5), ['fra', 'nyc', 'sin', 'sao', 'syd'], 'the suggested homes come first'); + assert.equal(new Set(opts).size, opts.length, 'no city twice'); assert.ok(opts.length > 150, `lots of cities (${opts.length})`); assert.ok(opts.every(c => ev(`homeOk('${c}')`)), 'only cities that work as a home'); assert.ok(!opts.some(c => ev(`!!CITY['${c}'].cn||!!CITY['${c}'].off`)), 'no hidden or Chinese cities'); assert.ok(!opts.includes('stg'), 'no city without transit to buy'); - assert.ok(ev("document.querySelectorAll('#homeSel optgroup').length") >= 5, 'grouped by continent'); + assert.ok(ev("document.querySelectorAll('#homeSel optgroup').length") >= 6, 'suggested plus continents'); + assert.equal(ev("document.getElementById('homeSel').value"), 'fra'); + assert.equal(ev("document.querySelectorAll('.starts .start').length"), 0, 'no tiles any more'); assert.deepEqual(errors, []); }); -test('picking any city starts the network there, and the tiles follow the choice', () => { +test('picking any city starts the network there, and the line under the drawer follows the choice', () => { const { ev, errors } = load(); choose(ev, 'lis'); assert.equal(ev('UI.startCity'), 'lis'); - assert.deepEqual(onTiles(ev), ['own'], 'the sixth tile lights up'); assert.equal(ev("document.getElementById('homeWhat').textContent"), 'Lisbon · ' + ev("REG[CITY.lis.reg]"), 'and names the city in full'); - ev("document.querySelector('.start[data-city=nyc]').click()"); - assert.deepEqual(onTiles(ev), ['nyc'], 'a suggested tile takes over again'); - assert.equal(ev("document.getElementById('homeSel').value"), '', 'and the dropdown resets'); - assert.match(ev("document.getElementById('homeWhat').textContent"), /more cities/); + choose(ev, 'nyc'); + assert.equal(ev("document.getElementById('homeWhat').textContent"), ev("tr('title.huge_eyeball_market_pricey')"), 'a suggested home says what it is like'); choose(ev, 'akl'); ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); assert.equal(ev('S.home'), 'akl'); @@ -45,12 +43,15 @@ test('a home that cannot work is refused, and the game falls back to Frankfurt', assert.deepEqual(errors, []); }); -test('the sixth tile works on a phone and in every language', () => { +test('the title screen works on a phone in every language: language first, the name on top, compact presets', () => { for (const lang of ['en', 'it', 'pt', 'fr', 'es', 'de']) { const { ev, errors } = load(lang === 'en' ? {} : { lang }); ev('window.innerWidth=360;showTitle()'); - assert.equal(ev("document.querySelector('label.start.own b').textContent"), ev("tr('title.anywhere_else')"), lang); - if (lang !== 'en') assert.notEqual(ev("tr('title.anywhere_else')"), 'Anywhere else', `${lang}: translated`); + const order = ev("(()=>{const c=document.getElementById('modalCard');const at=s=>[...c.querySelectorAll('*')].indexOf(c.querySelector(s));return [at('#langTitle'),at('.title-art'),at('#nmIn'),at('.doors'),at('#homeSel')].join(',')})()").split(',').map(Number); + assert.ok(order.every((v, i) => v >= 0 && (i === 0 || v > order[i - 1])), `${lang}: language, title, name, doors, home (${order})`); + assert.equal(ev("document.querySelectorAll('#modalCard .preset small,#modalCard .preset span').length"), 0, `${lang}: presets are just icon and name`); + assert.ok(ev("document.getElementById('presetWhat').textContent.length") > 10, `${lang}: the chosen preset explained below`); + if (lang !== 'en') assert.notEqual(ev("tr('title.suggested')"), 'Suggested', `${lang}: translated`); assert.deepEqual(errors, []); } }); diff --git a/tests/regions.test.js b/tests/regions.test.js index cba9320..0ae73fa 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -605,7 +605,7 @@ test('Africa: more countries, cables along both coasts, border costs and Cape to test('Australia: hard mode start in Sydney, dear transit and waves, cheap IX ports, NBN takes its cut', () => { const { ev, errors } = load(); ev("showTitle()"); - assert.ok(ev("!!document.querySelector('.start[data-city=\"syd\"]')"), 'Sydney is on the start screen'); + assert.ok(ev("!!document.querySelector('#homeSel optgroup:first-child option[value=syd]')"), 'Sydney is among the suggested homes'); ev("ACT.pickStart({city:'syd'});ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0"); assert.equal(ev('S.home'), 'syd'); assert.equal(ev("regionMult('syd')"), 3, 'transit into Australia costs more than Asia'); From f24abe8fc7d19f2363864232908ddc32c33d6c70 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 11:44:39 +0100 Subject: [PATCH 109/181] Puzzles keep going until three stars: a cheer for each new star, results at three or on Finish --- 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/92-puzzles.js | 6 ++++-- src/game/90-actions/95-puzzles.js | 1 + src/game/95-modals/95-puzzles.js | 7 ++++--- src/i18n/en.js | 2 ++ tests/puzzles.test.js | 6 +++++- 10 files changed, 26 insertions(+), 6 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 3e92480..5a70307 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2948,6 +2948,7 @@ "puzzles.every_star_in_this_pack_is":"Alle Sterne in diesem Paket gehören dir.", "puzzles.everything_at_once_across_oceans":"Alles auf einmal, über Ozeane. Knappe Budgets.", "puzzles.fat_pipes":"Dicke Rohre", +"puzzles.finish_here":"Hier aufhören", "puzzles.fjord_focus":"Fjord im Fokus", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Leitung {a} ⇄ {b}", @@ -3066,6 +3067,7 @@ "puzzles.your_pop":"Dein POP", "puzzles.your_routers_pick_the_path":"Deine Router wählen den Weg. Sag ihnen welchen: Metriken, niedrigste Latenz, Best Effort.", "puzzles.your_stars":"Deine Sterne", +"puzzles.your_stars_so_far":"Deine Sterne bisher", "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.", diff --git a/site/i18n/es.js b/site/i18n/es.js index fa2aec2..ddaaea1 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2946,6 +2946,7 @@ "puzzles.every_star_in_this_pack_is":"Todas las estrellas de este paquete son tuyas.", "puzzles.everything_at_once_across_oceans":"Todo a la vez, cruzando océanos. Presupuestos ajustados.", "puzzles.fat_pipes":"Tubos gordos", +"puzzles.finish_here":"Terminar aquí", "puzzles.fjord_focus":"Rumbo al fiordo", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", @@ -3064,6 +3065,7 @@ "puzzles.your_pop":"Tu POP", "puzzles.your_routers_pick_the_path":"Tus routers eligen el camino. Diles cuál: métricas, menor latencia, best effort.", "puzzles.your_stars":"Tus estrellas", +"puzzles.your_stars_so_far":"Tus estrellas hasta ahora", "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.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 030f85f..a45927a 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2946,6 +2946,7 @@ "puzzles.every_star_in_this_pack_is":"Toutes les étoiles de ce pack sont à toi.", "puzzles.everything_at_once_across_oceans":"Tout à la fois, par-delà les océans. Budgets serrés.", "puzzles.fat_pipes":"Gros tuyaux", +"puzzles.finish_here":"Terminer ici", "puzzles.fjord_focus":"Cap sur le fjord", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Circuit {a} ⇄ {b}", @@ -3064,6 +3065,7 @@ "puzzles.your_pop":"Ton POP", "puzzles.your_routers_pick_the_path":"Tes routeurs choisissent le chemin. Dis-leur lequel : métriques, latence minimale, best effort.", "puzzles.your_stars":"Tes étoiles", +"puzzles.your_stars_so_far":"Tes étoiles pour l'instant", "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.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 09c5feb..9afaeb6 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2946,6 +2946,7 @@ "puzzles.every_star_in_this_pack_is":"Tutte le stelle di questo pacchetto sono tue.", "puzzles.everything_at_once_across_oceans":"Tutto insieme, oltre gli oceani. Budget stretti.", "puzzles.fat_pipes":"Tubi grossi", +"puzzles.finish_here":"Finisci qui", "puzzles.fjord_focus":"Fuoco sul fiordo", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", @@ -3064,6 +3065,7 @@ "puzzles.your_pop":"Il tuo POP", "puzzles.your_routers_pick_the_path":"I tuoi router scelgono il percorso. Digli quale: metriche, latenza minima, best effort.", "puzzles.your_stars":"Le tue stelle", +"puzzles.your_stars_so_far":"Le tue stelle finora", "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.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 32d8965..0dba80c 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2946,6 +2946,7 @@ "puzzles.every_star_in_this_pack_is":"Todas as estrelas deste pacote são suas.", "puzzles.everything_at_once_across_oceans":"Tudo de uma vez, atravessando oceanos. Orçamentos apertados.", "puzzles.fat_pipes":"Canos grossos", +"puzzles.finish_here":"Terminar aqui", "puzzles.fjord_focus":"Foco no fiorde", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"Circuito {a} ⇄ {b}", @@ -3064,6 +3065,7 @@ "puzzles.your_pop":"Seu POP", "puzzles.your_routers_pick_the_path":"Seus routers escolhem o caminho. Diga qual: métricas, menor latência, best effort.", "puzzles.your_stars":"Suas estrelas", +"puzzles.your_stars_so_far":"Suas estrelas até agora", "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.", diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index 4b2b9ee..c840b9f 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -145,9 +145,11 @@ function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0]. function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();} function 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. +// Stars count the moment they are earned. // 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;} +// A new star below three is a cheer and a nudge, and play goes on; the results card opens at three stars, or when the +// player says they are done (the card's Finish button). +function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}return e;} // The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend. function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null}; if(e.stars{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:()=>{if(pzWkLoading())return;pzBegin(pzWkDef());}, + pzFinish:()=>{if(!pzOn())return;const e=pzEval();if(e.stars)pzResults(e,e.stars);}, 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','off'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop(city);sfx('build');haptic(10);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');pzAfter();}, diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index cb22b32..e0311fd 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -29,7 +29,7 @@ function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hi const w=e.worst; h+=!e.goal?`
🛡 ${tr('puzzles.n_1_deliver_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut_under_load')}
` :`
⚠️ ${tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(w.u),g:fmtG(w.g)})}
${w.lost.map(x=>esc(pzFlowName(P.dem[x.i]))).join(', ')}
`; - 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')}
`; + 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)}${(UI.pzTop||0)>0&&(UI.pzTop||0)<3?btn(tr('puzzles.finish_here'),'pzFinish',{},'sm'):''}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'ghost sm')}
`; if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} // Trenches on a pair get numbers, cables their names, so parallel links say where they run. function pzTrench(l){if(l.cable)return esc(CAB[l.cable].name);const us=[...new Set(pairLinks(l.a,l.b).filter(x=>!x.cable).map(pzUnit))];return tr('puzzles.trench_n',{n:us.indexOf(pzUnit(l))+1});} @@ -106,7 +106,7 @@ function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#2 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))}

+ openModal(`
${e.stars>=3?pzConfetti():''}
${done?tr('puzzles.puzzle_solved'):tr('puzzles.your_stars_so_far')}

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

${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.delivered'),tr('puzzles.every_bit_arrives'))}${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_under_load'):tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(e.worst.u),g:fmtG(e.worst.g)}))}
${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')}
`); @@ -114,6 +114,7 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left 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);} +function pzCheer(e,prev){toast(`${'⭐'.repeat(e.stars)}${'☆'.repeat(3-e.stars)}
${pzLine(e)}`,'goal');for(let i=prev;i{sfx('star');haptic(15);},(i-prev)*450+150);} // ---------- the list ---------- // 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=pzWkRec(p,w),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=pzDemTag(w); @@ -127,7 +128,7 @@ function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.lengt // Once, after the puzzles got traffic: the old stars are kept on the wall, the new set starts at zero. if(p.old&&!p.noted){h+=`
🖼️ ${tr('puzzles.puzzles_got_traffic_note',{n:p.old})}
`;p.noted=1;pzStore(p);} h+=`
${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}${p.old?`
🖼️ ${tr('puzzles.framed_n_stars_from_the_old',{n:p.old})}
`:''}
`; - 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')}
`; + if(pzOn())h+=`
${(UI.pzTop||0)>0&&(UI.pzTop||0)<3?btn(tr('puzzles.finish_here'),'pzFinish',{},'sm'):''}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; 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})}

`; diff --git a/src/i18n/en.js b/src/i18n/en.js index eec9b80..c0e470a 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2947,6 +2947,7 @@ "puzzles.every_star_in_this_pack_is":"Every star in this pack is yours.", "puzzles.everything_at_once_across_oceans":"Everything at once, across oceans. Tight budgets.", "puzzles.fat_pipes":"Fat Pipes", +"puzzles.finish_here":"Finish here", "puzzles.fjord_focus":"Fjord Focus", "puzzles.flash_boys":"Flash Boys", "puzzles.flow_circuit_a_b":"{a} ⇄ {b} circuit", @@ -3065,6 +3066,7 @@ "puzzles.your_pop":"Your POP", "puzzles.your_routers_pick_the_path":"Your routers pick the path. Tell them which: metrics, lowest latency, best effort.", "puzzles.your_stars":"Your stars", +"puzzles.your_stars_so_far":"Your stars so far", "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.", diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 8e1db0d..de3ba39 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -314,8 +314,12 @@ test('results card: stars, the next puzzle, a retry, a share line and stars left const { ev, errors } = load(); ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('eurotrip'))"); build(ev, REF.eurotrip.one); + assert.ok(ev("$('modal').hidden||!document.querySelector('#modalCard .pzres')"), 'two stars: no results card, play goes on'); + assert.match(ev("document.getElementById('toasts').textContent"), /One backhoe away/, 'a cheer with the next step instead'); + assert.ok(ev("!!document.querySelector('[data-act=pzFinish]')"), 'and a Finish button on the card'); + ev("document.querySelector('[data-act=pzFinish]').click()"); let card = ev("document.getElementById('modalCard').textContent"); - assert.match(card, /Puzzle solved/); + assert.match(card, /Your stars so far/); assert.equal(evalP(ev).stars, 2, 'delivered, and the budget star is on the house'); assert.match(card, /One backhoe away/); assert.match(card, /13 ⭐ left in this pack/); From da7f4e6927f130addaa104e763b6ce716269e069 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 17:34:38 +0100 Subject: [PATCH 110/181] Weekly scenario in the game: goal types, file validation, Scenarios row, streak and share line --- site/i18n/de.js | 61 +++++++++ site/i18n/es.js | 61 +++++++++ site/i18n/fr.js | 61 +++++++++ site/i18n/it.js | 61 +++++++++ site/i18n/pt.js | 61 +++++++++ src/game/60-features/20-scenarios.js | 6 +- src/game/60-features/70-scenario-progress.js | 5 +- src/game/60-features/94-scenarios-weekly.js | 125 +++++++++++++++++++ src/game/80-simulation/50-sanitize.js | 5 +- src/game/90-actions/89-game-and-settings.js | 5 +- src/game/94-dashboard/10-progress.js | 1 + src/game/95-modals/40-title.js | 2 +- src/i18n/en.js | 61 +++++++++ 13 files changed, 507 insertions(+), 8 deletions(-) create mode 100644 src/game/60-features/94-scenarios-weekly.js diff --git a/site/i18n/de.js b/site/i18n/de.js index 5a70307..82a1847 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3605,4 +3605,65 @@ "utilities.title":"Werkzeuge", "utilities.two_routers":"Mindestens zwei Router", "utilities.view_pop":"POP ansehen", +"wkscn.copy_my_result":"Mein Ergebnis kopieren", +"wkscn.desc_a_g_event_comes_to":"An Tag {day} kommt ein Event mit {g} nach {city}. Bau das Netz dafür, aus dem Nichts.", +"wkscn.desc_a_ship_dragged_its_anchor":"Ein Schiff hat seinen Anker über {cab} geschleift. Finde einen anderen Weg von {a} nach {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Eine Trading-Firma braucht {a} nach {b} unter {ms} ms, und zwar jeden Tag.", +"wkscn.desc_booters_picked_city_for_their":"Die Booter haben sich {city} für ihren Wochenausflug ausgesucht. Halte die Stellung.", +"wkscn.desc_cab_is_cut_for_the":"{cab} ist die ganze Runde über gekappt. Der Traffic muss trotzdem von {a} nach {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"In {city} steht der Lieblings-Boxsack des Internets. Alle paar Tage kommt eine Flut.", +"wkscn.desc_city_is_just_the_start":"{city} ist nur der Anfang: hol dir Ports an Exchanges in ganz {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} ist von Wasser und Ehrgeiz umgeben. Verbinde die Inseln.", +"wkscn.desc_city_on_a_shoestring":"{city} mit knappem Budget: wenig Geld, und jede Rechnung zählt.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle und Goggle reden schon wieder nicht miteinander. Starte in {city} und erreiche trotzdem alle.", +"wkscn.desc_every_exchange_in_reg_wants":"Jedes Exchange in {reg} will dich kennenlernen. Starte in {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Jede Millisekunde zwischen {a} und {b} kostet einen Trader eine Jacht. Rasier sie weg.", +"wkscn.desc_start_in_city_with_pocket":"Starte in {city} mit Taschengeld und wachse mit dem, was die Kunden zahlen.", +"wkscn.desc_start_on_city_and_string":"Starte in {city} und fädle die Inseln auf, ein Kabel nach dem anderen.", +"wkscn.desc_the_whole_city_is_watching":"An Tag {day} schaut ganz {city} zu. Sei bereit, {g} zu tragen.", +"wkscn.desc_two_giants_de_peered_over":"Zwei Riesen haben sich wegen einer Tabelle depeert. Deine Kunden in {city} wollen trotzdem das ganze Internet.", +"wkscn.event_name_city":"Die große Wochenshow in {city}", +"wkscn.goal_a_connected_pop_in_list":"Ein verbundener POP in {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} nach {b} unter {ms} ms, {n} Tage am Stück", +"wkscn.goal_deliver_the_event_in_city":"Liefere das {g}-Event in {city} voll aus, {dur} Tage ab Tag {day}", +"wkscn.goal_g_on_every_hop_from":"{g} auf jedem Hop von {a} nach {b}, {n} Tage am Stück", +"wkscn.goal_hold_n_floods":"Halte {n} Fluten", +"wkscn.goal_hold_n_floods_big_of":"Halte {n} Fluten, {big} davon ein Terabit oder mehr", +"wkscn.goal_ports_on_n_exchanges_in":"Ports an {n} Exchanges in {reg}", +"wkscn.goal_reach_r_and_serve_g":"Erreiche {r}% des Internets und liefere {g}", +"wkscn.goal_serve_g":"Liefere {g} Traffic", +"wkscn.loading_this_week_s_scenario":"Lade das Szenario dieser Woche…", +"wkscn.name_continental_breakfast":"Kontinentales Frühstück", +"wkscn.name_cut_and_run":"Schnitt und weg", +"wkscn.name_flood_week":"Flutwoche", +"wkscn.name_island_hopper":"Inselhüpfer", +"wkscn.name_light_speed_please":"Lichtgeschwindigkeit, bitte", +"wkscn.name_ludicrous_speed":"Wahnsinnige Geschwindigkeit", +"wkscn.name_not_on_speaking_terms":"Funkstille", +"wkscn.name_packet_monsoon":"Paketmonsun", +"wkscn.name_party_like_its_1999":"Party wie 1999", +"wkscn.name_peering_pressure":"Peering-Druck", +"wkscn.name_planting_flags":"Fahnen hissen", +"wkscn.name_ramen_profitable":"Ramen-Profitabel", +"wkscn.name_sea_you_soon":"Bis zum nächsten Meer", +"wkscn.name_shoestring_backbone":"Backbone für'n Appel und 'n Ei", +"wkscn.name_stream_team":"Stream-Team", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Nächstes Wochenszenario in {d} T. {h} Std.", +"wkscn.next_weekly_in_h_m":"Nächstes Wochenszenario in {h} Std. {m} Min.", +"wkscn.p_a_b_now":"{a} → {b} jetzt: {ms}", +"wkscn.p_days_in_a_row":"Tage am Stück", +"wkscn.p_event_delivered_in_full":"Event voll ausgeliefert", +"wkscn.p_exchange_ports_in_reg":"Exchange-Ports in {reg}", +"wkscn.p_g_on_day_d":"{g} an Tag {d}", +"wkscn.p_path_g_a_b":"{g}-Pfad {a} → {b}", +"wkscn.par_day_par":"Par: Tag {par}", +"wkscn.par_was_day_par":"Par war Tag {par}. Nächste Woche vielleicht.", +"wkscn.same_scenario_for_everyone_this_week":"Diese Woche dasselbe Szenario für alle", +"wkscn.share_line":"Series of Tubes Wochenszenario {key} „{name}“ gewonnen an Tag {d} (Par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Start in {city} · {d} Tage · {cash}", +"wkscn.under_par_par":"Im Par oder besser (Tag {par}). Schön gemacht.", +"wkscn.weekly_scenario_key":"Wochenszenario {key}", +"wkscn.won_day_d_par_par":"Gewonnen an Tag {d} (Par {par})", +"wkscn.won_on_day_d":"Gewonnen an Tag {d}!", }; diff --git a/site/i18n/es.js b/site/i18n/es.js index ddaaea1..f9f661a 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3603,4 +3603,65 @@ "utilities.title":"Utilidades", "utilities.two_routers":"Al menos dos routers", "utilities.view_pop":"Ver POP", +"wkscn.copy_my_result":"Copiar mi resultado", +"wkscn.desc_a_g_event_comes_to":"El día {day} llega a {city} un evento de {g}. Construye la red que necesita, desde cero.", +"wkscn.desc_a_ship_dragged_its_anchor":"Un barco arrastró el ancla sobre {cab}. Busca otro camino de {a} a {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Una firma de trading necesita {a} a {b} en menos de {ms} ms, y todos los días.", +"wkscn.desc_booters_picked_city_for_their":"Los booters eligieron {city} para su semana libre. Aguanta la línea.", +"wkscn.desc_cab_is_cut_for_the":"{cab} está cortado toda la partida. El tráfico tiene que llegar igual de {a} a {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} aloja el saco de boxeo favorito de internet. Espera una inundación cada pocos días.", +"wkscn.desc_city_is_just_the_start":"{city} es solo el principio: consigue puertos en exchanges por todo {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} está rodeada de agua y de ambición. Conecta las islas.", +"wkscn.desc_city_on_a_shoestring":"{city} con lo justo: poco dinero y cada factura cuenta.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle y Goggle han vuelto a dejar de hablarse. Empieza en {city} y llega a todos igualmente.", +"wkscn.desc_every_exchange_in_reg_wants":"Todos los exchanges de {reg} quieren conocerte. Empieza en {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Cada milisegundo entre {a} y {b} le cuesta un yate a un trader. Recórtalos.", +"wkscn.desc_start_in_city_with_pocket":"Empieza en {city} con calderilla y crece con lo que pagan los clientes.", +"wkscn.desc_start_on_city_and_string":"Empieza en {city} y ensarta las islas, un cable cada vez.", +"wkscn.desc_the_whole_city_is_watching":"El día {day} todo {city} está mirando. Prepárate para llevar {g}.", +"wkscn.desc_two_giants_de_peered_over":"Dos gigantes rompieron el peering por una hoja de cálculo. Tus clientes en {city} siguen queriendo todo internet.", +"wkscn.event_name_city":"El gran show de la semana en {city}", +"wkscn.goal_a_connected_pop_in_list":"Un POP conectado en {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} a {b} en menos de {ms} ms, {n} días seguidos", +"wkscn.goal_deliver_the_event_in_city":"Entrega completo el evento de {g} en {city}, {dur} días desde el día {day}", +"wkscn.goal_g_on_every_hop_from":"{g} en cada salto de {a} a {b}, {n} días seguidos", +"wkscn.goal_hold_n_floods":"Aguanta {n} inundaciones", +"wkscn.goal_hold_n_floods_big_of":"Aguanta {n} inundaciones, {big} de ellas de un terabit o más", +"wkscn.goal_ports_on_n_exchanges_in":"Puertos en {n} exchanges de {reg}", +"wkscn.goal_reach_r_and_serve_g":"Alcanza el {r}% de internet y sirve {g}", +"wkscn.goal_serve_g":"Sirve {g} de tráfico", +"wkscn.loading_this_week_s_scenario":"Cargando el escenario de esta semana…", +"wkscn.name_continental_breakfast":"Desayuno continental", +"wkscn.name_cut_and_run":"Cortar y correr", +"wkscn.name_flood_week":"Semana de inundaciones", +"wkscn.name_island_hopper":"Salta islas", +"wkscn.name_light_speed_please":"A la velocidad de la luz, por favor", +"wkscn.name_ludicrous_speed":"Velocidad absurda", +"wkscn.name_not_on_speaking_terms":"Ni se hablan", +"wkscn.name_packet_monsoon":"Monzón de paquetes", +"wkscn.name_party_like_its_1999":"De fiesta como en 1999", +"wkscn.name_peering_pressure":"Presión de peering", +"wkscn.name_planting_flags":"Plantando banderas", +"wkscn.name_ramen_profitable":"Rentable a base de ramen", +"wkscn.name_sea_you_soon":"Nos vemos en el mar", +"wkscn.name_shoestring_backbone":"Backbone con cuatro duros", +"wkscn.name_stream_team":"Equipo streaming", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Próximo escenario semanal en {d} d {h} h", +"wkscn.next_weekly_in_h_m":"Próximo escenario semanal en {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} ahora: {ms}", +"wkscn.p_days_in_a_row":"Días seguidos", +"wkscn.p_event_delivered_in_full":"Evento entregado completo", +"wkscn.p_exchange_ports_in_reg":"Puertos en exchanges de {reg}", +"wkscn.p_g_on_day_d":"{g} el día {d}", +"wkscn.p_path_g_a_b":"Ruta de {g} {a} → {b}", +"wkscn.par_day_par":"par: día {par}", +"wkscn.par_was_day_par":"El par era el día {par}. Quizá la semana que viene.", +"wkscn.same_scenario_for_everyone_this_week":"El mismo escenario para todos esta semana", +"wkscn.share_line":"Series of Tubes escenario semanal {key} «{name}» ganado el día {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Empieza en {city} · {d} días · {cash}", +"wkscn.under_par_par":"En par o mejor (día {par}). Bien hecho.", +"wkscn.weekly_scenario_key":"Escenario semanal {key}", +"wkscn.won_day_d_par_par":"Ganado el día {d} (par {par})", +"wkscn.won_on_day_d":"¡Ganado el día {d}!", }; diff --git a/site/i18n/fr.js b/site/i18n/fr.js index a45927a..f4056b9 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3603,4 +3603,65 @@ "utilities.title":"Utilitaires", "utilities.two_routers":"Au moins deux routeurs", "utilities.view_pop":"Voir le POP", +"wkscn.copy_my_result":"Copier mon résultat", +"wkscn.desc_a_g_event_comes_to":"Le jour {day}, un événement de {g} arrive à {city}. Construis le réseau qu'il lui faut, à partir de rien.", +"wkscn.desc_a_ship_dragged_its_anchor":"Un navire a traîné son ancre sur {cab}. Trouve un autre chemin de {a} à {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Une société de trading veut {a} à {b} en moins de {ms} ms, et tous les jours.", +"wkscn.desc_booters_picked_city_for_their":"Les booters ont choisi {city} pour leur semaine de sortie. Tiens bon.", +"wkscn.desc_cab_is_cut_for_the":"{cab} est coupé pour toute la partie. Le trafic doit quand même aller de {a} à {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} héberge le punching-ball préféré d'internet. Attends-toi à une crue tous les deux ou trois jours.", +"wkscn.desc_city_is_just_the_start":"{city} n'est que le début : prends des ports sur des exchanges partout en {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} est entourée d'eau et d'ambition. Relie les îles.", +"wkscn.desc_city_on_a_shoestring":"{city} avec des bouts de ficelle : peu d'argent, et chaque facture compte.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle et Goggle ne se parlent plus, encore. Démarre à {city} et touche tout le monde quand même.", +"wkscn.desc_every_exchange_in_reg_wants":"Chaque exchange de {reg} veut te rencontrer. Démarre à {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Chaque milliseconde entre {a} et {b} coûte un yacht à un trader. Rabote-les.", +"wkscn.desc_start_in_city_with_pocket":"Démarre à {city} avec de l'argent de poche et grandis avec ce que paient les clients.", +"wkscn.desc_start_on_city_and_string":"Démarre à {city} et enfile les îles comme des perles, un câble à la fois.", +"wkscn.desc_the_whole_city_is_watching":"Le jour {day}, tout {city} regarde. Sois prêt à porter {g}.", +"wkscn.desc_two_giants_de_peered_over":"Deux géants ont dépeeré pour un tableur. Tes clients à {city} veulent toujours tout internet.", +"wkscn.event_name_city":"Le grand show de la semaine à {city}", +"wkscn.goal_a_connected_pop_in_list":"Un POP relié à {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} à {b} en moins de {ms} ms, {n} jours d'affilée", +"wkscn.goal_deliver_the_event_in_city":"Livrer en entier l'événement de {g} à {city}, {dur} jours à partir du jour {day}", +"wkscn.goal_g_on_every_hop_from":"{g} sur chaque saut de {a} à {b}, {n} jours d'affilée", +"wkscn.goal_hold_n_floods":"Tenir {n} crues", +"wkscn.goal_hold_n_floods_big_of":"Tenir {n} crues, dont {big} d'un térabit ou plus", +"wkscn.goal_ports_on_n_exchanges_in":"Des ports sur {n} exchanges en {reg}", +"wkscn.goal_reach_r_and_serve_g":"Atteindre {r} % d'internet et servir {g}", +"wkscn.goal_serve_g":"Servir {g} de trafic", +"wkscn.loading_this_week_s_scenario":"Chargement du scénario de la semaine…", +"wkscn.name_continental_breakfast":"Petit-déjeuner continental", +"wkscn.name_cut_and_run":"Coupé, décalé", +"wkscn.name_flood_week":"Semaine des crues", +"wkscn.name_island_hopper":"Saute-îles", +"wkscn.name_light_speed_please":"À la vitesse de la lumière, s'il te plaît", +"wkscn.name_ludicrous_speed":"Vitesse grand V", +"wkscn.name_not_on_speaking_terms":"Ils ne se parlent plus", +"wkscn.name_packet_monsoon":"Mousson de paquets", +"wkscn.name_party_like_its_1999":"La fête comme en 1999", +"wkscn.name_peering_pressure":"Pression du peering", +"wkscn.name_planting_flags":"Planter des drapeaux", +"wkscn.name_ramen_profitable":"Rentable aux nouilles", +"wkscn.name_sea_you_soon":"À la mer prochaine", +"wkscn.name_shoestring_backbone":"Backbone à trois francs six sous", +"wkscn.name_stream_team":"Stream Team", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Prochain scénario de la semaine dans {d} j {h} h", +"wkscn.next_weekly_in_h_m":"Prochain scénario de la semaine dans {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} maintenant : {ms}", +"wkscn.p_days_in_a_row":"Jours d'affilée", +"wkscn.p_event_delivered_in_full":"Événement livré en entier", +"wkscn.p_exchange_ports_in_reg":"Ports d'exchange en {reg}", +"wkscn.p_g_on_day_d":"{g} le jour {d}", +"wkscn.p_path_g_a_b":"Chemin de {g} {a} → {b}", +"wkscn.par_day_par":"par : jour {par}", +"wkscn.par_was_day_par":"Le par était le jour {par}. La semaine prochaine, peut-être.", +"wkscn.same_scenario_for_everyone_this_week":"Le même scénario pour tout le monde cette semaine", +"wkscn.share_line":"Series of Tubes scénario de la semaine {key} « {name} » gagné le jour {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Départ à {city} · {d} jours · {cash}", +"wkscn.under_par_par":"Dans le par ou mieux (jour {par}). Bien joué.", +"wkscn.weekly_scenario_key":"Scénario de la semaine {key}", +"wkscn.won_day_d_par_par":"Gagné le jour {d} (par {par})", +"wkscn.won_on_day_d":"Gagné le jour {d} !", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index 9afaeb6..fe99435 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3603,4 +3603,65 @@ "utilities.title":"Utilità", "utilities.two_routers":"Almeno due router", "utilities.view_pop":"Mostra POP", +"wkscn.copy_my_result":"Copia il mio risultato", +"wkscn.desc_a_g_event_comes_to":"Il giorno {day} arriva a {city} un evento da {g}. Costruisci la rete che serve, da zero.", +"wkscn.desc_a_ship_dragged_its_anchor":"Una nave ha trascinato l'ancora su {cab}. Trova un'altra strada da {a} a {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Una società di trading vuole {a}–{b} sotto i {ms} ms, e tutti i giorni.", +"wkscn.desc_booters_picked_city_for_their":"I booter hanno scelto {city} per la loro settimana di gita. Tieni duro.", +"wkscn.desc_cab_is_cut_for_the":"{cab} è tagliato per tutta la partita. Il traffico deve comunque andare da {a} a {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} ospita il sacco da boxe preferito di internet. Aspettati una piena ogni pochi giorni.", +"wkscn.desc_city_is_just_the_start":"{city} è solo l'inizio: prendi porte sugli exchange in tutta {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} è circondata d'acqua e d'ambizione. Collega le isole.", +"wkscn.desc_city_on_a_shoestring":"{city} con pochi soldi: ogni bolletta conta.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle e Goggle hanno di nuovo smesso di parlarsi. Parti da {city} e raggiungi tutti lo stesso.", +"wkscn.desc_every_exchange_in_reg_wants":"Ogni exchange in {reg} vuole conoscerti. Parti da {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Ogni millisecondo tra {a} e {b} costa uno yacht a un trader. Limali via.", +"wkscn.desc_start_in_city_with_pocket":"Parti da {city} con la paghetta e cresci con quello che pagano i clienti.", +"wkscn.desc_start_on_city_and_string":"Parti da {city} e infila le isole come perle, un cavo alla volta.", +"wkscn.desc_the_whole_city_is_watching":"Il giorno {day} tutta {city} guarda. Preparati a portare {g}.", +"wkscn.desc_two_giants_de_peered_over":"Due giganti hanno chiuso il peering per un foglio di calcolo. I tuoi clienti a {city} vogliono comunque tutto internet.", +"wkscn.event_name_city":"Il grande show della settimana a {city}", +"wkscn.goal_a_connected_pop_in_list":"Un POP collegato a {cs}", +"wkscn.goal_a_to_b_under_ms":"{a}–{b} sotto i {ms} ms, {n} giorni di fila", +"wkscn.goal_deliver_the_event_in_city":"Consegna per intero l'evento da {g} a {city}, {dur} giorni dal giorno {day}", +"wkscn.goal_g_on_every_hop_from":"{g} su ogni hop da {a} a {b}, {n} giorni di fila", +"wkscn.goal_hold_n_floods":"Reggi {n} piene", +"wkscn.goal_hold_n_floods_big_of":"Reggi {n} piene, {big} da un terabit o più", +"wkscn.goal_ports_on_n_exchanges_in":"Porte su {n} exchange in {reg}", +"wkscn.goal_reach_r_and_serve_g":"Raggiungi il {r}% di internet e servi {g}", +"wkscn.goal_serve_g":"Servi {g} di traffico", +"wkscn.loading_this_week_s_scenario":"Carico lo scenario della settimana…", +"wkscn.name_continental_breakfast":"Colazione continentale", +"wkscn.name_cut_and_run":"Taglia e scappa", +"wkscn.name_flood_week":"Settimana delle piene", +"wkscn.name_island_hopper":"Saltaisole", +"wkscn.name_light_speed_please":"Alla velocità della luce, grazie", +"wkscn.name_ludicrous_speed":"Velocità assurda", +"wkscn.name_not_on_speaking_terms":"Non si parlano", +"wkscn.name_packet_monsoon":"Monsone di pacchetti", +"wkscn.name_party_like_its_1999":"Festa come nel 1999", +"wkscn.name_peering_pressure":"Pressione da peering", +"wkscn.name_planting_flags":"Piantare bandierine", +"wkscn.name_ramen_profitable":"In attivo a forza di ramen", +"wkscn.name_sea_you_soon":"Ci vediamo al mare", +"wkscn.name_shoestring_backbone":"Backbone con due spiccioli", +"wkscn.name_stream_team":"Stream Team", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Prossimo scenario settimanale tra {d} g {h} h", +"wkscn.next_weekly_in_h_m":"Prossimo scenario settimanale tra {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} adesso: {ms}", +"wkscn.p_days_in_a_row":"Giorni di fila", +"wkscn.p_event_delivered_in_full":"Evento consegnato per intero", +"wkscn.p_exchange_ports_in_reg":"Porte su exchange in {reg}", +"wkscn.p_g_on_day_d":"{g} il giorno {d}", +"wkscn.p_path_g_a_b":"Percorso da {g} {a} → {b}", +"wkscn.par_day_par":"par: giorno {par}", +"wkscn.par_was_day_par":"Il par era il giorno {par}. Magari la prossima settimana.", +"wkscn.same_scenario_for_everyone_this_week":"Lo stesso scenario per tutti questa settimana", +"wkscn.share_line":"Series of Tubes scenario settimanale {key} «{name}» vinto il giorno {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Parti da {city} · {d} giorni · {cash}", +"wkscn.under_par_par":"In par o meglio (giorno {par}). Ben fatto.", +"wkscn.weekly_scenario_key":"Scenario della settimana {key}", +"wkscn.won_day_d_par_par":"Vinto il giorno {d} (par {par})", +"wkscn.won_on_day_d":"Vinto il giorno {d}!", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 0dba80c..1eadf43 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3603,4 +3603,65 @@ "utilities.title":"Utilitários", "utilities.two_routers":"Pelo menos dois routers", "utilities.view_pop":"Ver POP", +"wkscn.copy_my_result":"Copiar meu resultado", +"wkscn.desc_a_g_event_comes_to":"No dia {day} chega a {city} um evento de {g}. Construa a rede de que ele precisa, do zero.", +"wkscn.desc_a_ship_dragged_its_anchor":"Um navio arrastou a âncora sobre o {cab}. Encontre outro caminho de {a} a {b}.", +"wkscn.desc_a_trading_firm_needs_a":"Uma firma de trading precisa de {a} a {b} em menos de {ms} ms, todo dia.", +"wkscn.desc_booters_picked_city_for_their":"Os booters escolheram {city} para a semana de folga deles. Segure a linha.", +"wkscn.desc_cab_is_cut_for_the":"{cab} está cortado a partida inteira. O tráfego ainda precisa ir de {a} a {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} hospeda o saco de pancadas favorito da internet. Espere uma enchente a cada poucos dias.", +"wkscn.desc_city_is_just_the_start":"{city} é só o começo: consiga portas em exchanges por toda a {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} está cercada de água e ambição. Conecte as ilhas.", +"wkscn.desc_city_on_a_shoestring":"{city} com o dinheiro contado: cada conta importa.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle e Goggle pararam de se falar de novo. Comece em {city} e alcance todo mundo mesmo assim.", +"wkscn.desc_every_exchange_in_reg_wants":"Todo exchange da {reg} quer conhecer você. Comece em {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Cada milissegundo entre {a} e {b} custa um iate a um trader. Corte-os.", +"wkscn.desc_start_in_city_with_pocket":"Comece em {city} com uns trocados e cresça com o que os clientes pagam.", +"wkscn.desc_start_on_city_and_string":"Comece em {city} e enfie as ilhas num colar, um cabo de cada vez.", +"wkscn.desc_the_whole_city_is_watching":"No dia {day} toda {city} está assistindo. Esteja pronto para levar {g}.", +"wkscn.desc_two_giants_de_peered_over":"Dois gigantes desfizeram o peering por causa de uma planilha. Seus clientes em {city} ainda querem a internet inteira.", +"wkscn.event_name_city":"O grande show da semana em {city}", +"wkscn.goal_a_connected_pop_in_list":"Um POP conectado em {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} a {b} em menos de {ms} ms, {n} dias seguidos", +"wkscn.goal_deliver_the_event_in_city":"Entregue por completo o evento de {g} em {city}, {dur} dias a partir do dia {day}", +"wkscn.goal_g_on_every_hop_from":"{g} em cada salto de {a} a {b}, {n} dias seguidos", +"wkscn.goal_hold_n_floods":"Segure {n} enchentes", +"wkscn.goal_hold_n_floods_big_of":"Segure {n} enchentes, {big} delas de um terabit ou mais", +"wkscn.goal_ports_on_n_exchanges_in":"Portas em {n} exchanges na {reg}", +"wkscn.goal_reach_r_and_serve_g":"Alcance {r}% da internet e entregue {g}", +"wkscn.goal_serve_g":"Entregue {g} de tráfego", +"wkscn.loading_this_week_s_scenario":"Carregando o cenário desta semana…", +"wkscn.name_continental_breakfast":"Café da manhã continental", +"wkscn.name_cut_and_run":"Corta e corre", +"wkscn.name_flood_week":"Semana das enchentes", +"wkscn.name_island_hopper":"Pula-ilhas", +"wkscn.name_light_speed_please":"Na velocidade da luz, por favor", +"wkscn.name_ludicrous_speed":"Velocidade absurda", +"wkscn.name_not_on_speaking_terms":"De mal", +"wkscn.name_packet_monsoon":"Monção de pacotes", +"wkscn.name_party_like_its_1999":"Festa como em 1999", +"wkscn.name_peering_pressure":"Pressão do peering", +"wkscn.name_planting_flags":"Fincando bandeiras", +"wkscn.name_ramen_profitable":"Lucrativo à base de miojo", +"wkscn.name_sea_you_soon":"Até o próximo mar", +"wkscn.name_shoestring_backbone":"Backbone com trocados", +"wkscn.name_stream_team":"Time do streaming", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Próximo cenário semanal em {d} d {h} h", +"wkscn.next_weekly_in_h_m":"Próximo cenário semanal em {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} agora: {ms}", +"wkscn.p_days_in_a_row":"Dias seguidos", +"wkscn.p_event_delivered_in_full":"Evento entregue por completo", +"wkscn.p_exchange_ports_in_reg":"Portas em exchanges na {reg}", +"wkscn.p_g_on_day_d":"{g} no dia {d}", +"wkscn.p_path_g_a_b":"Caminho de {g} {a} → {b}", +"wkscn.par_day_par":"par: dia {par}", +"wkscn.par_was_day_par":"O par era o dia {par}. Quem sabe semana que vem.", +"wkscn.same_scenario_for_everyone_this_week":"O mesmo cenário para todos nesta semana", +"wkscn.share_line":"Series of Tubes cenário semanal {key} “{name}” vencido no dia {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Comece em {city} · {d} dias · {cash}", +"wkscn.under_par_par":"No par ou melhor (dia {par}). Mandou bem.", +"wkscn.weekly_scenario_key":"Cenário semanal {key}", +"wkscn.won_day_d_par_par":"Vencido no dia {d} (par {par})", +"wkscn.won_on_day_d":"Vencido no dia {d}!", }; diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 162138f..a11ca57 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -2,12 +2,11 @@ gives the same world. Free play keeps using the browser's Math.random. */ const _rand=Math.random; Math.random=function(){if(S&&typeof S.rng==='number'){let t=(S.rng=(S.rng+0x6D2B79F5)|0);t=Math.imul(t^t>>>15,1|t);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}return _rand();}; -function isoWeek(dt){const d=new Date(Date.UTC(dt.getFullYear(),dt.getMonth(),dt.getDate()));const n=d.getUTCDay()||7;d.setUTCDate(d.getUTCDate()+4-n);const y0=new Date(Date.UTC(d.getUTCFullYear(),0,1));return {y:d.getUTCFullYear(),w:Math.ceil(((d-y0)/864e5+1)/7)};} const hopG=l=>l.kind==='vxc'?(VXC[l.vt]||VXC[0]).g:l.kind==='df'?Math.max(0,...(l.ch||[]).map(c=>optG(c,l))):LT[l.tier].g; function fastPath(a,b,g){if(!S.pops[a]||!S.pops[b])return false;const adj={};for(const l of S.links){if(linkDown(l)||hopG(l)S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name; +const scnName=()=>S.scn.wk?wsTxt(S.scn.wk.name):S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name; 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=[ @@ -27,7 +26,8 @@ const SCN=[ ]; const WEEK_CITIES=['fra','ams','lon','nyc','ash','sjc','sin','tok','syd','sao','jnb','bom','waw','ist','scl','hkg']; const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chaos',n:tr('scenarios.twice_the_failures')},{id:'poor',n:tr('scenarios.start_with_only_100k')},{id:'boom',n:tr('scenarios.eyeballs_grow_50_faster')},{id:'dk',n:tr('scenarios.every_ix_is_run_by_de')},{id:'sharks',n:tr('scenarios.shark_season_subsea_cuts_twice_as')}]; -function weekly(){const {y,w}=isoWeek(new Date());let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};} +// The in-browser weekly, when no published scenario came: same weeks as the published one (Sunday 06:00 Berlin). +function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};} const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);S.mode=o.mode||'normal'; diff --git a/src/game/60-features/70-scenario-progress.js b/src/game/60-features/70-scenario-progress.js index 7ebd962..4436e58 100644 --- a/src/game/60-features/70-scenario-progress.js +++ b/src/game/60-features/70-scenario-progress.js @@ -1,4 +1,5 @@ function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)return; + if(sc.id==='weekly'&&sc.wk){wsTick(d);return;} if(sc.id==='weekly'){if(d>=sc.days){sc.done=d;const score=Math.round(S.stats.peak||0);sc.score=score;let best=null;try{const wk=JSON.parse(localStorage.getItem('sot-weekly')||'{}');best=wk[sc.key];if(!best||score>best){wk[sc.key]=score;localStorage.setItem('sot-weekly',JSON.stringify(wk));}}catch(e){} const h=scnHof();h.weekly=h.weekly||{d:new Date().toISOString().slice(0,10)};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){} openModal(`
${tr('features.weekly_challenge_key',{key:esc(sc.key)})}

${tr('scenario_progress.your_score_score',{score:fmtG(score)})}

${best&&best>score?tr('scenario_progress.peak_traffic_served_in_one_year',{best:fmtG(best)}):best?tr('scenario_progress.peak_traffic_served_in_one_year_c7e5'):tr('scenario_progress.peak_traffic_served_in_one_year_a67b')}

${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);track('weekly_done');}return;} @@ -6,7 +7,7 @@ function scnTick(d){const sc=S.scn;if(!sc||sc.done||sc.failed)return; if(ok){sc.done=d;const h=scnHof();if(!h[sc.id]||h[sc.id].days>d)h[sc.id]={d:new Date().toISOString().slice(0,10),days:d};try{localStorage.setItem('sot-scn',JSON.stringify(h));}catch(e){}track('scenario_'+sc.id); openModal(`
${tr('common.scenario_complete')}

${tr('scenario_progress.name_done_in_d_days',{name:esc(def.n),d})}

${esc(def.goal)}. ${d

${btn(tr('scenario_progress.share_my_result'),'share',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}${btn(tr('common.more_scenarios'),'scenarios',{},'ghost')}
`);sfx('coin');} else if(d>=def.days){sc.failed=d;openModal(`
${tr('common.scenario_over')}

${tr('common.time_s_up')}

${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(def.goal),d:def.days})}

${btn(tr('common.try_again'),'startScn',{id:def.id},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);}} -function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){} +function scenarioModal(){wsEnsure();const h=scnHof(); openModal(`
${tr('common.scenarios')}

${tr('scenario_progress.pick_a_challenge')}

-
${tr('features.weekly_challenge_key',{key:esc(wk.key)})}
${tr('scenario_progress.start_in_city_mods_one_year',{city:esc(CITY[wk.city].name),mods:wk.mods.map(m=>esc(m.n)).join(' · ')})}${best?' '+tr('scenario_progress.your_best_best',{best:fmtG(best)}):''}
${btn(tr('common.play'),'startWeekly',{},'pink')}
+ ${wsRow()} ${SCN.map(x=>`
${esc(x.n)} ${h[x.id]?`${tr('features.done_in_d_days',{d:h[x.id].days})}`:''}
${esc(x.d)}
${tr('scenario_progress.goal_goal_time_d_days_start',{goal:esc(x.goal),d:x.days,city:esc(CITY[x.city].name)})}
${btn(tr('common.play'),'startScn',{id:x.id},'')}
`).join('')}`);} diff --git a/src/game/60-features/94-scenarios-weekly.js b/src/game/60-features/94-scenarios-weekly.js new file mode 100644 index 0000000..7d01c02 --- /dev/null +++ b/src/game/60-features/94-scenarios-weekly.js @@ -0,0 +1,125 @@ +/* ================= THE PUBLISHED WEEKLY SCENARIO ================= + The twin of the weekly puzzle: the same weeks (Sunday 06:00 Berlin, pzWeekKey), one themed scenario per week, + published by a GitHub workflow as scenarios/weekly/.json (scripts/weekly-scenario.js) and fetched only when the + Scenarios list opens. The file is data only: a theme, a start, rules from the scenario vocabulary, and a goal TYPE + with its parameters; every goal type is implemented once here, with its progress card. Missing, offline or wrong, + the in-browser weekly() stands in. Like every scenario it runs On-call plus its own rules (M4). */ +// What a {placeholder} holds: c a city, r a region, n a whole number, k a cable id. +const WS_P={a:'c',b:'c',city:'c',reg:'r',n:'n',g:'n',day:'n',ms:'n',cab:'k'}; +const WS_THEMES={ + budget:{i:'🪙',names:[N_('wkscn.name_shoestring_backbone'),N_('wkscn.name_ramen_profitable')],descs:[N_('wkscn.desc_city_on_a_shoestring'),N_('wkscn.desc_start_in_city_with_pocket')]}, + cable:{i:'✂️',names:[N_('wkscn.name_suez_you_later'),N_('wkscn.name_cut_and_run')],descs:[N_('wkscn.desc_cab_is_cut_for_the'),N_('wkscn.desc_a_ship_dragged_its_anchor')]}, + event:{i:'🎉',names:[N_('wkscn.name_party_like_its_1999'),N_('wkscn.name_stream_team')],descs:[N_('wkscn.desc_a_g_event_comes_to'),N_('wkscn.desc_the_whole_city_is_watching')]}, + flood:{i:'🌊',names:[N_('wkscn.name_flood_week'),N_('wkscn.name_packet_monsoon')],descs:[N_('wkscn.desc_city_hosts_the_internets_favourite'),N_('wkscn.desc_booters_picked_city_for_their')]}, + island:{i:'🏝️',names:[N_('wkscn.name_island_hopper'),N_('wkscn.name_sea_you_soon')],descs:[N_('wkscn.desc_start_on_city_and_string'),N_('wkscn.desc_city_is_surrounded_by_water')]}, + latency:{i:'⚡',names:[N_('wkscn.name_ludicrous_speed'),N_('wkscn.name_light_speed_please')],descs:[N_('wkscn.desc_a_trading_firm_needs_a'),N_('wkscn.desc_every_millisecond_between_a_and')]}, + region:{i:'🗺️',names:[N_('wkscn.name_continental_breakfast'),N_('wkscn.name_planting_flags')],descs:[N_('wkscn.desc_city_is_just_the_start'),N_('wkscn.desc_every_exchange_in_reg_wants')]}, + spat:{i:'🙊',names:[N_('wkscn.name_not_on_speaking_terms'),N_('wkscn.name_peering_pressure')],descs:[N_('wkscn.desc_cogentle_and_goggle_stopped_talking'),N_('wkscn.desc_two_giants_de_peered_over')]}, +}; +const wsRun=()=>S.scn.run|0; +const wsIxN=reg=>Object.keys(S.ixp).filter(c=>isIx(c)&&CITY[ixCity(c)]&&CITY[ixCity(c)].reg===reg).length; +const wsCs=p=>p.cs.map(c=>CITY[c].name).join(', '); +// The goal types. p: each parameter's kind and range ([kind,lo,hi]); ok(p) won; m(p) a number the generator calibrates +// against (and the progress bar reads); daily: the goal counts days in a row; prog(p) the card's rows. +const WS_GOALS={ + served:{p:{g:['n',5,50000]},l:N_('wkscn.goal_serve_g'),ok:p=>R.served>=p.g,m:()=>R.served,prog:p=>[pSrv(p.g)]}, + reach:{p:{r:['n',50,99],g:['n',1,50000]},l:N_('wkscn.goal_reach_r_and_serve_g'),ok:p=>R.reach>=p.r/100&&R.served>=p.g,m:()=>R.served,prog:p=>[{l:tr('common.reach'),v:R.reach,max:p.r/100,txt:`${pct(R.reach)} / ${p.r}%`},pSrv(p.g)]}, + path:{p:{a:['c'],b:['c'],g:['n',10,12800],n:['n',1,120]},daily:p=>fastPath(p.a,p.b,p.g),l:N_('wkscn.goal_g_on_every_hop_from'),ok:p=>wsRun()>=p.n,m:()=>wsRun(), + prog:p=>[pChk(tr('wkscn.p_path_g_a_b',{g:fmtG(p.g),a:CITY[p.a].name,b:CITY[p.b].name}),fastPath(p.a,p.b,p.g)),{l:tr('wkscn.p_days_in_a_row'),v:wsRun(),max:p.n,txt:`${wsRun()} / ${p.n}`}]}, + ix:{p:{reg:['r'],n:['n',2,60]},l:N_('wkscn.goal_ports_on_n_exchanges_in'),ok:p=>wsIxN(p.reg)>=p.n,m:p=>wsIxN(p.reg),prog:p=>{const n=wsIxN(p.reg);return [{l:tr('wkscn.p_exchange_ports_in_reg',{reg:WAVE_NAME[p.reg]}),v:n,max:p.n,txt:`${n} / ${p.n}`}];}}, + pops:{p:{cs:['cs',1,8]},l:N_('wkscn.goal_a_connected_pop_in_list'),ok:p=>p.cs.every(c=>pathExists(S.scn.home,c)),m:p=>p.cs.filter(c=>pathExists(S.scn.home,c)).length,prog:p=>p.cs.map(c=>pChk(tr('progress.pop_in_city',{city:CITY[c].name}),pathExists(S.scn.home,c)))}, + event:{p:{city:['c'],g:['n',10,6400],day:['n',20,360],dur:['n',1,10]},l:N_('wkscn.goal_deliver_the_event_in_city'),ok:()=>(S.stats.evFull||0)>=1,m:()=>S.stats.evFull||0, + setup:p=>S.biz.push({id:uid(),scripted:true,city:p.city,city2:null,reqs:[],name:tr('wkscn.event_name_city',{city:CITY[p.city].name}),type:'event',bw:p.g,rate:0,mood:100,since:0,start:p.day,dur:p.dur,fee:p.g*p.dur*70}), + prog:p=>[pChk(tr('wkscn.p_event_delivered_in_full'),(S.stats.evFull||0)>=1),{l:tr('common.traffic_served'),v:0,max:0,txt:tr('wkscn.p_g_on_day_d',{g:fmtG(p.g),d:p.day})}]}, + floods:{p:{n:['n',1,60],big:['n',0,20]},l:N_('wkscn.goal_hold_n_floods_big_of'),ok:p=>(S.stats.ddosOk||0)>=p.n&&(S.stats.ddosOkBig||0)>=p.big,m:()=>S.stats.ddosOk||0, + prog:p=>[{l:tr('common.floods_held'),v:S.stats.ddosOk||0,max:p.n,txt:`${S.stats.ddosOk||0} / ${p.n}`},...(p.big?[{l:tr('progress.terabit_floods_held'),v:S.stats.ddosOkBig||0,max:p.big,txt:`${S.stats.ddosOkBig||0} / ${p.big}`}]:[])]}, + lat:{p:{a:['c'],b:['c'],ms:['n',1,400],n:['n',1,120]},daily:p=>bestLat(p.a,p.b)<=p.ms,l:N_('wkscn.goal_a_to_b_under_ms'),ok:p=>wsRun()>=p.n,m:()=>wsRun(), + prog:p=>{const v=bestLat(p.a,p.b);return [pChk(tr('wkscn.p_a_b_now',{a:CITY[p.a].name,b:CITY[p.b].name,ms:isFinite(v)?v.toFixed(1)+' ms':tr('common.no_path')}),v<=p.ms),{l:tr('wkscn.p_days_in_a_row'),v:wsRun(),max:p.n,txt:`${wsRun()} / ${p.n}`}];}}, +}; +// Filled-in text: a label from the file and its typed parameters, in the player's language. +const wsVal=(k,x)=>{const t=WS_P[k];return t==='c'?CITY[x].name:t==='r'?WAVE_NAME[x]:t==='k'?CAB[x].name:k==='g'?fmtG(x):x;}; +const wsTxt=o=>{const v={};for(const k in o.p)v[k]=wsVal(k,o.p[k]);return tr(o.l,v);}; +function wsGoalTxt(j){const G=j.goal,p=G.p,v={};for(const k in p)v[k]=k==='cs'?wsCs(p):WS_P[k]?wsVal(k,p[k]):p[k];return tr(G.t==='floods'&&!p.big?N_('wkscn.goal_hold_n_floods'):WS_GOALS[G.t].l,v);} +// ---------- the file: never trusted ---------- +const WS_FIELDS=['v','key','theme','city','cash','days','lvl','rules','mods','goal','name','desc','seed','par','ref','rev']; +const WS_V=1,WS_RULES=['anchors','banCities','banPairs','ddos','spat']; +const wsPairOk=s=>typeof s==='string'&&CABLE_PAIRS.some(c=>s===`${c.cid}:${c.a}-${c.b}`); +function wsLab(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=WS_P[k],v=own(p,k)?p[k]:undefined; + if(t==='c'&&pzCityOk(v)||t==='r'&&typeof v==='string'&&own(WAVE_NAME,v)||t==='k'&&typeof v==='string'&&own(CAB,v)||t==='n'&&Number.isInteger(v)&&v>0&&v<1e6)out[k]=v;else return null;} + return {l:o.l,p:out};} +function wsGoal(o){if(!pzObj(o)||typeof o.t!=='string'||!own(WS_GOALS,o.t)||!pzObj(o.p))return null;const G=WS_GOALS[o.t],out={}; + if(Object.keys(o.p).length!==Object.keys(G.p).length)return null; + for(const k in G.p){const [t,lo,hi]=G.p[k],v=o.p[k]; + if(t==='c'){if(!pzCityOk(v))return null;}else if(t==='r'){if(typeof v!=='string'||!own(WAVE_NAME,v))return null;} + else if(t==='cs'){if(!Array.isArray(v)||v.lengthhi||!v.every(pzCityOk)||new Set(v).size!==v.length)return null;} + else if(!Number.isInteger(v)||vhi)return null; + out[k]=Array.isArray(v)?v.slice():v;} + if(out.a&&out.a===out.b)return null;return {t:o.t,p:out};} +// A checked copy of the file, or null. The copy is what a game stores and reloads (sanitize() checks it again). +function wsValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!WS_FIELDS.includes(k))||j.v!==WS_V||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(WS_THEMES,j.theme))return null; + const T=WS_THEMES[j.theme],I=(v,lo,hi)=>Number.isInteger(v)&&v>=lo&&v<=hi; + if(!pzCityOk(j.city)||!I(j.cash,50000,2e7)||!I(j.days,60,400)||!I(j.lvl,1,4)||!I(j.seed,1,2**31-1)||!I(j.par,1,j.days))return null; + if(j.rev!==undefined&&!I(j.rev,2,999))return null;if(j.ref!==undefined&&!pzObj(j.ref))return null; + const r=j.rules==null?{}:j.rules;if(!pzObj(r)||Object.keys(r).some(k=>!WS_RULES.includes(k)))return null;const rules={}; + for(const k in r){const v=r[k]; + if(k==='spat'||k==='ddos'){if(v!==true)return null;rules[k]=true;} + else if(k==='anchors'){if(!I(v,1,5))return null;rules[k]=v;} + else if(k==='banCities'){if(!Array.isArray(v)||v.length>6||!v.every(isCity)||v.includes(j.city))return null;rules[k]=v.slice();} + else{if(!Array.isArray(v)||v.length<1||v.length>40||!v.every(wsPairOk))return null;rules[k]=v.slice();}} + const mods=j.mods==null?[]:j.mods;if(!Array.isArray(mods)||mods.length>2||new Set(mods).size!==mods.length||!mods.every(m=>WEEK_MODS.some(x=>x.id===m)))return null; + const goal=wsGoal(j.goal);if(!goal)return null; + // A city the goal needs is never one the rules ban. + if(rules.banCities&&Object.values(goal.p).flat().some(c=>rules.banCities.includes(c)))return null; + if(goal.t==='event'&&goal.p.day+goal.p.dur>=j.days||goal.t==='floods'&&!rules.ddos)return null; + const name=wsLab(j.name,T.names),desc=wsLab(j.desc,T.descs);if(!name||!desc)return null; + const o={v:WS_V,key,theme:j.theme,city:j.city,cash:j.cash,days:j.days,lvl:j.lvl,rules,mods:mods.slice(),goal,name,desc,seed:j.seed,par:j.par};if(j.rev)o.rev=j.rev;return o;} +// ---------- fetching it: when the Scenarios list opens, never on page load ---------- +function wsEnsure(){const key=pzWeekKey(new Date()),w=UI.wsWk; + if(w&&w.key===key&&(w.st!=='fb'||Date.now()-w.at<5*60e3))return; + const st=UI.wsWk={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.wsWk!==st)return;if(def){st.def=def;st.st='ok';}else if(!st.def)st.st='fb';st.at=Date.now();wsRefresh();}; + 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;} + try{fetch(`scenarios/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>wsValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +const wsDef=()=>{const key=pzWeekKey(new Date()),w=UI.wsWk;return w&&w.key===key&&w.def?w.def:null;}; +const wsLoading=()=>{const w=UI.wsWk;return !!w&&w.st==='load'&&w.key===pzWeekKey(new Date());}; +function wsRefresh(){const el=$('wsRow');if(el)el.outerHTML=wsRow();} +// ---------- the player's record: started weeks (for the badge), wins and the streak ---------- +function wsLoad(){let j=null;try{j=JSON.parse(localStorage.getItem('sot-wkscn')||'null');}catch(e){}const o={go:{},w:{},streak:{last:null,n:0,best:0}};if(!pzObj(j))return o; + const K=/^\d{4}-W\d{2}$/;if(pzObj(j.go))for(const k in j.go)if(K.test(k))o.go[k]=1; + if(pzObj(j.w))for(const k in j.w){const x=j.w[k];if(K.test(k)&&pzObj(x)&&Number.isInteger(x.d)&&x.d>0)o.w[k]={d:x.d,rv:Number.isInteger(x.rv)?x.rv:1};} + const s=j.streak;if(pzObj(s)){o.streak.last=typeof s.last==='string'&&K.test(s.last)?s.last:null;for(const k of ['n','best'])o.streak[k]=Number.isInteger(s[k])&&s[k]>=0?s[k]:0;}return o;} +const wsStore=o=>{try{localStorage.setItem('sot-wkscn',JSON.stringify(o));}catch(e){}}; +// A win counts for its revision: when a week is regenerated (rev), last week's result for it no longer shows. +const wsWin=(o,d)=>{const x=d&&o.w[d.key];return x&&x.rv===(d.rev||1)?x:null;}; +function wsNew(){try{return !wsLoad().go[pzWeekKey(new Date())];}catch(e){return false;}} +const wsStreak=(o,key)=>{const s=o.streak;return s.last===key||s.last===pzPrevKey(key)?s.n:0;}; +// ---------- playing it ---------- +function wsBegin(j,nm){const d=wsValid(j,j&&j.key);if(!d)return false;const G=WS_GOALS[d.goal.t]; + const o=wsLoad();o.go[d.key]=1;wsStore(o); + beginGame(nm||UI.nm||(S&&S.name)||randomNetworkName(),d.city,{seed:d.seed,scn:{id:'weekly',key:d.key,n:wsTxt(d.name),days:d.days,cash:d.cash,rules:JSON.parse(JSON.stringify(d.rules)), + mods:d.mods.map(m=>WEEK_MODS.find(x=>x.id===m)),goal:wsGoalTxt(d),setup:()=>{S.scn.wk=d;S.scn.home=d.city;S.scn.run=0;S.lvl=Math.max(S.lvl||1,d.lvl);if(G.setup)G.setup(d.goal.p);}}}); + return true;} +const wsOk=()=>{const sc=S&&S.scn;if(!sc||!sc.wk)return false;const G=sc.wk.goal;try{return !!WS_GOALS[G.t].ok(G.p);}catch(e){return false;}}; +const wsMeasure=()=>{const G=S.scn.wk.goal;try{return +WS_GOALS[G.t].m(G.p)||0;}catch(e){return 0;}}; +function wsShareText(){const sc=S.scn,d=sc.wk;return tr('wkscn.share_line',{key:sc.key,name:wsTxt(d.name),d:sc.done,par:d.par});} +// Called by scnTick once a day for a published weekly scenario. +function wsTick(d){const sc=S.scn,w=sc.wk,G=WS_GOALS[w.goal.t]; + if(G.daily){let on=false;try{on=!!G.daily(w.goal.p);}catch(e){}sc.run=on?(sc.run|0)+1:0;} + if(wsOk()){sc.done=d;const o=wsLoad(),x=wsWin(o,w);if(!x||x.d>d)o.w[w.key]={d,rv:w.rev||1};const s=o.streak;if(s.last!==w.key){s.n=s.last===pzPrevKey(w.key)?s.n+1:1;s.last=w.key;s.best=Math.max(s.best,s.n);}wsStore(o);track('wkscn_won'); + openModal(`
${T_WS(w)} ${tr('wkscn.weekly_scenario_key',{key:esc(w.key)})}

${tr('wkscn.won_on_day_d',{d})}

${esc(wsGoalTxt(w))}. ${d<=w.par?tr('wkscn.under_par_par',{par:w.par}):tr('wkscn.par_was_day_par',{par:w.par})}

${esc(wsShareText())}

${btn(tr('wkscn.copy_my_result'),'wsShare',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);sfx('coin');} + else if(d>=sc.days){sc.failed=d;openModal(`
${tr('common.scenario_over')}

${tr('common.time_s_up')}

${tr('scenario_progress.goal_was_not_reached_in_d',{goal:esc(wsGoalTxt(w)),d:sc.days})}

${btn(tr('common.try_again'),'startWeekly',{},'pink big')}${btn(tr('common.keep_playing'),'closeModal',{},'ghost big')}
`);}} +const T_WS=w=>(WS_THEMES[w.theme]||{}).i||'📅'; +// The top row of the Scenarios list. +function wsRow(){const d=wsDef(),o=wsLoad(),key=pzWeekKey(new Date()),st=wsStreak(o,key),badge=o.go[key]?'':` ${tr('puzzles.new_this_sunday')}`,cd=`
⏳ ${wsNext(Date.now())}
`; + if(!d){const wk=weekly();let best=null;try{best=JSON.parse(localStorage.getItem('sot-weekly')||'{}')[wk.key];}catch(e){} + return `
📅 ${tr('wkscn.weekly_scenario_key',{key:esc(wk.key)})}${badge}
${wsLoading()?tr('wkscn.loading_this_week_s_scenario'):tr('features.weekly_challenge_key',{key:esc(wk.key)})}
${tr('scenario_progress.start_in_city_mods_one_year',{city:esc(CITY[wk.city].name),mods:wk.mods.map(m=>esc(m.n)).join(' · ')})}${best?' '+tr('scenario_progress.your_best_best',{best:fmtG(best)}):''}
${cd}
${btn(tr('common.play'),'startWeekly',{},'pink',wsLoading())}
`;} + const x=wsWin(o,d),mods=d.mods.map(m=>esc(WEEK_MODS.find(y=>y.id===m).n)); + return `
📅 ${tr('wkscn.weekly_scenario_key',{key:esc(d.key)})}${badge}
+
${T_WS(d)} ${esc(wsTxt(d.name))} ${x?`${tr('wkscn.won_day_d_par_par',{d:x.d,par:d.par})}`:''}
${esc(wsTxt(d.desc))}
+
🎯 ${esc(wsGoalTxt(d))}
${tr('wkscn.start_in_city_d_days_cash',{city:esc(CITY[d.city].name),d:d.days,cash:fmt$(d.cash)})}${mods.length?' · '+mods.join(' · '):''} · ${tr('wkscn.par_day_par',{par:d.par})}
+
${tr('wkscn.same_scenario_for_everyone_this_week')}${st?' · 🔥 '+trn('puzzles.n_week_streak',st):''}
${cd}
${btn(tr('common.play'),'startWeekly',{},x?'ghost':'pink')}
`;} +function wsNext(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('wkscn.next_weekly_in_d_h',{d,h}):tr('wkscn.next_weekly_in_h_m',{h,m:m%60});} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 3085777..d83a3a8 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -89,7 +89,10 @@ function migrate(s){sanitize(s); // Older saves have one contract per broker sale: fold a carrier's alien waves on one fiber into one contract. {const one=new Map();s.biz=s.biz.filter(b=>{if(b.type!=='wwave')return true;const k=b.link+'|'+b.name,a=one.get(k);if(!a){one.set(k,b);return true;} a.slots=(a.slots||0)+(b.slots||0);a.rate=(a.rate||0)+(b.rate||0);a.since=Math.min(a.since??0,b.since??0);a.mood=Math.min(a.mood??100,b.mood??100);a.folded=true;return false;}); - for(const a of one.values())if(a.folded){delete a.folded;const l=s.links.find(x=>x.id===a.link);if(l)a.what=wwWhat(l,a.slots);}}if(s.scn&&s.scn.id==='stg'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.local=true;for(const b of [...s.biz,...s.offers])if(Array.isArray(b.reqs))b.reqs=b.reqs.filter(k=>!REQS[k]||!REQS[k].can||(isCity(b.city)&&(!b.city2||isCity(b.city2))&&REQS[k].can(b,s)));if(s.ltv!==2){for(const l of s.links)if(l.kind==='wave'&&l.tier>=3)l.tier=Math.min(LT.length-1,l.tier+1);s.ltv=2;}if(s.dk){s.dk.m=s.dk.m||{};s.dk.add=s.dk.add||{};s.dk.ret=s.dk.ret||{};s.dk.retUsed=s.dk.retUsed||{};}s.hist=s.hist||[];s.loans=s.loans||[];s.loanOffers=s.loanOffers||[];s.loanStrikes=s.loanStrikes||0;for(const l of s.links||[])if(!l.kind)l.kind='wave'; + for(const a of one.values())if(a.folded){delete a.folded;const l=s.links.find(x=>x.id===a.link);if(l)a.what=wwWhat(l,a.slots);}}if(s.scn&&s.scn.id==='stg'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.local=true; + // A published weekly scenario keeps its file in the save: checked again here; a bad one plays on as the in-browser weekly. + if(s.scn&&typeof s.scn==='object'&&s.scn.wk!==undefined){const d=wsValid(s.scn.wk,s.scn.key);if(d){s.scn.wk=d;s.scn.home=d.city;s.scn.run=Number.isInteger(s.scn.run)&&s.scn.run>=0?s.scn.run:0;}else{delete s.scn.wk;delete s.scn.home;delete s.scn.run;}} + for(const b of [...s.biz,...s.offers])if(Array.isArray(b.reqs))b.reqs=b.reqs.filter(k=>!REQS[k]||!REQS[k].can||(isCity(b.city)&&(!b.city2||isCity(b.city2))&&REQS[k].can(b,s)));if(s.ltv!==2){for(const l of s.links)if(l.kind==='wave'&&l.tier>=3)l.tier=Math.min(LT.length-1,l.tier+1);s.ltv=2;}if(s.dk){s.dk.m=s.dk.m||{};s.dk.add=s.dk.add||{};s.dk.ret=s.dk.ret||{};s.dk.retUsed=s.dk.retUsed||{};}s.hist=s.hist||[];s.loans=s.loans||[];s.loanOffers=s.loanOffers||[];s.loanStrikes=s.loanStrikes||0;for(const l of s.links||[])if(!l.kind)l.kind='wave'; for(const c in s.pops){const p=s.pops[c];if(p.rgen===undefined){let g=0;const need=(i,key)=>{const k=RG.findIndex(r=>r[key]>=i);if(k>g)g=k;}; for(const l of s.links||[])if((l.a===c||l.b===c)&&l.kind==='wave')need(l.tier,'maxLT'); for(const t of s.transit||[])if(t.city===c)need(t.tier,'maxP');for(const x of s.pni||[])if(x.city===c)need(x.tier,'maxP');if(s.ixp&&s.ixp[c]!==undefined)need(s.ixp[c],'maxP');p.rgen=g;}}for(const b of s.biz||[])if(!b.reqs)b.reqs=BIZ_T[b.type]&&BIZ_T[b.type].div?['diverse']:[];for(const o of s.offers||[])if(!o.reqs)o.reqs=[];if(!s.lvl)s.lvl=1;s.nni=s.nni||[];s.cnLic=s.cnLic||{state:'none'};s.ev=s.ev||{};for(const l of s.links){if(!l.kind)l.kind='wave';if(l.mo===undefined)l.mo=Math.round(waveMo(l.km,l.sub,l.tier)*(l.mult||1));}for(const c in s.pops){if(!s.pops[c].routers)s.pops[c].routers=1;} diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index d81413e..eb5983f 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -10,7 +10,10 @@ Object.assign(ACT,{ puzzleDoor:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||randomNetworkName()).slice(0,24);if(typeof ACT.puzzleMenu==='function')ACT.puzzleMenu();else toast(tr('title.puzzles_are_coming_soon'),'goal');}, scenarios:()=>{UI.nm=(($('nmIn')&&$('nmIn').value)||UI.nm||(S&&S.name)||randomNetworkName()).slice(0,24);scenarioModal();}, startScn:({id})=>{const sc=SCN.find(x=>x.id===id);if(!sc)return;beginGame(UI.nm||(S&&S.name)||randomNetworkName(),sc.city,{scn:sc});}, - startWeekly:()=>{const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, + // The published weekly scenario when it came, else the in-browser one. + wsShare:()=>{if(!S||!S.scn||!S.scn.wk||!S.scn.done)return;const t=wsShareText(),copied=()=>toast(tr('puzzles.copied_paste_it_anywhere',{t:esc(t)}),'good'); + if(navigator.share&&isPhone()){navigator.share({text:t}).catch(()=>{});return;}try{navigator.clipboard.writeText(t).then(copied,()=>toast(esc(t),''));}catch(e){toast(esc(t),'');}track('wkscn_share');}, + startWeekly:()=>{const nm=UI.nm||(S&&S.name)||randomNetworkName();if(wsBegin(wsDef(),nm))return;const o=wsLoad();o.go[pzWeekKey(new Date())]=1;wsStore(o);const wk=weekly();beginGame(UI.nm||(S&&S.name)||randomNetworkName(),wk.city,{scn:wk,seed:wk.seed});}, pickStart:({city})=>{if(!homeOk(city))return;UI.startCity=city;const s=$('homeSel');if(s)s.value=city;const w=$('homeWhat');if(w)w.innerHTML=homeWhat();}, pickHome:({v})=>{if(v)ACT.pickStart({city:v});else ACT.pickStart({city:'fra'});}, // Delete this window's network and go back to the title (the other networks stay). diff --git a/src/game/94-dashboard/10-progress.js b/src/game/94-dashboard/10-progress.js index 111df9b..a400b8e 100644 --- a/src/game/94-dashboard/10-progress.js +++ b/src/game/94-dashboard/10-progress.js @@ -15,6 +15,7 @@ const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.5,txt:`${pct(R.re flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll(); return [{l:tr('common.floods_held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('progress.terabit_floods_held'),v:big,max:5,txt:`${big} / 5`},{l:tr('progress.floods_that_got_through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('progress.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('progress.days_in_a_row_with_99'),v:S.stats.clean||0,max:90,txt:tr('progress.n_of_m',{n:S.stats.clean||0,m:90})}]}; function scnProg(){const sc=S&&S.scn;if(!sc)return null; + if(sc.wk){const G=sc.wk.goal;let items=[];try{items=WS_GOALS[G.t].prog(G.p);}catch(e){}const meas=items.filter(x=>x.max);return {goal:wsGoalTxt(sc.wk),items,f:sc.done?1:meas.length?meas.reduce((a,x)=>a+Math.min(1,x.v/x.max),0)/meas.length:0};} if(sc.id==='weekly')return {goal:tr('common.serve_as_much_traffic_as_you'),items:[{l:tr('progress.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=[];} const meas=items.filter(x=>x.max),f=sc.done?1:meas.length?meas.reduce((a,x)=>a+Math.min(1,x.v/x.max),0)/meas.length:0;return {goal:def.goal,items,f};} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index ef1dc02..e1b7c1f 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -40,7 +40,7 @@ const doorAct={puzzle:'puzzleDoor',sandbox:'modeSet',normal:'modeSet',scn:'scena // The chosen preset in one line: its joke, then what actually changes. const presetWhat=k=>`${esc(PRESETS[k].d)} ${esc(PRESETS[k].x)}`; 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('')}

${presetWhat(pr)}

${Object.entries(CHAOS).map(([k,C])=>``).join('')}

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

`;} diff --git a/src/i18n/en.js b/src/i18n/en.js index c0e470a..cf18cc8 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3604,4 +3604,65 @@ "utilities.title":"Utilities", "utilities.two_routers":"At least two routers", "utilities.view_pop":"View PoP", +"wkscn.copy_my_result":"Copy my result", +"wkscn.desc_a_g_event_comes_to":"A {g} event comes to {city} on day {day}. Build the network it needs, from nothing.", +"wkscn.desc_a_ship_dragged_its_anchor":"A ship dragged its anchor across {cab}. Find another way from {a} to {b}.", +"wkscn.desc_a_trading_firm_needs_a":"A trading firm needs {a} to {b} under {ms} ms, and it needs it every day.", +"wkscn.desc_booters_picked_city_for_their":"The booters picked {city} for their week out. Hold the line.", +"wkscn.desc_cab_is_cut_for_the":"{cab} is cut for the whole run. Traffic still has to get from {a} to {b}.", +"wkscn.desc_city_hosts_the_internets_favourite":"{city} hosts the internet's favourite punching bag. Expect a flood every few days.", +"wkscn.desc_city_is_just_the_start":"{city} is just the start: get ports on exchanges all over {reg}.", +"wkscn.desc_city_is_surrounded_by_water":"{city} is surrounded by water and ambition. Connect the islands.", +"wkscn.desc_city_on_a_shoestring":"{city} on a shoestring: little cash, and every bill counts.", +"wkscn.desc_cogentle_and_goggle_stopped_talking":"Cogentle and Goggle have stopped talking again. Start in {city} and reach everyone anyway.", +"wkscn.desc_every_exchange_in_reg_wants":"Every exchange in {reg} wants to meet you. Start in {city}.", +"wkscn.desc_every_millisecond_between_a_and":"Every millisecond between {a} and {b} costs a trader a yacht. Shave them off.", +"wkscn.desc_start_in_city_with_pocket":"Start in {city} with pocket money and grow on what the customers pay.", +"wkscn.desc_start_on_city_and_string":"Start on {city} and string the islands together, one cable at a time.", +"wkscn.desc_the_whole_city_is_watching":"On day {day} all of {city} is watching. Be ready to carry {g}.", +"wkscn.desc_two_giants_de_peered_over":"Two giants de-peered over a spreadsheet. Your customers in {city} still want the whole internet.", +"wkscn.event_name_city":"The Big Weekly Show in {city}", +"wkscn.goal_a_connected_pop_in_list":"A connected POP in {cs}", +"wkscn.goal_a_to_b_under_ms":"{a} to {b} under {ms} ms, {n} days in a row", +"wkscn.goal_deliver_the_event_in_city":"Deliver the {g} event in {city} in full, {dur} days from day {day}", +"wkscn.goal_g_on_every_hop_from":"{g} on every hop from {a} to {b}, {n} days in a row", +"wkscn.goal_hold_n_floods":"Hold {n} floods", +"wkscn.goal_hold_n_floods_big_of":"Hold {n} floods, {big} of them a terabit or more", +"wkscn.goal_ports_on_n_exchanges_in":"Ports on {n} exchanges in {reg}", +"wkscn.goal_reach_r_and_serve_g":"Reach {r}% of the internet and serve {g}", +"wkscn.goal_serve_g":"Serve {g} of traffic", +"wkscn.loading_this_week_s_scenario":"Loading this week's scenario…", +"wkscn.name_continental_breakfast":"Continental Breakfast", +"wkscn.name_cut_and_run":"Cut and Run", +"wkscn.name_flood_week":"Flood Week", +"wkscn.name_island_hopper":"Island Hopper", +"wkscn.name_light_speed_please":"Light Speed, Please", +"wkscn.name_ludicrous_speed":"Ludicrous Speed", +"wkscn.name_not_on_speaking_terms":"Not On Speaking Terms", +"wkscn.name_packet_monsoon":"Packet Monsoon", +"wkscn.name_party_like_its_1999":"Party Like It's 1999", +"wkscn.name_peering_pressure":"Peering Pressure", +"wkscn.name_planting_flags":"Planting Flags", +"wkscn.name_ramen_profitable":"Ramen Profitable", +"wkscn.name_sea_you_soon":"Sea You Soon", +"wkscn.name_shoestring_backbone":"Shoestring Backbone", +"wkscn.name_stream_team":"Stream Team", +"wkscn.name_suez_you_later":"Suez You Later", +"wkscn.next_weekly_in_d_h":"Next weekly scenario in {d} d {h} h", +"wkscn.next_weekly_in_h_m":"Next weekly scenario in {h} h {m} min", +"wkscn.p_a_b_now":"{a} → {b} now: {ms}", +"wkscn.p_days_in_a_row":"Days in a row", +"wkscn.p_event_delivered_in_full":"Event delivered in full", +"wkscn.p_exchange_ports_in_reg":"Exchange ports in {reg}", +"wkscn.p_g_on_day_d":"{g} on day {d}", +"wkscn.p_path_g_a_b":"{g} path {a} → {b}", +"wkscn.par_day_par":"par: day {par}", +"wkscn.par_was_day_par":"Par was day {par}. Next week, maybe.", +"wkscn.same_scenario_for_everyone_this_week":"Same scenario for everyone this week", +"wkscn.share_line":"Series of Tubes weekly {key} “{name}” won day {d} (par {par}) · seriesoftub.es", +"wkscn.start_in_city_d_days_cash":"Start in {city} · {d} days · {cash}", +"wkscn.under_par_par":"At or under par (day {par}). Nicely done.", +"wkscn.weekly_scenario_key":"Weekly scenario {key}", +"wkscn.won_day_d_par_par":"Won day {d} (par {par})", +"wkscn.won_on_day_d":"Won on day {d}!", }; From d8df1e37f6d84dcd67ec1135eec6f9a6ee1ca6ff Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 17:34:38 +0100 Subject: [PATCH 111/181] Weekly scenario generator with a reference player, and weeks 2026-W44 to W46 --- scripts/lib/scenario-bot.js | 53 +++++ scripts/weekly-scenario.js | 297 ++++++++++++++++++++++++++++ site/scenarios/weekly/2026-W44.json | 1 + site/scenarios/weekly/2026-W45.json | 1 + site/scenarios/weekly/2026-W46.json | 1 + site/scenarios/weekly/index.json | 1 + 6 files changed, 354 insertions(+) create mode 100644 scripts/lib/scenario-bot.js create mode 100644 scripts/weekly-scenario.js create mode 100644 site/scenarios/weekly/2026-W44.json create mode 100644 site/scenarios/weekly/2026-W45.json create mode 100644 site/scenarios/weekly/2026-W46.json create mode 100644 site/scenarios/weekly/index.json diff --git a/scripts/lib/scenario-bot.js b/scripts/lib/scenario-bot.js new file mode 100644 index 0000000..bf811ea --- /dev/null +++ b/scripts/lib/scenario-bot.js @@ -0,0 +1,53 @@ +// The reference player for weekly scenarios (scripts/weekly-scenario.js). It plays inside the real game, headless, +// through the game's own actions (ACT.*, openLinkModal + buildLink), as a careful human would: broadband, transit and +// an exchange port at home on day 0, a NOC intern on standing orders for transit and routers, then the generator's +// plan one step at a time whenever the bank allows it, upgrading any wave that runs hot. It never reads the goal, so the +// same seed and plan always play the same game, and the generator can calibrate a goal from what it reached. +const BOT = String.raw`(()=>{ +const B=window.__wsBot={}; +const cheapNet=(c,avoid)=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!avoid.includes(n.id)&&!S.transit.some(t=>t.city===c&&t.net===n.id)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0]; +const reserve=()=>Math.max(60000,1.5*(R.costMo||0)); +const can=x=>S.cash>=x+reserve(); +const quiet=f=>{const t=window.toast;window.toast=()=>{};try{f();}finally{window.toast=t;}}; +function link(a,b,tier,via){UI.via=via||null;UI.route=null;openLinkModal(a,b);ACT.buildLink({tier});closeModal();return S.links.some(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));} +function ix(c){if(!S.pops[c])return;for(const x of (B.plan&&B.plan.allIx?ixIdsIn(c):[c])){if(!ixName(x)||S.ixp[x]!==undefined)continue;ACT.buyIx({city:x,tier:1,signed:true});if(S.ixp[x]!==undefined&&!S.rs[x])ACT.rs({city:x});}} +// Before a big event: transit enough for the event on top of the usual peak, and routers that can take it. +function prep(E){const c=E.city,need=(S.stats.peak||R.served||0)*1.2+E.g*1.15;let cap=()=>S.transit.filter(t=>t.city===c).reduce((a,t)=>a+PORT[t.tier].g*(t.n||1),0); + for(let k=0;k<12&&cap()t.city===c).sort((a,b)=>PORT[a.tier].g*(a.n||1)-PORT[b.tier].g*(b.n||1))[0];if(!t)break;const c0=cap(); + if(t.tier=need/4&&portOk(c,t.tier+1))ACT.buyTransit({city:c,net:t.net,tier:t.tier+1});else ACT.lagT({id:t.id,d:1});if(cap()===c0)break;} + for(let k=0;k<4;k++){const p=S.pops[c];if(!p||(p.routers||1)>=RMAX)break;const r0=p.routers||1;ACT.addRouter({city:c});if((p.routers||1)===r0)break;}} +B.start=(plan)=>{B.plan=plan;B.i=0;const c=S.scn.home||plan.home;quiet(()=>{ + ACT.launchBB({city:c}); + if(!scnRule('noTransit')){const n=cheapNet(c,plan.avoid||[]);if(n)ACT.buyTransit({city:c,net:n.id,tier:1});if(plan.tr2){const m=cheapNet(c,plan.avoid||[]);if(m)ACT.buyTransit({city:c,net:m.id,tier:1});}} + ix(c);if(plan.scrub)ACT.buildScrub({city:c,tier:plan.scrub});});}; +B.day=()=>{const P=B.plan,d=S.day;if(!P)return;quiet(()=>{ + // A month in, with the first bills paid: the intern keeps transit and routers ahead of the traffic. + if(d===30&&opsCanHire()&&!opsHired()&&rule('clock')){ACT.opsHire({id:'kevin'});closeModal();if(opsHired())for(const k of ['transit','routers','repair'])if(!S.ops.on[k])ACT.opsToggle({k});closeModal();} + if(d%7===0)for(const l of S.links){if(l.kind!=='wave'||l.tier>=LT.length-1||(R.load[l.id]||0)=P.event.day-21&&d { if (!ev('!!window.__wsBot')) ev(BOT); }; + +// Plays a weekly scenario file from day 0: the plan steps once a day, until the goal is met (when stop) or the days +// run out. Returns the day the goal was first met (or null), what the goal measure read each day, and the end state. +function play(ev, file, plan, { days, stop = true, measure = 'wsMeasure()' } = {}) { + install(ev); + ev(`localStorage.removeItem('sot-wkscn');wsBegin(${JSON.stringify(file)},'Ref');if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`); + if (ev('!!(S.scn&&S.scn.wk)') !== true) throw new Error('the game would not start this scenario'); + ev(`__wsBot.start(${JSON.stringify(plan)})`); + const won0 = ev('wsOk()'), n = days || ev('S.scn.days'); + // Each day: the bot moves, the day ticks (scnTick records a win), and we note the measure. + const out = JSON.parse(ev(`(()=>{const m=[];let won=null;for(let i=0;i<${n};i++){__wsBot.day();dayTick();closeModal();m.push(+(${measure}).toFixed(3));if(won===null&&S.scn.done)won=S.scn.done;if(won!==null&&${stop})break;if(S.lost)break;}return JSON.stringify({won,m,lost:!!S.lost,day:S.day,cash:Math.round(S.cash)});})()`)); + return { won0, ...out }; +} + +module.exports = { BOT, install, play }; diff --git a/scripts/weekly-scenario.js b/scripts/weekly-scenario.js new file mode 100644 index 0000000..a7a45b1 --- /dev/null +++ b/scripts/weekly-scenario.js @@ -0,0 +1,297 @@ +#!/usr/bin/env node +// The weekly scenario generator, the twin of scripts/weekly-puzzle.js. Every Sunday .github/workflows/weekly-puzzle.yml +// runs both; this one publishes site/scenarios/weekly/.json, which the game fetches when the Scenarios list opens +// (src/game/60-features/94-scenarios-weekly.js). It loads the real game headless, so it uses the game's own cities, +// cables, prices, week keys, file validator and goal code. +// +// node scripts/weekly-scenario.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing +// node scripts/weekly-scenario.js --key 2026-W45 that week (--force replaces an existing file) +// node scripts/weekly-scenario.js --next 3 this week and the next two +// node scripts/weekly-scenario.js --check re-play every week not over yet with this game; a week its reference +// no longer wins is regenerated with rev + 1 (see refresh()); then +// validate every file. Fails only if that fails. +// --page FILE / --dir DIR another build of the game / where the files live +// +// How a scenario is made: pick a theme the last weeks did not have (TEMPLATES, plain data), a home city from another part +// of the world than the last weeks', its rules and the reference plan (which links to build, in order). Then the +// reference player (scripts/lib/scenario-bot.js) plays it through the game's own actions with the scenario's seed. The +// goal's number is calibrated from that run (what the reference reached about three quarters of the way in), and the +// scenario is verified: not won on day 0, won by the reference with time to spare. Its finishing day is the par. +const fs = require('node:fs'); +const path = require('node:path'); +const BOT = require('./lib/scenario-bot'); + +const ROOT = path.join(__dirname, '..'); +const SCHEMA = 1, HISTORY = 4, THEME_GAP = 4, REG_GAP = 3, ATTEMPTS = 12, AT = 0.8, MARGIN = 0.9; + +// ---------- the templates: data only. `home` names a city pool, `goal` a goal type of the game, `plan` a planner ---------- +const TEMPLATES = { + budget: { goal: 'served', home: 'big', days: [240, 300], cash: [150000, 250000], lvl: 2, mods: ['pricey'], plan: 'spread', hops: 4 }, + spat: { goal: 'reach', home: 'big', days: [240, 300], cash: [500000, 800000], lvl: 2, rules: { spat: true }, plan: 'spread', hops: 3, tr2: true, avoid: ['cog'] }, + region: { goal: 'ix', home: 'ixrich', days: [270, 365], cash: [200000, 350000], lvl: 2, plan: 'exchanges', hops: 14 }, + event: { goal: 'event', home: 'big', days: [180, 240], cash: [500000, 900000], lvl: 2, plan: 'spread', hops: 2, sizes: [1600, 800, 400, 200] }, + flood: { goal: 'floods', home: 'big', days: [240, 300], cash: [1500000, 2500000], lvl: 3, rules: { ddos: true }, plan: 'spread', hops: 2, scrub: 1 }, + island: { goal: 'pops', home: 'island', days: [240, 365], cash: [250000, 500000], lvl: 3, plan: 'islands', hops: 3 }, + cable: { goal: 'path', home: 'landing', days: [270, 365], cash: [200000, 400000], lvl: 3, plan: 'detour', g: [400, 800], n: 45 }, + latency: { goal: 'lat', home: 'fast', days: [180, 270], cash: [300000, 600000], lvl: 3, plan: 'fast', n: 60 }, +}; + +// ---------- the game, headless ---------- +function game(file) { + const { load } = require('../tests/harness'); + let g = load(file ? { file } : {}); + if (file && !g.ev("typeof wsValid==='function'")) { console.warn(`warning: ${file} has no weekly scenarios yet; using src/ instead`); g = load(); } + return g; +} +const J = (ev, s) => JSON.parse(ev(`JSON.stringify(${s})`)); + +// ---------- 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 between = (r, [lo, hi], step) => lo + Math.floor(r() * ((hi - lo) / step + 1)) * step; +// A goal number players can read: two significant digits, rounded down. +const nice = (x) => { if (x < 10) return Math.max(1, Math.floor(x)); const p = 10 ** (Math.floor(Math.log10(x)) - 1); return Math.floor(x / p) * p; }; + +// ---------- the world, as the game sees it ---------- +function world(ev) { + const cities = J(ev, `Object.values(CITY).filter(c=>pzCityOk(c.id)).map(c=>({id:c.id,reg:c.reg,P:c.P,land:lands(c)[0],nl:lands(c).length,ix:ixIdsIn(c.id).length,lon:c.lon,lat:c.lat}))`); + const C = Object.fromEntries(cities.map((c) => [c.id, c])); + const pairs = J(ev, 'CABLE_PAIRS.map(p=>[p.cid,p.a,p.b])').filter(([, a, b]) => C[a] && C[b]); + const byLand = {}; for (const c of cities) (byLand[c.land] = byLand[c.land] || []).push(c.id); + 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)); }; + const cabs = (c) => pairs.filter(([, a, b]) => a === c || b === c); + const pools = { + big: cities.filter((c) => c.P >= 150 && byLand[c.land].length >= 5).map((c) => c.id), + ixrich: cities.filter((c) => c.ix && cities.filter((x) => x.reg === c.reg && x.land === c.land && x.ix && km(c.id, x.id) < 2500).length >= 9).map((c) => c.id), + island: cities.filter((c) => byLand[c.land].length <= 2 && c.nl === 1 && cabs(c.id).length >= 2).map((c) => c.id), + landing: cities.filter((c) => c.P >= 100 && cabs(c.id).length >= 3).map((c) => c.id), + fast: cities.filter((c) => c.P >= 100 && cabs(c.id).length >= 2).map((c) => c.id), + }; + return { cities, C, pairs, byLand, km, cabs, pools }; +} +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); + +// ---------- drafts: a template, a home, rules, the goal's fixed parameters and the reference plan ---------- +// Plans are lists of steps for the reference player: {k:'hop',v:[a,b,tier,via]} lights a wave a-b (a new POP at b). +function draft(g, W, theme, r, hist) { + const T = TEMPLATES[theme], free = (c) => !hist.cities.has(c) && !hist.regs.includes(W.C[c].reg); + const homes = W.pools[T.home].filter(free); if (!homes.length) return null; + const home = pick(r, homes), H = W.C[home]; + const f = { theme, city: home, cash: between(r, T.cash, 50000), days: between(r, T.days, 10), lvl: T.lvl, rules: { ...(T.rules || {}) }, mods: (T.mods || []).slice() }; + const plan = { home, bb: true, ix: true, steps: [], avoid: T.avoid || [], tr2: !!T.tr2, scrub: T.scrub || 0 }; + const hop = (a, b, t = 1, via = null) => plan.steps.push({ k: 'hop', v: [a, b, t, via] }); + const land = W.byLand[H.land].filter((c) => c !== home && W.km(home, c) < 1500); + let goal = null, words = {}; + if (T.plan === 'spread') { + // Overland to the nearest big cities, each from the closest POP already built. + const to = near(W, home, land.filter((c) => W.C[c].P >= 60), T.hops); if (to.length < Math.min(2, T.hops)) return null; + const built = [home]; for (const c of to) { hop(near(W, c, built, 1)[0], c); built.push(c); } + if (theme === 'budget') goal = { t: 'served', p: { g: 0 } }; + if (theme === 'spat') goal = { t: 'reach', p: { r: 99, g: 0 } }; + if (theme === 'flood') goal = { t: 'floods', p: { n: 0, big: 0 } }; + if (theme === 'event') { const day = Math.round(f.days * (0.6 + r() * 0.15)); goal = { t: 'event', p: { city: home, g: 0, day, dur: 3 + Math.floor(r() * 3) } }; plan.event = { city: home, day }; words = { day }; } + } else if (T.plan === 'exchanges') { + const to = near(W, home, W.cities.filter((c) => c.reg === H.reg && c.land === H.land && c.ix).map((c) => c.id), T.hops); if (to.length < T.hops) return null; + const built = [home]; for (const c of to) { hop(near(W, c, built, 1)[0], c); built.push(c); } + plan.allIx = true; goal = { t: 'ix', p: { reg: H.reg, n: 0 } }; words = { reg: H.reg }; + } else { + // Cable work: plan inside the game, which knows each pair's cables under this scenario's rules. + let a = home, b = null, cs = null; + if (theme === 'cable') { + // Cut one cable everywhere it lands; the goal is its far end, the long way round. + const mine = W.cabs(home).filter(([, x, y]) => W.C[x].land !== W.C[y].land && W.C[x === home ? y : x].P >= 60); + if (!mine.length) return null; + const [cid, x, y] = pick(r, mine); b = x === home ? y : x; + // The whole cable, and every other cable straight from home to its far end: the corridor is closed. + const cut = new Set([cid, ...W.pairs.filter(([, p, q]) => (p === home && q === b) || (p === b && q === home)).map(([c]) => c)]); + f.rules.banPairs = W.pairs.filter(([c, p, q]) => c === cid || (cut.has(c) && [p, q].includes(home) && [p, q].includes(b))).map(([c, p, q]) => `${c}:${p}-${q}`); + if (f.rules.banPairs.length > 40) return null; + const gb = pick(r, T.g); plan.tier = J(g.ev, `LT.findIndex(x=>x.g>=${gb})`); + goal = { t: 'path', p: { a, b, g: gb, n: T.n } }; words = { cab: cid, a, b }; + } else if (theme === 'island') { + const hops = W.cabs(home).map(([, x, y]) => (x === home ? y : x)).filter((c, i, s) => s.indexOf(c) === i && W.km(home, c) < 6000); + if (hops.length < 2) return null; + // The nearest islands a cable away, and one more island further out. + const isl = W.pools.island.filter((c) => c !== home && W.km(home, c) < 9000 && !hops.includes(c)); + cs = [...near(W, home, hops, 2), ...near(W, home, isl, 1 + Math.floor(r() * 2))]; + if (cs.length < 3) return null; + goal = { t: 'pops', p: { cs } }; + } else if (theme === 'latency') { + // Far enough that the fast way takes more than one cable. + const ok = W.cities.filter((c) => c.P >= 100 && c.land !== H.land && W.km(home, c.id) > 5000 && W.km(home, c.id) < 11000 && W.cabs(c.id).length >= 2).map((c) => c.id); + if (!ok.length) return null; b = pick(r, ok); goal = { t: 'lat', p: { a, b, ms: 0, n: T.n } }; words = { a, b }; + } + plan.targets = cs || [b]; plan.fast = theme === 'latency'; + f.goal = goal; + return { f, plan, words, T }; + } + f.goal = goal; + return { f, plan, words, T }; +} + +// ---------- names and descriptions: labels and their fill-ins ---------- +function texts(ev, d, r) { + const T = J(ev, `WS_THEMES['${d.f.theme}']`), p = d.f.goal.p; + const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], o = {}; + for (const k of need) o[k] = k === 'city' ? d.f.city : k === 'ms' ? p.ms : k === 'g' ? p.g : k === 'n' ? p.n : d.words[k]; + return { l, p: o }; }; + return { name: fill(pick(r, T.names)), desc: fill(pick(r, T.descs)) }; +} + +// ---------- playing a draft ---------- +const fileOf = (key, d, seed, extra) => ({ v: SCHEMA, key, theme: d.f.theme, city: d.f.city, cash: d.f.cash, days: d.f.days, lvl: d.f.lvl, rules: d.f.rules, mods: d.f.mods, goal: d.f.goal, ...extra, seed, ref: d.plan }); +// Cable plans are made in the game, once the scenario's rules are in force: the shortest chain of POPs to each target. +function cablePlan(ev, plan) { + if (!plan.targets) return plan; + const steps = J(ev, `(()=>{const home=S.scn.home,T=${JSON.stringify(plan.targets)},fast=${!!plan.fast},out=[],have=new Set([home]); + const ok=c=>pzCityOk(c)&&cityOn(c)&&!cnCity(c); + const edges=u=>{const o=[];for(const p of CABLE_PAIRS){const v=p.a===u?p.b:p.b===u?p.a:null;if(!v||!ok(v))continue;const cs=cablesOk(u,v);if(!cs.length)continue; + const c=cs.slice().sort((x,y)=>x.km*(CAB[x.cid].lat||1)-y.km*(CAB[y.cid].lat||1))[0];o.push([v,c.km*(CAB[c.cid].lat||1)/200,c.cid]);} + for(const c of CITIES)if(c.id!==u&&ok(c.id)&&!isSub(u,c.id)&&kmBetween(u,c.id)<(fast?4000:1800))o.push([c.id,kmBetween(u,c.id)*1.3/200,null]);return o;}; + for(const t of T){if(have.has(t))continue;const d={},pv={},done=new Set();for(const h of have)d[h]=0; + for(;;){let u=null;for(const k in d)if(!done.has(k)&&(u===null||d[k]=1')) { p.g = size; return { plan: o.plan }; } } + return null; + } + if (t === 'lat') { + const o = run(g, file, d.plan, at); if (!o) return null; + const best = g.ev(`bestLat('${p.a}','${p.b}')`); if (!isFinite(best)) return null; + p.ms = Math.ceil(best * 1.03 + 0.5); return { plan: o.plan }; + } + const o = run(g, file, d.plan, at); if (!o) return null; + const m = o.res.m, v = m[m.length - 1]; + if (t === 'served') p.g = nice(Math.min(...m.slice(-14))); + if (t === 'reach') { if (g.ev('R.reach') < 0.99) return null; p.g = nice(Math.min(...m.slice(-14))); } + if (t === 'ix') p.n = Math.floor(v); + if (t === 'floods') { p.n = Math.floor(v); p.big = Math.min(5, g.ev('S.stats.ddosOkBig||0')); } + if ((p.g !== undefined && p.g < 5) || (p.n !== undefined && p.n < 2)) return null; + return { plan: o.plan }; +} + +// The game's validator decides what a scenario is; then it must need play, and the reference must win with time to spare. +function verify(g, j) { + const { ev } = g; + if (!ev(`!!wsValid(${JSON.stringify(j)},'${j.key}')`)) return { ok: false, why: 'the game rejects the file' }; + // Played with the longest clock the game allows, so a late win still shows its day (the days change nothing else). + const res = BOT.play(ev, { ...j, days: 400 }, j.ref, { stop: true }); + if (res.won0) return { ok: false, why: 'won on day 0' }; + if (!res.won) return { ok: false, why: `the reference does not win in ${j.days} days` }; + if (res.won > j.days * MARGIN) return { ok: false, late: res.won, why: `the reference wins only on day ${res.won} of ${j.days}` }; + if (res.won < 40) return { ok: false, why: `the reference wins already on day ${res.won} of ${j.days}` }; + return { ok: true, par: res.won }; +} + +// ---------- one week ---------- +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() : []); +function history(W, dir, key) { + const files = list(dir).filter((k) => k < key).slice(-HISTORY).map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8'))); + return { themes: files.slice(-THEME_GAP).map((f) => f.theme), regs: files.slice(-REG_GAP).map((f) => W.C[f.city] && W.C[f.city].reg).filter(Boolean), cities: new Set(files.map((f) => f.city)) }; +} +function generate(g, key, dir) { + const { ev } = g, W = world(ev); + if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`); + const hist = history(W, dir, key), free = Object.keys(TEMPLATES).sort().filter((t) => !hist.themes.includes(t)), h = hash('scn|' + key); + const order = free.map((_, i) => free[(h + i) % free.length]); + for (const theme of order) { + for (let at = 0; at < ATTEMPTS; at++) { + const r = rng(hash(`${key}|${theme}|${at}`)), d = draft(g, W, theme, r, hist); + if (!d) continue; + const seed = 1 + (hash(`${key}|seed|${at}`) % 2147483646), c = calibrate(g, d, key, seed); + if (!c) { console.warn(`${key}: rejected a ${theme} scenario in ${d.f.city}: no goal to calibrate`); continue; } + d.plan = c.plan; + const w = texts(ev, d, r), j = fileOf(key, d, seed, { name: w.name, desc: w.desc, par: 1 }); + let v = verify(g, j); + // A goal with a fixed bar (a path, a set of POPs, a latency) gets the days the reference needed, and a third more. + const day = v.ok ? v.par : v.late; + if (day && ['path', 'pops', 'lat'].includes(j.goal.t)) { j.days = Math.min(365, Math.max(180, Math.ceil(day / 0.7 / 10) * 10)); v = verify(g, j); } + if (v.ok) { j.par = v.par; return order0(j); } + console.warn(`${key}: rejected a ${theme} scenario in ${d.f.city}: ${v.why}`); + } + } + throw new Error(`${key}: no scenario survived verification`); +} +// Fields in a fixed order, so files diff well. +const order0 = (j) => { const o = {}; for (const k of ['v', 'key', 'rev', 'theme', 'city', 'cash', 'days', 'lvl', 'rules', 'mods', 'goal', 'name', 'desc', 'seed', 'par', 'ref']) if (j[k] !== undefined) o[k] = j[k]; return o; }; + +// --check: every file is what the game accepts, under its own name, listed in the index; weeks not over yet still verify. +function check(g, dir, now = Date.now()) { + const { ev } = g, 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(`!!wsValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; } + if (!j.ref || !Array.isArray(j.ref.steps)) { bad.push(`${k}: no reference plan`); continue; } + if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j); if (!v.ok) bad.push(`${k}: ${v.why}`); else if (v.par !== j.par) bad.push(`${k}: par is ${j.par}, the reference wins on day ${v.par}`); } + } + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* reported below */ } + if (keys.length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys))) bad.push('index.json does not list exactly the weekly files'); + return bad; +} +/* --check, first part: a release can change prices, cables or the simulation under weeks already published. Every week + not over yet is re-played with this game. Still won with time to spare: only its par follows. Not any more: it is + regenerated for the same key, deterministically, with rev + 1, so last week's wins for it no longer show. Past weeks + are only replaced when the game rejects them outright. */ +function refresh(g, dir, now = Date.now()) { + const { ev } = g, fixed = [], bad = []; + for (const k of list(dir)) { + let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated */ } + const valid = !!j && ev(`!!wsValid(${JSON.stringify(j)},'${k}')`) && j.ref && Array.isArray(j.ref.steps), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now; + if (valid && !live) continue; + const v = valid ? verify(g, j) : null; + if (v && v.ok) { if (v.par !== j.par) { j.par = v.par; writeWeek(dir, j); fixed.push(`${k}: new par ${v.par}`); } continue; } + const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1; + let n; try { n = order0({ ...generate(g, k, dir), rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; } + writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}, a ${n.theme} scenario in ${n.city}`); + } + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ } + if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); } + return { fixed, 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, verify, check, refresh, list, writeWeek, TEMPLATES }; + +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/scenarios/weekly')), g = game(opt('--page') && path.resolve(opt('--page'))); + if (args.includes('--check')) { + const r = refresh(g, dir); + for (const x of r.fixed) console.log(`fixed: ${x}`); + const bad = [...r.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 scenario(s) OK`); + process.exit(bad.length ? 1 : 0); + } + 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} in ${j.city}, ${j.days} days, goal ${j.goal.t} ${JSON.stringify(j.goal.p)}, par ${j.par}`); + } +} diff --git a/site/scenarios/weekly/2026-W44.json b/site/scenarios/weekly/2026-W44.json new file mode 100644 index 0000000..8424bfe --- /dev/null +++ b/site/scenarios/weekly/2026-W44.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W44","theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":3,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":24,"big":1}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":195,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":1}} diff --git a/site/scenarios/weekly/2026-W45.json b/site/scenarios/weekly/2026-W45.json new file mode 100644 index 0000000..498ff4f --- /dev/null +++ b/site/scenarios/weekly/2026-W45.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W45","theme":"event","city":"bog","cash":900000,"days":230,"lvl":2,"rules":{},"mods":[],"goal":{"t":"event","p":{"city":"bog","g":400,"day":159,"dur":3}},"name":{"l":"wkscn.name_party_like_its_1999","p":{}},"desc":{"l":"wkscn.desc_the_whole_city_is_watching","p":{"day":159,"city":"bog","g":400}},"seed":169037385,"par":162,"ref":{"home":"bog","bb":true,"ix":true,"steps":[{"k":"hop","v":["bog","mde",1,null]},{"k":"hop","v":["bog","uio",1,null]}],"avoid":[],"tr2":false,"scrub":0,"event":{"city":"bog","day":159,"g":400}}} diff --git a/site/scenarios/weekly/2026-W46.json b/site/scenarios/weekly/2026-W46.json new file mode 100644 index 0000000..df843d6 --- /dev/null +++ b/site/scenarios/weekly/2026-W46.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W46","theme":"spat","city":"fih","cash":750000,"days":250,"lvl":2,"rules":{"spat":true},"mods":[],"goal":{"t":"reach","p":{"r":99,"g":370}},"name":{"l":"wkscn.name_not_on_speaking_terms","p":{}},"desc":{"l":"wkscn.desc_two_giants_de_peered_over","p":{"city":"fih"}},"seed":61791269,"par":183,"ref":{"home":"fih","bb":true,"ix":true,"steps":[{"k":"hop","v":["fih","lad",1,null]},{"k":"hop","v":["fih","dla",1,null]}],"avoid":["cog"],"tr2":true,"scrub":0}} diff --git a/site/scenarios/weekly/index.json b/site/scenarios/weekly/index.json new file mode 100644 index 0000000..8955841 --- /dev/null +++ b/site/scenarios/weekly/index.json @@ -0,0 +1 @@ +{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]} From 0ece48a79d166abf67ec5a5ba5cda02831cd4650 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 17:34:38 +0100 Subject: [PATCH 112/181] Ship weekly scenarios with the weekly puzzle run; docs and skills --- .claude/skills/github-pages/SKILL.md | 4 +++- .claude/skills/release/SKILL.md | 6 +++++- .github/workflows/release.yml | 17 ++++++++++------- .github/workflows/weekly-puzzle.yml | 20 +++++++++++--------- docs/ARCHITECTURE.md | 11 +++++++++++ site/sw.js | 4 ++-- 6 files changed, 42 insertions(+), 20 deletions(-) diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index 69d4a49..205db5b 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -47,7 +47,9 @@ added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in th 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, and regenerates (in the build, deterministically) any week not over yet that the release's prices no longer fit. 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`. +Puzzles list opens and never trusts; the service worker serves them network-first. The weekly scenario rides along in +the same run: `scripts/weekly-scenario.js` writes `site/scenarios/weekly/.json` (fetched when the Scenarios list +opens), committed and deployed with the puzzle, never by a second workflow. See `docs/ARCHITECTURE.md`. ## Before you hand back a change that touches the build, deploy or loading diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 99f8b4d..509d3fb 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -21,12 +21,16 @@ version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly `gh workflow run release.yml --ref -f tag= -f weekly=true`). A release includes every weekly file on `main` when it builds. +The weekly scenario (`site/scenarios/weekly/`, `scripts/weekly-scenario.js`) ships in the same run and the same way: +`--key`, `--force` and `--check` work alike. Its `--check` replays each week not over yet with the reference plan in +the file; a new par is just written, a week the reference no longer wins is regenerated with `rev` + 1. + **Prices change, weeks follow.** `--check` re-solves every week not over yet with the game it runs; a week whose budget no longer verifies is regenerated deterministically (the same puzzle with a new budget if that works, else a fresh one for the same key) with `rev` + 1, which resets players' stars for that week only. Past weeks are left alone unless the game rejects them. `release.yml` runs it before the tests on every deploy and fails only if a week cannot be regenerated. A change to prices, cables or cities fails `npm test` until you run `node scripts/weekly-puzzle.js --check` -and commit the regenerated files with it. +and commit the regenerated files with it (and `node scripts/weekly-scenario.js --check` for the scenarios). ## Only release when Frederic says so diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fe2070b..0d1ad7a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,15 +70,17 @@ jobs: 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 + - name: Weekly puzzles and scenarios 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 + for d in site/puzzles/weekly site/scenarios/weekly; do + if git cat-file -e "FETCH_HEAD:$d" 2>/dev/null; then + rm -rf "$d" + git checkout FETCH_HEAD -- "$d" + echo "$d: $(ls "$d" | grep -c '^[0-9].*\.json$')" + fi + done - run: npm ci # This release's prices may no longer fit a week already published: --check regenerates every week not over # yet whose budget no longer verifies (deterministically, so main's next weekly run commits the same files), @@ -89,11 +91,12 @@ jobs: # 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 + if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi - run: npm test if: ${{ !inputs.weekly }} - name: Test the weekly puzzles against this release if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }} - run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js + run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js 2>/dev/null) - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build - uses: actions/upload-pages-artifact@v5 diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml index 0629330..9ac5cfa 100644 --- a/.github/workflows/weekly-puzzle.yml +++ b/.github/workflows/weekly-puzzle.yml @@ -1,8 +1,8 @@ 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. +# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js) and scenario (scripts/weekly-scenario.js), +# commit them to main as a data-only change, and redeploy the live release with them, once. Weeks start Sunday +# 06:00 Berlin time; 03:37 UTC is 04:37 in winter and 05:37 in summer, so the files are live before the week starts. # # 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 @@ -47,27 +47,29 @@ jobs: - run: npm ci # Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current. - name: Fit the published weeks to main - run: node scripts/weekly-puzzle.js --check - - name: Make the puzzle + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check + - name: Make the puzzle and the scenario 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" + node scripts/weekly-scenario.js --key "$KEY" else node scripts/weekly-puzzle.js + node scripts/weekly-scenario.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 + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js - name: Commit it to main run: | set -euo pipefail - git add site/puzzles/weekly + git add site/puzzles/weekly site/scenarios/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 status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/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 ' ')" + commit -m "Weekly puzzle and scenario $(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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ecdacda..7af5613 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -74,6 +74,7 @@ Development runs on `npm run dev` (assembles on every request, reloads on save); | `.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) | +| `scripts/weekly-scenario.js`, `scripts/lib/scenario-bot.js`, `site/scenarios/weekly/` | The weekly scenario generator, its reference player and its output (see below) | | `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) | ## Globals @@ -177,6 +178,16 @@ so `auto-release.yml` stays quiet) and starts `release.yml` from the live releas 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. +The weekly scenario is its twin, in the same weeks and the same workflow run: `scripts/weekly-scenario.js` writes +`site/scenarios/weekly/.json`. A template (plain data in the script) picks a theme, a home city, rules from the +scenario vocabulary (`scnRule` keys, `WEEK_MODS`) and a goal type with parameters; each goal type (`WS_GOALS` in +`src/game/60-features/94-scenarios-weekly.js`) is implemented once in the game, with its progress card. A reference +player (`scripts/lib/scenario-bot.js`) plays it through `ACT`, seeded with the scenario's seed; the goal's number is +calibrated from that run, the scenario must not be won on day 0, the reference must win with a tenth of the days to +spare, and its finishing day is the par. The file keeps the reference plan (`ref`), which `--check` replays. The game +fetches the file when the Scenarios list opens, checks it with `wsValid()` (again in `sanitize()` on load), and falls +back to the in-browser `weekly()`. + ## Saves, imports and migration - `save()` writes `S` to localStorage every few seconds and after actions, into this window's slot diff --git a/site/sw.js b/site/sw.js index 6c895f6..2e0924c 100644 --- a/site/sw.js +++ b/site/sw.js @@ -25,8 +25,8 @@ 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/')) { + // Weekly puzzles and scenarios are published between releases: ask the network first, and keep a copy for offline. + if (local && (url.pathname.startsWith('/puzzles/weekly/') || url.pathname.startsWith('/scenarios/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; From 3dbd508b6435f7f3e9d8a7414b719e08d73c2ac9 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 17:40:51 +0100 Subject: [PATCH 113/181] Tests for the weekly scenario; C1 covers committed weeks; CHANGELOG --- .claude/skills/gameplay-rules/SKILL.md | 2 +- CHANGELOG.md | 1 + tests/gameplay-rules.test.js | 10 ++ tests/weekly-scenario.test.js | 208 +++++++++++++++++++++++++ 4 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 tests/weekly-scenario.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 092aa0f..b8c5146 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -52,7 +52,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | Id | Rule | Why | | --- | --- | --- | -| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0. | A goal must need play. | +| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. | | C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. | | C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. | diff --git a/CHANGELOG.md b/CHANGELOG.md index bf31011..5d2a230 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,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. - Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. - A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, 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 weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands 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, 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). - 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. - 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, sold-out routes and de-peering at exchanges. 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. diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 3c2c1f7..5123f89 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -282,6 +282,16 @@ test('C1: every scenario has a goal its card checks, and none is won on day 0', if (g.ev(`(()=>{try{return !!${def}.ok();}catch(e){return false;}})()`)) bad.push(id + ': won on day 0'); if (!g.ev(`typeof SCN_PROG['${id}']==='function'&&scnProg().items.length>0`)) bad.push(id + ': no progress card (SCN_PROG)'); } + // The published weekly scenarios too: each committed week starts, has its goal type's card, and needs play. + const wdir = path.join(__dirname, '..', 'site', 'scenarios', 'weekly'); + for (const f of fs.readdirSync(wdir).filter((x) => /^\d{4}-W\d{2}\.json$/.test(x))) { + const j = fs.readFileSync(path.join(wdir, f), 'utf8'), id = 'weekly ' + f.slice(0, -5); + if (!g.ev(`wsBegin(${j},'S')`)) { bad.push(id + ': the game rejects it'); continue; } + g.ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute()'); + if (g.ev('wsOk()')) bad.push(id + ': won on day 0'); + if (!g.ev('scnProg().items.length>0&&!!scnName()&&!!wsGoalTxt(S.scn.wk)')) bad.push(id + ': no progress card or goal'); + if (g.ev('S.rules.preset') !== 'oncall') bad.push(id + ': not On-call (M4)'); + } fail('C1', bad, 'give it n, d, goal, ok(), days, a city and a SCN_PROG entry; its goal must need play'); assert.deepEqual(g.errors, []); }); diff --git a/tests/weekly-scenario.test.js b/tests/weekly-scenario.test.js new file mode 100644 index 0000000..22906f7 --- /dev/null +++ b/tests/weekly-scenario.test.js @@ -0,0 +1,208 @@ +// The published weekly scenario: the generator (scripts/weekly-scenario.js) and its reference player, --check, and the +// game's side: fetched only when the Scenarios list opens, validated strictly, the in-browser weekly as the fallback, +// a goal type and progress card for each kind of week, the win, the streak and the share line. +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-scenario'); + +const DIR = path.join(__dirname, '..', 'site', 'scenarios', 'weekly'); +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-wkscn-')); +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)); +const serveFile = (ev, j) => ev(`UI.wsWk=null;window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(j)})})`); +// One file per goal type, from the committed ones where a week has it: enough to check every card. +const GOALS = { + served: { theme: 'budget', goal: { t: 'served', p: { g: 200 } }, desc: { l: 'wkscn.desc_city_on_a_shoestring', p: { city: 'fra' } } }, + reach: { theme: 'spat', rules: { spat: true }, goal: { t: 'reach', p: { r: 99, g: 150 } }, desc: { l: 'wkscn.desc_two_giants_de_peered_over', p: { city: 'fra' } } }, + path: { theme: 'cable', rules: { banPairs: ['grace:nyc-lon'] }, goal: { t: 'path', p: { a: 'fra', b: 'nyc', g: 400, n: 30 } }, desc: { l: 'wkscn.desc_cab_is_cut_for_the', p: { cab: 'grace', a: 'fra', b: 'nyc' } } }, + ix: { theme: 'region', goal: { t: 'ix', p: { reg: 'EU', n: 8 } }, desc: { l: 'wkscn.desc_every_exchange_in_reg_wants', p: { reg: 'EU', city: 'fra' } } }, + pops: { theme: 'island', goal: { t: 'pops', p: { cs: ['ams', 'par'] } }, desc: { l: 'wkscn.desc_city_is_surrounded_by_water', p: { city: 'fra' } } }, + event: { theme: 'event', goal: { t: 'event', p: { city: 'fra', g: 400, day: 120, dur: 3 } }, desc: { l: 'wkscn.desc_a_g_event_comes_to', p: { g: 400, city: 'fra', day: 120 } } }, + floods: { theme: 'flood', rules: { ddos: true }, goal: { t: 'floods', p: { n: 20, big: 2 } }, desc: { l: 'wkscn.desc_booters_picked_city_for_their', p: { city: 'fra' } } }, + lat: { theme: 'latency', goal: { t: 'lat', p: { a: 'fra', b: 'nyc', ms: 40, n: 30 } }, desc: { l: 'wkscn.desc_a_trading_firm_needs_a', p: { a: 'fra', b: 'nyc', ms: 40 } } }, +}; +const NAME = { budget: 'wkscn.name_shoestring_backbone', spat: 'wkscn.name_peering_pressure', cable: 'wkscn.name_cut_and_run', region: 'wkscn.name_planting_flags', island: 'wkscn.name_island_hopper', event: 'wkscn.name_stream_team', flood: 'wkscn.name_flood_week', latency: 'wkscn.name_ludicrous_speed' }; +const fileFor = (t, key) => { const x = GOALS[t]; return { v: 1, key, theme: x.theme, city: 'fra', cash: 500000, days: 240, lvl: 2, rules: x.rules || {}, mods: [], goal: x.goal, name: { l: NAME[x.theme], p: {} }, desc: x.desc, seed: 42, par: 180, ref: { steps: [] } }; }; + +test('generator: deterministic for a week, and every theme a template the game knows', () => { + const g = G.game(), a = tmp(), b = tmp(); + const j1 = G.generate(g, '2027-W10', a), j2 = G.generate(G.game(), '2027-W10', b); + assert.deepEqual(j1, j2, 'same key, same scenario'); + const themes = JSON.parse(g.ev('JSON.stringify(Object.keys(WS_THEMES))')).sort(), goals = JSON.parse(g.ev('JSON.stringify(Object.keys(WS_GOALS))')); + assert.deepEqual(Object.keys(G.TEMPLATES).sort(), themes, 'a template for each theme'); + for (const T of Object.values(G.TEMPLATES)) assert.ok(goals.includes(T.goal), `${T.goal} is a goal type of the game`); + assert.deepEqual(g.errors, []); +}); + +test('every committed week verifies: not won on day 0, the reference wins on its par with time to spare', () => { + const g = G.game(), files = committed(); + assert.ok(files.length >= 3, 'this week and the next two are committed'); + for (const j of files) { + const v = G.verify(g, j); + assert.ok(v.ok, `${j.key}: ${v.why}`); + assert.equal(v.par, j.par, `${j.key}: par`); + assert.ok(j.days >= 180 && j.days <= 365, `${j.key}: ${j.days} days, playable in a sitting or two`); + } + // Varied: no theme twice in a row, and the weeks start in different parts of the world. + for (let i = 1; i < files.length; i++) assert.notEqual(files[i].theme, files[i - 1].theme); + assert.equal(new Set(files.map((f) => g.ev(`CITY['${f.city}'].reg`))).size, files.length); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(DIR, 'index.json'), 'utf8')), { v: 1, weeks: G.list(DIR) }); + assert.deepEqual(g.errors, []); +}); + +test('the file is checked field by field, and --check rejects a tampered one', () => { + const { ev, errors } = load(), j = committed()[0], ok = (x, key = j.key) => ev(`!!wsValid(${JSON.stringify(x)},'${key}')`); + assert.equal(ok(j), true); + const bad = { + 'another week': [j, '2020-W01'], 'not a week': [{ ...j, key: '2026-W99' }, '2026-W99'], + 'unknown field': [{ ...j, x: 1 }], 'old schema': [{ ...j, v: 0 }], 'unknown theme': [{ ...j, theme: 'pirates' }], + 'unknown city': [{ ...j, city: 'nope' }], 'days': [{ ...j, days: 5000 }], 'cash': [{ ...j, cash: -1 }], 'par after the end': [{ ...j, par: j.days + 1 }], + 'seed': [{ ...j, seed: 1.5 }], 'unknown rule': [{ ...j, rules: { noTransit: true } }], 'rule value': [{ ...j, rules: { spat: 'yes' } }], + 'bogus cable pair': [{ ...j, rules: { banPairs: ['nope:a-b'] } }], 'home banned': [{ ...j, rules: { banCities: [j.city] } }], + 'unknown mod': [{ ...j, mods: ['godmode'] }], 'too many mods': [{ ...j, mods: ['pricey', 'chaos', 'poor'] }], + 'unknown goal type': [{ ...j, goal: { t: 'win', p: {} } }], 'goal number': [{ ...j, goal: { t: 'served', p: { g: 1e9 } } }], + 'goal missing a parameter': [{ ...j, goal: { t: 'path', p: { a: 'fra', b: 'nyc', g: 100 } } }], + 'goal extra parameter': [{ ...j, goal: { t: 'served', p: { g: 100, x: 1 } } }], 'goal city': [{ ...j, goal: { t: 'lat', p: { a: 'fra', b: 'fra', ms: 10, n: 5 } } }], + 'floods without the flood rule': [{ ...j, rules: {}, goal: { t: 'floods', p: { n: 5, big: 0 } } }], + 'event after the end': [{ ...j, goal: { t: 'event', p: { city: j.city, g: 100, day: 360, dur: 5 } }, days: 300 }], + 'name from another theme': [{ ...j, name: { l: 'puzzles_weekly.detour', p: {} } }], 'text with code': [{ ...j, desc: { l: j.desc.l, p: { ...j.desc.p, x: '' } } }], + 'label placeholder': [{ ...j, desc: { l: j.desc.l, p: Object.fromEntries(Object.keys(j.desc.p).map((k) => [k, 'nope'])) } }], + }; + for (const [why, [x, key]] of Object.entries(bad)) assert.equal(ok(x, key || x.key), false, why); + const dir = tmp(); + for (const f of committed()) fs.writeFileSync(path.join(dir, f.key + '.json'), JSON.stringify(f) + '\n'); + fs.copyFileSync(path.join(DIR, 'index.json'), path.join(dir, 'index.json')); + fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, goal: { t: 'win', p: {} } })); + const g = G.game(); + assert.deepEqual(G.check(g, dir, 0).filter((x) => x.startsWith(j.key)), [`${j.key}: the game rejects it`]); + assert.deepEqual(errors, []); +}); + +test('--check: a week the reference no longer wins is regenerated as a new revision, a new par is just written', () => { + const g = G.game(), dir = tmp(), j = committed()[0]; + fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, par: j.par + 1 }) + '\n'); + const now = g.ev(`pzWeekStart('${j.key}')`); + let r = G.refresh(g, dir, now); + assert.ok(r.fixed.includes(`${j.key}: new par ${j.par}`), r.fixed.join('; ')); + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8')).rev, undefined, 'a new par keeps the revision'); + // A goal its reference plan never reaches: as if a release changed the world under the week. + fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify({ ...j, goal: { t: 'pops', p: { cs: ['scl'] } }, ref: { ...j.ref, steps: [] } }) + '\n'); + r = G.refresh(g, dir, now); + const n = JSON.parse(fs.readFileSync(path.join(dir, j.key + '.json'), 'utf8')); + assert.equal(n.rev, 2, r.fixed.join('; ') + r.bad.join('; ')); + assert.ok(G.verify(g, n).ok); + // Past weeks keep their files. + assert.deepEqual(G.refresh(g, dir, now + 30 * 864e5).fixed, []); + assert.deepEqual(G.check(g, dir, now), []); + assert.deepEqual(g.errors, []); +}); + +test('the page never asks for a weekly scenario on load, only when the Scenarios list 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=>/scenarios/.test(u)).length"), 0, 'nothing on the title screen'); + ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()"); + assert.equal(ev("__f.filter(u=>/scenarios/.test(u)).length"), 0, 'nothing while playing'); + ev('ACT.scenarios({})'); + const key = ev('pzWeekKey(new Date())'); + assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/scenarios/.test(u)))"), JSON.stringify([`scenarios/weekly/${key}.json`])); + ev('closeModal();ACT.scenarios({})'); + assert.equal(ev("__f.filter(u=>/scenarios/.test(u)).length"), 1, 'once is enough while it is loading'); + await tick(); + assert.deepEqual(errors, []); +}); + +test('the published scenario is played when it is good, the in-browser weekly when it is missing, offline or bad', async () => { + const { ev, dom, errors } = load(), key = ev('pzWeekKey(new Date())'), good = { ...committed()[1], key }; + 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, city: 'nope' })})})`, 'an unknown city'], + [`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'], + ]) { + ev(`UI.wsWk=null;window.fetch=()=>${how}`); ev('ACT.scenarios({})'); await tick(); + assert.equal(ev('wsDef()'), null, why); + assert.match(dom.window.document.getElementById('wsRow').textContent, new RegExp(ev(`tr('features.weekly_challenge_key',{key:'${key}'})`)), why); + ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev("S.scn.id==='weekly'&&!S.scn.wk&&S.scn.key"), key, `${why}: the in-browser weekly`); + } + serveFile(ev, good); ev('ACT.scenarios({})'); await tick(); + assert.match(dom.window.document.getElementById('wsRow').textContent, new RegExp(ev('wsTxt(wsDef().name)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))); + ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('S.scn.wk.key'), key); + assert.equal(ev('S.rules.preset'), 'oncall', 'M4: On-call'); + assert.equal(ev('S.cash'), good.mods.includes('poor') ? 100000 : good.cash); + assert.deepEqual(errors, []); +}); + +test('every goal type has a progress card, needs play, and wins, streaks and shares', () => { + const { ev, dom, errors } = load(), key = ev('pzWeekKey(new Date())'); + for (const t of Object.keys(GOALS)) { + const f = fileFor(t, key); + assert.equal(ev(`wsBegin(${JSON.stringify(f)},'T')`), true, t); + ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute();renderAll()'); + assert.equal(ev('wsOk()'), false, `${t}: not won on day 0`); + assert.ok(ev('scnProg().items.length') > 0, `${t}: a progress card`); + const card = ev('scnCard()'); + assert.doesNotMatch(card, /wkscn\.|\{\w+\}|undefined|NaN/, `${t}: ${card}`); + if (t === 'event') assert.equal(ev("S.biz.filter(b=>b.type==='event'&&b.start===120&&b.bw===400).length"), 1, 'the event is booked'); + if (t === 'floods') assert.equal(ev("scnRule('ddos')"), true); + } + // A win: a POP goal met on day 1, recorded for the week, with a streak and the share line. + ev("localStorage.removeItem('sot-wkscn')"); + ev(`wsBegin(${JSON.stringify(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`); + // Waves take a few days to light (real lead times), so the goal is met once they are up. + const build = "for(const c of ['ams','par']){UI.via=null;openLinkModal('fra',c);ACT.buildLink({tier:1});closeModal();}for(let i=0;i<90&&!S.scn.done;i++)dayTick()"; + ev(build); + const d = ev('S.scn.done'); + assert.ok(d > 0 && d < 90, `won on day ${d}`); + assert.match(dom.window.document.getElementById('modal').textContent, new RegExp(`Won on day ${d}!`)); + assert.equal(ev('wsShareText()'), `Series of Tubes weekly ${key} “Island Hopper” won day ${d} (par 180) · seriesoftub.es`); + const rec = JSON.parse(ev("localStorage.getItem('sot-wkscn')")); + assert.deepEqual(rec.w[key], { d, rv: 1 }); + assert.equal(rec.streak.n, 1); + // Last week won too: the streak grows; a gap starts it again. + ev(`localStorage.setItem('sot-wkscn',JSON.stringify({go:{},w:{},streak:{last:pzPrevKey('${key}'),n:3,best:3}}))`); + ev(`wsBegin(${JSON.stringify(fileFor('pops', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal()`); + ev(build); + assert.equal(JSON.parse(ev("localStorage.getItem('sot-wkscn')")).streak.n, 4); + assert.equal(ev(`wsStreak(wsLoad(),pzKeyAdd('${key}',2))`), 0); + assert.deepEqual(errors, []); +}); + +test('saves keep the scenario, checked again on load; a tampered one plays on as the in-browser weekly', () => { + const { ev, errors } = load(), key = ev('pzWeekKey(new Date())'); + ev(`wsBegin(${JSON.stringify(fileFor('path', key))},'T');if(UI.pendGame)ACT.pitchSkip();closeModal();S.scn.run=7`); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev("S.scn.wk.goal.t+':'+S.scn.run+':'+S.scn.home"), 'path:7:fra'); + ev("S.scn.wk.goal={t:'win',p:{}};S.scn.run='x';S=migrate(JSON.parse(JSON.stringify(S)));compute();renderAll()"); + assert.equal(ev("S.scn.id+':'+(S.scn.wk===undefined)+':'+(S.scn.run===undefined)"), 'weekly:true:true'); + ev('for(let i=0;i<3;i++)dayTick();scnCard()'); + assert.deepEqual(errors, []); +}); + +test('weekly scenario in every language and on a 360 px phone, with the door badge until started', async () => { + for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { + const { ev, dom, errors } = load({ lang }), key = ev('pzWeekKey(new Date())'), doc = dom.window.document; + ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()"); + const badge = () => !!doc.querySelector('.door[data-door=scn] .pznew'); + assert.equal(badge(), true, `${lang}: badge before the week is started`); + for (const j of committed()) { + serveFile(ev, { ...j, key }); ev('ACT.scenarios({})'); await tick(); + const row = doc.getElementById('wsRow'); + assert.doesNotMatch(row.textContent, /wkscn\.|\{\w+\}|undefined|NaN/, `${lang} ${j.key}: no raw labels or placeholders`); + assert.notEqual(ev('wsTxt(wsDef().desc)'), ev("(d=>EN[d.l].replace(/\\{(\\w+)\\}/g,(m,k)=>wsVal(k,d.p[k])))(wsDef().desc)"), `${lang}: translated text`); + ev("document.querySelector('#wsRow [data-act=startWeekly]').click();if(UI.pendGame)ACT.pitchSkip();closeModal();renderAll()"); + assert.doesNotMatch(ev('scnCard()'), /wkscn\.|\{\w+\}|undefined|NaN/, `${lang} ${j.key}: card`); + } + ev('showTitle()'); + assert.equal(badge(), false, `${lang}: no badge once started`); + assert.deepEqual(errors, [], lang); + } +}); From be63e3df67bafcc90a4fc06817c31983b62c0318 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 18:01:27 +0100 Subject: [PATCH 114/181] Title: a hidden label for the language picker; the How the Internet Works card is checked in How to play --- src/game/95-modals/40-title.js | 2 +- tests/i18n.test.js | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index e1b7c1f..49bd5ea 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -12,7 +12,7 @@ const homeWhat=()=>START5.includes(UI.startCity)?esc(START_D()[UI.startCity]):`$ function showTitle(){ const list=slotIdx(true),top=slotTop(list),many=list.length>1||(list.length===1&&list[0]!==top); if(UI.nm==null)UI.nm=randomNetworkName(); - openModal(`
${langPick('langTitle')}
+ openModal(`
${langPick('langTitle')}

Series
of Tubes

${tr('title.build_an_internet_lay_fiber_between')}

${isPhone()?installRow():''} ${top?`
${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}
`:''} diff --git a/tests/i18n.test.js b/tests/i18n.test.js index 8c5480c..08b4f74 100644 --- a/tests/i18n.test.js +++ b/tests/i18n.test.js @@ -155,8 +155,9 @@ for (const lang of ['en', 'it', 'pt', 'fr', 'es', 'de']) { } if (lang === 'de') { assert.match(ev("document.getElementById('modalCard').textContent"), /Spielanleitung/); - // the link card to the real "How the Internet Works" site used to be hard-coded English - assert.match(ev("document.getElementById('modalCard').textContent"), /Wie funktioniert das Internet\?/); + // the link card to the real "How the Internet Works" site used to be hard-coded English; it lives in How to play + assert.match(ev("(()=>{showHelp&&showHelp();return document.getElementById('modalCard').textContent})()"), /Wie funktioniert das Internet\?/); + ev("showTitle()"); assert.equal(ev("document.querySelector('#hud [data-act=bank] .lbl').textContent"), 'Kasse · Bank'); // networking jargon stays English in German (Peering, Dark Fiber); plain "fiber" is Glasfaser assert.equal(ev("tr('common.peering')"), 'Peering'); From a98a0f7154c34ee1c4cb40135bc88155928aea0a Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 18:56:44 +0100 Subject: [PATCH 115/181] WIP: own AS number on the title --- src/game/60-features/20-scenarios.js | 2 +- src/game/90-actions/89-game-and-settings.js | 2 +- src/game/95-modals/40-title.js | 9 +++++++-- src/styles/40-modal.css | 4 +++- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index a11ca57..82738b6 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -30,7 +30,7 @@ const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chao function weekly(){const [y,w]=pzWeekKey(new Date()).split('-W').map(Number);let r=(y*100+w)*2654435761>>>0;const nx=()=>{r=(r*1103515245+12345)>>>0;return r/4294967296;};const city=WEEK_CITIES[Math.floor(nx()*WEEK_CITIES.length)];const mods=[];while(mods.length<2){const m=WEEK_MODS[Math.floor(nx()*WEEK_MODS.length)];if(!mods.includes(m))mods.push(m);}return {id:'weekly',key:`${y}-W${String(w).padStart(2,'0')}`,seed:y*100+w,city,mods,days:365};} const scnRule=k=>!!(S&&S.scn&&S.scn.rules&&S.scn.rules[k]); function scnHof(){try{return JSON.parse(localStorage.getItem('sot-scn')||'{}')||{};}catch(e){return {};}} -function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);S.mode=o.mode||'normal'; +function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,city,o];openModal(pitchHtml(true));return;}if(pzOn())pzLeave();slotLeave();slotNew();newGame(nm,city);{const a=+(UI.asnTxt||UI.asnSug||0);if(asnOk(a))S.asn=a;UI.asnSug=null;}S.mode=o.mode||'normal'; // The rules are picked here and locked for the life of the network. Scenarios run on On-call plus their own rules. {const pr=o.scn?'oncall':S.mode==='sandbox'?'sandbox':S.mode==='puzzle'?'puzzle':own(PRESETS,o.preset)&&o.preset!=='sandbox'&&o.preset!=='puzzle'?o.preset:'oncall';S.rules=makeRules(pr,o.scn?{}:o.rules);} if(S.mode==='sandbox'){S.cash=1e9;S.lvl=LEVELS.length;if(!chaosMul()){S.nextFail=1e9;S.nextEvent=1e9;}} diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index eb5983f..bbd6d2c 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -1,6 +1,6 @@ Object.assign(ACT,{ randomName:()=>{const input=$('nmIn');if(input)input.value=UI.nm=randomNetworkName(input.value);}, - start:()=>{const nm=(($('nmIn')&&$('nmIn').value)||randomNetworkName()).slice(0,24),sb=UI.mode==='sandbox'; + start:()=>{if(UI.asnTxt&&!asnOk(+UI.asnTxt)){toast(tr('title.asn_not_usable'),'bad');const i=$('asnIn');if(i){i.classList.add('bad');i.focus();}return;}const nm=(($('nmIn')&&$('nmIn').value)||randomNetworkName()).slice(0,24),sb=UI.mode==='sandbox'; beginGame(nm,homeOk(UI.startCity)?UI.startCity:'fra',sb?{mode:'sandbox',rules:{chaos:own(CHAOS,UI.sbChaos)?UI.sbChaos:'none'}}:{mode:'normal',preset:NORMAL_PRESETS.includes(UI.preset)?UI.preset:'oncall'});}, // Title-screen doors and their options toggle in place, so the name being typed and the city stay as they are. modeSet:({m})=>{if(m!=='sandbox'&&m!=='normal')return;UI.mode=m;document.querySelectorAll('.door').forEach(b=>b.classList.toggle('on',b.dataset.door===m));const n=$('doorNormal'),x=$('doorSandbox');if(n)n.hidden=m!=='normal';if(x)x.hidden=m!=='sandbox';}, diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index 49bd5ea..e285888 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -9,19 +9,24 @@ function homePick(){const cs=Object.keys(CITY).filter(c=>homeOk(c)&&!START5.incl return g.length?`${g.map(opt).join('')}`:'';}).join('')}`;} // The line under the drawer: what the suggested home is like, or which continent another city is on. const homeWhat=()=>START5.includes(UI.startCity)?esc(START_D()[UI.startCity]):`${esc(CITY[UI.startCity].name)} · ${esc(REG[CITY[UI.startCity].reg])}`; +/* Your own AS number (#135): any public 16- or 32-bit ASN, but not AS 0, AS_TRANS, the documentation and private ranges, or + one a network on the map already uses. Left empty, the game picks one from the private-looking 200000s as before. */ +const asnOk=a=>Number.isInteger(a)&&a>=1&&a<=4294967294&&a!==23456&&!(a>=64496&&a<=131071)&&!(a>=4200000000)&&!NETS.some(n=>n.asn===a); +const asnSuggest=()=>{for(;;){const a=200000+Math.floor(Math.random()*15000);if(asnOk(a))return a;}}; function showTitle(){ const list=slotIdx(true),top=slotTop(list),many=list.length>1||(list.length===1&&list[0]!==top); - if(UI.nm==null)UI.nm=randomNetworkName(); + if(UI.nm==null)UI.nm=randomNetworkName();if(UI.asnSug==null)UI.asnSug=asnSuggest(); openModal(`
${langPick('langTitle')}

Series
of Tubes

${tr('title.build_an_internet_lay_fiber_between')}

${isPhone()?installRow():''} ${top?`
${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}
`:''} ${many?slotsHtml():''} -
${btn(tr('common.another_one'),'randomName',{},'ghost sm')}
+
${doorsHtml()} ${homePick()}

${homeWhat()}

${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); $('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;}); + $('asnIn').addEventListener('input',e=>{UI.asnTxt=e.target.value.replace(/\D/g,'').slice(0,10);if(e.target.value!==UI.asnTxt)e.target.value=UI.asnTxt;e.target.classList.toggle('bad',!!UI.asnTxt&&!asnOk(+UI.asnTxt));}); } // "What's new": shown once to returning players after an update, or on demand. function whatsNew(returning,force){ diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 01c2101..2e27172 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -109,7 +109,9 @@ label.f+select.pick{width:100%} label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink2);margin:12px 0 5px} 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);color:var(--ink);-webkit-text-fill-color:var(--ink)} .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} +.network-name{flex-wrap:nowrap}.nmwrap{position:relative;flex:1 1 auto;min-width:0}.nmwrap input.t{width:100%;padding-right:44px;font-size:16px} +.reroll{position:absolute;right:6px;top:50%;transform:translateY(-50%);width:32px;height:32px;border-radius:50%;border:2px solid var(--ink);background:#22C47A;color:#fff;font:900 18px/1 var(--display);cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}.reroll:active{transform:translateY(-50%) rotate(-90deg)} +.asnwrap{display:flex;align-items:center;gap:4px;flex:0 0 auto;font:800 14px var(--display);color:var(--ink2)}.asnwrap input.t{width:112px;font-size:16px;padding:8px 8px}.asnwrap input.t.bad{border-color:#E03A3A;background:#FFE8E8} .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} From 8ccf84cf4a82c7b3c3f921ce14011de5961a7f58 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 18:59:07 +0100 Subject: [PATCH 116/181] Pick your own AS number next to the name; a round green arrow for another name (#135) --- 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/i18n/en.js | 2 ++ src/styles/40-modal.css | 2 +- tests/own-asn.test.js | 32 ++++++++++++++++++++++++++++++++ 9 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 tests/own-asn.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d2a230..4d9898a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,7 @@ All notable changes to this project are documented here. The project follows - When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. - The Networks list shows 100 networks at a time, with a button for the rest, so it opens quickly now that every country has its own networks. - A tidier start screen: language first, then your network's name, the doors, three compact difficulty buttons with the chosen one explained below, and one drop-down for your home city with the five suggested homes at the top. +- Pick your own AS number next to your network's name when you start (#135). Leave it empty and the game picks one, and the round green arrow in the name box suggests another name. ## [1.37.0] — 2026-10-28 diff --git a/site/i18n/de.js b/site/i18n/de.js index 82a1847..b0585cb 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3519,7 +3519,9 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · noch {n} Tage", "supply_chain.your_price_lock_covers_you_until":"Deine Preisgarantie gilt bis {date}.", "title.a_billion_dollars_and_every_toy":"Eine Milliarde Dollar und jedes Spielzeug im Laden.", +"title.as_number":"AS-Nummer", "title.asia_hub_great_peering_far_from":"Asien-Drehkreuz. Tolles Peering, weit weg von zu Hause.", +"title.asn_not_usable":"Diese AS-Nummer routet nicht: Wähle eine von 1 bis 4294967294, die kein Netz auf der Karte nutzt (kein AS 0, 23456, keine Dokumentations- oder privaten Bereiche). Leer lassen für eine zufällige.", "title.back_to_my_network":"Zurück zu meinem Netz", "title.big_hungry_market_few_providers":"Großer, hungriger Markt, wenige Anbieter.", "title.build_an_internet_lay_fiber_between":"Baue deinen eigenen ISP auf. Verlege Glasfaser zwischen Städten, kauf Transit, peere an Exchanges, gewinne Geschäftskunden und halte deine Privatkunden bei Laune, während Bagger, Haie und Route Leaks alles tun, um dich aufzuhalten.", diff --git a/site/i18n/es.js b/site/i18n/es.js index f9f661a..d81f013 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3517,7 +3517,9 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · quedan {n} días", "supply_chain.your_price_lock_covers_you_until":"Tu precio fijo te cubre hasta {date}.", "title.a_billion_dollars_and_every_toy":"Mil millones de dólares y todos los juguetes de la tienda.", +"title.as_number":"Número de AS", "title.asia_hub_great_peering_far_from":"Hub de Asia. Gran peering, lejos de casa.", +"title.asn_not_usable":"Ese número de AS no enruta: elige uno de 1 a 4294967294 que no use ninguna red del mapa (ni AS 0, ni 23456, ni rangos de documentación o privados). Déjalo vacío para uno al azar.", "title.back_to_my_network":"Volver a mi red", "title.big_hungry_market_few_providers":"Mercado enorme y hambriento, pocos proveedores.", "title.build_an_internet_lay_fiber_between":"Construye un internet. Tiende fibra entre ciudades, compra tránsito, haz peering en intercambios, firma con empresas y mantén contentos a los eyeballs mientras retroexcavadoras, tiburones y fugas de rutas hacen lo posible por detenerte.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f4056b9..d8e7f47 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3517,7 +3517,9 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · encore {n} jours", "supply_chain.your_price_lock_covers_you_until":"Votre blocage des prix vous couvre jusqu’au {date}.", "title.a_billion_dollars_and_every_toy":"Un milliard de dollars et tous les jouets du magasin.", +"title.as_number":"Numéro d'AS", "title.asia_hub_great_peering_far_from":"Hub de l’Asie. Super peering, loin de chez soi.", +"title.asn_not_usable":"Ce numéro d'AS ne route pas : choisis-en un de 1 à 4294967294 qu'aucun réseau de la carte n'utilise (pas d'AS 0, 23456, ni de plages de documentation ou privées). Laisse vide pour un numéro au hasard.", "title.back_to_my_network":"Retour à mon réseau", "title.big_hungry_market_few_providers":"Gros marché affamé, peu d’opérateurs.", "title.build_an_internet_lay_fiber_between":"Construis un Internet. Pose de la fibre entre les villes, achète du transit, fais du peering aux IX, signe des entreprises et garde les eyeballs contents pendant que pelleteuses, requins et fuites de routes font tout pour t’arrêter.", diff --git a/site/i18n/it.js b/site/i18n/it.js index fe99435..58c52b8 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3517,7 +3517,9 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · {n} giorni rimasti", "supply_chain.your_price_lock_covers_you_until":"Il tuo blocco dei prezzi ti copre fino al {date}.", "title.a_billion_dollars_and_every_toy":"Un miliardo di dollari e tutti i giocattoli del negozio.", +"title.as_number":"Numero di AS", "title.asia_hub_great_peering_far_from":"Hub dell’Asia. Ottimo peering, lontano da casa.", +"title.asn_not_usable":"Quel numero di AS non instrada: scegline uno da 1 a 4294967294 che nessuna rete sulla mappa usa (niente AS 0, 23456, intervalli di documentazione o privati). Lascia vuoto per uno a caso.", "title.back_to_my_network":"Torna alla mia rete", "title.big_hungry_market_few_providers":"Mercato grande e affamato, pochi provider.", "title.build_an_internet_lay_fiber_between":"Costruisci un internet. Posa fibra tra le città, compra transit, fai peering agli exchange, metti sotto contratto le aziende e tieni contenti gli eyeball, mentre ruspe, squali e route leak fanno di tutto per fermarti.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 1eadf43..cd27409 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3517,7 +3517,9 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · faltam {n} dias", "supply_chain.your_price_lock_covers_you_until":"Seu congelamento de preços te cobre até {date}.", "title.a_billion_dollars_and_every_toy":"Um bilhão de dólares e todos os brinquedos da loja.", +"title.as_number":"Número de AS", "title.asia_hub_great_peering_far_from":"Hub da Ásia. Ótimo peering, longe de casa.", +"title.asn_not_usable":"Esse número de AS não roteia: escolha um de 1 a 4294967294 que nenhuma rede do mapa use (nada de AS 0, 23456, faixas de documentação ou privadas). Deixe vazio para um aleatório.", "title.back_to_my_network":"Voltar para minha rede", "title.big_hungry_market_few_providers":"Mercado grande e faminto, poucos provedores.", "title.build_an_internet_lay_fiber_between":"Construa uma internet. Lance fibra entre cidades, compre transit, faça peering nos exchanges, feche contratos com empresas e mantenha os eyeballs felizes enquanto retroescavadeiras, tubarões e route leaks fazem de tudo para te parar.", diff --git a/src/i18n/en.js b/src/i18n/en.js index cf18cc8..81093a4 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3518,7 +3518,9 @@ "supply_chain.what_p_n_days_left":"{what} +{p} · {n} days left", "supply_chain.your_price_lock_covers_you_until":"Your price lock covers you until {date}.", "title.a_billion_dollars_and_every_toy":"A billion dollars and every toy in the shop.", +"title.as_number":"AS number", "title.asia_hub_great_peering_far_from":"Asia hub. Great peering, far from home.", +"title.asn_not_usable":"That AS number won't route: pick one from 1 to 4294967294 that no network on the map uses (no AS 0, 23456, documentation or private ranges). Leave it empty for a random one.", "title.back_to_my_network":"Back to my network", "title.big_hungry_market_few_providers":"Big hungry market, few providers.", "title.build_an_internet_lay_fiber_between":"Build an internet. Lay fiber between cities, buy transit, peer at exchanges, sign up businesses, and keep the eyeballs happy while backhoes, sharks and route leaks do their best to stop you.", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 2e27172..4050efa 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -111,7 +111,7 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .network-name{display:flex;flex-wrap:wrap;align-items:center;gap:8px} .network-name{flex-wrap:nowrap}.nmwrap{position:relative;flex:1 1 auto;min-width:0}.nmwrap input.t{width:100%;padding-right:44px;font-size:16px} .reroll{position:absolute;right:6px;top:50%;transform:translateY(-50%);width:32px;height:32px;border-radius:50%;border:2px solid var(--ink);background:#22C47A;color:#fff;font:900 18px/1 var(--display);cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}.reroll:active{transform:translateY(-50%) rotate(-90deg)} -.asnwrap{display:flex;align-items:center;gap:4px;flex:0 0 auto;font:800 14px var(--display);color:var(--ink2)}.asnwrap input.t{width:112px;font-size:16px;padding:8px 8px}.asnwrap input.t.bad{border-color:#E03A3A;background:#FFE8E8} +.asnwrap{display:flex;align-items:center;gap:4px;flex:0 0 auto;font:800 14px var(--display);color:var(--ink2)}.asnwrap input.t{width:92px;font-size:15px;padding:8px 6px}.asnwrap input.t::placeholder{color:var(--ink2);opacity:.7}.asnwrap input.t.bad{border-color:#E03A3A;background:#FFE8E8} .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} diff --git a/tests/own-asn.test.js b/tests/own-asn.test.js new file mode 100644 index 0000000..c39ec0b --- /dev/null +++ b/tests/own-asn.test.js @@ -0,0 +1,32 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('pick your own AS number next to the name, or leave it empty for a random one (#135)', () => { + const { ev, errors } = load(); + assert.ok(ev("!!document.querySelector('.network-name .nmwrap #nmIn')&&!!document.querySelector('.nmwrap .reroll[data-act=randomName]')"), 'round reroll button inside the name box'); + const sug = ev("+document.getElementById('asnIn').placeholder"); + assert.ok(ev(`asnOk(${sug})`), 'the suggestion is usable'); + const set = v => ev(`(()=>{const i=document.getElementById('asnIn');i.value=${JSON.stringify(v)};i.dispatchEvent(new Event('input'));return i.value})()`); + assert.equal(set('AS 2-0-1-9-1-7'), '201917', 'only digits stay'); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('S.asn'), 201917); + assert.match(ev("document.getElementById('hAsn').textContent"), /AS201917/); + assert.deepEqual(errors, []); +}); + +test('an AS number that would not route is refused before the game starts', () => { + const { ev, errors } = load(); + for (const bad of ['0', '23456', '64512', '4200000001', String(ev('NETS[0].asn'))]) { + assert.equal(ev(`asnOk(${bad})`), false, bad); + } + ev("(()=>{const i=document.getElementById('asnIn');i.value='64512';i.dispatchEvent(new Event('input'))})()"); + assert.ok(ev("document.getElementById('asnIn').classList.contains('bad')")); + ev('ACT.start({})'); + assert.equal(ev('S'), null, 'no game'); + assert.match(ev("document.getElementById('toasts').textContent"), /won't route/); + ev("(()=>{const i=document.getElementById('asnIn');i.value='';i.dispatchEvent(new Event('input'))})()"); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + assert.ok(ev('asnOk(S.asn)&&S.asn>=200000'), 'empty: a random one'); + assert.deepEqual(errors, []); +}); From 2699634e0f417df5338cccca31f8969ac41ee474 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:07:44 +0100 Subject: [PATCH 117/181] PNI list: remember where each flow leaves, and price a PNI per POP from it (#175) --- src/game/70-rules/38-pni-value.js | 44 ++++++++++++++++++++++++++++ src/game/80-simulation/30-compute.js | 8 +++-- 2 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 src/game/70-rules/38-pni-value.js diff --git a/src/game/70-rules/38-pni-value.js b/src/game/70-rules/38-pni-value.js new file mode 100644 index 0000000..193e8bc --- /dev/null +++ b/src/game/70-rules/38-pni-value.js @@ -0,0 +1,44 @@ +/* ---------- Is a PNI worth it? (#175, #172) ---------- + How you reach each network today, and what a PNI at one POP would take over: the traffic your users there send + to that network over transit, an exchange or a PNI elsewhere, priced with the real billing functions. Information + only: nothing here changes routing or billing. Built once per routing result (R.fl), not per row. */ +const PNI_HOT=0.8; +let PNIX=null; +function pniIdx(){if(PNIX&&PNIX.R===R)return PNIX; + const ix={},pn={}; + for(const c in S.ixp){const nm=ixName(c);for(const id of ixSessions(c)){const a=ix[id]||(ix[id]=[]);if(!a.includes(nm))a.push(nm);}} + for(const p of S.pni)(pn[p.net]||(pn[p.net]=[])).push(p); + return PNIX={R,fl:{},ix,pn};} +// One POP's flows by network, added up the first time that POP is asked about. +function pniFlows(c){const X=pniIdx();let m=X.fl[c];if(m)return m;m=X.fl[c]={}; + for(const f of R.fl||[]){if(f.junk||f.c!==c)continue;let o=m[f.n];if(!o)o=m[f.n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}}; + o.u+=f.rem;o.t+=f.gt;o.ix+=f.gi;o.p+=f.gp;o.h+=f.gh;if(f.gt)o.T[f.ti]=(o.T[f.ti]||0)+f.gt;if(f.gi)o.I[f.ii]=(o.I[f.ii]||0)+f.gi;} + return m;} +// One status, most direct first. c: the POP you are looking at (null: anywhere). +function pniStat(id,c){const X=pniIdx(),ps=X.pn[id]||[],h=c?ps.find(p=>p.city===c):null; + if(h)return {k:'here',p:h}; + const el=[...new Set(ps.filter(p=>pniOn(p)).map(p=>p.city))];if(el.length)return {k:'else',cities:el}; + if(X.ix[id])return {k:'ix',ixs:X.ix[id]}; + if(R.cone[id])return {k:'cone',by:NET[R.cone[id]]||coneVia(id)}; + return {k:R.reachable[id]?'t':'none'};} +const pniList=a=>a.length>2?tr('pni_list.list_more',{list:a.slice(0,2).join(', '),n:a.length-2}):a.join(', '); +const PNI_ICON={here:'🔗',else:'🔗',ix:'🤝',cone:'🧺',t:'💸',none:'🚫'}; +function pniChip(id,c){const s=pniStat(id,c);let t; + if(s.k==='here'){const p=s.p;t=!pniOn(p)?tr('pni_list.chip_pni_here_on_order'):tr('pni_list.chip_pni_here',{port:((p.n||1)>1?p.n+'×':'')+pniPN(p),p:pct(Math.min(1,(R.usePni[p.id]||0)/lagCap(pniG(p),p.n)))});} + else if(s.k==='else'){const l=pniList(s.cities.map(x=>CITY[x].name));t=c?tr('pni_list.chip_pni_elsewhere',{list:l}):tr('pni_list.chip_pni_at',{list:l});} + else if(s.k==='ix')t=tr('pni_list.chip_peers_at',{list:pniList(s.ixs)}); + else if(s.k==='cone')t=s.by?tr('pni_list.chip_via_cone',{net:s.by.name}):tr('pni_list.chip_via_a_cone'); + else t=s.k==='t'?tr('pni_list.chip_via_transit'):tr('pni_list.chip_not_reached'); + return `${PNI_ICON[s.k]} ${esc(t)}`;} +/* What a new PNI with `id` at `c` would carry and save per month. It takes your users' traffic there that now + leaves over transit, an exchange or a PNI elsewhere, or does not leave at all for want of room, up to its port; transit is billed on the 95th percentile, + so the saving is the bill now minus the bill with that much less (commits included). */ +function pniVal(id,c){const o=pniFlows(c)[id]||{t:0,ix:0,p:0,h:0,u:0,T:{},I:{}},want=o.t+o.ix+o.p+o.u; + const lo=pniMin(id);let tier=-1;for(let i=lo;i=want)break;} + if(tier<0)tier=lo;const g=Math.min(want,PORT[tier].g),gt=Math.min(o.t,g);let saved=0; + if(gt>0)for(const tid in o.T){const t=S.transit.find(x=>x.id===tid);if(!t)continue;const q=R.p95[tid]??(R.useT[tid]||0),x=gt*o.T[tid]/o.t;saved+=transitMo(t,q)-transitMo(t,Math.max(0,q-x));} + const cost=pniMo({net:id,tier,n:1},g); + // Then what you drop today for want of room, then a hot exchange port's share. + const drop=Math.min(o.u,g-gt);let ixLeft=g-gt-drop,hot=0;for(const x in o.I){if(ixLeft<=0)break;const m=Math.min(ixLeft,o.I[x]);ixLeft-=m;const cp=S.ixp[x]!==undefined?ixCap(x):0;if(cp>0&&(R.useIx[x]||0)>=PNI_HOT*cp)hot+=m;} + const val=saved-cost,worth=g>=1&&(val>0||hot>=1||drop>=1); + return {...o,want,g,tier,saved,cost,val,hot,drop,worth};} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 175a393..ccfb0e2 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -51,7 +51,7 @@ function compute(){ 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],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;}; + 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,gt:0,gi:0,gp:0,gh:0,ti:null,ii:null};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). @@ -199,7 +199,9 @@ function compute(){ // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then // it gets worse, and past 50 ms broadband and internet services count as bad service (#…). if(path.length){let ms=P.ms;if(ms===undefined){ms=0;for(const l of path)ms+=l.lat;P.ms=ms;}const rtt=2*ms; - if(rtt>LAT_OK){LATP[f.ci]+=ok*latLoss(rtt);if(!P.fg){P.fg=0;FARL.push(P,f.ci,e.ci);}P.fg+=ok;}}}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok;} + if(rtt>LAT_OK){LATP[f.ci]+=ok*latLoss(rtt);if(!P.fg){P.fg=0;FARL.push(P,f.ci,e.ci);}P.fg+=ok;}}}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok; + // Where each flow left (the PNI list asks what a PNI here would take over, #175). + if(e.k==='t'){f.gt+=ok;f.ti=e.id;}else if(e.k==='ix'){f.gi+=ok;f.ii=e.id;}else if(e.k==='p'){if(e.net===f.n&&e.city===f.c)f.gh+=ok;else f.gp+=ok;}} return amt; }; // Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths @@ -294,5 +296,5 @@ function compute(){ C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix); R2.costMo=Object.values(C).reduce((a,b)=>a+b,0); R2.revMo=V.eyeballs+V.business+V.ix+V.grant; - R=R2;UI.hotMap=hotByCity(); + Object.defineProperty(R2,'fl',{value:flows});R=R2;UI.hotMap=hotByCity(); } From d48fdbf2e5f073cacaa1740de540dffe3459719e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:07:44 +0100 Subject: [PATCH 118/181] PNI list: status chips, value line, worth-it tag, filters and groups by type (#175, #172) --- site/i18n/de.js | 28 +++++++++++++++++++++ site/i18n/es.js | 28 +++++++++++++++++++++ site/i18n/fr.js | 28 +++++++++++++++++++++ site/i18n/it.js | 28 +++++++++++++++++++++ site/i18n/pt.js | 28 +++++++++++++++++++++ src/game/90-actions/45-pni-list.js | 6 +++++ src/game/90-actions/70-dashboard-lists.js | 2 +- src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/50-city-panel.js | 8 +----- src/game/93-ui/52-pni-list.js | 30 +++++++++++++++++++++++ src/game/95-modals/35-pni-all.js | 2 +- src/i18n/en.js | 28 +++++++++++++++++++++ src/styles/20-drawers.css | 9 +++++++ 13 files changed, 217 insertions(+), 10 deletions(-) create mode 100644 src/game/90-actions/45-pni-list.js create mode 100644 src/game/93-ui/52-pni-list.js diff --git a/site/i18n/de.js b/site/i18n/de.js index 82a1847..60f712d 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2843,6 +2843,34 @@ "pni_all.pni_size":"PNI-Größe", "pni_all.setup_total":"Einrichtung gesamt", "pni_all.traffic_charges_apply":"Dazu kommen Traffic-Gebühren von {price} pro Gbps.", +"pni_list.chip_not_reached":"Nicht erreichbar", +"pni_list.chip_peers_at":"Peering an {list}", +"pni_list.chip_pni_at":"PNI in {list}", +"pni_list.chip_pni_elsewhere":"PNI woanders: {list}", +"pni_list.chip_pni_here":"PNI hier · {port} · {p}", +"pni_list.chip_pni_here_on_order":"PNI hier · bestellt", +"pni_list.chip_via_a_cone":"Über den Cone eines Peers", +"pni_list.chip_via_cone":"Über den Cone von {net}", +"pni_list.chip_via_transit":"Über Transit", +"pni_list.f_all":"Alle", +"pni_list.f_pni":"Schon PNI", +"pni_list.f_transit":"Über Transit", +"pni_list.f_worth":"Lohnt sich", +"pni_list.list_more":"{list} +{n}", +"pni_list.little_to_gain_here":"Hier gibt's wenig zu holen: {g}", +"pni_list.n_here":"{g} hier", +"pni_list.n_networks_w_worth_it":{"one":"{n} Netz · {w} lohnt sich","other":"{n} Netze · {w} lohnen sich"}, +"pni_list.nothing_matches":"Kein Netz hier passt zu diesem Filter.", +"pni_list.saves_minus_cost":"Spart {saved} Transit im Monat; der PNI kostet {cost} im Monat.", +"pni_list.sort_az":"Sortierung: A–Z", +"pni_list.sort_worth":"Sortierung: lohnende zuerst", +"pni_list.via_drop":"{g} verworfen", +"pni_list.via_haul":"{g} über den Backbone", +"pni_list.via_ix":"{g} IX", +"pni_list.via_transit":"{g} Transit", +"pni_list.with_port":"{port}-PNI: {val}", +"pni_list.worth_it":"Lohnt sich", +"pni_list.worth_rule":"⭐ Lohnt sich: Ein PNI hier spart mehr Transit, als er im Monat kostet, trägt mindestens 1 Gbps, die du heute verwirfst, oder nimmt mindestens 1 Gbps von einem Exchange-Port, der zu 80 % voll ist.", "pnis.a_new_region_is_coming_online":"Eine neue Region geht bald online. Sie geht seit 2019 bald online.", "pnis.about_n_days_to_go_nothing":"Noch etwa {n} Tage. Nichts zu tun außer warten oder nachhaken.", "pnis.augment_with_net_delivered_in_city":"Erweiterung mit {net} in {city} geliefert.
Jetzt {port}.", diff --git a/site/i18n/es.js b/site/i18n/es.js index f9f661a..eaf4705 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2841,6 +2841,34 @@ "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.", +"pni_list.chip_not_reached":"Sin alcance", +"pni_list.chip_peers_at":"Peering en {list}", +"pni_list.chip_pni_at":"PNI en {list}", +"pni_list.chip_pni_elsewhere":"PNI en otro sitio: {list}", +"pni_list.chip_pni_here":"PNI aquí · {port} · {p}", +"pni_list.chip_pni_here_on_order":"PNI aquí · pedido", +"pni_list.chip_via_a_cone":"Por el cono de un peer", +"pni_list.chip_via_cone":"Por el cono de {net}", +"pni_list.chip_via_transit":"Por tránsito", +"pni_list.f_all":"Todas", +"pni_list.f_pni":"Ya con PNI", +"pni_list.f_transit":"Por tránsito", +"pni_list.f_worth":"Merece la pena", +"pni_list.list_more":"{list} +{n}", +"pni_list.little_to_gain_here":"Poco que ganar aquí: {g}", +"pni_list.n_here":"{g} aquí", +"pni_list.n_networks_w_worth_it":{"one":"{n} red · {w} merecen la pena","other":"{n} redes · {w} merecen la pena"}, +"pni_list.nothing_matches":"Ninguna red de aquí coincide con este filtro.", +"pni_list.saves_minus_cost":"Ahorra {saved} de tránsito al mes; el PNI cuesta {cost} al mes.", +"pni_list.sort_az":"Orden: A–Z", +"pni_list.sort_worth":"Orden: las que merecen la pena primero", +"pni_list.via_drop":"{g} descartados", +"pni_list.via_haul":"{g} por el backbone", +"pni_list.via_ix":"{g} IX", +"pni_list.via_transit":"{g} tránsito", +"pni_list.with_port":"PNI de {port}: {val}", +"pni_list.worth_it":"Merece la pena", +"pni_list.worth_rule":"⭐ Merece la pena: un PNI aquí ahorra más tránsito del que cuesta al mes, lleva al menos 1 Gbps que hoy descartas, o quita al menos 1 Gbps de un puerto de exchange lleno al 80 %.", "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 f4056b9..351224b 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2841,6 +2841,34 @@ "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.", +"pni_list.chip_not_reached":"Non joignable", +"pni_list.chip_peers_at":"Peering à {list}", +"pni_list.chip_pni_at":"PNI à {list}", +"pni_list.chip_pni_elsewhere":"PNI ailleurs : {list}", +"pni_list.chip_pni_here":"PNI ici · {port} · {p}", +"pni_list.chip_pni_here_on_order":"PNI ici · en commande", +"pni_list.chip_via_a_cone":"Via le cône d'un peer", +"pni_list.chip_via_cone":"Via le cône de {net}", +"pni_list.chip_via_transit":"Via le transit", +"pni_list.f_all":"Tous", +"pni_list.f_pni":"Déjà en PNI", +"pni_list.f_transit":"Via le transit", +"pni_list.f_worth":"Rentable", +"pni_list.list_more":"{list} +{n}", +"pni_list.little_to_gain_here":"Peu à gagner ici : {g}", +"pni_list.n_here":"{g} ici", +"pni_list.n_networks_w_worth_it":{"one":"{n} réseau · {w} rentable(s)","other":"{n} réseaux · {w} rentable(s)"}, +"pni_list.nothing_matches":"Aucun réseau ici ne correspond à ce filtre.", +"pni_list.saves_minus_cost":"Économise {saved} de transit par mois ; le PNI coûte {cost} par mois.", +"pni_list.sort_az":"Tri : A–Z", +"pni_list.sort_worth":"Tri : les rentables d'abord", +"pni_list.via_drop":"{g} perdus", +"pni_list.via_haul":"{g} par le backbone", +"pni_list.via_ix":"{g} IX", +"pni_list.via_transit":"{g} transit", +"pni_list.with_port":"PNI {port} : {val}", +"pni_list.worth_it":"Rentable", +"pni_list.worth_rule":"⭐ Rentable : un PNI ici économise plus de transit qu'il ne coûte par mois, transporte au moins 1 Gbps que tu perds aujourd'hui, ou retire au moins 1 Gbps d'un port d'exchange rempli à 80 %.", "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 fe99435..a71d3dd 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2841,6 +2841,34 @@ "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.", +"pni_list.chip_not_reached":"Non raggiunta", +"pni_list.chip_peers_at":"Peering a {list}", +"pni_list.chip_pni_at":"PNI a {list}", +"pni_list.chip_pni_elsewhere":"PNI altrove: {list}", +"pni_list.chip_pni_here":"PNI qui · {port} · {p}", +"pni_list.chip_pni_here_on_order":"PNI qui · ordinato", +"pni_list.chip_via_a_cone":"Tramite il cono di un peer", +"pni_list.chip_via_cone":"Tramite il cono di {net}", +"pni_list.chip_via_transit":"Tramite transit", +"pni_list.f_all":"Tutte", +"pni_list.f_pni":"Già in PNI", +"pni_list.f_transit":"Tramite transit", +"pni_list.f_worth":"Conviene", +"pni_list.list_more":"{list} +{n}", +"pni_list.little_to_gain_here":"Poco da guadagnare qui: {g}", +"pni_list.n_here":"{g} qui", +"pni_list.n_networks_w_worth_it":{"one":"{n} rete · {w} conviene","other":"{n} reti · {w} convengono"}, +"pni_list.nothing_matches":"Nessuna rete qui corrisponde a questo filtro.", +"pni_list.saves_minus_cost":"Risparmi {saved} di transit al mese; il PNI costa {cost} al mese.", +"pni_list.sort_az":"Ordine: A–Z", +"pni_list.sort_worth":"Ordine: prima quelle che convengono", +"pni_list.via_drop":"{g} persi", +"pni_list.via_haul":"{g} sul backbone", +"pni_list.via_ix":"{g} IX", +"pni_list.via_transit":"{g} transit", +"pni_list.with_port":"PNI da {port}: {val}", +"pni_list.worth_it":"Conviene", +"pni_list.worth_rule":"⭐ Conviene: un PNI qui ti fa risparmiare più transit di quanto costa al mese, porta almeno 1 Gbps che oggi perdi, oppure toglie almeno 1 Gbps da una porta di exchange piena all'80%.", "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 1eadf43..f3f7b21 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2841,6 +2841,34 @@ "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.", +"pni_list.chip_not_reached":"Sem alcance", +"pni_list.chip_peers_at":"Peering em {list}", +"pni_list.chip_pni_at":"PNI em {list}", +"pni_list.chip_pni_elsewhere":"PNI noutro sítio: {list}", +"pni_list.chip_pni_here":"PNI aqui · {port} · {p}", +"pni_list.chip_pni_here_on_order":"PNI aqui · encomendado", +"pni_list.chip_via_a_cone":"Pelo cone de um peer", +"pni_list.chip_via_cone":"Pelo cone de {net}", +"pni_list.chip_via_transit":"Por trânsito", +"pni_list.f_all":"Todas", +"pni_list.f_pni":"Já com PNI", +"pni_list.f_transit":"Por trânsito", +"pni_list.f_worth":"Compensa", +"pni_list.list_more":"{list} +{n}", +"pni_list.little_to_gain_here":"Pouco a ganhar aqui: {g}", +"pni_list.n_here":"{g} aqui", +"pni_list.n_networks_w_worth_it":{"one":"{n} rede · {w} compensam","other":"{n} redes · {w} compensam"}, +"pni_list.nothing_matches":"Nenhuma rede aqui corresponde a este filtro.", +"pni_list.saves_minus_cost":"Poupa {saved} de trânsito por mês; o PNI custa {cost} por mês.", +"pni_list.sort_az":"Ordem: A–Z", +"pni_list.sort_worth":"Ordem: as que compensam primeiro", +"pni_list.via_drop":"{g} perdidos", +"pni_list.via_haul":"{g} pelo backbone", +"pni_list.via_ix":"{g} IX", +"pni_list.via_transit":"{g} trânsito", +"pni_list.with_port":"PNI de {port}: {val}", +"pni_list.worth_it":"Compensa", +"pni_list.worth_rule":"⭐ Compensa: um PNI aqui poupa mais trânsito do que custa por mês, leva pelo menos 1 Gbps que hoje perdes, ou tira pelo menos 1 Gbps de uma porta de exchange cheia a 80%.", "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/90-actions/45-pni-list.js b/src/game/90-actions/45-pni-list.js new file mode 100644 index 0000000..93c3abb --- /dev/null +++ b/src/game/90-actions/45-pni-list.js @@ -0,0 +1,6 @@ +// The PNI list's filter, sort and folded groups (#175, #172): view state only, never saved. +Object.assign(ACT,{ + pniFilter:({f})=>{UI.pniF=['all','t','worth','pni'].includes(f)?f:'all';listReset('pni');renderPanel();}, + pniGrp:({g,o})=>{if(!PNI_GRP.includes(g))return;UI.pniOpen=UI.pniOpen||{};UI.pniOpen[g]=!!o;renderPanel();}, + pniSort:()=>{UI.pniSort=UI.pniSort==='az'?'worth':'az';renderPanel();}, +}); diff --git a/src/game/90-actions/70-dashboard-lists.js b/src/game/90-actions/70-dashboard-lists.js index 3bb414b..96ae70d 100644 --- a/src/game/90-actions/70-dashboard-lists.js +++ b/src/game/90-actions/70-dashboard-lists.js @@ -1,6 +1,6 @@ Object.assign(ACT,{ 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'&&k!=='nets')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;if(k==='nets'){renderLeft();return;}renderDash();}, + listMore:({k})=>{if(k!=='conn'&&k!=='cust'&&k!=='nets'&&k!=='pni')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;if(k==='nets'){renderLeft();return;}if(k==='pni'){renderPanel();return;}renderDash();}, custF:({v})=>{UI.kf=UI.kf||{};UI.kf.f=v==='sad'?'sad':'';listReset('cust');renderDash();}, custCity:({v})=>{UI.kf=UI.kf||{};UI.kf.city=isCity(v)?v:'';listReset('cust');renderDash();}, custSort:({k})=>{if(!['mood','mo','name','city'].includes(k))return;listReset('cust');if(UI.custSort===k)UI.custDir=-(UI.custDir||1);else{UI.custSort=k;UI.custDir=k==='mo'?-1:1;}renderDash();}, diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 8991ade..d9cfe64 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -82,7 +82,7 @@ function renderLeft(){checkLayer(); // Shown 100 at a time like the dashboard lists: every country's own eyeballs made this list long (2.0). const nl=(foc?[foc]:out?ntLost():NETS).filter(n=>!n.tail||UI.tailOpen||foc||out); for(const n of nl.slice(0,listN('nets'))){ - 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):''}
`;} + 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)})}`:''}
${pniChip(n.id,null)}
${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):''}
`;} h+=listMore('nets',nl.length,n=>trn('hud_and_panels.n_more_networks',n)); 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')}
`; } diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index b816232..a9e5de5 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -54,13 +54,7 @@ function cityPanel(c){ h+=portNote(c); h+=ixSection(c); h+=`

${tr('city_panel.private_interconnects_pni')}

${tr('city_panel.a_dedicated_cross_connect_to_one',{dc:esc(siteName(c,'a'))})}

`; - const here=NETS.filter(n=>n.pops.includes(c)); - for(const n of here){const pn=S.pni.find(x=>x.city===c&&x.net===n.id),chk=peerOk(n.id,'pni',c); - h+=`
${logo(n)}
${esc(n.name)} ${n.pol}
`; - if(pn&&!pniOn(pn))h+=pniWait(pn,c); - else if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(pniG(pn),pn.n);h+=`
${(pn.n||1)>1?`${pn.n}×${pniPN(pn)} LAG`:pniPN(pn)} PNI${fmtG(u)}
${pn.up?`
${tr('city_panel.augment_on_order_port_about_n',{port:(pn.up.n>1?pn.up.n+'×':'')+(pn.up.g1?'1G':PORT[pn.up.tier].n),n:Math.max(0,pn.up.ready-S.day)})} ${btn(tr('common.chase_it'),'pniChase',{id:pn.id},'ghost sm')}
`:''}
${prefCtl('p',pn.id,pn.pref)}${siteCtl('p',pn.id,c,pn.site)}
${PORT.map((P2,i)=>!pn.up&&!msfNope(n.id,c)&&(i>pn.tier||(pn.g1&&i===0))?btn((a=>(pn.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a))({port:P2.n,cost:fmt$((1500+P2.setup/2)*(pn.n||1)),mo:fmt$(P2.pni*(pn.n||1))}),'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)||S.cash<(1500+P2.setup/2)*(pn.n||1)):'').join('')}${(pn.n||1)1?btn(tr('common.member'),'lagP',{id:pn.id,d:-1},'ghost sm'):''}${NET[n.id].cn?btn(pn.sacrif?tr('common.sacrificial_choke'):tr('city_panel.make_sacrificial_contains_floods_1_2'),'sacrif',{id:pn.id},pn.sacrif?'green sm':'sm'):''}${btn(UI.confirm===pn.id?tr('common.really_remove'):tr('common.remove'),'cancelPni',{id:pn.id},'ghost sm')}
`;} - else{h+=chk.ok?`
${pniG1(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:'1G',cost:fmt$(PNI_G1_COST),mo:fmt$(Math.round(PORT[0].pni/2))}),'pni',{city:c,net:n.id,tier:-1},'sm',S.cashportShown(i)&&i>=pniMin(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(1500+P2.setup/2),mo:fmt$(P2.pni)}),'pni',{city:c,net:n.id,tier:i},'sm',S.cash<1500+P2.setup/2||!portOk(c,i)):'').join('')}
${pniEta(n.id)}${pniMin(n.id)?' · '+tr('city_panel.no_10g_net_starts_at_100g',{net:esc(n.name)}):pniG1(n.id)?' · '+tr('city_panel.sells_pnis_down_to_1g'):''}
${chk.fee?`
${tr('city_panel.paid_peering_price_mo_on_top',{price:fmt$(chk.fee)})}
`:''}`:`
${esc(chk.why)}
`;} - h+=`
`;} + h+=pniListHtml(c); h+=`

${tr('common.embedded_caches')}

${tr('city_panel.cdns_put_free_cache_servers_inside')}

`; for(const n of NETS.filter(n=>n.cache)){const have=S.caches.filter(x=>x.city===c&&x.net===n.id),dem=R.demTo[n.id]||0,ok=dem>=n.cache.min; h+=`
${logo(n)}
${esc(n.cache.name)}
${tr('common.from_net',{net:esc(n.name)})} · ${have.length?`${trn('common.n_box',have.length)} · ${tr('city_panel.serving_v',{v:fmtG(have.reduce((a,x)=>a+(R.useCache[x.id]||0),0))})}`:tr('city_panel.100g_per_box')}
${!ok?`
${tr('city_panel.needs_min_gbps_of_traffic_to',{min:n.cache.min,net:esc(n.name),now:dem.toFixed(1)})}
`:''}
diff --git a/src/game/93-ui/52-pni-list.js b/src/game/93-ui/52-pni-list.js new file mode 100644 index 0000000..b0af4d6 --- /dev/null +++ b/src/game/93-ui/52-pni-list.js @@ -0,0 +1,30 @@ +/* ---------- The PNI list of a POP (#175, #172) ---------- + Every network here answers three questions: how you reach it today (one chip), whether a PNI here is worth it + (a value line from live routing) and whether you can get one (the order buttons, policy and lead time). Sorted by + monthly value, filtered, grouped by type; groups with nothing to do (no PNI there, nothing you could order that moves 1 Gbps) stay folded. */ +const PNI_GRP=['t1','t2','eye','cdn','paid'],pniGrpOf=n=>n.pol==='paid'?'paid':n.type; +const pniGrpL=k=>k==='paid'?tr('ops.p_paid'):TYPE_L[k]; +function pniValLine(n,c,v){ + if(v.g<1)return `
${tr('pni_list.little_to_gain_here',{g:fmtG(v.want)})}
`; + const via=[v.t>=0.05?tr('pni_list.via_transit',{g:fmtG(v.t)}):'',v.ix>=0.05?tr('pni_list.via_ix',{g:fmtG(v.ix)}):'',v.p>=0.05?tr('pni_list.via_haul',{g:fmtG(v.p)}):'',v.u>=0.05?tr('pni_list.via_drop',{g:fmtG(v.u)}):''].filter(Boolean).join(' · '); + const val=(v.val>0?'+':'')+tr('common.price_mo',{price:fmt$(Math.round(v.val))}); + return `
${tr('pni_list.n_here',{g:fmtG(v.want)})}: ${via} → ${tr('pni_list.with_port',{port:PORT[v.tier].n,val})}
`;} +function pniRow(c,n,pn,v,chk){let h=`
${logo(n)}
${esc(n.name)} ${n.pol}${v&&v.worth?` ⭐ ${tr('pni_list.worth_it')}`:''}
${pniChip(n.id,c)}
${v?pniValLine(n,c,v):''}`; + if(pn&&!pniOn(pn))h+=pniWait(pn,c); + else if(pn){const u=R.usePni[pn.id]||0,cap=lagCap(pniG(pn),pn.n);h+=`
${(pn.n||1)>1?`${pn.n}×${pniPN(pn)} LAG`:pniPN(pn)} PNI${fmtG(u)}
${pn.up?`
${tr('city_panel.augment_on_order_port_about_n',{port:(pn.up.n>1?pn.up.n+'×':'')+(pn.up.g1?'1G':PORT[pn.up.tier].n),n:Math.max(0,pn.up.ready-S.day)})} ${btn(tr('common.chase_it'),'pniChase',{id:pn.id},'ghost sm')}
`:''}
${prefCtl('p',pn.id,pn.pref)}${siteCtl('p',pn.id,c,pn.site)}
${PORT.map((P2,i)=>!pn.up&&!msfNope(n.id,c)&&(i>pn.tier||(pn.g1&&i===0))?btn((a=>(pn.n||1)>1?tr('common.upgrade_all_to_port_cost_mo',a):tr('common.upgrade_port_cost_mo_mo',a))({port:P2.n,cost:fmt$((1500+P2.setup/2)*(pn.n||1)),mo:fmt$(P2.pni*(pn.n||1))}),'pni',{city:c,net:n.id,tier:i},'sm',!portOk(c,i)||S.cash<(1500+P2.setup/2)*(pn.n||1)):'').join('')}${(pn.n||1)1?btn(tr('common.member'),'lagP',{id:pn.id,d:-1},'ghost sm'):''}${NET[n.id].cn?btn(pn.sacrif?tr('common.sacrificial_choke'):tr('city_panel.make_sacrificial_contains_floods_1_2'),'sacrif',{id:pn.id},pn.sacrif?'green sm':'sm'):''}${btn(UI.confirm===pn.id?tr('common.really_remove'):tr('common.remove'),'cancelPni',{id:pn.id},'ghost sm')}
`;} + else{h+=chk.ok?`
${pniG1(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:'1G',cost:fmt$(PNI_G1_COST),mo:fmt$(Math.round(PORT[0].pni/2))}),'pni',{city:c,net:n.id,tier:-1},'sm',S.cashportShown(i)&&i>=pniMin(n.id)?btn(tr('city_panel.port_cost_mo_mo',{port:P2.n,cost:fmt$(1500+P2.setup/2),mo:fmt$(P2.pni)}),'pni',{city:c,net:n.id,tier:i},'sm',S.cash<1500+P2.setup/2||!portOk(c,i)):'').join('')}
${pniEta(n.id)}${pniMin(n.id)?' · '+tr('city_panel.no_10g_net_starts_at_100g',{net:esc(n.name)}):pniG1(n.id)?' · '+tr('city_panel.sells_pnis_down_to_1g'):''}
${chk.fee?`
${tr('city_panel.paid_peering_price_mo_on_top',{price:fmt$(chk.fee)})}
`:''}`:`
${esc(chk.why)}
`;} + return h+`
`;} +function pniListHtml(c){const f=UI.pniF||'all',az=UI.pniSort==='az',open=UI.pniOpen||{}; + const rows=NETS.filter(n=>n.pops.includes(c)).map(n=>{const pn=S.pni.find(x=>x.city===c&&x.net===n.id)||null;const chk=pn?null:peerOk(n.id,'pni',c),v=pn?null:pniVal(n.id,c);return {n,pn,v,chk,s:pniStat(n.id,c).k,go:!!pn||(chk.ok&&v.g>=1)};}); + const keep=r=>f==='all'||(f==='t'&&(r.s==='t'||r.s==='none'))||(f==='worth'&&r.v&&r.v.worth)||(f==='pni'&&(r.s==='here'||r.s==='else')); + const val=r=>r.v?r.v.val:-Infinity; + rows.sort((a,b)=>az?a.n.name.localeCompare(b.n.name):(b.v&&b.v.worth)-(a.v&&a.v.worth)||val(b)-val(a)||a.n.name.localeCompare(b.n.name)); + let h=`
${[['all',tr('pni_list.f_all')],['t',tr('pni_list.f_transit')],['worth',tr('pni_list.f_worth')],['pni',tr('pni_list.f_pni')]].map(([k,l])=>btn(l,'pniFilter',{f:k},f===k?'sm':'ghost sm')).join('')}${btn(az?tr('pni_list.sort_az'):tr('pni_list.sort_worth'),'pniSort',{},'ghost sm')}

${tr('pni_list.worth_rule')}

`; + const shown=rows.filter(keep);if(!shown.length)return h+`

${tr('pni_list.nothing_matches')}

`; + let left=listN('pni'),tot=0; + for(const g of PNI_GRP){const gr=shown.filter(r=>pniGrpOf(r.n)===g);if(!gr.length)continue; + const w=gr.filter(r=>r.v&&r.v.worth).length,act=w||gr.some(r=>r.go),isOpen=f!=='all'||(open[g]??act); + h+=`
${btn(`${isOpen?'▾':'▸'} ${esc(pniGrpL(g))} ${trn('pni_list.n_networks_w_worth_it',gr.length,{w})}`,'pniGrp',{g,o:isOpen?0:1},'ghost sm')}
`; + if(!isOpen)continue;tot+=gr.length; + for(const r of gr){if(left--<=0)break;h+=pniRow(c,r.n,r.pn,r.v,r.chk);}} + return h+listMore('pni',tot,n=>trn('hud_and_panels.n_more_networks',n));} diff --git a/src/game/95-modals/35-pni-all.js b/src/game/95-modals/35-pni-all.js index f9dfcfc..4fa8047 100644 --- a/src/game/95-modals/35-pni-all.js +++ b/src/game/95-modals/35-pni-all.js @@ -13,7 +13,7 @@ function pniAllModal(net,tier=1){const b=pniBatch(net,tier);if(!b)return;UI.pniA ${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)}

`:''} + ${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)}
${pniChip(id,null)}

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

`).join('')}
`:b.orders.length?`
${pniChip(net,null)}

${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')}

`:''} diff --git a/src/i18n/en.js b/src/i18n/en.js index cf18cc8..446cf1d 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2842,6 +2842,34 @@ "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.", +"pni_list.chip_not_reached":"Not reached", +"pni_list.chip_peers_at":"Peers at {list}", +"pni_list.chip_pni_at":"PNI at {list}", +"pni_list.chip_pni_elsewhere":"PNI elsewhere: {list}", +"pni_list.chip_pni_here":"PNI here · {port} · {p}", +"pni_list.chip_pni_here_on_order":"PNI here · on order", +"pni_list.chip_via_a_cone":"Via a peer's cone", +"pni_list.chip_via_cone":"Via {net}'s cone", +"pni_list.chip_via_transit":"Via transit", +"pni_list.f_all":"All", +"pni_list.f_pni":"Already PNI", +"pni_list.f_transit":"Via transit", +"pni_list.f_worth":"Worth it", +"pni_list.list_more":"{list} +{n}", +"pni_list.little_to_gain_here":"Little to gain here: {g}", +"pni_list.n_here":"{g} here", +"pni_list.n_networks_w_worth_it":{"one":"{n} network · {w} worth it","other":"{n} networks · {w} worth it"}, +"pni_list.nothing_matches":"No network here matches this filter.", +"pni_list.saves_minus_cost":"Saves {saved} of transit a month; the PNI costs {cost} a month.", +"pni_list.sort_az":"Sort: A–Z", +"pni_list.sort_worth":"Sort: worth it first", +"pni_list.via_drop":"{g} dropped", +"pni_list.via_haul":"{g} hauled", +"pni_list.via_ix":"{g} IX", +"pni_list.via_transit":"{g} transit", +"pni_list.with_port":"{port} PNI: {val}", +"pni_list.worth_it":"Worth it", +"pni_list.worth_rule":"⭐ Worth it: a PNI here saves more transit than it costs each month, carries at least 1 Gbps you drop today, or takes at least 1 Gbps off an exchange port that is 80% full.", "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/src/styles/20-drawers.css b/src/styles/20-drawers.css index cf5509c..bd9b547 100644 --- a/src/styles/20-drawers.css +++ b/src/styles/20-drawers.css @@ -51,6 +51,15 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .tag.t1{background:var(--t1)} .tag.t2{background:var(--t2)} .tag.cdn{background:var(--cdn)} .tag.eye{background:var(--eye)} .tag.open{background:var(--ok)} .tag.selective{background:var(--warn);color:var(--ink)} .tag.restrictive{background:var(--bad)} .tag.paid{background:var(--me)} .tag.st{background:var(--paper);color:var(--ink)} +/* PNI list (#175): one status chip per network, a one-line value, folded groups. Chips wrap on narrow screens. */ +.tag.worth{background:var(--warn);color:var(--ink)} +.pchips{display:flex;flex-wrap:wrap;gap:4px;margin:3px 0} +.pchip{display:inline-block;max-width:100%;border:1.5px solid var(--ink);border-radius:999px;padding:0 7px;font-size:11px;font-weight:800;line-height:1.5;background:var(--paper);color:var(--ink);overflow-wrap:anywhere} +.pchip.pk-here,.pchip.pk-else{background:var(--ok);color:#fff} +.pchip.pk-ix{background:var(--t2);color:#fff} +.pchip.pk-none{background:var(--bad);color:#fff} +.pval{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%} +.pgrp{margin:8px 0 2px}.pgrp .b{width:100%;text-align:left} .tag.st.on{background:var(--ink);color:#fff} .bar{height:11px;border:2px solid var(--ink);border-radius:7px;background:var(--paper);overflow:hidden;margin:3px 0} .stack{display:flex;height:16px;border:2px solid var(--ink);border-radius:8px;overflow:hidden;margin:4px 0 6px;background:var(--paper)} From 71f459c4e9b3e4b5fa124061dd64f8c91ee8839b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:07:44 +0100 Subject: [PATCH 119/181] PNI list: tests and changelog (#175, #172) --- CHANGELOG.md | 1 + tests/pni-list.test.js | 135 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 tests/pni-list.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d2a230..d2c6300 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,7 @@ All notable changes to this project are documented here. The project follows - When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. - The Networks list shows 100 networks at a time, with a button for the rest, so it opens quickly now that every country has its own networks. - A tidier start screen: language first, then your network's name, the doors, three compact difficulty buttons with the chosen one explained below, and one drop-down for your home city with the five suggested homes at the top. +- Every network in a POP's PNI list now shows how you reach it today and whether a PNI there is worth the cross-connect (#175, #172). A chip says PNI here (with size and load), PNI elsewhere, which exchanges you peer at, whose customer cone carries it, transit only or not reached; a value line shows how much of its traffic leaves from that POP over transit, exchanges or other PNIs, and what a PNI there would save or cost a month. The best candidates get a ⭐ Worth it tag, the list sorts them first, filters to All, Via transit, Worth it or Already PNI, and groups networks by type, with idle groups folded. The same chip shows in the Networks tab and in the bulk PNI preview. ## [1.37.0] — 2026-10-28 diff --git a/tests/pni-list.test.js b/tests/pni-list.test.js new file mode 100644 index 0000000..c479412 --- /dev/null +++ b/tests/pni-list.test.js @@ -0,0 +1,135 @@ +// The PNI list (#175, #172): how you reach each network, whether a PNI here is worth it, sorted, filtered and grouped. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Frankfurt with 100G of Cogentle transit and 50G of eyeballs: nothing dropped, everything over transit. +const fra = (ev, d = 50) => { + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + ev(`S.pops.fra.bb.d=${d};S.grace=null;ACT.buyTransit({city:'fra',net:'cog',tier:1});for(const t of S.transit)t.ready=0;compute()`); +}; +const chip = (ev, id, c = 'fra') => ev(`(()=>{const d=document.createElement('div');d.innerHTML=pniChip('${id}',${c ? `'${c}'` : 'null'});return d.textContent})()`); + +test('one status chip per network, most direct first', () => { + const { ev, errors } = load(); + fra(ev); + assert.equal(chip(ev, 'ggl'), '💸 Via transit'); + // PNI here, with its size and load + ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()"); + const load_ = ev("pct(R.usePni[S.pni[0].id]/100)"); + assert.equal(chip(ev, 'ggl'), `🔗 PNI here · 100G · ${load_}`); + // On order shows as such + ev("S.pni[0].ready=S.day+20;compute()"); + assert.equal(chip(ev, 'ggl'), '🔗 PNI here · on order'); + ev("S.pni[0].ready=0;compute()"); + // Elsewhere: the city names, and in the Networks tab (no POP) "PNI at" + ev("for(const c of ['ams','lon','par'])S.pni.push({id:'x'+c,net:'nfx',city:c,tier:1});compute()"); + assert.equal(chip(ev, 'nfx'), '🔗 PNI elsewhere: Amsterdam, London +1'); + assert.equal(chip(ev, 'ggl', null), '🔗 PNI at Frankfurt'); + // IX session + ev("ACT.buyIx({city:'fra',tier:1,signed:true});S.peers['akm@fra']=true;compute()"); + assert.equal(chip(ev, 'akm'), `🤝 Peers at ${ev("ixName('fra')")}`); + // Through a peer's customer cone: named after the peer that carries it (R.cone) + ev("S.pni.push({id:'pntt',net:'ntt',city:'fra',tier:1});compute()"); + assert.equal(ev("R.cone.voc"), 'ntt'); + assert.equal(chip(ev, 'voc'), `🧺 Via ${ev("NET.ntt.name")}'s cone`); + // Not reached once transit goes + ev("S.transit=[];compute()"); + assert.equal(ev("R.reachable.lvl"), false); + assert.equal(chip(ev, 'lvl'), '🚫 Not reached'); + assert.deepEqual(errors, []); +}); + +test('the value line matches the transit bill by hand, and the worth-it rule', () => { + const { ev, errors } = load(); + fra(ev); + const v = ev("pniVal('ggl','fra')"); + const t = ev("(()=>{const t=S.transit[0];return {q:R.p95[t.id],per:transitPerG(NET[t.net],t.city,premOn(t))*S.priceMul,floor:PORT[t.tier].g*0.2}})()"); + assert.ok(v.t > 1 && v.ix === 0 && v.p === 0 && v.u < 1e-6, 'all of it over transit'); + assert.ok(t.q - v.t > t.floor, 'above the commit, so each Gbps saved is the per-Gbps price'); + assert.ok(Math.abs(v.saved - v.t * t.per) < 1e-6, 'saved = Gbps × transit price'); + assert.equal(v.cost, ev("PORT[1].pni"), 'a 100G PNI with Goggle (no fee, no per-G)'); + assert.equal(v.tier, 1, 'the smallest port Goggle accepts'); + assert.equal(v.val, v.saved - v.cost); + assert.equal(v.worth, v.val > 0); + // Below the commit floor nothing is saved: a tiny network has little to gain. + const small = ev("pniVal('pst','fra')"); + assert.ok(small.g < 1 && !small.worth); + // A full transit port drops traffic: a PNI that carries it is worth it even if it saves no transit. + ev("S.pops.fra.bb.d=400;compute()"); + const big = ev("pniVal('nfx','fra')"); + assert.ok(big.u >= 1 && big.drop >= 1 && big.worth, 'dropped traffic makes it worth it'); + // Information only: routing is the same with or without the list reading it. + const before = ev("JSON.stringify(R.usePni)+R.served"); + ev("renderAll();UI.sel={type:'city',id:'fra'};UI.tab='peer';renderPanel();compute()"); + assert.equal(ev("JSON.stringify(R.usePni)+R.served"), before); + assert.deepEqual(errors, []); +}); + +test('the PNI list: worth it first, filters, groups by type folded when idle, phones', () => { + const { ev, errors, dom } = load(); + dom.window.innerWidth = 360; + fra(ev, 400); + ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()"); + const panel = () => { ev("UI.sel={type:'city',id:'fra'};UI.tab='peer';UI._ph=null;renderPanel()"); return dom.window.document.getElementById('panelBody'); }; + let p = panel(); + const heads = [...p.querySelectorAll('.pgrp')].map(x => x.textContent); + assert.ok(heads.length >= 4, 'grouped by type'); + assert.match(heads[0], /Tier 1/); + assert.ok(heads.some(h => /Paid peering/.test(h)), 'paid networks get their own group'); + // A group with nothing worth it and no PNI stays folded; one with a worth-it network is open, best first. + const rows = ev("(()=>{const r=NETS.filter(n=>n.pops.includes('fra')&&n.type==='cdn'&&n.pol!=='paid').map(n=>({id:n.id,v:pniVal(n.id,'fra')})).filter(x=>!S.pni.some(p=>p.net===x.id));return r})()"); + const w = rows.filter(r => r.v.worth).sort((a, b) => b.v.val - a.v.val); + assert.ok(w.length, 'some content network is worth it at 400G of demand'); + const names = [...p.querySelectorAll('.prow .nm')].map(x => x.textContent); + const first = ev(`NET.${w[0].id}.name`); + assert.ok(names.some(n => n.startsWith(first) && /Worth it/.test(n)), 'best candidate is tagged'); + assert.equal(p.querySelectorAll('.prow .pchip').length, names.length, 'every row has a status chip'); + assert.ok(p.querySelector('.pval'), 'value line'); + // Filters + ev("ACT.pniFilter({f:'pni'})");p = panel(); + assert.deepEqual([...p.querySelectorAll('.prow .nm')].map(x => x.textContent.split(' ')[0]), [ev("NET.ggl.name").split(' ')[0]]); + ev("ACT.pniFilter({f:'worth'})");p = panel(); + assert.ok([...p.querySelectorAll('.prow .nm')].every(x => /Worth it/.test(x.textContent))); + ev("ACT.pniFilter({f:'t'})");p = panel(); + assert.ok([...p.querySelectorAll('.pchip')].every(x => /Via transit|Not reached/.test(x.textContent))); + // Folding and unfolding by hand, A-Z sort + ev("ACT.pniFilter({f:'all'})"); + ev("ACT.pniGrp({g:'t1',o:0})");p = panel(); + assert.match(p.querySelector('.pgrp').textContent, /▸/); + ev("ACT.pniGrp({g:'t1',o:1});ACT.pniSort()");p = panel(); + assert.match(p.textContent, /Sort: A–Z/); + // Phone: chips wrap, value text stays on one line + const css = ev("[...document.querySelectorAll('style')].map(s=>s.textContent).join('')"); + assert.match(css, /\.pchips\{display:flex;flex-wrap:wrap/); + assert.match(css, /\.pval\{white-space:nowrap;overflow:hidden;text-overflow:ellipsis/); + assert.equal(ev("isPhone()"), true); + assert.deepEqual(errors, []); +}); + +test('the same chip in the Networks tab and the bulk PNI preview', () => { + const { ev, errors, dom } = load(); + fra(ev); + ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()"); + ev("UI.sel=null;UI.left='nets';UI.leftOpen=true;UI._lh=null;renderLeft()"); + const left = dom.window.document.getElementById('leftBody'); + assert.ok(left.querySelectorAll('.pchip').length >= 10); + assert.ok(/PNI at Frankfurt/.test(left.textContent), 'Goggle shows its PNI'); + ev("ACT.pniAllOpen({net:null})"); + const m = dom.window.document.getElementById('modal'); + assert.ok(m.querySelectorAll('.pchip').length > 0); + assert.ok(/Via transit/.test(m.textContent), 'bulk preview chips'); + assert.deepEqual(errors, []); +}); + +test('every language renders the PNI list without raw labels', () => { + for (const lang of ['de', 'es', 'fr', 'it', 'pt']) { + const { ev, errors, dom } = load({ lang }); + fra(ev, 400); + ev("UI.sel={type:'city',id:'fra'};UI.tab='peer';renderPanel();UI.left='nets';UI.leftOpen=true;renderLeft()"); + const txt = dom.window.document.getElementById('panelBody').textContent + dom.window.document.getElementById('leftBody').textContent; + assert.doesNotMatch(txt, /pni_list\./, lang); + assert.ok(dom.window.document.querySelector('#panelBody .pchip'), lang); + assert.deepEqual(errors, [], lang); + } +}); From 4e17728a2089fb849880022bb82289d66d7fba9d Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:12:44 +0100 Subject: [PATCH 120/181] Specialist play: capability offers, vendor demo units, pioneer fiber, consortium seats and charters (#187, #173) --- 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 ++++++- src/game/10-catalog/30-supply-chain.js | 4 +- src/game/10-catalog/50-dark-fiber.js | 2 +- src/game/60-features/35-capacity-deals.js | 2 +- src/game/60-features/36-specialist.js | 96 +++++++++++++++++++ src/game/60-features/60-share-card.js | 1 + src/game/60-features/80-new-game.js | 2 +- src/game/80-simulation/50-sanitize.js | 1 + .../80-simulation/80-geography-and-latency.js | 2 +- .../80-simulation/90-sites-and-service.js | 4 +- src/game/88-days/10-day-tick.js | 6 +- src/game/88-days/20-badges.js | 2 + src/game/90-actions/85-routing-and-routers.js | 2 +- src/game/90-actions/86-specialist.js | 11 +++ src/game/90-actions/87-fiber-and-hardware.js | 10 +- src/game/90-actions/90-action-helpers.js | 6 +- src/game/93-ui/40-hud-and-panels.js | 6 +- src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/70-link-panels.js | 10 +- src/game/94-dashboard/50-lease-swaps.js | 4 +- src/game/95-modals/90-fiber-modals.js | 8 +- src/i18n/en.js | 34 ++++++- 26 files changed, 346 insertions(+), 39 deletions(-) create mode 100644 src/game/60-features/36-specialist.js create mode 100644 src/game/90-actions/86-specialist.js diff --git a/site/i18n/de.js b/site/i18n/de.js index 82a1847..709264e 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1772,7 +1772,6 @@ "fiber_and_hardware.those_optics_need_the_regen_site":"Diese Optiken brauchen den Regen-Standort.
Entferne zuerst die Langstreckenkanäle oder behalte den Standort.", "fiber_modals.a_fiber_pair_of_your_own":"Ein eigenes Faserpaar. Das Glas ist billig, die Technik nicht: Du kaufst ein Line System mit einem Verstärker alle {km} km und dann Optiken für jeden Kanal. Deine Technik kann ausfallen, und du reparierst sie.", "fiber_modals.a_fiber_pair_on_cable_km":"Ein Faserpaar auf {cable}, {km} km. Es teilt sich das Kabel mit den Waves aller anderen, Anker inklusive.", -"fiber_modals.build_your_own_level_3":"Selbst bauen Level 3", "fiber_modals.build_your_own_price_n_days":"Selbst bauen {price} · ~{n} Tage", "fiber_modals.dark_fiber_across_the_chinese_border":"Dark Fiber über die chinesische Grenze ist nicht zu haben. Kauf stattdessen eine grenzüberschreitende Wave.", "fiber_modals.dark_fiber_unlocks_at_customer_level":"Dark Fiber wird ab Kundenlevel 2 freigeschaltet. Du brauchst die Größe, damit sich eigene optische Technik lohnt.", @@ -3507,6 +3506,39 @@ "sold_out.tier_1s_never_peer_at_ixs":"Tier 1s peeren nie an IXs", "sold_out.wants_need_gbps_of_traffic_from":"Will ≥ {need} Gbps Traffic von dir (du schickst {dem})", "sold_out.wants_you_to_be_a_tier":"Will, dass du Tier 2 bist oder ≥ {need} Gbps dorthin schickst (du schickst {dem})", +"specialist.a_b_km_km_ready_in":"{a} ⇄ {b} · {km} km · etwa {ms} ms · fertig in etwa {n} Tagen", +"specialist.a_consortium_is_selling_seats_on":"Ein Konsortium verkauft Plätze auf {name}, einem neuen Kabel von {a} nach {b}. Eigene Faserpaare darauf, noch bevor du Tier 1 bist.", +"specialist.ask_for_a_demo_unit_p_n":"Demogerät: +{p} %, {n} Tage", +"specialist.charter_signed_name":"Charta unterschrieben: {name}.", +"specialist.consortium_seat":"Konsortialplatz", +"specialist.consortium_seat_name":"Konsortialplatz: {name}", +"specialist.demo_unit_ships_in_n_days":"Demogerät kommt in {n} Tagen", +"specialist.dig_your_own_as_a_pioneer":"Selbst graben als Pionier (+{p} %) · {price} · {n} Tage", +"specialist.global_backbone":"Globaler Backbone", +"specialist.includes_pops_at_the_landings_price":"Inklusive POPs an den Landestationen: {price}.", +"specialist.keep_it":"Behalten", +"specialist.low_latency_boutique":"Low-Latency-Boutique", +"specialist.n_fiber_pairs":{"one":"{n} Faserpaar","other":"{n} Faserpaare"}, +"specialist.part_owner_of_the_sea":"Miteigentümer des Meeres", +"specialist.pick":"Wählen", +"specialist.pick_a_charter":"Wähle eine Charta", +"specialist.routes_r_of_n_beat_the":"Finanzrouten, auf denen deine eigene Glasfaser schneller ist als jeder gemietete Weg: {r}/{n} · zahlende Latenzkunden: {c}/{m}", +"specialist.speed_of_light":"Lichtgeschwindigkeit", +"specialist.spotted_your_broadband_in_a_one":"Sie haben dein Breitband in {a} entdeckt, einer der großen Privatkunden-Städte.", +"specialist.spotted_your_cap_of_dark_fiber":"Sie haben deine {cap} beleuchtete Dark Fiber zwischen {a} und {b} entdeckt.", +"specialist.spotted_your_ms_ms_a_b_path":"Sie haben deinen {ms}-ms-Weg {a}–{b} entdeckt.", +"specialist.spotted_your_two_diverse_paths_a":"Sie haben deine zwei getrennten Wege zwischen {a} und {b} entdeckt.", +"specialist.take_a_seat_on_a_consortium":"Nimm einen Platz auf einem Konsortialkabel", +"specialist.the_classic_game_grow_everywhere_and":"Das klassische Spiel: überall wachsen, Kunden folgen deinem Level, Tier 1 ist der Sieg.", +"specialist.the_consortium_runs_the_cable_your":"Das Konsortium betreibt das Kabel und seine Repeater. Deine Paare beleuchtest du mit eigenen Optiken; ein Schnitt im Kabel trifft auch sie.", +"specialist.the_vendor_ships_a_demo_name":"Der Hersteller schickt in {n} Tagen ein Demo-{name}. Bis dein Level aufholt, kostet jedes Gerät {p} % mehr.", +"specialist.trading_firms_and_other_latency_customers":"Handelsfirmen und andere Latenzkunden melden sich öfter und zahlen {p} % mehr. Gewinne Lichtgeschwindigkeit: schlag die schnellste gemietete Latenz auf {r} Finanzrouten mit eigener Glasfaser, während {c} Latenzkunden zahlen. Tier 1 zählt weiterhin.", +"specialist.what_kind_of_network_are_you":"Was für ein Netz baust du? Du kannst noch {n} Tage wählen; bis dahin bist du ein Globaler Backbone.", +"specialist.win_as_a_low_latency_boutique":"Gewinne als Low-Latency-Boutique", +"specialist.won_on_date_your_own_glass":"Gewonnen am {date}: deine eigene Glasfaser schlug jeden gemieteten Weg.", +"specialist.you_own_n_fiber_pairs_on":"Unterschrieben: dir gehören {n} Faserpaare auf {name}, {a} ⇄ {b}. Die Kabelschiffe legen ab; fertig in etwa {d} Tagen.", +"specialist.your_own_fiber_pairs_on_a":"Eigene Faserpaare auf einem neuen Seekabel: zahl jetzt deinen Anteil am Bau und beleuchte sie mit eigenen Optiken, wenn es anlandet.", +"specialist.your_own_glass_beats_every_leased":"Deine eigene Glasfaser schlägt auf drei Finanzrouten jeden gemieteten Weg, und die Trader zahlen dafür. Die Boutique hat gewonnen!", "supply_chain.as_when_you_started":"wie bei deinem Start", "supply_chain.chip_shortage_every_router_vendor_is":"Chipmangel!
Jeder Router-Hersteller wartet auf dieselben Chips. Neue Router und Router-Upgrades kosten {n} Tage lang 40 % mehr. Lieferzeit: „ja“.", "supply_chain.every_cable_ship_is_booked":"Jedes Kabelschiff ist ausgebucht.
Hyperscaler haben jedes Kabelschiff und jeden Grabungstrupp der Welt angeheuert. Neue Glasfaser- und Kabelbauten kosten {n} Tage lang 30 % mehr.", diff --git a/site/i18n/es.js b/site/i18n/es.js index f9f661a..89e2892 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1770,7 +1770,6 @@ "fiber_and_hardware.those_optics_need_the_regen_site":"Esas ópticas necesitan el sitio regenerador.
Quita primero los canales de larga distancia, o conserva el sitio.", "fiber_modals.a_fiber_pair_of_your_own":"Un par de fibra propio. El vidrio es barato, el equipo no: compras un sistema de línea con un amplificador cada {km} km, y luego ópticas para cada canal. Tu equipo puede fallar, y tú lo arreglas.", "fiber_modals.a_fiber_pair_on_cable_km":"Un par de fibra en {cable}, {km} km. Comparte cable con las ondas de todos los demás, anclas incluidas.", -"fiber_modals.build_your_own_level_3":"Construye el tuyo nivel 3", "fiber_modals.build_your_own_price_n_days":"Construye el tuyo {price} · ~{n} días", "fiber_modals.dark_fiber_across_the_chinese_border":"La fibra oscura que cruza la frontera china no está a la venta. Compra una onda transfronteriza.", "fiber_modals.dark_fiber_unlocks_at_customer_level":"La fibra oscura se desbloquea en el nivel de cliente 2. Necesitas la escala para justificar comprar tu propio equipo óptico.", @@ -3505,6 +3504,39 @@ "sold_out.tier_1s_never_peer_at_ixs":"Los Tier 1 nunca hacen peering en IX", "sold_out.wants_need_gbps_of_traffic_from":"Quiere ≥ {need} Gbps de tráfico tuyo (envías {dem})", "sold_out.wants_you_to_be_a_tier":"Quiere que seas Tier 2, o que le envíes ≥ {need} Gbps (envías {dem})", +"specialist.a_b_km_km_ready_in":"{a} ⇄ {b} · {km} km · unos {ms} ms · lista en unos {n} días", +"specialist.a_consortium_is_selling_seats_on":"Un consorcio vende plazas en {name}, un cable nuevo de {a} a {b}. Tus propios pares de fibra en él, antes de ser Tier 1.", +"specialist.ask_for_a_demo_unit_p_n":"Unidad demo: +{p}%, {n} días", +"specialist.charter_signed_name":"Carta firmada: {name}.", +"specialist.consortium_seat":"Plaza en el consorcio", +"specialist.consortium_seat_name":"Plaza en el consorcio: {name}", +"specialist.demo_unit_ships_in_n_days":"La unidad demo llega en {n} días", +"specialist.dig_your_own_as_a_pioneer":"Excava la tuya como pionero (+{p}%) · {price} · {n} días", +"specialist.global_backbone":"Backbone global", +"specialist.includes_pops_at_the_landings_price":"Incluye POPs en los aterrizajes: {price}.", +"specialist.keep_it":"Mantener", +"specialist.low_latency_boutique":"Boutique de baja latencia", +"specialist.n_fiber_pairs":{"one":"{n} par de fibra","other":"{n} pares de fibra"}, +"specialist.part_owner_of_the_sea":"Copropietario del mar", +"specialist.pick":"Elegir", +"specialist.pick_a_charter":"Elige una carta", +"specialist.routes_r_of_n_beat_the":"Rutas financieras más rápidas por tu propia fibra que por cualquier camino alquilado: {r}/{n} · clientes de latencia que pagan: {c}/{m}", +"specialist.speed_of_light":"Velocidad de la luz", +"specialist.spotted_your_broadband_in_a_one":"Vieron tu banda ancha en {a}, una de las grandes ciudades de usuarios.", +"specialist.spotted_your_cap_of_dark_fiber":"Vieron tus {cap} de fibra oscura iluminada entre {a} y {b}.", +"specialist.spotted_your_ms_ms_a_b_path":"Vieron tu camino {a}–{b} de {ms} ms.", +"specialist.spotted_your_two_diverse_paths_a":"Vieron tus dos caminos diversos entre {a} y {b}.", +"specialist.take_a_seat_on_a_consortium":"Toma una plaza en un cable de consorcio", +"specialist.the_classic_game_grow_everywhere_and":"El juego clásico: crece en todas partes, los clientes siguen tu nivel y Tier 1 es la victoria.", +"specialist.the_consortium_runs_the_cable_your":"El consorcio opera el cable y sus repetidores. Tus pares los iluminas con tus propias ópticas; un corte en el cable también los corta.", +"specialist.the_vendor_ships_a_demo_name":"El fabricante envía un {name} de demostración en {n} días. Hasta que tu nivel lo alcance, cada unidad cuesta un {p}% más.", +"specialist.trading_firms_and_other_latency_customers":"Las firmas de trading y otros clientes de latencia llaman más a menudo y pagan un {p}% más. Gana Velocidad de la luz: supera la latencia alquilada más rápida en {r} rutas financieras con tu propia fibra mientras {c} clientes de latencia te pagan. Tier 1 sigue contando.", +"specialist.what_kind_of_network_are_you":"¿Qué tipo de red estás construyendo? Puedes elegir durante {n} días más; hasta entonces eres un Backbone global.", +"specialist.win_as_a_low_latency_boutique":"Gana como boutique de baja latencia", +"specialist.won_on_date_your_own_glass":"Ganado el {date}: tu propia fibra superó todos los caminos alquilados.", +"specialist.you_own_n_fiber_pairs_on":"Firmado: tienes {n} pares de fibra en {name}, {a} ⇄ {b}. Zarpan los buques cableros; listo en unos {d} días.", +"specialist.your_own_fiber_pairs_on_a":"Tus propios pares de fibra en un cable submarino nuevo: paga ahora tu parte de la obra e ilumínalos con tus ópticas cuando llegue a tierra.", +"specialist.your_own_glass_beats_every_leased":"Tu propia fibra supera todos los caminos alquilados en tres rutas financieras, y los traders pagan por ello. ¡La boutique ha ganado!", "supply_chain.as_when_you_started":"igual que cuando empezaste", "supply_chain.chip_shortage_every_router_vendor_is":"¡Escasez de chips!
Todos los fabricantes de routers esperan los mismos chips. Los routers nuevos y sus mejoras cuestan un 40 % más durante {n} días. Plazo de entrega: «sí».", "supply_chain.every_cable_ship_is_booked":"Todos los barcos cableros están reservados.
Los hiperescaladores han contratado todos los barcos cableros y cuadrillas de zanjas del planeta. La fibra y los cables nuevos cuestan un 30 % más durante {n} días.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f4056b9..b24feae 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1770,7 +1770,6 @@ "fiber_and_hardware.those_optics_need_the_regen_site":"Ces optiques ont besoin du site de régénération.
Retire d’abord les canaux longue distance, ou garde le site.", "fiber_modals.a_fiber_pair_of_your_own":"Une paire de fibres rien qu’à toi. Le verre ne coûte pas cher, le matériel si : tu achètes un système de ligne avec un amplificateur tous les {km} km, puis des optiques pour chaque canal. Ton matériel peut tomber en panne, et c’est toi qui répares.", "fiber_modals.a_fiber_pair_on_cable_km":"Une paire de fibres sur {cable}, {km} km. Elle partage le câble avec les longueurs d’onde de tout le monde, ancres comprises.", -"fiber_modals.build_your_own_level_3":"Construire la tienne niveau 3", "fiber_modals.build_your_own_price_n_days":"Construire la tienne {price} · ~{n} jours", "fiber_modals.dark_fiber_across_the_chinese_border":"La fibre noire à travers la frontière chinoise n’est pas à vendre. Achète plutôt une longueur d’onde transfrontalière.", "fiber_modals.dark_fiber_unlocks_at_customer_level":"La fibre noire se débloque au niveau clients 2. Il te faut la taille critique pour justifier l’achat de ton propre matériel optique.", @@ -3505,6 +3504,39 @@ "sold_out.tier_1s_never_peer_at_ixs":"Les Tier 1 ne font jamais de peering sur les IX", "sold_out.wants_need_gbps_of_traffic_from":"Veut ≥ {need} Gbps de trafic de ta part (tu en envoies {dem})", "sold_out.wants_you_to_be_a_tier":"Veut que tu sois Tier 2, ou que tu lui envoies ≥ {need} Gbps (tu en envoies {dem})", +"specialist.a_b_km_km_ready_in":"{a} ⇄ {b} · {km} km · environ {ms} ms · prêt dans environ {n} jours", +"specialist.a_consortium_is_selling_seats_on":"Un consortium vend des places sur {name}, un nouveau câble de {a} à {b}. Tes propres paires de fibre dessus, avant d'être Tier 1.", +"specialist.ask_for_a_demo_unit_p_n":"Unité de démo : +{p} %, {n} jours", +"specialist.charter_signed_name":"Charte signée : {name}.", +"specialist.consortium_seat":"Place au consortium", +"specialist.consortium_seat_name":"Place au consortium : {name}", +"specialist.demo_unit_ships_in_n_days":"L'unité de démo arrive dans {n} jours", +"specialist.dig_your_own_as_a_pioneer":"Creuse la tienne en pionnier (+{p} %) · {price} · {n} jours", +"specialist.global_backbone":"Backbone mondial", +"specialist.includes_pops_at_the_landings_price":"POPs aux atterrissements compris : {price}.", +"specialist.keep_it":"Garder", +"specialist.low_latency_boutique":"Boutique basse latence", +"specialist.n_fiber_pairs":{"one":"{n} paire de fibre","other":"{n} paires de fibre"}, +"specialist.part_owner_of_the_sea":"Copropriétaire de la mer", +"specialist.pick":"Choisir", +"specialist.pick_a_charter":"Choisis une charte", +"specialist.routes_r_of_n_beat_the":"Routes financières plus rapides sur ta propre fibre que tout chemin loué : {r}/{n} · clients latence qui paient : {c}/{m}", +"specialist.speed_of_light":"Vitesse de la lumière", +"specialist.spotted_your_broadband_in_a_one":"Ils ont repéré ton haut débit à {a}, une des grandes villes d'abonnés.", +"specialist.spotted_your_cap_of_dark_fiber":"Ils ont repéré tes {cap} de fibre noire allumée entre {a} et {b}.", +"specialist.spotted_your_ms_ms_a_b_path":"Ils ont repéré ton chemin {a}–{b} à {ms} ms.", +"specialist.spotted_your_two_diverse_paths_a":"Ils ont repéré tes deux chemins diversifiés entre {a} et {b}.", +"specialist.take_a_seat_on_a_consortium":"Prends une place sur un câble de consortium", +"specialist.the_classic_game_grow_everywhere_and":"Le jeu classique : grandis partout, les clients suivent ton niveau, et Tier 1 est la victoire.", +"specialist.the_consortium_runs_the_cable_your":"Le consortium exploite le câble et ses répéteurs. Tes paires, tu les allumes avec tes propres optiques ; une coupure du câble les coupe aussi.", +"specialist.the_vendor_ships_a_demo_name":"Le constructeur envoie un {name} de démo dans {n} jours. Tant que ton niveau ne l'a pas rattrapé, chaque unité coûte {p} % de plus.", +"specialist.trading_firms_and_other_latency_customers":"Les sociétés de trading et autres clients latence appellent plus souvent et paient {p} % de plus. Gagne Vitesse de la lumière : bats la latence louée la plus rapide sur {r} routes financières avec ta propre fibre pendant que {c} clients latence te paient. Tier 1 compte toujours.", +"specialist.what_kind_of_network_are_you":"Quel genre de réseau construis-tu ? Tu peux choisir encore {n} jours ; d'ici là tu es un Backbone mondial.", +"specialist.win_as_a_low_latency_boutique":"Gagne en boutique basse latence", +"specialist.won_on_date_your_own_glass":"Gagné le {date} : ta propre fibre a battu tous les chemins loués.", +"specialist.you_own_n_fiber_pairs_on":"Signé : tu possèdes {n} paires de fibre sur {name}, {a} ⇄ {b}. Les câbliers appareillent ; prêt dans environ {d} jours.", +"specialist.your_own_fiber_pairs_on_a":"Tes propres paires de fibre sur un nouveau câble sous-marin : paie ta part du chantier maintenant, allume-les avec tes optiques quand il atterrit.", +"specialist.your_own_glass_beats_every_leased":"Ta propre fibre bat tous les chemins loués sur trois routes financières, et les traders paient pour ça. La boutique a gagné !", "supply_chain.as_when_you_started":"comme à vos débuts", "supply_chain.chip_shortage_every_router_vendor_is":"Pénurie de puces !
Tous les fabricants de routeurs attendent les mêmes puces. Les routeurs neufs et les mises à niveau coûtent 40 % de plus pendant {n} jours. Délai de livraison : « oui ».", "supply_chain.every_cable_ship_is_booked":"Tous les câbliers sont réservés.
Les hyperscalers ont loué chaque câblier et chaque équipe de tranchée de la planète. Les nouvelles fibres et les nouveaux câbles coûtent 30 % de plus pendant {n} jours.", diff --git a/site/i18n/it.js b/site/i18n/it.js index fe99435..7f68acb 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1770,7 +1770,6 @@ "fiber_and_hardware.those_optics_need_the_regen_site":"Quelle ottiche hanno bisogno del sito di rigenerazione.
Rimuovi prima i canali long-haul, oppure tieni il sito.", "fiber_modals.a_fiber_pair_of_your_own":"Una coppia di fibre tutta tua. Il vetro costa poco, l’hardware no: compri un sistema di linea con un amplificatore ogni {km} km, poi le ottiche per ogni canale. Il tuo hardware può guastarsi, e lo ripari tu.", "fiber_modals.a_fiber_pair_on_cable_km":"Una coppia di fibre su {cable}, {km} km. Condivide il cavo con le wave di tutti gli altri, ancore comprese.", -"fiber_modals.build_your_own_level_3":"Costruiscila tu livello 3", "fiber_modals.build_your_own_price_n_days":"Costruiscila tu {price} · ~{n} giorni", "fiber_modals.dark_fiber_across_the_chinese_border":"La dark fiber attraverso il confine cinese non è in vendita. Compra piuttosto una wave transfrontaliera.", "fiber_modals.dark_fiber_unlocks_at_customer_level":"La dark fiber si sblocca al livello clienti 2. Ti serve la scala per giustificare l’acquisto di hardware ottico tutto tuo.", @@ -3505,6 +3504,39 @@ "sold_out.tier_1s_never_peer_at_ixs":"I Tier 1 non fanno mai peering agli IX", "sold_out.wants_need_gbps_of_traffic_from":"Vuole ≥ {need} Gbps di traffico da te (ne mandi {dem})", "sold_out.wants_you_to_be_a_tier":"Vuole che tu sia un Tier 2, o che gli mandi ≥ {need} Gbps (ne mandi {dem})", +"specialist.a_b_km_km_ready_in":"{a} ⇄ {b} · {km} km · circa {ms} ms · pronto tra circa {n} giorni", +"specialist.a_consortium_is_selling_seats_on":"Un consorzio vende posti su {name}, un nuovo cavo da {a} a {b}. Coppie di fibra tue, prima di essere Tier 1.", +"specialist.ask_for_a_demo_unit_p_n":"Unità demo: +{p}%, {n} giorni", +"specialist.charter_signed_name":"Statuto firmato: {name}.", +"specialist.consortium_seat":"Posto nel consorzio", +"specialist.consortium_seat_name":"Posto nel consorzio: {name}", +"specialist.demo_unit_ships_in_n_days":"L'unità demo arriva tra {n} giorni", +"specialist.dig_your_own_as_a_pioneer":"Scava la tua da pioniere (+{p}%) · {price} · {n} giorni", +"specialist.global_backbone":"Backbone globale", +"specialist.includes_pops_at_the_landings_price":"POP agli approdi inclusi: {price}.", +"specialist.keep_it":"Tienilo", +"specialist.low_latency_boutique":"Boutique a bassa latenza", +"specialist.n_fiber_pairs":{"one":"{n} coppia di fibra","other":"{n} coppie di fibra"}, +"specialist.part_owner_of_the_sea":"Comproprietario del mare", +"specialist.pick":"Scegli", +"specialist.pick_a_charter":"Scegli uno statuto", +"specialist.routes_r_of_n_beat_the":"Rotte finanziarie più veloci sulla tua fibra che su qualsiasi percorso in affitto: {r}/{n} · clienti latenza paganti: {c}/{m}", +"specialist.speed_of_light":"Velocità della luce", +"specialist.spotted_your_broadband_in_a_one":"Hanno notato la tua banda larga a {a}, una delle grandi città di utenti.", +"specialist.spotted_your_cap_of_dark_fiber":"Hanno notato i tuoi {cap} di dark fiber accesa tra {a} e {b}.", +"specialist.spotted_your_ms_ms_a_b_path":"Hanno notato il tuo percorso {a}–{b} da {ms} ms.", +"specialist.spotted_your_two_diverse_paths_a":"Hanno notato i tuoi due percorsi diversi tra {a} e {b}.", +"specialist.take_a_seat_on_a_consortium":"Prendi un posto su un cavo di consorzio", +"specialist.the_classic_game_grow_everywhere_and":"Il gioco classico: cresci ovunque, i clienti seguono il tuo livello e Tier 1 è la vittoria.", +"specialist.the_consortium_runs_the_cable_your":"Il consorzio gestisce il cavo e i suoi ripetitori. Le tue coppie le accendi con le tue ottiche; un taglio del cavo taglia anche loro.", +"specialist.the_vendor_ships_a_demo_name":"Il vendor spedisce un {name} demo tra {n} giorni. Finché il tuo livello non lo raggiunge, ogni unità costa il {p}% in più.", +"specialist.trading_firms_and_other_latency_customers":"Le società di trading e gli altri clienti latenza chiamano più spesso e pagano il {p}% in più. Vinci Velocità della luce: batti la latenza in affitto più veloce su {r} rotte finanziarie con la tua fibra mentre {c} clienti latenza ti pagano. Tier 1 conta ancora.", +"specialist.what_kind_of_network_are_you":"Che rete stai costruendo? Puoi scegliere ancora per {n} giorni; fino ad allora sei un Backbone globale.", +"specialist.win_as_a_low_latency_boutique":"Vinci come boutique a bassa latenza", +"specialist.won_on_date_your_own_glass":"Vinto il {date}: la tua fibra ha battuto ogni percorso in affitto.", +"specialist.you_own_n_fiber_pairs_on":"Firmato: hai {n} coppie di fibra su {name}, {a} ⇄ {b}. Le navi posacavi salpano; pronto tra circa {d} giorni.", +"specialist.your_own_fiber_pairs_on_a":"Coppie di fibra tue su un nuovo cavo sottomarino: paga ora la tua quota della posa e accendile con le tue ottiche quando approda.", +"specialist.your_own_glass_beats_every_leased":"La tua fibra batte ogni percorso in affitto su tre rotte finanziarie, e i trader pagano per questo. La boutique ha vinto!", "supply_chain.as_when_you_started":"come quando hai iniziato", "supply_chain.chip_shortage_every_router_vendor_is":"Carenza di chip!
Tutti i produttori di router aspettano gli stessi chip. Router nuovi e upgrade costano il 40% in più per {n} giorni. Tempi di consegna: “sì”.", "supply_chain.every_cable_ship_is_booked":"Tutte le navi posacavi sono prenotate.
Gli hyperscaler hanno noleggiato ogni nave posacavi e ogni squadra di scavo del pianeta. Nuove fibre e nuovi cavi costano il 30% in più per {n} giorni.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 1eadf43..d24c0e8 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1770,7 +1770,6 @@ "fiber_and_hardware.those_optics_need_the_regen_site":"Essas ópticas precisam do site de regeneração.
Remova primeiro os canais long-haul, ou mantenha o site.", "fiber_modals.a_fiber_pair_of_your_own":"Um par de fibra só seu. O vidro é barato, o equipamento não: você compra um line system com um amplificador a cada {km} km, depois a óptica de cada canal. Seu equipamento pode falhar, e quem conserta é você.", "fiber_modals.a_fiber_pair_on_cable_km":"Um par de fibra no {cable}, {km} km. Divide o cabo com as waves de todo mundo, âncoras incluídas.", -"fiber_modals.build_your_own_level_3":"Construir a sua nível 3", "fiber_modals.build_your_own_price_n_days":"Construir a sua {price} · ~{n} dias", "fiber_modals.dark_fiber_across_the_chinese_border":"Dark fiber atravessando a fronteira chinesa não está à venda. Compre uma wave transfronteiriça.", "fiber_modals.dark_fiber_unlocks_at_customer_level":"Dark fiber desbloqueia no nível de clientes 2. Você precisa de escala para justificar comprar seu próprio equipamento óptico.", @@ -3505,6 +3504,39 @@ "sold_out.tier_1s_never_peer_at_ixs":"Tier 1 nunca faz peering em IX", "sold_out.wants_need_gbps_of_traffic_from":"Quer ≥ {need} Gbps de tráfego seu (você manda {dem})", "sold_out.wants_you_to_be_a_tier":"Quer que você seja Tier 2, ou que mande ≥ {need} Gbps para ele (você manda {dem})", +"specialist.a_b_km_km_ready_in":"{a} ⇄ {b} · {km} km · cerca de {ms} ms · pronto em cerca de {n} dias", +"specialist.a_consortium_is_selling_seats_on":"Um consórcio está vendendo lugares no {name}, um cabo novo de {a} a {b}. Seus próprios pares de fibra nele, antes de ser Tier 1.", +"specialist.ask_for_a_demo_unit_p_n":"Unidade demo: +{p}%, {n} dias", +"specialist.charter_signed_name":"Carta assinada: {name}.", +"specialist.consortium_seat":"Lugar no consórcio", +"specialist.consortium_seat_name":"Lugar no consórcio: {name}", +"specialist.demo_unit_ships_in_n_days":"A unidade demo chega em {n} dias", +"specialist.dig_your_own_as_a_pioneer":"Cave a sua como pioneiro (+{p}%) · {price} · {n} dias", +"specialist.global_backbone":"Backbone global", +"specialist.includes_pops_at_the_landings_price":"Inclui POPs nas estações de ancoragem: {price}.", +"specialist.keep_it":"Manter", +"specialist.low_latency_boutique":"Boutique de baixa latência", +"specialist.n_fiber_pairs":{"one":"{n} par de fibra","other":"{n} pares de fibra"}, +"specialist.part_owner_of_the_sea":"Coproprietário do mar", +"specialist.pick":"Escolher", +"specialist.pick_a_charter":"Escolha uma carta", +"specialist.routes_r_of_n_beat_the":"Rotas financeiras mais rápidas na sua fibra do que em qualquer caminho alugado: {r}/{n} · clientes de latência pagando: {c}/{m}", +"specialist.speed_of_light":"Velocidade da luz", +"specialist.spotted_your_broadband_in_a_one":"Eles viram sua banda larga em {a}, uma das grandes cidades de usuários.", +"specialist.spotted_your_cap_of_dark_fiber":"Eles viram seus {cap} de dark fiber acesa entre {a} e {b}.", +"specialist.spotted_your_ms_ms_a_b_path":"Eles viram seu caminho {a}–{b} de {ms} ms.", +"specialist.spotted_your_two_diverse_paths_a":"Eles viram seus dois caminhos diversos entre {a} e {b}.", +"specialist.take_a_seat_on_a_consortium":"Pegue um lugar num cabo de consórcio", +"specialist.the_classic_game_grow_everywhere_and":"O jogo clássico: cresça em todo lugar, os clientes seguem seu nível e Tier 1 é a vitória.", +"specialist.the_consortium_runs_the_cable_your":"O consórcio opera o cabo e seus repetidores. Seus pares você acende com suas próprias ópticas; um corte no cabo corta eles também.", +"specialist.the_vendor_ships_a_demo_name":"O fabricante envia um {name} de demonstração em {n} dias. Até seu nível alcançar, cada unidade custa {p}% a mais.", +"specialist.trading_firms_and_other_latency_customers":"Firmas de trading e outros clientes de latência ligam mais vezes e pagam {p}% a mais. Vença Velocidade da luz: supere a latência alugada mais rápida em {r} rotas financeiras com sua própria fibra enquanto {c} clientes de latência pagam você. Tier 1 continua valendo.", +"specialist.what_kind_of_network_are_you":"Que tipo de rede você está construindo? Você pode escolher por mais {n} dias; até lá você é um Backbone global.", +"specialist.win_as_a_low_latency_boutique":"Vença como boutique de baixa latência", +"specialist.won_on_date_your_own_glass":"Vencido em {date}: sua própria fibra superou todos os caminhos alugados.", +"specialist.you_own_n_fiber_pairs_on":"Assinado: você tem {n} pares de fibra no {name}, {a} ⇄ {b}. Os navios lançadores zarpam; pronto em cerca de {d} dias.", +"specialist.your_own_fiber_pairs_on_a":"Seus próprios pares de fibra num cabo submarino novo: pague agora sua parte da obra e acenda com suas ópticas quando ele chegar.", +"specialist.your_own_glass_beats_every_leased":"Sua própria fibra supera todos os caminhos alugados em três rotas financeiras, e os traders pagam por isso. A boutique venceu!", "supply_chain.as_when_you_started":"como no começo", "supply_chain.chip_shortage_every_router_vendor_is":"Falta de chips!
Todo fabricante de roteador está esperando os mesmos chips. Roteadores novos e upgrades custam 40% a mais por {n} dias. Prazo de entrega: “sim”.", "supply_chain.every_cable_ship_is_booked":"Todos os navios lançadores de cabo estão reservados.
Os hyperscalers contrataram todos os navios e todas as equipes de escavação do planeta. Novas fibras e novos cabos custam 30% a mais por {n} dias.", diff --git a/src/game/10-catalog/30-supply-chain.js b/src/game/10-catalog/30-supply-chain.js index 07f79e7..8fc363b 100644 --- a/src/game/10-catalog/30-supply-chain.js +++ b/src/game/10-catalog/30-supply-chain.js @@ -22,10 +22,10 @@ function hwCard(){if(!S||!rule('market')||(S.day<=HW_FREE&&!hwShock()&&!hwLock() :`

${tr('supply_chain.routers_optics_and_new_builds_at')}

${btn(tr('supply_chain.lock_prices_for_a_year_cost',{cost:fmt$(hwLockCost())}),'hwLock',{},'sm',S.cash`}
`;} // Routers past the standard cage (#157) need a cage extension: pricier to install, and rent on top. const RCAGE=6,CAGE_MUL=1.5,CAGE_MO=2000; -const routerCost=(g,rt)=>Math.round((ROUTER_COST+RG[g].cost*0.8)*((rt||1)>=RCAGE?CAGE_MUL:1)*hwMul('rt')); +const routerCost=(g,rt)=>Math.round((ROUTER_COST+RG[g].cost*0.8)*((rt||1)>=RCAGE?CAGE_MUL:1)*hwMul('rt')*techMul(RG[g].lvl)); const routerMo=g=>ROUTER_MO+RG[g].mo,cageMo=rt=>Math.max(0,(rt||1)-RCAGE)*CAGE_MO; // Old routers go on eBuy when you swap models or remove one (#82), like spare optics (#45). Chassis age faster. -const ROUTER_RESALE=0.3,tradeIn=(g,n)=>Math.round(RG[g].cost*n*ROUTER_RESALE),swapCost=(c,g)=>{const p=S.pops[c],rt=p.routers||1;return Math.max(0,Math.round(RG[g].cost*rt*hwMul('rt'))-tradeIn(p.rgen||0,rt));}; +const ROUTER_RESALE=0.3,tradeIn=(g,n)=>Math.round(RG[g].cost*n*ROUTER_RESALE),swapCost=(c,g)=>{const p=S.pops[c],rt=p.routers||1;return Math.max(0,Math.round(RG[g].cost*rt*hwMul('rt')*techMul(RG[g].lvl))-tradeIn(p.rgen||0,rt));}; const RMAX=16; // The plain, badge-less model of each class is the default upgrade path; the others are side-grades. const mainRG=k=>RG.findIndex(r=>r.cls===k&&!r.badge); diff --git a/src/game/10-catalog/50-dark-fiber.js b/src/game/10-catalog/50-dark-fiber.js index 246000f..f6286a9 100644 --- a/src/game/10-catalog/50-dark-fiber.js +++ b/src/game/10-catalog/50-dark-fiber.js @@ -8,7 +8,7 @@ const AMP_EVERY=100, AMP_COST=8000, AMP_MO=300; /* Your own trench holds more than one fiber pair (#35). Once a ROADMaster is full you can light the next pair: another ROADMaster and another chain of amplifiers, 64 more channels. Regen huts are shared. */ const isRdm=y=>y==='roadm'||y==='cl'; -const PAIRS_MAX=4,PAIRS_BIG=8,PAIRS_LV=12,SUB_PAIRS_MAX=8,SUB_PAIR_UP=1500000,pairsMax=l=>l.sub?SUB_PAIRS_MAX:lvl()>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,chMax=l=>DF_SYS[l.sys].max*(isRdm(l.sys)&&l.own?Math.max(1,l.pairs|0):1), +const PAIRS_MAX=4,PAIRS_BIG=8,PAIRS_LV=12,SUB_PAIRS_MAX=8,SUB_PAIR_UP=1500000,pairsMax=l=>l.seat?Math.max(1,l.pairs|0):l.sub?SUB_PAIRS_MAX:lvl()>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,chMax=l=>DF_SYS[l.sys].max*(isRdm(l.sys)&&l.own?Math.max(1,l.pairs|0):1), pairCost=l=>DF_SYS[isRdm(l.sys)?l.sys:'roadm'].cost+(l.sub?SUB_PAIR_UP:ampCount(l.km)*AMP_COST); const OPT={ zr4:{n:'Ackackia 400ZR+',g:400,cost:12000,reach:1500,modes:[[400,1500],[200,3000]],rg:1,lvl:2,sys:'lite',blurb:tr('dark_fiber.coherent_pluggable_in_the_router_no')}, diff --git a/src/game/60-features/35-capacity-deals.js b/src/game/60-features/35-capacity-deals.js index 68049f6..bdb5c51 100644 --- a/src/game/60-features/35-capacity-deals.js +++ b/src/game/60-features/35-capacity-deals.js @@ -26,7 +26,7 @@ function capOffer(a,b,t,nm){const T=BIZ_T[t],km=kmBetween(a,b),n=pick(T.opts),o= if(t==='capfib'){o.bw=1;o.slots=n;o.rate=Math.round(dfLeaseMo(km)*n*1.5);o.win=dfBuildDays(km)+150;} else{o.bw=t==='capw'?n*400:n;o.rate=Math.round((150+km*0.08)*T.km);o.win=t==='capsub'?300+Math.floor(Math.random()*121):180+Math.floor(Math.random()*91);} return o;} -function capDealTick(d){const q=S.capDeal;if(!q||q.at!==d)return;S.capDeal=null;const pool=(CAP_ROUTES[q.c]||[]).filter(r=>isCity(r[0])&&isCity(r[1])).slice(),out=[]; +function capDealTick(d){const q=S.capDeal;if(!q||q.at!==d)return;S.capDeal=null;seatConf(q.c);const pool=(CAP_ROUTES[q.c]||[]).filter(r=>isCity(r[0])&&isCity(r[1])).slice(),out=[]; while(out.length<3&&pool.length){const [a,b,t]=pool.splice(Math.floor(Math.random()*pool.length),1)[0],T=BIZ_T[t]; const nm=()=>{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;};out.push(capOffer(a,b,t,nm));} if(!out.length)return;S.offers.push(...out); diff --git a/src/game/60-features/36-specialist.js b/src/game/60-features/36-specialist.js new file mode 100644 index 0000000..855834f --- /dev/null +++ b/src/game/60-features/36-specialist.js @@ -0,0 +1,96 @@ +/* ---------- Specialist play (#187, #173) ---------- + You do not have to grow everywhere to grow up. Customers call when your network can already serve them, not only + when your level says so; gear one level ahead comes early as a vendor demo unit at a premium; a seat on a + consortium cable is the way onto your own subsea glass before Tier 1; and a charter picks what you set out to be. */ +const FIN=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash']; +// What a capability brings in, and why the offer says it came. +const SPOT_W={lat:N_('specialist.spotted_your_ms_ms_a_b_path'),df:N_('specialist.spotted_your_cap_of_dark_fiber'),div:N_('specialist.spotted_your_two_diverse_paths_a'),eye:N_('specialist.spotted_your_broadband_in_a_one')}; +const SPOT_BIG=12,SPOT_DF=0.75; +const latMaxOf=(a,b)=>+(kmBetween(a,b)/200*1.35).toFixed(1); +let BIGEYE=null;const bigEye=()=>BIGEYE||(BIGEYE=CITIES.slice().sort((x,y)=>y.P-x.P).slice(0,SPOT_BIG).map(c=>c.id)); +// Worked out at most once a day (and again when the network changes shape): offers spawn far less often than that. +let SPOTC=null; +function spots(){const lv=lvl(),k=S.day+'|'+lv+'|'+S.links.length+'|'+Object.keys(S.pops).length+'|'+charter();if(SPOTC&&SPOTC.s===S&&SPOTC.k===k)return SPOTC.v;const v=spots0(lv);SPOTC={s:S,k,v};return v;} +function spots0(lv){const out=[];if(gatesOpen()||S.scn)return out;const up=t=>BIZ_T[t].lv>lv,mine=Object.keys(S.pops); + if(up('hft')){const f=FIN.filter(c=>S.pops[c]);for(let i=0;iS.day||linkDown(l))continue;const g=dfCap(l); + for(const t of dci){const T=BIZ_T[t];if(g>=T.opts[0]*SPOT_DF&&(!T.div||reqCan('diverse',{city:l.a,city2:l.b})))out.push({t,a:l.a,b:l.b,k:'df',n:g});}} + if(up('sov')){const by={};for(const c of mine)(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c); + for(const cs of Object.values(by))for(let i=0;i=0.95)out.push({t:'cgame',a:c,b:null,k:'eye',n:0}); + return out;} +// A spotted customer starts at the smallest size its type comes in; your level makes them bigger and more frequent. +function spawnSpot(t,s){const T=BIZ_T[t],list=T.names.filter(n=>!S.usedNames.includes(n)),name=list.length?pick(list):pick(T.names);useName(name); + const o={id:uid(),city:s.a,city2:s.b,name,type:t,bw:T.opts[0],reqs:[],exp:S.day+40,spot:{k:s.k,n:s.n}}; + o.rate=T.l2?Math.round((150+kmBetween(s.a,s.b)*0.08)*T.km*(T.lat?latPay():1)*(T.div?1+REQS.diverse.bonus:1)):T.rate; + if(T.lat){o.reqs=['lat'];o.latMax=latMaxOf(s.a,s.b);}else if(T.div)o.reqs=['diverse']; + S.offers.push(o);} +function spotWhy(o){const s=o&&o.spot;if(!s||!own(SPOT_W,s.k))return ''; + return `
🔭 ${tr(SPOT_W[s.k],{ms:s.n,cap:fmtCap(s.n),a:CITY[o.city].name,b:o.city2?CITY[o.city2].name:''})}
`;} + +/* Vendor demo units: gear one level above yours, early, at a markup and after a short wait. Never two levels ahead. */ +const DEMO_MUL=1.6,DEMO_DAYS=14; +function demoItem(k,id){return k==='rg'?RG[+id]||null:k==='sys'?(own(DF_SYS,id)?DF_SYS[id]:null):k==='opt'?(own(OPT,id)?OPT[id]:null):null;} +const demoAt=(k,id)=>{const d=S&&S.demo&&S.demo[k+':'+id];return d===undefined?null:d;}; +const demoCan=L=>!gatesOpen()&&L===lvl()+1; +function techOk(k,id,L){if(L<=lvl())return true;const d=demoAt(k,id);return demoCan(L)&&d!==null&&d<=S.day;} +const techMul=L=>L>lvl()?DEMO_MUL:1; +function demoBtn(k,id,L,lock,cls){const d=demoAt(k,id);if(!demoCan(L))return btn(lock,'demoAsk',{k,id},cls,true); + if(d!==null&&d>S.day)return btn(tr('specialist.demo_unit_ships_in_n_days',{n:d-S.day}),'demoAsk',{k,id},cls,true); + return btn(tr('specialist.ask_for_a_demo_unit_p_n',{p:Math.round((DEMO_MUL-1)*100),n:leadDays(DEMO_DAYS)}),'demoAsk',{k,id},cls);} +const sysCost=k=>Math.round(DF_SYS[k].cost*techMul(DF_SYS[k].lvl)); +// Digging your own fiber before level 3: the pioneer pays for the permits nobody has asked for yet. +const PIONEER=1.6; +const digMul=()=>lvl()>=3?1:PIONEER,digCost=km=>Math.round(dfBuildCost(km)*digMul()); + +/* A seat on a consortium cable (#173): pay your share of the build, wait for the ship, and own fiber pairs on it, + lit with your own optics like your own cable. Capacity conferences offer them, and now and then a consortium calls. */ +const SEAT_ROUTES={ + lon:[['nyc','bde','Amity Ville'],['lis','for','Ella Fitz-Link'],['mrs','sin','Sea, Me, We, Us, Them'],['lon','lag','Equi-Not']], + hnl:[['syd','lax','Southern Double-Cross'],['tok','sea','Kuro-Show'],['sin','hkg','Dim Sum Express'],['syd','akl','Tasman Devil']], +}; +const SEAT_N=[1,2,4],SEAT_SHARE=10,SEAT_LV=2,SEAT_ODDS=240,SEAT_EXP=30; +const seatKm=(a,b)=>Math.round(kmBetween(a,b)*1.2),seatCost=(km,n)=>Math.round(ownCabCost(km)*n/SEAT_SHARE),seatMo=(km,n)=>Math.round(ownCabMo(km)*n/SEAT_SHARE),seatDays=km=>Math.max(1,Math.round(ownCabDays(km)*0.6)); +const seatRoute=name=>Object.values(SEAT_ROUTES).flat().find(r=>r[2]===name); +// A conference names its own routes; a cold call is about a route with one of your POPs at an end. Picked by a hash, not +// by the dice, so the rest of the game rolls exactly as before. +function seatOffer(c,d){const rs=(c?SEAT_ROUTES[c]||[]:Object.values(SEAT_ROUTES).flat()).filter(r=>isCity(r[0])&&isCity(r[1])&&(c||S.pops[r[0]]||S.pops[r[1]])&&!S.links.some(l=>l.seat&&l.cname===r[2])); + if(!rs.length)return null;const r=rs[hstr(S.asn+'|seat|'+d)%rs.length];return {a:r[0],b:r[1],name:r[2],km:seatKm(r[0],r[1]),exp:d+SEAT_EXP};} +function seatConf(c){if(S.seatOff||lvl()!S.pops[c]).reduce((x,c)=>x+popCost(c),0); + return `
🚢 ${tr('specialist.consortium_seat_name',{name:esc(o.name)})}
${tr('specialist.a_b_km_km_ready_in',{a:CITY[o.a].name,b:CITY[o.b].name,km:o.km.toLocaleString(),n:seatDays(o.km),ms:linkLat({kind:'df',own:true,sub:true,km:o.km,seaDesign:'standard'}).toFixed(1)})} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
+
${tr('specialist.your_own_fiber_pairs_on_a')}${pop?' '+tr('specialist.includes_pops_at_the_landings_price',{price:fmt$(pop)}):''}
+
${SEAT_N.map(n=>{const c=seatCost(o.km,n)+pop;return btn(`${trn('specialist.n_fiber_pairs',n)} ${fmt$(c)} · ${tr('common.price_mo',{price:fmt$(seatMo(o.km,n))})}`,'seatBuy',{n},'sm',S.cash
`;} +function seatPanel(l){if(!l.seat)return '';return `
${tr('specialist.consortium_seat')}${esc(l.cname||'')} · ${trn('specialist.n_fiber_pairs',Math.max(1,l.pairs|0))}

${tr('specialist.the_consortium_runs_the_cable_your')}

`;} + +/* Charters: what the network sets out to be, picked once at the start of a Normal game. Global backbone is the game as + it always was; the Low-latency boutique sells speed to traders and has its own win, Speed of Light. */ +const CHARTERS={global:{i:'🌐',n:N_('specialist.global_backbone'),d:N_('specialist.the_classic_game_grow_everywhere_and')},boutique:{i:'⚡',n:N_('specialist.low_latency_boutique'),d:N_('specialist.trading_firms_and_other_latency_customers')}}; +const CHARTER_DAYS=30,LAT_PAY=1.4,SOL_ROUTES=3,SOL_CUST=2; +const charter=()=>S&&!S.scn&&S.mode==='normal'&&S.charter==='boutique'?'boutique':'global'; +const latPay=()=>charter()==='boutique'?LAT_PAY:1; +// The fastest a leased wave or fiber gets between two cities: overland, or the quickest cable on the route. +function leasedLat(a,b){let best=isSub(a,b)?Infinity:kmBetween(a,b)*1.25/200;for(const c of cablesFor(a,b))best=Math.min(best,c.km*Math.min(CAB[c.cid].lat||1,1.25)/200);return best;} +const ownGlass=l=>l.kind==='df'&&l.own&&l.ready<=S.day&&dfCap(l)>0; +let SOLC=null; +function solRoutes(){const k=S.day+'|'+S.links.length+'|'+S.links.reduce((n,l)=>n+(l.ch||[]).length,0);if(SOLC&&SOLC.s===S&&SOLC.k===k)return SOLC.v; + const f=FIN.filter(c=>S.pops[c]),v=[];if(S.links.some(ownGlass))for(let i=0;iS.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].lat&&b.mood>=50&&reqOk(b)).length; +function charterCard(){if(S.scn||S.mode!=='normal')return ''; + if(!S.chartSet&&S.day<=CHARTER_DAYS)return `
${tr('specialist.pick_a_charter')}
${tr('specialist.what_kind_of_network_are_you',{n:CHARTER_DAYS-S.day})}
${Object.entries(CHARTERS).map(([k,C])=>`
${C.i} ${tr(C.n)}
${tr(C.d,{p:Math.round((LAT_PAY-1)*100),r:SOL_ROUTES,c:SOL_CUST})}
${btn(charter()===k?tr('specialist.keep_it'):tr('specialist.pick'),'charter',{k},k==='global'?'ghost sm':'pink sm')}
`).join('')}
`; + if(charter()!=='boutique')return ''; + if(S.solWon)return `
⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.won_on_date_your_own_glass',{date:dateStr(S.solWon)})}
`; + const r=solRoutes();return `
⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.routes_r_of_n_beat_the',{r:Math.min(r.length,SOL_ROUTES),n:SOL_ROUTES,c:Math.min(solCust(),SOL_CUST),m:SOL_CUST})}
${r.slice(0,SOL_ROUTES).map(x=>`
✓ ${CITY[x.a].name} ⇄ ${CITY[x.b].name}: ${tr('common.ms_ms_one_way',{ms:x.o.toFixed(1)})} < ${x.l.toFixed(1)}
`).join('')}
`;} +// Once a day: seats expire or call, and the boutique checks its win. +function specDay(d){if(S.seatOff&&S.seatOff.exp<=d)S.seatOff=null; + if(!S.seatOff&&!S.scn&&S.mode!=='puzzle'&&lvl()>=SEAT_LV&&hstr(S.asn+'|seatcall|'+d)%SEAT_ODDS===0)seatConf(null); + if(charter()==='boutique'&&!S.solWon&&solRoutes().length>=SOL_ROUTES&&solCust()>=SOL_CUST){S.solWon=Math.max(1,d);track('win_sol');toast(`⚡ ${tr('specialist.speed_of_light')}
${tr('specialist.your_own_glass_beats_every_leased')}`,'goal');sfx('coin');checkBadges();}} +// Saves: the charter, demo orders, a seat on offer and the boutique's win. Old saves are Global backbone, picked. +function specSanitize(s){s.charter=s.charter==='boutique'&&s.mode==='normal'&&!s.scn?'boutique':'global';s.chartSet=s.chartSet===false&&s.day<=CHARTER_DAYS?false:true; + const dm={};if(s.demo&&typeof s.demo==='object'&&!Array.isArray(s.demo))for(const key of Object.keys(s.demo).slice(0,64)){const [k,id]=key.split(':');if(demoItem(k,id)&&Number.isFinite(+s.demo[key]))dm[key]=Math.round(+s.demo[key]);}s.demo=dm; + const o=s.seatOff;s.seatOff=o&&typeof o==='object'&&typeof o.name==='string'&&seatRoute(o.name)&&seatRoute(o.name)[0]===o.a&&seatRoute(o.name)[1]===o.b?{a:o.a,b:o.b,name:o.name,km:seatKm(o.a,o.b),exp:num(o.exp,0)}:null; + s.solWon=Number.isFinite(+s.solWon)&&+s.solWon>0?Math.round(+s.solWon):0; + for(const l of s.links)if(l.seat!==undefined){if(l.seat===true&&l.kind==='df'&&l.own&&l.sub)l.pairs=Math.max(1,Math.min(Math.max(...SEAT_N),l.pairs|0));else delete l.seat;} + for(const b of [...s.biz,...s.offers])if(b.spot!==undefined){const x=b.spot;if(x&&typeof x==='object'&&own(SPOT_W,x.k))b.spot={k:x.k,n:num(x.n,0)};else delete b.spot;}} diff --git a/src/game/60-features/60-share-card.js b/src/game/60-features/60-share-card.js index 9f01726..1b86351 100644 --- a/src/game/60-features/60-share-card.js +++ b/src/game/60-features/60-share-card.js @@ -17,6 +17,7 @@ function shareCanvas(){const Wc=1200,Hc=630,cv=document.createElement('canvas'); // stats const got=BADGES.filter(b=>S.ach&&S.ach[b.id]!==undefined),rk={l:0,e:1,r:2,c:3},lv=b=>bvar(S.achP&&S.achP[b.id]).lv,top=got.slice().sort((a,b)=>rk[a.r]-rk[b.r]||lv(b)-lv(a)).slice(0,8); const rows=[[tr('common.peak_traffic'),fmtG(S.stats.peak||0)],[tr('common.peered'),pct(R.peerShare||0)],[tr('common.pops'),tr('share_card.n_in_r_regions',{n:Object.keys(S.pops).length,r:regionsCount()})],[tr('common.links'),String(S.links.length)],[tr('common.customers'),String(S.biz.length)],[tr('common.incidents_survived'),String(S.stats.survived||0)],[tr('common.shark_bites'),String(S.stats.sharks||0)],[tr('common.badges'),`${got.length}/${BADGES.length}`]]; + if(S.solWon)rows.unshift(['⚡ '+tr('specialist.speed_of_light'),dateStr(S.solWon)]); 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. diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 9b4230a..a625c42 100644 --- a/src/game/60-features/80-new-game.js +++ b/src/game/60-features/80-new-game.js @@ -1,6 +1,6 @@ function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, ltv:2,t1v:3,auV:1,ops:opsNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, - done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{},rules:makeRules('oncall')}; + 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'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0}; } diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index d83a3a8..434d745 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -83,6 +83,7 @@ function sanitize(s){ three Normal presets, unchanged (its validated mods kept). So an edited or imported save cannot stop the clock or print money. */ {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} + specSanitize(s); 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;} function migrate(s){sanitize(s); diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index e98bdaa..db11458 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -45,4 +45,4 @@ function waveRoute(a,b,mult,border){const cabs=cablesOk(a,b),sub=isSub(a,b);let function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)return landMult(a,b)>1?`

${landWhy(a,b)}

`:'';const wr=waveRoute(a,b,1,false); const opts=(sub?[]:[{v:'land',l:`${tr('common.overland')} ${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} ${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · '+tr('geography_and_latency.old_cuts_often'):''}`}))); return `

${tr('common.route')}

${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}
${wr&&wr.cab?`

${esc(CAB[wr.cab].blurb)} ${tr('geography_and_latency.all_your_waves_on_one_cable')}

`:''}`;} -function bestLat(a,b){const ls=S.links.filter(l=>!linkDown(l));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]!linkDown(l)&&(!f||f(l)));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]i<=RG[S.pops[c]?(S.pops[c].rgen||0):0].maxLT);} function waveNeed(i){const g=RG.find(r=>r.maxLT>=i);return g?tr('sites_and_service.pn_routers',{pn:g.pn}):'?';} function routerModels(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1; - return `
${RG.map((M,i)=>{if(i===g)return '';const why=modelFits(c,i),lk=M.lvl>lvl(); - return `
${esc(M.n)} ${M.pn} · ${tr('sites_and_service.n_ports',{n:M.ports})} · ${fmtG(M.cap)} · ${tr('sites_and_service.boots_in_n_min',{n:M.boot})}${M.flaky?' · '+tr('common.crashes_more'):''}
${esc(M.blurb)}
${why?`
${esc(why)}
`:''}
${btn(lk?tr('sites_and_service.level_n',{n:M.lvl}):tr('sites_and_service.swap_cost_mo_mo',{cost:fmt$(swapCost(c,i)),mo:fmt$(M.mo*rt)}),'upRouter',{city:c,g:i},'sm',lk||!!why||S.cash`;}).join('')}
`;} + return `
${RG.map((M,i)=>{if(i===g)return '';const why=modelFits(c,i),lk=!techOk('rg',i,M.lvl); + return `
${esc(M.n)} ${M.pn} · ${tr('sites_and_service.n_ports',{n:M.ports})} · ${fmtG(M.cap)} · ${tr('sites_and_service.boots_in_n_min',{n:M.boot})}${M.flaky?' · '+tr('common.crashes_more'):''}
${esc(M.blurb)}
${why?`
${esc(why)}
`:''}
${lk?demoBtn('rg',i,M.lvl,tr('sites_and_service.level_n',{n:M.lvl}),'sm'):btn(tr('sites_and_service.swap_cost_mo_mo',{cost:fmt$(swapCost(c,i)),mo:fmt$(M.mo*rt)}),'upRouter',{city:c,g:i},'sm',!!why||S.cash`;}).join('')}
`;} function portNote(c){const p=S.pops[c];if(!p)return '';const g=p.rgen||0;return RG[g].maxP${tr('sites_and_service.your_model_here_tops_out_at',{model:esc(RG[g].n),pn:RG[g].pn})}

`:'';} // Service: what you deliver, times how it feels. Traffic backhauled far to transit is slow, and users notice. const latSlow=c=>!!(R&&R.latF&&R.latF[c]<0.97&&R.latFar[c]); diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 3aab042..eb2c34c 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -71,6 +71,7 @@ function dayTick(){ checkGoals(); scnTick(d); confTick(d); + specDay(d); // money trouble if(S.cash<0){S.neg++;if(S.neg===1)toast(tr('day_tick.you_are_in_the_red_cancel'),'bad');} else S.neg=0; @@ -89,7 +90,10 @@ function spawnOffer(){ // 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');} + // What your network can already serve calls too, at a lower weight and the smallest size (#187). + const sp=spots(),spT=[...new Set(sp.map(s=>s.t))],bq=charter()==='boutique';for(const x of spT){types.push(x);if(x==='hft'&&bq)types.push(x,x);}if(bq&&lv>=2)types.push('hft','hft'); const t=pick(types),T=BIZ_T[t]; + if(T.lv>lv&&spT.includes(t)){spawnSpot(t,pick(sp.filter(s=>s.t===t)));return;} if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;} if(T.nni){const city=pick(fabC),prov=pick(FABS.filter(f=>f.cities.includes(city))).id,bw=pick(T.opts),others=mine.filter(c=>c!==city),city2=T.l2&&others.length?pick(others):null;if(T.l2&&!city2)return; const base=pick(BIZ_N.filter(n=>!S.usedNames.includes(n)).concat(BIZ_N)).replace(/ (Inc\.|Co\.|Ltd)$/,'');const name=tr('day_tick.name_via_fab',{name:base,fab:FAB[prov].name});useName(base); @@ -104,7 +108,7 @@ function spawnOffer(){ 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));} - let rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate; + let rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km*(T.lat?latPay():1)):T.rate; if(CITY[city].au&&!T.l2&&!T.fiber&&!T.event){rate=Math.round(rate*AU_ARPU);bw=Math.min(bw,pick(T.opts.slice(0,2)));} if(T.div&&!reqCan('diverse',{city,city2}))return; const reqs=T.div?['diverse']:T.lat?['lat']:[];if((t==='hyper'||t==='ai'||t==='gpu')&&Math.random()<0.4)reqs.push('metro');const pool=Object.keys(REQS).filter(k=>!reqs.includes(k)&&!REQS[k].only&&(!REQS[k].l2||T.l2)&&(!REQS[k].ip||!T.l2)&&reqCan(k,{city,city2})); diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 0de9fa4..0492fe1 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -26,6 +26,8 @@ const BADGES=[ {id:'giants',i:'🏭',t:tr('badges.friend_of_giants'),d:tr('badges.hold_deals_at_3_different_ai'),r:'e',ok:()=>new Set(S.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].mega).flatMap(b=>bCities(b))).size>=3}, {id:'landlord',i:'🧵',t:tr('common.trench_landlord'),d:tr('badges.lease_hundreds_of_fiber_pairs_to'),r:'e',ok:()=>S.biz.some(b=>b.type==='pairs')}, {id:'t1',i:'👑',t:tr('common.tier_1'),d:tr('badges.go_transit_free'),r:'e',ok:()=>!!S.won}, + {id:'sol',i:'⚡',t:tr('specialist.speed_of_light'),d:tr('specialist.win_as_a_low_latency_boutique'),r:'e',ok:()=>!!S.solWon}, + {id:'seat',i:'🚢',t:tr('specialist.part_owner_of_the_sea'),d:tr('specialist.take_a_seat_on_a_consortium'),r:'r',ok:()=>S.links.some(l=>l.seat)}, {id:'bait',i:'🎣',t:tr('common.shark_bait'),d:tr('badges.get_bitten_by_sharks_3_times'),r:'l',ok:()=>(st().sharks||0)>=3}, {id:'nines',i:'💎',t:tr('common.five_nines'),d:tr('badges.serve_99_5_of_demand_every'),r:'l',ok:()=>(st().clean||0)>=365}, {id:'fifty',i:'🗺️',t:tr('badges.everywhere_at_once'),d:tr('badges.have_pops_in_50_cities'),r:'l',ok:()=>Object.keys(S.pops).length>=50}, diff --git a/src/game/90-actions/85-routing-and-routers.js b/src/game/90-actions/85-routing-and-routers.js index 8883dac..f0a8041 100644 --- a/src/game/90-actions/85-routing-and-routers.js +++ b/src/game/90-actions/85-routing-and-routers.js @@ -6,7 +6,7 @@ Object.assign(ACT,{ addRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)>=RMAX)return;if(!spend(routerCost(p.rgen||0,p.routers||1)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');after();}, models:()=>{UI.models=!UI.models;renderPanel();}, rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;}p.routers--;{const back=tradeIn(p.rgen||0,1);if(back>0){S.cash+=back;toast(tr('routing_and_routers.sold_a_model_on_ebuy_price',{model:esc(RG[p.rgen||0].n),price:fmt$(back)}),'good');}}after();}, - upRouter:({city,g})=>{const p=S.pops[city];if(!p)return;g=g===undefined?mainRG(RG[p.rgen||0].cls+1):+g;if(!RG[g]||g===(p.rgen||0))return;{const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;}}if(RG[g].lvl>lvl()){toast(tr('routing_and_routers.model_unlocks_at_customer_level_lv',{model:esc(RG[g].n),lv:RG[g].lvl}),'bad');sfx('err');return;} + upRouter:({city,g})=>{const p=S.pops[city];if(!p)return;g=g===undefined?mainRG(RG[p.rgen||0].cls+1):+g;if(!RG[g]||g===(p.rgen||0))return;{const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;}}if(!techOk('rg',g,RG[g].lvl)){toast(tr('routing_and_routers.model_unlocks_at_customer_level_lv',{model:esc(RG[g].n),lv:RG[g].lvl}),'bad');sfx('err');return;} const rt=p.routers||1,old=p.rgen||0;if(p.rupDay===S.day){toast(tr('routing_and_routers.the_new_routers_in_city_are',{city:CITY[city].name}),'bad');sfx('err');return;}const back=tradeIn(old,rt);if(!spend(swapCost(city,g)))return;p.rgen=g;p.rupDay=S.day;if(back>0)toast(tr('routing_and_routers.sold_the_old_model_on_ebuy',{model:esc(RG[old].n),price:fmt$(back)}),'good'); if(rt===1&&popIdle(city))toast(tr('routing_and_routers.new_router_in_city_swapped_before',{city:CITY[city].name}),'good'); else if(rt===1){const sl=slowBoot(city),dd=sl?3:1;p.down=Math.max(p.down||0,S.day+dd);addInc({type:'maint',ref:city,until:S.day+dd,msg:sl?tr('routing_and_routers.swapping_the_only_router_in_city',{city:CITY[city].name,model:RG[g].n,how:pick(SLOW_BOOT),n:dd}):tr('routing_and_routers.swapping_the_only_router_in_city_d5b5',{city:CITY[city].name,model:RG[g].n}),cost:0});toast(`${tr('routing_and_routers.maintenance_window_in_city',{city:CITY[city].name})}
${sl?tr('routing_and_routers.one_router_and_this_one_takes',{n:dd}):tr('routing_and_routers.one_router_means_downtime_during_the')}`,'bad');} diff --git a/src/game/90-actions/86-specialist.js b/src/game/90-actions/86-specialist.js new file mode 100644 index 0000000..9737a11 --- /dev/null +++ b/src/game/90-actions/86-specialist.js @@ -0,0 +1,11 @@ +Object.assign(ACT,{ + demoAsk:({k,id})=>{const it=demoItem(k,id);if(!it||!demoCan(it.lvl)||demoAt(k,id)!==null)return;S.demo=S.demo||{};const at=S.day+leadDays(DEMO_DAYS);S.demo[k+':'+id]=at; + toast(tr('specialist.the_vendor_ships_a_demo_name',{name:esc(it.n),n:at-S.day,p:Math.round((DEMO_MUL-1)*100)}),'good');after();}, + seatBuy:({n})=>{const o=S.seatOff;n=+n;if(!o||o.exp<=S.day||!SEAT_N.includes(n))return;const miss=[o.a,o.b].filter(c=>!S.pops[c]),cost=seatCost(o.km,n)+miss.reduce((x,c)=>x+popCost(c),0);if(!spend(cost))return; + for(const c of miss)S.pops[c]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}; + const id=uid(),days=seatDays(o.km);S.links.push({id,a:o.a,b:o.b,kind:'df',own:true,sub:true,seat:true,seaDesign:'standard',sys:'roadm',ch:[],km:o.km,cable:null,cname:o.name,mo:seatMo(o.km,n),trench:'seat:'+id,cut:0,day:S.day,ready:S.day+days,spares:false,pairs:n,paid:seatCost(o.km,n)}); + S.seatOff=null;S.stats.seats=(S.stats.seats||0)+1;UI.sel={type:'link',id}; + toast(tr('specialist.you_own_n_fiber_pairs_on',{n,name:esc(o.name),a:CITY[o.a].name,b:CITY[o.b].name,d:days}),'goal');sfx('build');after();}, + seatNo:()=>{S.seatOff=null;after();}, + charter:({k})=>{if(!own(CHARTERS,k)||S.chartSet||S.scn||S.mode!=='normal')return;S.charter=k;S.chartSet=true;toast(tr('specialist.charter_signed_name',{name:tr(CHARTERS[k].n)}),'good');after();}, +}); diff --git a/src/game/90-actions/87-fiber-and-hardware.js b/src/game/90-actions/87-fiber-and-hardware.js index d51e5ce..46e3bad 100644 --- a/src/game/90-actions/87-fiber-and-hardware.js +++ b/src/game/90-actions/87-fiber-and-hardware.js @@ -1,7 +1,7 @@ Object.assign(ACT,{ dfMode:({m})=>{UI.lmode=m;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, seaPackage:({k})=>{if(!own(SUB_UPGRADES,k))return;UI['sea'+k]=!UI['sea'+k];if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, - subUpgrade:({id,k})=>{const l=S.links.find(l=>l.id===id);if(!l||l.kind!=='df'||!l.own||!l.sub||!own(SUB_UPGRADES,k)||lvl()<4||l['sub'+k]!==undefined)return;if(!spend(subUpgradeCost(l,k)))return;l.paid=(l.paid>0?l.paid:ownCabCost(l.km))+subUpgradeCost(l,k);l['sub'+k]=Math.max(S.day,l.ready||0)+leadDays(SUB_UPGRADES[k].days);after();}, + subUpgrade:({id,k})=>{const l=S.links.find(l=>l.id===id);if(!l||l.kind!=='df'||!l.own||!l.sub||l.seat||!own(SUB_UPGRADES,k)||lvl()<4||l['sub'+k]!==undefined)return;if(!spend(subUpgradeCost(l,k)))return;l.paid=(l.paid>0?l.paid:ownCabCost(l.km))+subUpgradeCost(l,k);l['sub'+k]=Math.max(S.day,l.ready||0)+leadDays(SUB_UPGRADES[k].days);after();}, seaDesign:({v})=>{if(!own(SEA_DESIGNS,v))return;UI.seaDesign=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, ownCab:()=>{UI.lmode='df';UI.dfSrc='cable';UI.seaDesign='standard';UI.seaterminal=UI.seaengineering=false;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, dfSrc:({v})=>{UI.dfSrc=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, @@ -14,8 +14,8 @@ Object.assign(ACT,{ S.stats.ownCab=(S.stats.ownCab||0)+1;UI.dfSrc='lease';closeModal();UI.sel={type:'link',id}; toast(tr('fiber_and_hardware.the_ship_sets_sail_name_your',{ship,name:cname,km:km.toLocaleString(),a:CITY[a].name,b:CITY[b].name,n:days}),'goal');sfx('build');after();}, orderDf:()=>{const p=UI.pending;if(!p)return;const {a,b}=p;if(!dfAllowed(a,b))return;const sc=isSub(a,b)?subDfCable(a,b):null,km=sc?sc.km:kmBetween(a,b); - const own=UI.dfSrc==='build'&&lvl()>=3&&!sc,sys=DF_SYS[UI.dfSys]&&DF_SYS[UI.dfSys].lvl<=lvl()?UI.dfSys:'lite';if(lvl()<2)return; - const up=(own?dfBuildCost(km):0)+DF_SYS[sys].cost+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return; + const own=UI.dfSrc==='build'&&!sc,sys=DF_SYS[UI.dfSys]&&techOk('sys',UI.dfSys,DF_SYS[UI.dfSys].lvl)?UI.dfSys:'lite';if(lvl()<2)return; + const up=(own?digCost(km):0)+sysCost(sys)+ampCount(km)*AMP_COST+(S.pops[b]?0:popCost(b));if(!spend(up))return; if(!S.pops[b])S.pops[b]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}; const sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'),id=uid(); const l={id,a,b,kind:'df',own,sys,ch:[],km,sub:!!sc,cable:sc?sc.cid:null,mo:own?Math.round(km*0.15):dfLeaseMo(km),trench:sc?'cab:'+sc.cid:id,cut:0,day:S.day,ready:S.day+(own?dfBuildDays(km):leadDays(IRU_DAYS)),spares:false}; @@ -27,10 +27,10 @@ Object.assign(ACT,{ addCh:({id,o})=>{const l=S.links.find(x=>x.id===id),O=OPT[o];if(!l||!O||l.kind!=='df')return;const why=chWhy(l,o);if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:O.n,why:esc(why)}),'bad');sfx('err');return;}if(!portGate(l.a,1)||!portGate(l.b,1))return;const sp=spareN(o)>0;if(!spend(chCost(l,o)))return;if(sp)S.spares[o]--;(l.ch=l.ch||[]).push(o);floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,`+${O.n}`,'#FF4F9A');after();}, rmCh:({id,o})=>{const l=S.links.find(x=>x.id===id);if(!l||!OPT[o])return;const i=(l.ch||[]).lastIndexOf(o);if(i<0)return;l.ch.splice(i,1);S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('fiber_and_hardware.optic_to_spares',{optic:OPT[o].n}),'#7B61FF');after();}, hwLock:()=>{if(hwLock())return;const c=hwLockCost();if(!spend(c))return;S.hw=S.hw||{};S.hw.lock={until:S.day+HW_LOCK_DAYS,mul:hwTrend(S.day)};toast(tr('fiber_and_hardware.prices_locked_until_date_your_vendor',{date:dateStr(S.hw.lock.until)}),'good');after();}, - buySpare:({o})=>{if(!OPT[o]||OPT[o].lvl>lvl()||spareN(o)>=64)return;if(!spend(optCost(o)))return;S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;sfx('build');after();}, + buySpare:({o})=>{if(!OPT[o]||!techOk('opt',o,OPT[o].lvl)||spareN(o)>=64)return;if(!spend(optCost(o)))return;S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)+1;sfx('build');after();}, sellSpare:({o})=>{if(!OPT[o]||spareN(o)<1)return;S.spares[o]--;const v=spareValue(o);S.cash+=v;toast(tr('fiber_and_hardware.sold_a_spare_optic_on_ebuy',{optic:OPT[o].n,price:fmt$(v),p:pct(SPARE_RESALE)}),'good');sfx('coin');after();}, addPair:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||!isRdm(l.sys)||l.ready>S.day)return;const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return;if((l.ch||[]).length+soldSlots(l){const l=S.links.find(x=>x.id===id),to=l&&sysNext(l);if(!to||DF_SYS[to].lvl>lvl())return;if(!spend(sysUpCost(l)))return;l.sys=to;if(l.ready<=S.day){l.eqDown=S.day+1;toast(tr('fiber_and_hardware.line_system_swap_all_channels_are'),'bad');}after();}, + upSys:({id})=>{const l=S.links.find(x=>x.id===id),to=l&&sysNext(l);if(!to||!techOk('sys',to,DF_SYS[to].lvl))return;if(!spend(sysUpCost(l)))return;l.sys=to;if(l.ready<=S.day){l.eqDown=S.day+1;toast(tr('fiber_and_hardware.line_system_swap_all_channels_are'),'bad');}after();}, spares:({id})=>{const l=S.links.find(x=>x.id===id);if(!l)return;l.spares=!l.spares;sfx('click');after();}, crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.ready<=S.day+1)return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(S.day+1,l.ready-30*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('fiber_and_hardware.more_crews_on_site_construction_is',saved,{n:saved}),'good');after();}, addGen:({city})=>{const p=S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,tr('common.generator'),'#FF8A3D');after();}, diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 32e9458..c92ff51 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -13,12 +13,12 @@ function dfAllowed(a,b){if(isSub(a,b))return !!subDfCable(a,b);return cnCity(a)= for free (only the regen sites' transponders are new), or you sell it on eBuy for part of the price. */ const SPARE_RESALE=0.4,spareN=o=>(S&&S.spares&&S.spares[o])|0,spareValue=o=>Math.round(optCost(o)*SPARE_RESALE); function chCost(l,o){const r=REGEN_CH*(l.regen|0);return Math.round(optCost(o)*(spareN(o)>0?r:1+r));} -function optCost(o){return Math.round(OPT[o].cost*hwMul('opt')*(S&&S.ev&&S.ev.tariff>S.day?1.4:1));} +function optCost(o){return Math.round(OPT[o].cost*techMul(OPT[o].lvl)*hwMul('opt')*(S&&S.ev&&S.ev.tariff>S.day?1.4:1));} // Line systems upgrade in place: Rainbow → ROADMaster → C+L. Every lit pair gets the new gear. -const sysNext=l=>l.sys==='lite'?'roadm':l.sys==='roadm'?'cl':null,sysUpCost=l=>{const t=sysNext(l);return t?DF_SYS[t].cost*(t==='cl'&&l.own?Math.max(1,l.pairs|0):1):0;}; +const sysNext=l=>l.sys==='lite'?'roadm':l.sys==='roadm'?'cl':null,sysUpCost=l=>{const t=sysNext(l);return t?sysCost(t)*(t==='cl'&&l.own?Math.max(1,l.pairs|0):1):0;}; function pairBtn(l){if(!l.own||!isRdm(l.sys)||l.ready>S.day)return '';const n=Math.max(1,l.pairs|0);if(n>=pairsMax(l))return `${tr('action_helpers.n_fiber_pairs_lit_the_trench',{n})}`; const full=(l.ch||[]).length+soldSlots(l)>=chMax(l),c=pairCost(l);return btn(l.sub?tr('action_helpers.light_fiber_pair_n_price',{n:n+1,price:fmt$(c)}):tr('action_helpers.light_fiber_pair_n_price_mo',{n:n+1,price:fmt$(c),mo:fmt$(ampCount(l.km)*AMP_MO)}),'addPair',{id:l.id},full?'pink sm':'ghost sm',!full||S.cashlvl())return tr('action_helpers.unlocks_at_customer_level_n',{n:O.lvl});if(O.sys==='roadm'&&!isRdm(l.sys))return tr('action_helpers.needs_a_roadmaster_9000_line_system');if(!optMode(o,l)){const mx=optModes(o,l).at(-1)[1];if(l.sub&&l.own)return tr('action_helpers.this_channel_reaches_max_km_on',{max:mx.toLocaleString(),span:spanKm(l).toLocaleString()});return tr('action_helpers.too_far_even_at_its_slowest',{span:spanKm(l).toLocaleString(),max:mx.toLocaleString()});} +function chWhy(l,o){const O=OPT[o];if(!techOk('opt',o,O.lvl))return tr('action_helpers.unlocks_at_customer_level_n',{n:O.lvl});if(O.sys==='roadm'&&!isRdm(l.sys))return tr('action_helpers.needs_a_roadmaster_9000_line_system');if(!optMode(o,l)){const mx=optModes(o,l).at(-1)[1];if(l.sub&&l.own)return tr('action_helpers.this_channel_reaches_max_km_on',{max:mx.toLocaleString(),span:spanKm(l).toLocaleString()});return tr('action_helpers.too_far_even_at_its_slowest',{span:spanKm(l).toLocaleString(),max:mx.toLocaleString()});} 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].cls``).join('')+(innerWidth<760?``:''); let h=''; if(UI.left==='goals'){ - h+=scnCard()+lvlCard()+t1Card(); + h+=charterCard()+scnCard()+lvlCard()+t1Card(); const cur=GOALS.find(g=>S.done[g.id]===undefined); 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'){ {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(); + h+=confSection()+seatSection(); {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)} + 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)}`:''}
${spotWhy(o)}${bRisk(o)}${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(', ')})}
`}
`;} }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',{},'')}
`; diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index b816232..3450c4c 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -76,7 +76,7 @@ function cityPanel(c){
${tr('common.forwarding_chip')}${esc(G.chip)}
${tr('common.boot_time')}${slowBoot(c)?`${tr('city_panel.n_min_a_slow_one',{n:bootMin(c)})}`:tr('city_panel.n_min',{n:bootMin(c)})}
${slowBoot(c)?`

${tr('city_panel.this_chassis_takes_forever_to_boot')}

`:''}
${tr('common.forwarding_load')}${fmtG(nl)} / ${fmtG(nc)}
${nl>=nc*0.95?`

${tr('city_panel.maxed_out_traffic_here_is_being')}

`:''} -
${N?btn(N.lvl>lvl()?tr('city_panel.model_level_lv',{model:esc(N.n),lv:N.lvl}):tr('city_panel.upgrade_to_model_cost_mo_mo',{model:esc(N.n),cost:fmt$(swapCost(c,Ni)),mo:fmt$(N.mo*rt)}),'upRouter',{city:c,g:Ni},'pink',N.lvl>lvl()||S.cash=RCAGE?CAGE_MO:0))}),'addRouter',{city:c},'',S.cash1?btn(tr('common.remove_one'),'rmRouter',{city:c},'ghost sm'):''}
+
${N?(!techOk('rg',Ni,N.lvl)?demoBtn('rg',Ni,N.lvl,tr('city_panel.model_level_lv',{model:esc(N.n),lv:N.lvl}),'pink'):btn(tr('city_panel.upgrade_to_model_cost_mo_mo',{model:esc(N.n),cost:fmt$(swapCost(c,Ni)),mo:fmt$(N.mo*rt)}),'upRouter',{city:c,g:Ni},'pink',S.cash=RCAGE?CAGE_MO:0))}),'addRouter',{city:c},'',S.cash1?btn(tr('common.remove_one'),'rmRouter',{city:c},'ghost sm'):''}
${rt>=RCAGE&&rt${tr('city_panel.the_standard_cage_holds_n_routers',{n:RCAGE,mo:fmt$(CAGE_MO)})}

`:''}${rt>=RMAX?`

${tr('city_panel.this_pop_has_the_most_routers',{n:RMAX})}

`:''}${rt>RCAGE?`
${tr('city_panel.cage_extension')}${fmt$(cageMo(rt))}/mo
`:''} ${UI.models?routerModels(c):''} ${N||UI.models?`

${(p.rgen||0)>0?tr('city_panel.prices_include_p_back_for_the',{p:fmt$(tradeIn(p.rgen||0,rt))})+' ':''}${p.rupDay===S.day?tr('city_panel.new_routers_went_in_today_the')+' ':''}${rt>1?tr('city_panel.rolling_upgrade_one_router_at_a'):tr('city_panel.with_one_router_the_upgrade_needs')}

`:''} diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index e95310b..47c95d0 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -102,29 +102,29 @@ function dfPanel(l){ h+=`

${l.own?tr('common.under_construction'):tr('common.being_spliced')}

${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}${tr('common.n_days_left',{n:l.ready-S.day})}
${l.own?`
${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',l.ready<=S.day+1||S.cash`:''}

${tr('link_panels.you_can_pre_install_optics_now')}

`;} else if(inc&&linkDown(l))h+=`

${tr('common.dark_6bf5')}

${esc(inc.msg)}

${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; h+=`

${tr('common.capacity')}

${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${fmtG(load)} / ${fmtG(cap)}
- ${l.own&&l.sub?`
${tr('common.cable_design')}${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}
`:''} + ${seatPanel(l)}${l.own&&l.sub?`
${tr('common.cable_design')}${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}
`:''}
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${tr('link_panels.n_amp_huts',{n:amps})}${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}
${!bld&&!(l.ch||[]).length?`

${tr('link_panels.this_fiber_is_dark_add_optics')}

`:''}
`; 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')}

`}
`;} h+=`

${tr('common.optics')}

${tr('link_panels.each_channel_is_a_pair_of')}

`; - if(l.own&&l.sub)h+=subUpgradePanel(l); + if(l.own&&l.sub&&!l.seat)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)}
`:''}${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`;} + 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)}
`:''}${!techOk('opt',k,O.lvl)&&demoCan(O.lvl)?`
${demoBtn('opt',k,O.lvl,'','ghost sm')}
`:''}${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); h+=`

${tr('common.line_system')}

${esc(sysD.n)}${tr('link_panels.n_amplifiers',{n:amps})}
-
${tr('common.regen_sites')}${rg?tr('link_panels.n_optical_spans_of_km_km',{n:rg,km:spanKm(l).toLocaleString()}):tr('common.none')}

${tr('link_panels.a_regen_site_turns_the_light',{price:fmt$(REGEN_MO)})}

${l.sub&&l.own?`

${tr('link_panels.no_regen_sites_in_the_middle')}

`:`
${rg`}

${esc(sysD.blurb)}

${(()=>{const t=sysNext(l);if(!t)return '';const T=DF_SYS[t],c=sysUpCost(l);return T.lvl>lvl()?btn(tr('link_panels.sys_level_n',{sys:T.n,n:T.lvl}),'upSys',{id:l.id},'sm',true):btn(tr('link_panels.upgrade_to_sys_price',{sys:T.n,price:fmt$(c)}),'upSys',{id:l.id},'sm',S.cash

${tr('link_panels.spare_optics_and_amplifier_cards_on')}

`; +
${tr('common.regen_sites')}${rg?tr('link_panels.n_optical_spans_of_km_km',{n:rg,km:spanKm(l).toLocaleString()}):tr('common.none')}

${tr('link_panels.a_regen_site_turns_the_light',{price:fmt$(REGEN_MO)})}

${l.sub&&l.own?`

${tr('link_panels.no_regen_sites_in_the_middle')}

`:`
${rg`}

${esc(sysD.blurb)}

${(()=>{const t=sysNext(l);if(!t)return '';const T=DF_SYS[t],c=sysUpCost(l);return !techOk('sys',t,T.lvl)?demoBtn('sys',t,T.lvl,tr('link_panels.sys_level_n',{sys:T.n,n:T.lvl}),'sm'):btn(tr('link_panels.upgrade_to_sys_price',{sys:T.n,price:fmt$(c)}),'upSys',{id:l.id},'sm',S.cash

${tr('link_panels.spare_optics_and_amplifier_cards_on')}

`; {const sib=pairLinks(l.a,l.b).filter(x=>x!==l&&x.kind!=='vxc');h+=`

${tr('common.redundancy')}

${sib.length?tr('link_panels.other_links_between_these_cities'):tr('link_panels.this_is_the_only_link_between')}

${sib.map(x=>`
${esc(capName(x))} ${linkDown(x)?''+tr('common.cut')+'':''}${x.standby?' '+tr('common.standby')+'':''}
${(x.trench||x.id)===(l.trench||l.id)?tr('common.same_trench'):tr('common.diverse_route')}
${btn(tr('common.open'),'selLink',{id:x.id},'ghost sm')}
`).join('')}
${btn(tr('link_panels.add_parallel_link'),'addParallel',{id:l.id},'pink sm')}
`;} h+=`${trafficSection(l)}${metricSection(l)}
${btn(UI.confirm===l.id?tr('link_panels.really_give_it_up'):(l.own?tr('link_panels.abandon_the_fiber'):tr('link_panels.cancel_the_iru')),'rmLink',{id:l.id},'ghost sm')}${cabBack(l)>0?`

${tr('link_panels.giving_it_up_now_returns_price',{price:fmt$(cabBack(l))})}

`:''}
`; return h; } 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(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})}
${spotWhy(o)}${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/50-lease-swaps.js b/src/game/94-dashboard/50-lease-swaps.js index 155489b..d56dcee 100644 --- a/src/game/94-dashboard/50-lease-swaps.js +++ b/src/game/94-dashboard/50-lease-swaps.js @@ -20,10 +20,10 @@ function leaseSwaps(){const by={}; if(op&&op.n<=DF_SYS[sys].max)x.opts.push(swapOpt('iru',DF_SYS[sys].cost+ampCount(km)*AMP_COST+op.up,dfLeaseMo(km)+ampCount(km)*AMP_MO+op.mo,leadDays(IRU_DAYS),wmo));} // Dig on land, lay a cable between landing stations (even ones that share a landmass), or both. const whys=[];for(const cab of [false,true]){if(cab?!seaCab(a,b):sub)continue; - const why=cab?ownCabWhy(a,b):!dfAllowed(a,b)?tr('lease_swaps.nobody_lets_you_dig_on_this'):lvl()<3?tr('lease_swaps.digging_your_own_fiber_unlocks_at'):''; + const why=cab?ownCabWhy(a,b):!dfAllowed(a,b)?tr('lease_swaps.nobody_lets_you_dig_on_this'):lvl()<2?tr('lease_swaps.digging_your_own_fiber_unlocks_at'):''; if(why){whys.push(why);continue;}const km=cab?ownCabKm(a,b):kmBetween(a,b),op=swapOptics(km,cap,cab,'roadm'); if(!op){whys.push(tr('lease_swaps.no_optic_you_can_buy_reaches',{km:km.toLocaleString()}));continue;} - x.opts.push(swapOpt(cab?'cab':'own',(cab?ownCabCost(km):dfBuildCost(km)+DF_SYS.roadm.cost+ampCount(km)*AMP_COST)+op.up,(cab?ownCabMo(km):Math.round(km*0.15)+ampCount(km)*AMP_MO)+op.mo,cab?ownCabDays(km):dfBuildDays(km),mo));} + x.opts.push(swapOpt(cab?'cab':'own',(cab?ownCabCost(km):digCost(km)+DF_SYS.roadm.cost+ampCount(km)*AMP_COST)+op.up,(cab?ownCabMo(km):Math.round(km*0.15)+ampCount(km)*AMP_MO)+op.mo,cab?ownCabDays(km):dfBuildDays(km),mo));} x.why=x.opts.some(o=>o.k!=='iru')?'':whys.join(' '); const sv=[...x.opts.map(o=>o.save),x.lit].filter(v=>v!==undefined);if(sv.length)x.best=Math.max(...sv);return x;}) .sort((p,q)=>((p.best===undefined)-(q.best===undefined))||(q.best||0)-(p.best||0)||q.mo-p.mo);} diff --git a/src/game/95-modals/90-fiber-modals.js b/src/game/95-modals/90-fiber-modals.js index bfeed30..9e66fc7 100644 --- a/src/game/95-modals/90-fiber-modals.js +++ b/src/game/95-modals/90-fiber-modals.js @@ -7,13 +7,13 @@ function dfModalBody(a,b,km,pop){ if(landX(a,b)&&cnCity(a)===cnCity(b))return `

${tr('fiber_modals.nobody_sells_one_fiber_pair_across')}

`+sea; if(!dfAllowed(a,b))return `

${tr('fiber_modals.dark_fiber_across_the_chinese_border')}

`+sea; if(lvl()<2)return `

${tr('fiber_modals.dark_fiber_unlocks_at_customer_level')}

`+sea; - const src=UI.dfSrc==='build'&&lvl()>=3&&!sc?'build':'lease',sys=DF_SYS[UI.dfSys]&&DF_SYS[UI.dfSys].lvl<=lvl()?UI.dfSys:'lite',amps=ampCount(km); - const up=(src==='build'?dfBuildCost(km):0)+DF_SYS[sys].cost+amps*AMP_COST+pop,mo=(src==='build'?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO; + const src=UI.dfSrc==='build'&&!sc?'build':'lease',sys=DF_SYS[UI.dfSys]&&techOk('sys',UI.dfSys,DF_SYS[UI.dfSys].lvl)?UI.dfSys:'lite',amps=ampCount(km); + const up=(src==='build'?digCost(km):0)+sysCost(sys)+amps*AMP_COST+pop,mo=(src==='build'?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO; const w=Math.round(waveMo(km,false,4)); return `

${tr('fiber_modals.a_fiber_pair_of_your_own',{km:AMP_EVERY})}

-

${tr('common.the_glass')}

${btn(tr('fiber_modals.lease_an_iru_price_mo_ready_n',{price:fmt$(dfLeaseMo(km)),n:leadDays(IRU_DAYS)}),'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${sc?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):btn(lvl()>=3?tr('fiber_modals.build_your_own_price_n_days',{price:fmt$(dfBuildCost(km)),n:dfBuildDays(km)}):tr('fiber_modals.build_your_own_level_3'),'dfSrc',{v:'build'},src==='build'?'pink':'ghost',lvl()<3)}${sea?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):''}
${sc?`

${tr('fiber_modals.a_fiber_pair_on_cable_km',{cable:esc(CAB[sc.cid].name),km:sc.km.toLocaleString()})}

`:''} +

${tr('common.the_glass')}

${btn(tr('fiber_modals.lease_an_iru_price_mo_ready_n',{price:fmt$(dfLeaseMo(km)),n:leadDays(IRU_DAYS)}),'dfSrc',{v:'lease'},src==='lease'?'pink':'ghost')}${sc?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):btn(lvl()>=3?tr('fiber_modals.build_your_own_price_n_days',{price:fmt$(dfBuildCost(km)),n:dfBuildDays(km)}):tr('specialist.dig_your_own_as_a_pioneer',{price:fmt$(digCost(km)),n:dfBuildDays(km),p:Math.round((PIONEER-1)*100)}),'dfSrc',{v:'build'},src==='build'?'pink':'ghost')}${sea?btn(cabOpen()?tr('modals.lay_your_own_subsea_cable'):tr('modals.your_own_subsea_cable_tier_1'),'ownCab',{},'ghost',!!ownCabWhy(a,b)):''}
${sc?`

${tr('fiber_modals.a_fiber_pair_on_cable_km',{cable:esc(CAB[sc.cid].name),km:sc.km.toLocaleString()})}

`:''} ${src==='build'?`

${tr('fiber_modals.your_own_trench_almost_no_rent')}

`:''} -

${tr('common.line_system')}

${Object.keys(DF_SYS).map(k=>btn(`${DF_SYS[k].n} ${DF_SYS[k].lvl>lvl()?tr('fiber_modals.level_n',{n:DF_SYS[k].lvl}):fmt$(DF_SYS[k].cost)}`,'dfSys',{v:k},sys===k?'pink':'ghost',DF_SYS[k].lvl>lvl())).join('')}
+

${tr('common.line_system')}

${Object.keys(DF_SYS).map(k=>btn(`${DF_SYS[k].n} ${!techOk('sys',k,DF_SYS[k].lvl)?tr('fiber_modals.level_n',{n:DF_SYS[k].lvl}):fmt$(sysCost(k))}`,'dfSys',{v:k},sys===k?'pink':'ghost',!techOk('sys',k,DF_SYS[k].lvl))).join('')}
${Object.keys(DF_SYS).filter(k=>!techOk('sys',k,DF_SYS[k].lvl)&&demoCan(DF_SYS[k].lvl)).map(k=>`
${demoBtn('sys',k,DF_SYS[k].lvl,'','ghost sm')} ${DF_SYS[k].n}
`).join('')}

${esc(DF_SYS[sys].blurb)} ${trn('fiber_modals.plus_n_in_line_amplifier_price',amps,{price:fmt$(AMP_COST),mo:fmt$(AMP_MO)})}

${km>reachOn(OPT.tp16.reach,!!sc)?`

${tr('fiber_modals.km_km_is_longer_than_any',{km:km.toLocaleString()})}

`:''}
${tr('common.due_now')}${fmt$(up)}
${tr('common.monthly')}${tr('common.price_mo',{price:fmt$(mo)})}

${tr('fiber_modals.for_comparison_a_leased_1_6t',{price:fmt$(w)})}

diff --git a/src/i18n/en.js b/src/i18n/en.js index cf18cc8..ae7d65d 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1771,7 +1771,6 @@ "fiber_and_hardware.those_optics_need_the_regen_site":"Those optics need the regen site.
Remove the long-haul channels first, or keep the site.", "fiber_modals.a_fiber_pair_of_your_own":"A fiber pair of your own. The glass is cheap, the gear is not: you buy a line system with an amplifier every {km} km, then optics for each channel. Your gear can fail, and you fix it.", "fiber_modals.a_fiber_pair_on_cable_km":"A fiber pair on {cable}, {km} km. It shares the cable with everyone else's waves, anchors included.", -"fiber_modals.build_your_own_level_3":"Build your own level 3", "fiber_modals.build_your_own_price_n_days":"Build your own {price} · ~{n} days", "fiber_modals.dark_fiber_across_the_chinese_border":"Dark fiber across the Chinese border is not for sale. Buy a cross-border wave instead.", "fiber_modals.dark_fiber_unlocks_at_customer_level":"Dark fiber unlocks at customer level 2. You need the scale to justify buying your own optical gear.", @@ -3506,6 +3505,39 @@ "sold_out.tier_1s_never_peer_at_ixs":"Tier 1s never peer at IXs", "sold_out.wants_need_gbps_of_traffic_from":"Wants ≥ {need} Gbps of traffic from you (you send {dem})", "sold_out.wants_you_to_be_a_tier":"Wants you to be a Tier 2, or send ≥ {need} Gbps to it (you send {dem})", +"specialist.a_b_km_km_ready_in":"{a} ⇄ {b} · {km} km · about {ms} ms · ready in about {n} days", +"specialist.a_consortium_is_selling_seats_on":"A consortium is selling seats on {name}, a new cable from {a} to {b}. Your own fiber pairs on it, before you are Tier 1.", +"specialist.ask_for_a_demo_unit_p_n":"Demo unit: +{p}%, {n} days", +"specialist.charter_signed_name":"Charter signed: {name}.", +"specialist.consortium_seat":"Consortium seat", +"specialist.consortium_seat_name":"Consortium seat: {name}", +"specialist.demo_unit_ships_in_n_days":"Demo unit ships in {n} days", +"specialist.dig_your_own_as_a_pioneer":"Dig your own as a pioneer (+{p}%) · {price} · {n} days", +"specialist.global_backbone":"Global backbone", +"specialist.includes_pops_at_the_landings_price":"Includes POPs at the landings: {price}.", +"specialist.keep_it":"Keep it", +"specialist.low_latency_boutique":"Low-latency boutique", +"specialist.n_fiber_pairs":{"one":"{n} fiber pair","other":"{n} fiber pairs"}, +"specialist.part_owner_of_the_sea":"Part-owner of the sea", +"specialist.pick":"Pick", +"specialist.pick_a_charter":"Pick a charter", +"specialist.routes_r_of_n_beat_the":"Finance routes faster on your own glass than any leased path: {r}/{n} · paying latency customers: {c}/{m}", +"specialist.speed_of_light":"Speed of Light", +"specialist.spotted_your_broadband_in_a_one":"They spotted your broadband in {a}, one of the big eyeball cities.", +"specialist.spotted_your_cap_of_dark_fiber":"They spotted your {cap} of lit dark fiber between {a} and {b}.", +"specialist.spotted_your_ms_ms_a_b_path":"They spotted your {ms} ms {a}–{b} path.", +"specialist.spotted_your_two_diverse_paths_a":"They spotted your two diverse paths between {a} and {b}.", +"specialist.take_a_seat_on_a_consortium":"Take a seat on a consortium cable", +"specialist.the_classic_game_grow_everywhere_and":"The classic game: grow everywhere, customers follow your level, and Tier 1 is the win.", +"specialist.the_consortium_runs_the_cable_your":"The consortium runs the cable and its repeaters. Your pairs are yours to light with your own optics; a cut on the cable cuts them too.", +"specialist.the_vendor_ships_a_demo_name":"The vendor ships a demo {name} in {n} days. Until your level catches up, every unit costs {p}% more.", +"specialist.trading_firms_and_other_latency_customers":"Trading firms and other latency customers call more often and pay {p}% more. Win Speed of Light: beat the fastest leased latency on {r} finance routes with your own glass while {c} latency customers pay you. Tier 1 still counts.", +"specialist.what_kind_of_network_are_you":"What kind of network are you building? You can pick for {n} more days; until then you are a Global backbone.", +"specialist.win_as_a_low_latency_boutique":"Win as a low-latency boutique", +"specialist.won_on_date_your_own_glass":"Won on {date}: your own glass beat every leased path.", +"specialist.you_own_n_fiber_pairs_on":"Signed: you own {n} fiber pairs on {name}, {a} ⇄ {b}. The cable ships sail; it is ready in about {d} days.", +"specialist.your_own_fiber_pairs_on_a":"Your own fiber pairs on a new subsea cable: pay your share of the build now, light them with your own optics when it lands.", +"specialist.your_own_glass_beats_every_leased":"Your own glass beats every leased path on three finance routes, and the traders pay for it. The boutique has won!", "supply_chain.as_when_you_started":"as when you started", "supply_chain.chip_shortage_every_router_vendor_is":"Chip shortage!
Every router vendor is waiting for the same chips. New routers and router upgrades cost 40% more for {n} days. Lead time: “yes”.", "supply_chain.every_cable_ship_is_booked":"Every cable ship is booked.
Hyperscalers have hired every cable ship and trenching crew on the planet. New fiber and cable builds cost 30% more for {n} days.", From d6856591b44451879b32b2b8c6cab5b252f56a3c Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:12:44 +0100 Subject: [PATCH 121/181] Tests for specialist play, and gameplay rule F3: specialist paths only bring servable customers --- .claude/skills/gameplay-rules/SKILL.md | 1 + tests/gameplay-rules.test.js | 21 ++- tests/specialist.test.js | 170 +++++++++++++++++++++++++ 3 files changed, 191 insertions(+), 1 deletion(-) create mode 100644 tests/specialist.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index b8c5146..ecb01ed 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -62,3 +62,4 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | --- | --- | --- | | F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. | New players learn before they get punished. | | F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. | +| F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. | diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 5123f89..ce95537 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -163,7 +163,7 @@ test('N2: names are puns: no network, cable, exchange, data center, router or op const norm = (s) => String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’`]/g, "'").replace(/\s+/g, ' ').trim(); const real = new Set(REAL_NAMES.map(norm)); const names = J(`[...NETS.map(n=>['network',n.name]),...CABLES.map(c=>['cable',c.name]),...XIX.map(x=>['exchange',x.name]), - ...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n])].filter(x=>x[1])`); + ...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]])].filter(x=>x[1])`); fail('N2', names.filter(([, n]) => real.has(norm(n))).map(([k, n]) => `${k} “${n}” is a real name`), 'find a pun'); fail('N2', names.filter(([, n]) => /-ish\b/i.test(n)).map(([k, n]) => `${k} “${n}”`), 'no lazy -ish names: find a real pun, or keep the plain word'); }); @@ -343,6 +343,25 @@ test('F2: a simple build in a start city makes money within three months on On-c fail('F2', bad, 'a balance change made the start too hard; fix the balance, or argue for a new N in the gameplay-rules skill'); }); +test('F3: a specialist path only brings customers you can already serve', () => { + const g = load(); + g.ev("ACT.start({});S.cash=1e9;S.lvl=1;for(const c of ['nyc','chi','ash'])S.pops[c]=S.pops[c]||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}"); + g.ev("S.links.push({id:'w',a:'nyc',b:'chi',kind:'wave',tier:2,km:kmBetween('nyc','chi'),cut:0,mo:0},{id:'d',a:'chi',b:'ash',kind:'df',own:true,sys:'roadm',ch:['zr4','zr4','zr4','zr4'],km:kmBetween('chi','ash'),sub:false,cable:null,mo:0,trench:'d',cut:0,day:0,ready:0,spares:false},{id:'e',a:'nyc',b:'ash',kind:'df',own:true,sys:'roadm',ch:['zr4'],km:kmBetween('nyc','ash'),sub:false,cable:null,mo:0,trench:'e',cut:0,day:0,ready:0,spares:false});compute()"); + const Jg = (x) => JSON.parse(g.ev(`JSON.stringify(${x})`)); + const sp = Jg('spots()'); + assert.ok(sp.length > 0, 'F3: the reference network is spotted'); + const bad = []; + for (const s of sp) { + const T = Jg(`BIZ_T.${s.t}`); + if (!(T.lv > 1)) bad.push(`${s.t} needs no spotting at level 1`); + if (![s.a, s.b].filter(Boolean).every((c) => g.ev(`!!S.pops['${c}']`))) bad.push(`${s.t} names a city without a POP`); + if (s.k === 'lat' && !(g.ev(`bestLat('${s.a}','${s.b}')<=latMaxOf('${s.a}','${s.b}')`))) bad.push(`${s.t} ${s.a}–${s.b} is too slow`); + if (s.k === 'df' && !(s.n >= T.opts[0] * 0.75)) bad.push(`${s.t} ${s.a}–${s.b} asks for far more than the fiber carries`); + } + fail('F3', bad, 'spots0() must only name what the network can serve, or nearly'); + assert.deepEqual(g.errors, []); +}); + test('no page errors while checking the rules', () => { assert.deepEqual(errors, []); }); diff --git a/tests/specialist.test.js b/tests/specialist.test.js new file mode 100644 index 0000000..f877d43 --- /dev/null +++ b/tests/specialist.test.js @@ -0,0 +1,170 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Specialist play (#187, #173): capability offers, vendor demo units, pioneer fiber, consortium seats, charters. +const start = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"; +const pop = (c) => `S.pops['${c}']=S.pops['${c}']||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};`; +const df = (id, a, b, ch, own = true) => `S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:${own},sys:'roadm',ch:${JSON.stringify(ch)},km:kmBetween('${a}','${b}'),sub:false,cable:null,mo:0,trench:'${id}',cut:0,day:0,ready:0,spares:false});`; +// Spawn offers until one of a type shows up (or give up), with everything else cleared out of the way. +const spawnUntil = (ev, type, n = 400) => ev(`(()=>{for(let i=0;i<${n};i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>o.type==='${type}');if(o)return JSON.stringify(o);}return 'null';})()`); + +test('#187 a capability brings its customers before the level does, only when you can serve them', () => { + const { ev, dom, errors } = load(); + ev(start); + ev(`S.lvl=1;${pop('nyc')}${pop('chi')}compute()`); + assert.equal(ev("spots().filter(s=>s.t==='hft').length"), 0, 'no low-latency path, no trading firm'); + assert.equal(JSON.parse(spawnUntil(ev, 'hft')), null, 'level 1 alone never brings HFT'); + ev("S.links.push({id:'w',a:'nyc',b:'chi',kind:'wave',tier:2,km:kmBetween('nyc','chi'),cut:0,mo:0});compute()"); + const s = JSON.parse(ev("JSON.stringify(spots().find(s=>s.t==='hft'))")); + assert.deepEqual([s.a, s.b].sort(), ['chi', 'nyc']); + const o = JSON.parse(spawnUntil(ev, 'hft')); + assert.ok(o, 'the trading firm calls'); + assert.equal(o.bw, ev("BIZ_T.hft.opts[0]"), 'at the smallest size'); + assert.deepEqual(o.reqs, ['lat']); + assert.ok(o.latMax >= s.n, 'and the path you have already meets it'); + assert.equal(o.spot.k, 'lat'); + ev("ACT.leftTab({t:'deals'});renderAll()"); + assert.match(dom.window.document.body.innerHTML, /They spotted your [\d.]+ ms (New York|Chicago)–(New York|Chicago) path/); + // Lit dark fiber with enough capacity brings AI interconnects (level 4) to a level 3 network; not the bigger DCI. + ev(`S.lvl=3;${df('d', 'nyc', 'chi', ['zr4', 'zr4'])}compute()`); + const t = JSON.parse(ev("JSON.stringify([...new Set(spots().map(s=>s.t))])")); + assert.ok(t.includes('ai'), 'AI training interconnect'); + assert.ok(!t.includes('hyper'), 'not a hyperscaler DCI three times its size'); + assert.ok(!t.includes('hft'), 'level 3 gets HFT anyway: no spotting needed'); + ev("S.lvl=5"); + assert.ok(!ev("spots().some(s=>s.t==='ai')"), 'once the level brings them, they are ordinary offers'); + assert.equal(ev("(()=>{S.rules.gates='open';const n=spots().length;S.rules.gates='ladder';return n;})()"), 0, 'open gates need no spotting'); + assert.deepEqual(errors, []); +}); + +test('#187 vendor demo units: one level ahead, a wait and a markup', () => { + const { ev, errors } = load(); + ev(start); + ev('S.lvl=1'); + assert.equal(ev("RG[1].lvl"), 2); + assert.equal(ev("techOk('rg',1,2)"), false); + ev("ACT.demoAsk({k:'rg',id:2})"); + assert.equal(ev("demoAt('rg',2)"), null, 'never two levels ahead'); + ev("ACT.demoAsk({k:'rg',id:1})"); + const at = ev("demoAt('rg',1)"); + assert.equal(at - ev('S.day'), ev('leadDays(DEMO_DAYS)'), 'a short wait'); + ev("ACT.upRouter({city:'fra',g:1})"); + assert.equal(ev("S.pops.fra.rgen||0"), 0, 'not before it ships'); + ev(`S.day=${at}`); + assert.equal(ev("techOk('rg',1,2)"), true); + assert.equal(ev("swapCost('fra',1)"), ev("Math.round(RG[1].cost*hwMul('rt')*1.6)-tradeIn(0,1)"), '+60%'); + const cash = ev('S.cash'); + ev("ACT.upRouter({city:'fra',g:1})"); + assert.equal(ev("S.pops.fra.rgen"), 1); + assert.ok(cash - ev('S.cash') > 0); + // Optics and line systems the same way. + ev("S.lvl=2;ACT.demoAsk({k:'opt',id:'zr8'});ACT.demoAsk({k:'sys',id:'roadm'})"); + assert.ok(ev("demoAt('opt','zr8')!==null&&demoAt('sys','roadm')!==null")); + ev("S.day+=30"); + assert.equal(ev("optCost('zr8')"), ev("Math.round(OPT.zr8.cost*1.6*hwMul('opt'))")); + assert.equal(ev("sysCost('roadm')"), ev("Math.round(DF_SYS.roadm.cost*1.6)")); + ev('S.lvl=3'); + assert.equal(ev("optCost('zr8')"), ev("Math.round(OPT.zr8.cost*hwMul('opt'))"), 'list price once your level catches up'); + assert.equal(ev("demoCan(5)"), false); + assert.deepEqual(errors, []); +}); + +test('#187 pioneer fiber: dig your own before level 3, at a markup', () => { + const { ev, errors } = load(); + ev(start); + ev(`S.lvl=2;${pop('ams')}UI.dfSrc='build';UI.dfSys='lite';UI.pending={a:'fra',b:'ams'};`); + const km = ev("kmBetween('fra','ams')"); + assert.equal(ev(`digCost(${km})`), ev(`Math.round(dfBuildCost(${km})*1.6)`)); + const cash = ev('S.cash'); + ev('ACT.orderDf()'); + const l = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.kind==='df'))")); + assert.ok(l && l.own, 'your own trench'); + assert.equal(cash - ev('S.cash'), ev(`digCost(${km})+DF_SYS.lite.cost+ampCount(${km})*AMP_COST`)); + ev('S.lvl=3'); + assert.equal(ev(`digCost(${km})`), ev(`dfBuildCost(${km})`), 'no markup at level 3'); + assert.deepEqual(errors, []); +}); + +test('#173 a consortium seat: offer, pay, build, light, cut, save', () => { + const { ev, dom, errors } = load(); + ev(start); + ev("S.lvl=3;S.capDeal={at:S.day,c:'lon'};capDealTick(S.day)"); + const off = JSON.parse(ev('JSON.stringify(S.seatOff)')); + assert.ok(off && ev(`SEAT_ROUTES.lon.some(r=>r[2]===${JSON.stringify(off.name)})`), 'a capacity conference offers a seat on one of its routes'); + ev("ACT.leftTab({t:'deals'});renderAll()"); + assert.match(dom.window.document.body.innerHTML, /Consortium seat: /); + // A seat short enough to light with level 2 optics. + ev("S.lvl=2;S.seatOff={a:'syd',b:'akl',name:'Tasman Devil',km:seatKm('syd','akl'),exp:S.day+30}"); + const km = ev('S.seatOff.km'); + const cash = ev('S.cash'), popC = ev("popCost('syd')+popCost('akl')"); + ev('ACT.seatBuy({n:2})'); + assert.equal(cash - ev('S.cash'), ev(`seatCost(${km},2)`) + popC, 'your share of the build, and the landing POPs'); + const l = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.seat))")); + assert.ok(l.own && l.sub && l.pairs === 2 && l.ready > ev('S.day'), 'your own subsea glass, being laid'); + assert.equal(ev('S.seatOff'), null); + assert.equal(ev("pairsMax(S.links.find(l=>l.seat))"), 2, 'only the pairs you bought'); + // Save and load keep it. + ev('const s=migrate(JSON.parse(JSON.stringify(S)));window.__s=s'); + assert.equal(ev("__s.links.find(l=>l.seat).pairs"), 2); + // It lands and lights with your own optics. + ev(`S.day=${l.ready};S.pops.syd.rgen=S.pops.akl.rgen=1;ACT.addCh({id:'${l.id}',o:'zr4'});compute()`); + assert.ok(ev(`dfCap(S.links.find(l=>l.id==='${l.id}'))`) > 0, 'lit'); + ev(`ACT.subUpgrade({id:'${l.id}',k:'terminal'})`); + assert.equal(ev(`S.links.find(l=>l.id==='${l.id}').subterminal`), undefined, 'the consortium owns the terminals'); + // A cut on the cable cuts your share. + ev(`S.links=S.links.filter(l=>l.id==='${l.id}');eval('('+fireFailure.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')()`); + assert.ok(ev(`linkDown(S.links.find(l=>l.id==='${l.id}'))`), 'the cut takes your pairs down too'); + assert.deepEqual(errors, []); +}); + +test('#187 the Low-latency boutique: pick it on day 0, traders weigh more and pay more, Speed of Light wins', () => { + const { ev, dom, errors } = load(); + ev(start); + ev("ACT.leftTab({t:'goals'});renderAll()"); + assert.match(dom.window.document.body.innerHTML, /Pick a charter/); + ev("window.innerWidth=360;renderAll()"); + assert.match(dom.window.document.body.innerHTML, /Low-latency boutique/, 'on a phone too'); + ev("window.innerWidth=1280"); + assert.equal(ev('charter()'), 'global', 'Global backbone until you pick'); + ev("ACT.charter({k:'boutique'})"); + assert.equal(ev('charter()'), 'boutique'); + ev("ACT.charter({k:'global'})"); + assert.equal(ev('charter()'), 'boutique', 'picked once'); + // More and better-paid trading firms than a global backbone with the same network. + const count = (k) => { + const g = load(); + g.ev(start); + g.ev(`S.lvl=2;S.charter='${k}';${pop('nyc')}${pop('chi')}compute()`); + return JSON.parse(g.ev("(()=>{let n=0,r=0;for(let i=0;i<300;i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>o.type==='hft');if(o){n++;if(o.reqs.length===1)r=o.rate/(150+kmBetween(o.city,o.city2)*0.08)/BIZ_T.hft.km;}}return JSON.stringify({n,r});})()")); + }; + const gl = count('global'), bq = count('boutique'); + assert.ok(bq.n > gl.n * 1.5, `boutique traders call more (${bq.n} vs ${gl.n})`); + assert.ok(Math.abs(bq.r - 1.4) < 0.02 && Math.abs(gl.r - 1) < 0.02, 'and pay 40% more'); + // Speed of Light: three finance routes faster on your own glass than any lease, and two paying latency customers. + ev(`S.lvl=2;${pop('nyc')}${pop('chi')}${pop('ash')}${df('a', 'nyc', 'chi', ['zr4'])}${df('b', 'chi', 'ash', ['zr4'])}${df('c', 'nyc', 'ash', ['zr4'])}compute()`); + assert.equal(ev('solRoutes().length'), 3); + ev('specDay(S.day)'); + assert.equal(ev('S.solWon'), 0, 'not without paying customers'); + ev("for(const [a,b] of [['nyc','chi'],['chi','ash']])S.biz.push({id:uid(),city:a,city2:b,name:'T',type:'hft',bw:1,rate:1000,reqs:['lat'],latMax:latMaxOf(a,b),mood:100,since:0});compute();specDay(S.day)"); + assert.equal(ev('S.solWon'), Math.max(1, ev('S.day')), 'Speed of Light'); + ev('checkBadges()'); + assert.notEqual(ev("S.ach.sol"), undefined, 'and its badge'); + ev("renderAll()"); + assert.match(dom.window.document.body.innerHTML, /Won on /); + assert.deepEqual(errors, []); +}); + +test('#187 old saves load as Global backbone; scenarios ignore charters', () => { + const { ev, errors } = load(); + ev(start); + ev("const o=JSON.parse(JSON.stringify(S));for(const k of ['charter','chartSet','demo','seatOff','solWon'])delete o[k];o.links.push({id:'q',a:'fra',b:'ams',kind:'df',own:false,sub:false,seat:true,sys:'lite',ch:[],km:400,ready:0});window.__o=migrate(o)"); + assert.equal(ev('__o.charter'), 'global'); + assert.equal(ev('__o.chartSet'), true, 'no charter card for an old save'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(__o.demo)')), {}); + assert.equal(ev('__o.seatOff'), null); + assert.equal(ev("__o.links.find(l=>l.id==='q').seat"), undefined, 'a forged seat is dropped'); + ev("S.charter='boutique';S.scn={id:'x'}"); + assert.equal(ev('charter()'), 'global'); + assert.deepEqual(errors, []); +}); From c40e30234a8d66930ad0c02abaf53bbf47946db3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:12:44 +0100 Subject: [PATCH 122/181] CHANGELOG: specialist play (#187, #173) --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d2a230..77943f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. +- Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price. +- Take a seat on a new consortium subsea cable (#173). Capacity conferences offer them, and now and then a consortium calls from level 2: pay your share of the build, wait for the ship, then own one, two or four fiber pairs and light them with your own optics, your way onto your own subsea glass before Tier 1. A cut on that cable cuts your pairs too. +- Pick a charter in your first month of a Normal game: Global backbone (the game as you know it, and the default) or Low-latency boutique (#187). The boutique gets more trading firms, pays them 40% more and has its own win, Speed of Light: beat the fastest leased latency on three finance routes with your own glass while two latency customers pay you. It comes with a badge and shows on your share card. - 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. - Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. - A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, 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. From 1065630d29028ac3126f4beab0cac217a2448d73 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:38:23 +0100 Subject: [PATCH 123/181] Make the #134 exchange-name test independent of which failure the dice pick --- tests/issues.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/issues.test.js b/tests/issues.test.js index da2fa5d..6778ef4 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -1310,7 +1310,7 @@ test('#134 an exchange named after its city does not repeat the city in messages const labs = JSON.parse(ev("JSON.stringify(lagsN().filter(o=>o.k==='ix').map(o=>o.lab))")); assert.ok(labs.includes('IX.brrr Campinas LAG'), labs.join(' | ')); assert.ok(labs.some(l => / LAG in Frankfurt$/.test(l)), labs.join(' | ')); - ev("S.inc=[];eval('('+fireFailure.toString().replace('type=pick(f);}',\"type='maxpfx';}\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()"); + ev("S.inc=[];eval('('+fireFailure.toString().replace(\"if(type==='funny'){\",\"type='funny';if(type==='funny'){\").replace('type=pick(f);}',\"type='maxpfx';}\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()"); const msg = ev("S.inc.map(i=>i.msg).join(' ')"); assert.match(msg, /IX\.brrr Campinas/); assert.doesNotMatch(msg, /in Campinas/); From 826ccbef46ca77be732ccff35ac165f6b39cd0b9 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:51:35 +0100 Subject: [PATCH 124/181] Scenario playtest: goals that need the theme, tighter days, a real Anchors Away Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up (island POPs won without crossing anything). Fibre to the Basement also needs 500 Gbps served (it was won on day 2). Anchors Away: nobody sells transit in Tallinn, ships really do cut the Baltic links about three times a link-year, and the 99.5% streak no longer counts Great Firewall losses. In the Cogentle Spat, Goggle peers only once you send it eight times the usual traffic. Flood Season's terabit floods count when scrubbing or Flowspec took them. Days cut where a reference won in a tenth of the time; Stepping Stones and Mid-Atlantic Accent start with 5M; Mid-Atlantic Accent's description no longer claims Lisbon to Lagos is too long for 1.6T. --- site/i18n/de.js | 16 ++++----- site/i18n/es.js | 16 ++++----- site/i18n/fr.js | 16 ++++----- site/i18n/it.js | 16 ++++----- site/i18n/pt.js | 16 ++++----- src/game/60-features/20-scenarios.js | 33 ++++++++++++------- src/game/60-features/94-scenarios-weekly.js | 2 +- src/game/70-rules/20-exchanges.js | 4 ++- src/game/70-rules/70-sold-out.js | 3 +- .../80-simulation/80-geography-and-latency.js | 2 ++ src/game/85-incidents/20-failures.js | 12 ++++--- src/game/88-days/10-day-tick.js | 5 ++- src/game/94-dashboard/10-progress.js | 8 ++--- src/i18n/en.js | 16 ++++----- 14 files changed, 93 insertions(+), 72 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 7bbc9ff..e070d5e 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2893,16 +2893,16 @@ "progress.a_port_on_ix_brrr_manaus":"Ein Port am IX.brrr Manaus", "progress.broadband_in_city":"Breitband in {city}", "progress.carnaval_delivered_in_full":"Karneval vollständig ausgeliefert", +"progress.city_on_your_network":"{city} in deinem Netz", "progress.customer_level_lv_of_max":"Kundenlevel {lv} von {max}", "progress.days_in_a_row_at_g":"Tage am Stück mit {g} oder mehr", "progress.days_in_a_row_with_99":"Tage am Stück mit 99,5 % bedient", "progress.done_in_d_days":"Geschafft in {d} Tagen!", "progress.floods_that_got_through":"Fluten, die durchgekommen sind", -"progress.ix_brrr_ports":"IX.brrr-Ports", +"progress.ix_brrr_ports_on_your_backbone":"IX.brrr-Ports an deinem Backbone", "progress.n_of_m":"{n} von {m}", "progress.next_name_unlocks_what":"Als Nächstes: {name} schaltet {what} frei", "progress.not_tier_1_right_now_why":"Gerade nicht Tier 1: {why}.", -"progress.pop_in_city":"POP in {city}", "progress.terabit_floods_held":"Abgewehrte Terabit-Fluten", "progress.under_attack_now":"Gerade unter Beschuss", "progress.your_score_peak_traffic":"Dein Ergebnis: Spitzen-Traffic", @@ -3332,14 +3332,15 @@ "scenarios.90_days_in_a_row_with":"90 Tage am Stück mit 99,5 % der Nachfrage bedient", "scenarios.99_reach_and_150_gbps_served":"99 % Reichweite und 150 Gbps bedient", "scenarios.99_reach_and_200_gbps_served":"99 % Reichweite und 200 Gbps bedient, ohne pleitezugehen", -"scenarios.a_path_from_cape_town_to":"Ein Pfad von Kapstadt nach Kairo, POPs in Lagos und Nairobi, und 150 Gbps bedient", +"scenarios.a_path_from_cape_town_to_cairo_lagos":"Ein Pfad von Kapstadt nach Kairo, Lagos und Nairobi auch in deinem Netz, und 150 Gbps bedient", "scenarios.a_path_from_los_angeles_to":"Ein Pfad von Los Angeles nach Sydney mit 1.6T auf jedem Hop, ein Pfad von Los Angeles nach Tokio, und 150 Gbps bedient", "scenarios.a_path_from_marseille_to_singapore":"Ein Pfad von Marseille nach Singapur, und 80 Gbps zwischen Asien und dem Rest deines Netzes, 30 Tage am Stück", "scenarios.amsterdam_hosting_capital_of_europe":"Amsterdam, Hosting-Hauptstadt Europas, mitten in der Botnetz-Hochsaison. Jeder smarte Toaster, jedes Babyfon und jeder ungepatchte Kühlschrank der Welt hat sich für eine Seite entschieden, und es ist nicht deine. Alle paar Tage eine Flut, immer mehr davon im Terabit-Bereich, während auch alles andere weiter kaputtgeht. Du startest mit größerer Hardware freigeschaltet, und die wirst du brauchen.", -"scenarios.broadband_in_sydney_melbourne":"Breitband in Sydney, Melbourne, Brisbane, Adelaide und Perth, und zwei verschiedene Kabel nach Übersee", +"scenarios.broadband_in_sydney_melbourne_served":"Breitband in Sydney, Melbourne, Brisbane, Adelaide und Perth, zwei verschiedene Kabel nach Übersee, und 500 Gbps bedient", "scenarios.cape_to_cairo":"Vom Kap nach Kairo", "scenarios.cape_town_build_a_network_across":"Kapstadt. Bau ein Netz quer durch Afrika: Jede Grenze will ihre eigene Genehmigung, und die Hälfte der Stromnetze ist nicht auf deiner Seite.", "scenarios.cogentle_and_goggle_are_not_speaking":"Cogentle und Goggle reden nicht miteinander, und diesmal für immer. Kauf den billigen Transit, wenn du dich traust.", +"scenarios.connect_panama_city_to_bogota_lima":"Bogotá, Lima, Santiago und São Paulo mit Panama-Stadt verbunden, und 150 Gbps bedient", "scenarios.deliver_carnaval_in_full":"Liefere den Karneval vollständig aus", "scenarios.every_cable_through_the_red_sea":"Jedes Kabel durchs Rote Meer ist gekappt, und der Hop nach Ägypten auch. Bring Marseille trotzdem mit Singapur ins Gespräch: um Afrika herum, über Land oder andersherum um den Planeten.", "scenarios.every_ix_is_run_by_de":"Jeder IX wird von DE-KICKS betrieben", @@ -3351,9 +3352,8 @@ "scenarios.mid_atlantic_accent":"Mittelatlantischer Akzent", "scenarios.only_spatzle_ix":"Nur Spätzle-IX", "scenarios.order_and_progress":"Ordnung und Fortschritt", -"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.ponta_delgada_azores_lisbon_lagos":"Ponta Delgada auf den Azoren, mitten im Atlantik. Florida–Spanien ist einfach zu lang für eine 1.6T-Wave: direkt hinüber trägt sie nur 1.2T. Lande auf den Inseln dazwischen, starte das Licht neu, und jeder Hop läuft mit 1.6T oder besser. Lissabon–Lagos schafft 1.6T am Stück, aber teuer: über die Kanaren ist es billiger. Du startest mit freigeschalteter 1.6T-Hardware.", +"scenarios.ports_on_15_ix_brrr_exchanges_backbone":"Ports an 15 IX.brrr-Exchanges, die dein Backbone mit São Paulo verbindet, einer davon in Manaus, und 200 Gbps bedient", "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.", @@ -3366,7 +3366,7 @@ "scenarios.start_in_stuttgart_where_nobody":"Start in Stuttgart, wo niemand Transit verkauft. Erreiche das Internet nur über Peering, PNIs, Caches und deine eigene Glasfaser. Kein Transit, nirgends, niemals.", "scenarios.start_with_only_100k":"Start mit nur $100k", "scenarios.sydney_2013_the_toilet_paper_group":"Sydney, 2013. Die Toilet Paper Group hat ihre eigene Glasfaser in die Keller von Wohnhäusern verlegt, und das nationale Netz hat „Rosinenpickerei“ geschrien. Du bist dran: Lass das Nearly Broadband Network links liegen, zahl die Abgabe und sei als Erster da.", -"scenarios.tallinn_ships_drag_their_anchors":"Tallinn. Schiffe schleifen ihre Anker dreimal so oft wie üblich über die Ostseekabel.", +"scenarios.tallinn_nobody_sells_transit_anchors":"Tallinn, wo niemand Transit verkauft: dein Internet liegt jenseits des Wassers. Schiffe schleifen ihre Anker dreimal so oft wie üblich über die Ostseekabel.", "scenarios.the_cogentle_spat":"Der Cogentle-Zoff", "scenarios.transit_costs_30_more":"Transit kostet 30 % mehr", "scenarios.twice_the_failures":"Doppelt so viele Ausfälle", diff --git a/site/i18n/es.js b/site/i18n/es.js index 6c4a07f..5baa724 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2891,16 +2891,16 @@ "progress.a_port_on_ix_brrr_manaus":"Un puerto en IX.brrr Manaos", "progress.broadband_in_city":"Banda ancha en {city}", "progress.carnaval_delivered_in_full":"Carnaval entregado por completo", +"progress.city_on_your_network":"{city} en tu red", "progress.customer_level_lv_of_max":"Nivel de cliente {lv} de {max}", "progress.days_in_a_row_at_g":"Días seguidos con {g} o más", "progress.days_in_a_row_with_99":"Días seguidos con el 99,5 % servido", "progress.done_in_d_days":"¡Hecho en {d} días!", "progress.floods_that_got_through":"Inundaciones que pasaron", -"progress.ix_brrr_ports":"Puertos IX.brrr", +"progress.ix_brrr_ports_on_your_backbone":"Puertos IX.brrr en tu backbone", "progress.n_of_m":"{n} de {m}", "progress.next_name_unlocks_what":"Siguiente: {name} desbloquea {what}", "progress.not_tier_1_right_now_why":"Ahora no eres Tier 1: {why}.", -"progress.pop_in_city":"POP en {city}", "progress.terabit_floods_held":"Inundaciones de terabits contenidas", "progress.under_attack_now":"Bajo ataque ahora", "progress.your_score_peak_traffic":"Tu puntuación: tráfico pico", @@ -3330,14 +3330,15 @@ "scenarios.90_days_in_a_row_with":"90 días seguidos con el 99,5 % de la demanda servida", "scenarios.99_reach_and_150_gbps_served":"99 % de alcance y 150 Gbps servidos", "scenarios.99_reach_and_200_gbps_served":"99 % de alcance y 200 Gbps servidos sin arruinarte", -"scenarios.a_path_from_cape_town_to":"Un camino de Ciudad del Cabo a El Cairo, POPs en Lagos y Nairobi, y 150 Gbps servidos", +"scenarios.a_path_from_cape_town_to_cairo_lagos":"Un camino de Ciudad del Cabo a El Cairo, con Lagos y Nairobi también en tu red, y 150 Gbps servidos", "scenarios.a_path_from_los_angeles_to":"Un camino de Los Ángeles a Sídney con 1.6T en cada salto, un camino de Los Ángeles a Tokio, y 150 Gbps servidos", "scenarios.a_path_from_marseille_to_singapore":"Un camino de Marsella a Singapur, y 80 Gbps entre Asia y el resto de tu red durante 30 días seguidos", "scenarios.amsterdam_hosting_capital_of_europe":"Ámsterdam, capital del hosting de Europa, en plena temporada de botnets. Todas las tostadoras inteligentes, vigilabebés y frigoríficos sin parchear del planeta han elegido bando, y no es el tuyo. Una inundación cada pocos días, cada vez más en terabits, mientras todo lo demás también se rompe. Empiezas con equipo mayor desbloqueado, y lo vas a necesitar.", -"scenarios.broadband_in_sydney_melbourne":"Banda ancha en Sídney, Melbourne, Brisbane, Adelaida y Perth, y dos cables distintos al extranjero", +"scenarios.broadband_in_sydney_melbourne_served":"Banda ancha en Sídney, Melbourne, Brisbane, Adelaida y Perth, dos cables distintos al extranjero, y 500 Gbps servidos", "scenarios.cape_to_cairo":"De El Cabo a El Cairo", "scenarios.cape_town_build_a_network_across":"Ciudad del Cabo. Construye una red por África: cada frontera quiere su propio permiso, y la mitad de las redes eléctricas no están de tu parte.", "scenarios.cogentle_and_goggle_are_not_speaking":"Cogentle y Goggle no se hablan, y esta vez es para siempre. Compra el tránsito barato si te atreves.", +"scenarios.connect_panama_city_to_bogota_lima":"Bogotá, Lima, Santiago y São Paulo unidas a Ciudad de Panamá, y 150 Gbps servidos", "scenarios.deliver_carnaval_in_full":"Entrega el Carnaval por completo", "scenarios.every_cable_through_the_red_sea":"Todos los cables del Mar Rojo están cortados, y también el salto a Egipto. Consigue igualmente que Marsella hable con Singapur: rodeando África, por tierra, o dando la vuelta al planeta por el otro lado.", "scenarios.every_ix_is_run_by_de":"Todos los IX los gestiona DE-KICKS", @@ -3349,9 +3350,8 @@ "scenarios.mid_atlantic_accent":"Acento mesoatlántico", "scenarios.only_spatzle_ix":"Solo Spätzle-IX", "scenarios.order_and_progress":"Orden y Progreso", -"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.ponta_delgada_azores_lisbon_lagos":"Ponta Delgada, en las Azores, a medio camino por el Atlántico. De Florida a España es demasiado largo para una onda de 1.6T: en línea recta, lleva 1.2T. Aterriza en las islas intermedias, empieza la luz de nuevo, y cada salto va a 1.6T o más. De Lisboa a Lagos el 1.6T llega de un tirón, pero caro: las Canarias salen más baratas. Empiezas con equipo de 1.6T desbloqueado.", +"scenarios.ports_on_15_ix_brrr_exchanges_backbone":"Puertos en 15 intercambios IX.brrr que tu backbone une a São Paulo, uno de ellos en Manaos, y 200 Gbps servidos", "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.", @@ -3364,7 +3364,7 @@ "scenarios.start_in_stuttgart_where_nobody":"Empieza en Stuttgart, donde nadie vende tránsito. Llega a internet solo por peering, PNIs, cachés y tu propia fibra. Sin tránsito en ningún sitio, nunca.", "scenarios.start_with_only_100k":"Empieza con solo $100k", "scenarios.sydney_2013_the_toilet_paper_group":"Sídney, 2013. El Toilet Paper Group tendió su propia fibra hasta los sótanos de los edificios, y la red nacional gritó que escogía lo mejor. Te toca: sáltate la Nearly Broadband Network, paga el gravamen y llega primero.", -"scenarios.tallinn_ships_drag_their_anchors":"Tallin. Los barcos arrastran sus anclas sobre los cables del Báltico tres veces más a menudo de lo normal.", +"scenarios.tallinn_nobody_sells_transit_anchors":"Tallin, donde nadie vende tránsito: tu internet está al otro lado del agua. Los barcos arrastran sus anclas sobre los cables del Báltico tres veces más a menudo de lo normal.", "scenarios.the_cogentle_spat":"La riña de Cogentle", "scenarios.transit_costs_30_more":"El tránsito cuesta un 30 % más", "scenarios.twice_the_failures":"El doble de fallos", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 294d294..37a5cb3 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2891,16 +2891,16 @@ "progress.a_port_on_ix_brrr_manaus":"Un port sur IX.brrr Manaus", "progress.broadband_in_city":"Internet à domicile à {city}", "progress.carnaval_delivered_in_full":"Carnaval servi en entier", +"progress.city_on_your_network":"{city} sur votre réseau", "progress.customer_level_lv_of_max":"Niveau clients {lv} sur {max}", "progress.days_in_a_row_at_g":"Jours d’affilée à {g} ou plus", "progress.days_in_a_row_with_99":"Jours d’affilée à 99,5 % servi", "progress.done_in_d_days":"Fini en {d} jours !", "progress.floods_that_got_through":"Vagues passées", -"progress.ix_brrr_ports":"Ports IX.brrr", +"progress.ix_brrr_ports_on_your_backbone":"Ports IX.brrr sur votre backbone", "progress.n_of_m":"{n} sur {m}", "progress.next_name_unlocks_what":"Prochain : {name} débloque {what}", "progress.not_tier_1_right_now_why":"Pas Tier 1 pour l’instant : {why}.", -"progress.pop_in_city":"POP à {city}", "progress.terabit_floods_held":"Vagues térabit encaissées", "progress.under_attack_now":"Sous attaque", "progress.your_score_peak_traffic":"Ton score : pic de trafic", @@ -3330,14 +3330,15 @@ "scenarios.90_days_in_a_row_with":"90 jours d’affilée avec 99,5 % de la demande servie", "scenarios.99_reach_and_150_gbps_served":"99 % de couverture et 150 Gbps servis", "scenarios.99_reach_and_200_gbps_served":"99 % de couverture et 200 Gbps servis sans faire faillite", -"scenarios.a_path_from_cape_town_to":"Un chemin du Cap au Caire, des POP à Lagos et Nairobi, et 150 Gbps servis", +"scenarios.a_path_from_cape_town_to_cairo_lagos":"Un chemin du Cap au Caire, avec Lagos et Nairobi aussi sur votre réseau, et 150 Gbps servis", "scenarios.a_path_from_los_angeles_to":"Un chemin de Los Angeles à Sydney en 1.6T sur chaque saut, un chemin de Los Angeles à Tokyo, et 150 Gbps servis", "scenarios.a_path_from_marseille_to_singapore":"Un chemin de Marseille à Singapour, et 80 Gbps entre l’Asie et le reste de ton réseau pendant 30 jours d’affilée", "scenarios.amsterdam_hosting_capital_of_europe":"Amsterdam, capitale européenne de l’hébergement, en pleine saison des botnets. Chaque grille-pain connecté, babyphone et frigo jamais patché de la planète a choisi son camp, et ce n’est pas le tien. Une vague tous les quelques jours, de plus en plus souvent dans les térabits, pendant que tout le reste continue de casser aussi. Tu commences avec du matériel plus gros déjà débloqué, et tu en auras besoin.", -"scenarios.broadband_in_sydney_melbourne":"Internet à domicile à Sydney, Melbourne, Brisbane, Adélaïde et Perth, et deux câbles différents vers l’étranger", +"scenarios.broadband_in_sydney_melbourne_served":"Internet à domicile à Sydney, Melbourne, Brisbane, Adélaïde et Perth, deux câbles différents vers l’étranger, et 500 Gbps servis", "scenarios.cape_to_cairo":"Du Cap au Caire", "scenarios.cape_town_build_a_network_across":"Le Cap. Construis un réseau à travers l’Afrique : chaque frontière veut son propre permis, et la moitié des réseaux électriques ne sont pas de ton côté.", "scenarios.cogentle_and_goggle_are_not_speaking":"Cogentle et Goggle ne se parlent plus, et cette fois c’est définitif. Achète le transit pas cher, si tu l’oses.", +"scenarios.connect_panama_city_to_bogota_lima":"Bogotá, Lima, Santiago et São Paulo reliées à Panama, et 150 Gbps servis", "scenarios.deliver_carnaval_in_full":"Assurer tout le Carnaval", "scenarios.every_cable_through_the_red_sea":"Tous les câbles de la mer Rouge sont coupés, tout comme le saut vers l’Égypte. Fais quand même parler Marseille et Singapore : par le tour de l’Afrique, par voie terrestre, ou par l’autre côté de la planète.", "scenarios.every_ix_is_run_by_de":"Tous les IX sont gérés par DE-KICKS", @@ -3349,9 +3350,8 @@ "scenarios.mid_atlantic_accent":"Accent mi-atlantique", "scenarios.only_spatzle_ix":"Que du Spätzle-IX", "scenarios.order_and_progress":"Ordre et progrès", -"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.ponta_delgada_azores_lisbon_lagos":"Ponta Delgada, aux Açores, à mi-chemin de l’Atlantique. De la Floride à l’Espagne, c’est juste trop long pour une onde de 1.6T : en ligne droite, elle transporte 1.2T. Atterrissez sur les îles entre les deux, relancez la lumière, et chaque saut passe à 1.6T ou mieux. De Lisbonne à Lagos, le 1.6T passe d’une traite, mais cher : les Canaries coûtent moins. Vous commencez avec l’équipement 1.6T débloqué.", +"scenarios.ports_on_15_ix_brrr_exchanges_backbone":"Des ports sur 15 IX.brrr que votre backbone relie à São Paulo, dont un à Manaus, et 200 Gbps servis", "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.", @@ -3364,7 +3364,7 @@ "scenarios.start_in_stuttgart_where_nobody":"Démarre à Stuttgart, où personne ne vend de transit. Atteins Internet uniquement via peering, PNI, caches et ta propre fibre. Aucun transit, nulle part, jamais.", "scenarios.start_with_only_100k":"Démarre avec seulement $100k", "scenarios.sydney_2013_the_toilet_paper_group":"Sydney, 2013. Le Toilet Paper Group a tiré sa propre fibre jusqu’au sous-sol des immeubles, et le réseau national a crié à l’écrémage. À toi : passe outre le Nearly Broadband Network, paie la taxe et arrive le premier.", -"scenarios.tallinn_ships_drag_their_anchors":"Tallinn. Les navires traînent leurs ancres sur les câbles de la Baltique trois fois plus souvent que d’habitude.", +"scenarios.tallinn_nobody_sells_transit_anchors":"Tallinn, où personne ne vend de transit : votre internet est de l’autre côté de l’eau. Les navires traînent leurs ancres sur les câbles de la Baltique trois fois plus souvent que d’habitude.", "scenarios.the_cogentle_spat":"La brouille Cogentle", "scenarios.transit_costs_30_more":"Le transit coûte 30 % de plus", "scenarios.twice_the_failures":"Deux fois plus de pannes", diff --git a/site/i18n/it.js b/site/i18n/it.js index dfb1b8a..6e9d5ec 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2891,16 +2891,16 @@ "progress.a_port_on_ix_brrr_manaus":"Una porta su IX.brrr Manaus", "progress.broadband_in_city":"Banda larga a {city}", "progress.carnaval_delivered_in_full":"Carnevale servito per intero", +"progress.city_on_your_network":"{city} sulla tua rete", "progress.customer_level_lv_of_max":"Livello clienti {lv} di {max}", "progress.days_in_a_row_at_g":"Giorni di fila con almeno {g}", "progress.days_in_a_row_with_99":"Giorni di fila con il 99,5% servito", "progress.done_in_d_days":"Fatto in {d} giorni!", "progress.floods_that_got_through":"Ondate passate", -"progress.ix_brrr_ports":"Porte IX.brrr", +"progress.ix_brrr_ports_on_your_backbone":"Porte IX.brrr sulla tua dorsale", "progress.n_of_m":"{n} su {m}", "progress.next_name_unlocks_what":"Prossimo: {name} sblocca {what}", "progress.not_tier_1_right_now_why":"Al momento non sei Tier 1: {why}.", -"progress.pop_in_city":"POP a {city}", "progress.terabit_floods_held":"Ondate terabit respinte", "progress.under_attack_now":"Sotto attacco ora", "progress.your_score_peak_traffic":"Il tuo punteggio: picco di traffico", @@ -3330,14 +3330,15 @@ "scenarios.90_days_in_a_row_with":"90 giorni di fila con il 99.5% della domanda servita", "scenarios.99_reach_and_150_gbps_served":"99% di copertura e 150 Gbps serviti", "scenarios.99_reach_and_200_gbps_served":"99% di copertura e 200 Gbps serviti senza andare in rovina", -"scenarios.a_path_from_cape_town_to":"Un percorso da Città del Capo al Cairo, POP a Lagos e Nairobi, e 150 Gbps serviti", +"scenarios.a_path_from_cape_town_to_cairo_lagos":"Un percorso da Città del Capo al Cairo, con Lagos e Nairobi anche loro sulla tua rete, e 150 Gbps serviti", "scenarios.a_path_from_los_angeles_to":"Un percorso da Los Angeles a Sydney con 1.6T su ogni tratta, un percorso da Los Angeles a Tokyo e 150 Gbps serviti", "scenarios.a_path_from_marseille_to_singapore":"Un percorso da Marsiglia a Singapore, e 80 Gbps tra l’Asia e il resto della tua rete per 30 giorni di fila", "scenarios.amsterdam_hosting_capital_of_europe":"Amsterdam, capitale europea dell’hosting, in piena stagione delle botnet. Ogni tostapane smart, baby monitor e frigo mai aggiornato della Terra ha scelto da che parte stare, e non è la tua. Un’ondata ogni pochi giorni, sempre più spesso nei terabit, mentre tutto il resto continua a rompersi. Parti con l’attrezzatura più grossa già sbloccata, e ti servirà.", -"scenarios.broadband_in_sydney_melbourne":"Banda larga a Sydney, Melbourne, Brisbane, Adelaide e Perth, e due cavi diversi verso l’estero", +"scenarios.broadband_in_sydney_melbourne_served":"Banda larga a Sydney, Melbourne, Brisbane, Adelaide e Perth, due cavi diversi verso l’estero, e 500 Gbps serviti", "scenarios.cape_to_cairo":"Dal Capo al Cairo", "scenarios.cape_town_build_a_network_across":"Città del Capo. Costruisci una rete attraverso l’Africa: ogni confine vuole il suo permesso, e metà delle reti elettriche non sono dalla tua parte.", "scenarios.cogentle_and_goggle_are_not_speaking":"Cogentle e Goggle non si parlano, e stavolta è per sempre. Compra il transit economico, se hai il coraggio.", +"scenarios.connect_panama_city_to_bogota_lima":"Bogotá, Lima, Santiago e São Paulo collegate a Panama City, e 150 Gbps serviti", "scenarios.deliver_carnaval_in_full":"Servi il Carnaval per intero", "scenarios.every_cable_through_the_red_sea":"Ogni cavo nel Mar Rosso è tagliato, e anche il salto verso l’Egitto. Fai parlare Marseille con Singapore lo stesso: girando intorno all’Africa, via terra o dall’altra parte del pianeta.", "scenarios.every_ix_is_run_by_de":"Ogni IX è gestito da DE-KICKS", @@ -3349,9 +3350,8 @@ "scenarios.mid_atlantic_accent":"Accento medio-atlantico", "scenarios.only_spatzle_ix":"Solo Spätzle-IX", "scenarios.order_and_progress":"Ordine e Progresso", -"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.ponta_delgada_azores_lisbon_lagos":"Ponta Delgada, nelle Azzorre, a metà dell’Atlantico. Dalla Florida alla Spagna è appena troppo lungo per un’onda da 1.6T: in linea diretta porta 1.2T. Approda sulle isole in mezzo, fai ripartire la luce e ogni tratto va a 1.6T o più. Da Lisbona a Lagos l’1.6T arriva in un colpo solo, ma a caro prezzo: le Canarie costano meno. Parti con l’attrezzatura da 1.6T sbloccata.", +"scenarios.ports_on_15_ix_brrr_exchanges_backbone":"Porte su 15 exchange IX.brrr che la tua dorsale collega a São Paulo, una delle quali a Manaus, e 200 Gbps serviti", "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.", @@ -3364,7 +3364,7 @@ "scenarios.start_in_stuttgart_where_nobody":"Parti da Stuttgart, dove nessuno vende transit. Raggiungi internet solo con peering, PNI, cache e la tua fibra. Niente transit, da nessuna parte, mai.", "scenarios.start_with_only_100k":"Parti con soli $100k", "scenarios.sydney_2013_the_toilet_paper_group":"Sydney, 2013. Il Toilet Paper Group ha portato la sua fibra nelle cantine dei condomini, e la rete nazionale ha gridato al cherry-picking. Tocca a te: salta la Nearly Broadband Network, paga il contributo e arriva per primo.", -"scenarios.tallinn_ships_drag_their_anchors":"Tallinn. Le navi trascinano le ancore sui cavi del Baltico tre volte più spesso del solito.", +"scenarios.tallinn_nobody_sells_transit_anchors":"Tallinn, dove nessuno vende transit: la tua internet è al di là del mare. Le navi trascinano le ancore sui cavi del Baltico tre volte più spesso del solito.", "scenarios.the_cogentle_spat":"La lite Cogentle", "scenarios.transit_costs_30_more":"Il transit costa il 30% in più", "scenarios.twice_the_failures":"Guasti raddoppiati", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index de70a42..58402fb 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2891,16 +2891,16 @@ "progress.a_port_on_ix_brrr_manaus":"Uma porta no IX.brrr Manaus", "progress.broadband_in_city":"Banda larga em {city}", "progress.carnaval_delivered_in_full":"Carnaval entregue por completo", +"progress.city_on_your_network":"{city} na sua rede", "progress.customer_level_lv_of_max":"Nível de clientes {lv} de {max}", "progress.days_in_a_row_at_g":"Dias seguidos com {g} ou mais", "progress.days_in_a_row_with_99":"Dias seguidos com 99,5% atendido", "progress.done_in_d_days":"Feito em {d} dias!", "progress.floods_that_got_through":"Enxurradas que passaram", -"progress.ix_brrr_ports":"Portas no IX.brrr", +"progress.ix_brrr_ports_on_your_backbone":"Portas no IX.brrr no seu backbone", "progress.n_of_m":"{n} de {m}", "progress.next_name_unlocks_what":"Próximo: {name} desbloqueia {what}", "progress.not_tier_1_right_now_why":"Não é Tier 1 agora: {why}.", -"progress.pop_in_city":"POP em {city}", "progress.terabit_floods_held":"Enxurradas de terabit contidas", "progress.under_attack_now":"Sob ataque agora", "progress.your_score_peak_traffic":"Sua pontuação: pico de tráfego", @@ -3330,14 +3330,15 @@ "scenarios.90_days_in_a_row_with":"90 dias seguidos com 99.5% da demanda servida", "scenarios.99_reach_and_150_gbps_served":"99% de alcance e 150 Gbps servidos", "scenarios.99_reach_and_200_gbps_served":"99% de alcance e 200 Gbps entregues sem quebrar", -"scenarios.a_path_from_cape_town_to":"Um caminho da Cidade do Cabo ao Cairo, POPs em Lagos e Nairóbi, e 150 Gbps atendidos", +"scenarios.a_path_from_cape_town_to_cairo_lagos":"Um caminho da Cidade do Cabo ao Cairo, com Lagos e Nairóbi também na sua rede, e 150 Gbps atendidos", "scenarios.a_path_from_los_angeles_to":"Um caminho de Los Angeles a Sydney com 1.6T em cada trecho, um caminho de Los Angeles a Tóquio e 150 Gbps atendidos", "scenarios.a_path_from_marseille_to_singapore":"Um caminho de Marselha a Singapura, e 80 Gbps entre a Ásia e o resto da sua rede por 30 dias seguidos", "scenarios.amsterdam_hosting_capital_of_europe":"Amsterdã, capital europeia do hosting, em plena temporada de botnets. Cada torradeira smart, babá eletrônica e geladeira sem patch da Terra escolheu um lado, e não é o seu. Uma enxurrada a cada poucos dias, cada vez mais na casa dos terabits, enquanto todo o resto continua quebrando também. Você começa com equipamento maior desbloqueado, e vai precisar.", -"scenarios.broadband_in_sydney_melbourne":"Banda larga em Sydney, Melbourne, Brisbane, Adelaide e Perth, e dois cabos diferentes para o exterior", +"scenarios.broadband_in_sydney_melbourne_served":"Banda larga em Sydney, Melbourne, Brisbane, Adelaide e Perth, dois cabos diferentes para o exterior, e 500 Gbps servidos", "scenarios.cape_to_cairo":"Do Cabo ao Cairo", "scenarios.cape_town_build_a_network_across":"Cidade do Cabo. Construa uma rede pela África: cada fronteira quer sua própria licença, e metade das redes elétricas não está do seu lado.", "scenarios.cogentle_and_goggle_are_not_speaking":"Cogentle e Goggle não se falam, e desta vez é pra sempre. Compre o transit barato, se tiver coragem.", +"scenarios.connect_panama_city_to_bogota_lima":"Bogotá, Lima, Santiago e São Paulo ligadas à Cidade do Panamá, e 150 Gbps servidos", "scenarios.deliver_carnaval_in_full":"Entregue o Carnaval completo", "scenarios.every_cable_through_the_red_sea":"Todos os cabos pelo Mar Vermelho foram cortados, e o salto para o Egito também. Faça Marseille falar com Singapore mesmo assim: contornando a África, por terra ou pelo outro lado do planeta.", "scenarios.every_ix_is_run_by_de":"Todo IX é operado pela DE-KICKS", @@ -3349,9 +3350,8 @@ "scenarios.mid_atlantic_accent":"Sotaque do meio do Atlântico", "scenarios.only_spatzle_ix":"Só Spätzle-IX", "scenarios.order_and_progress":"Ordem e Progresso", -"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.ponta_delgada_azores_lisbon_lagos":"Ponta Delgada, nos Açores, no meio do Atlântico. Da Flórida à Espanha é um pouco longo demais para uma onda de 1.6T: em linha direta, ela leva 1.2T. Pouse nas ilhas no meio, recomece a luz, e cada trecho roda a 1.6T ou mais. De Lisboa a Lagos dá 1.6T de uma vez, mas sai caro: as Canárias custam menos. Você começa com equipamento de 1.6T desbloqueado.", +"scenarios.ports_on_15_ix_brrr_exchanges_backbone":"Portas em 15 exchanges IX.brrr que o seu backbone liga a São Paulo, uma delas em Manaus, e 200 Gbps servidos", "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.", @@ -3364,7 +3364,7 @@ "scenarios.start_in_stuttgart_where_nobody":"Comece em Stuttgart, onde ninguém vende transit. Alcance a internet só com peering, PNIs, caches e sua própria fibra. Nada de transit, em lugar nenhum, nunca.", "scenarios.start_with_only_100k":"Comece com só $100k", "scenarios.sydney_2013_the_toilet_paper_group":"Sydney, 2013. O Toilet Paper Group levou a própria fibra até o porão dos prédios, e a rede nacional reclamou de cherry-picking. Sua vez: pule a Nearly Broadband Network, pague a taxa e chegue primeiro.", -"scenarios.tallinn_ships_drag_their_anchors":"Tallinn. Os navios arrastam âncoras sobre os cabos do Báltico três vezes mais que o normal.", +"scenarios.tallinn_nobody_sells_transit_anchors":"Tallinn, onde ninguém vende trânsito: a sua internet fica do outro lado do mar. Os navios arrastam âncoras sobre os cabos do Báltico três vezes mais que o normal.", "scenarios.the_cogentle_spat":"A briga da Cogentle", "scenarios.transit_costs_30_more":"Transit custa 30% a mais", "scenarios.twice_the_failures":"O dobro de falhas", diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 82738b6..123bd62 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -8,21 +8,30 @@ function pathExists(a,b){if(!S.pops[a]||!S.pops[b])return false;const adj={};for // Looked up rather than read from the save, so it follows a language switch mid-scenario. const scnName=()=>S.scn.wk?wsTxt(S.scn.wk.name):S.scn.id==='weekly'?tr('scenarios.weekly_key',{key:S.scn.key}):SCN.find(x=>x.id===S.scn.id)?.n||S.scn.name; 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; +// Ports count only on POPs your backbone joins to São Paulo: islands of POPs with a port each skipped the Amazon (playtest). +const FTTB_G=500; +const brIxN=()=>CITIES.filter(c=>c.br&&S.ixp[c.id]!==undefined&&(c.id==='sao'||pathExists('sao',c.id))).length; +// Days and cash were tuned in the 2.0.0 playtest (tests/scenarios-playtest.test.js): a reference player wins each one in +// roughly a fifth to a half of its days, and the obvious shortcut does not win. The 1.6T scenarios start with enough cash to +// build the whole chain on day 0 and still last until the traffic goal. 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_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:'stg',n:tr('scenarios.only_spatzle_ix'),city:'stg',cash:400000,days:365,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:365,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:240,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}, - {id:'darien',n:tr('common.mind_the_gap'),city:'pan',cash:900000,days:730,rules:{},d:tr('scenarios.start_in_panama_city_nothing_crosses'),goal:tr('scenarios.pops_in_bogota_lima_santiago_and'),ok:()=>['bog','lim','scl','sao'].every(c=>S.pops[c])&&R.served>=150}, - {id:'c2c',n:tr('scenarios.cape_to_cairo'),city:'cpt',cash:2000000,days:1095,rules:{},d:tr('scenarios.cape_town_build_a_network_across'),goal:tr('scenarios.a_path_from_cape_town_to'),ok:()=>pathExists('cpt','cai')&&S.pops.lag&&S.pops.nbo&&R.served>=150}, - {id:'ixbr',n:tr('scenarios.order_and_progress'),city:'sao',cash:2500000,days:1095,rules:{},d:tr('scenarios.sao_paulo_brazil_is_a_continent'),goal:tr('scenarios.ports_on_15_ix_brrr_exchanges'),ok:()=>brIxN()>=15&&S.ixp.mao!==undefined&&R.served>=200}, - {id:'gangnam',n:tr('scenarios.gangnam_style_peering'),city:'icn',cash:900000,days:365,rules:{},d:tr('scenarios.seoul_the_fastest_hungriest_eyeballs'),goal:tr('scenarios.99_reach_and_200_gbps_served'),ok:()=>R.reach>=0.99&&R.served>=200}, + // Connected, not just present: four island POPs with local transit won on day 40 without crossing anything (playtest). + {id:'darien',n:tr('common.mind_the_gap'),city:'pan',cash:900000,days:180,rules:{},d:tr('scenarios.start_in_panama_city_nothing_crosses'),goal:tr('scenarios.connect_panama_city_to_bogota_lima'),ok:()=>['bog','lim','scl','sao'].every(c=>pathExists('pan',c))&&R.served>=150}, + // Lagos and Nairobi on the network too: one long wave to Cairo plus two empty POPs was not a network across Africa. + {id:'c2c',n:tr('scenarios.cape_to_cairo'),city:'cpt',cash:2000000,days:365,rules:{},d:tr('scenarios.cape_town_build_a_network_across'),goal:tr('scenarios.a_path_from_cape_town_to_cairo_lagos'),ok:()=>pathExists('cpt','cai')&&pathExists('cpt','lag')&&pathExists('cpt','nbo')&&R.served>=150}, + {id:'ixbr',n:tr('scenarios.order_and_progress'),city:'sao',cash:600000,days:240,rules:{},d:tr('scenarios.sao_paulo_brazil_is_a_continent'),goal:tr('scenarios.ports_on_15_ix_brrr_exchanges_backbone'),ok:()=>brIxN()>=15&&S.ixp.mao!==undefined&&R.served>=200}, + {id:'gangnam',n:tr('scenarios.gangnam_style_peering'),city:'icn',cash:900000,days:240,rules:{},d:tr('scenarios.seoul_the_fastest_hungriest_eyeballs'),goal:tr('scenarios.99_reach_and_200_gbps_served'),ok:()=>R.reach>=0.99&&R.served>=200}, {id:'flood',n:tr('common.flood_season'),city:'ams',cash:2000000,days:365,rules:{ddos:true},setup:()=>{S.lvl=Math.max(S.lvl||1,3);},d:tr('scenarios.amsterdam_hosting_capital_of_europe'),goal:tr('scenarios.hold_20_floods_5_of_them'),ok:()=>(S.stats.ddosOk||0)>=20&&(S.stats.ddosOkBig||0)>=5}, - {id:'fttb',n:tr('scenarios.fibre_to_the_basement'),city:'syd',cash:1500000,days:730,rules:{levy:true},d:tr('scenarios.sydney_2013_the_toilet_paper_group'),goal:tr('scenarios.broadband_in_sydney_melbourne'),ok:()=>AU_BB.every(c=>S.pops[c]&&S.pops[c].bb)&&auExits()>=2}, - {id:'baltic',n:tr('common.anchors_away'),city:'tll',cash:500000,days:540,rules:{anchors:3},d:tr('scenarios.tallinn_ships_drag_their_anchors'),goal:tr('scenarios.90_days_in_a_row_with'),ok:()=>(S.stats.clean||0)>=90}, - {id:'pac',n:tr('common.stepping_stones'),city:'hnl',cash:3000000,days:1095,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.honolulu_in_the_middle_of_the'),goal:tr('scenarios.a_path_from_los_angeles_to'),ok:()=>fastPath('lax','syd',1600)&&pathExists('lax','tok')&&R.served>=150}, - {id:'atl',n:tr('scenarios.mid_atlantic_accent'),city:'pdl',cash:3000000,days:1095,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.ponta_delgada_in_the_azores_halfway'),goal:tr('scenarios.1_6t_on_every_hop_from'),ok:()=>fastPath('mia','mad',1600)&&fastPath('lis','lag',1600)&&R.served>=100}, + // Traffic served too: broadband in five cities and two cables were bought on day 1 and won on day 2 (playtest). + {id:'fttb',n:tr('scenarios.fibre_to_the_basement'),city:'syd',cash:1500000,days:365,rules:{levy:true},d:tr('scenarios.sydney_2013_the_toilet_paper_group'),goal:tr('scenarios.broadband_in_sydney_melbourne_served'),ok:()=>AU_BB.every(c=>S.pops[c]&&S.pops[c].bb)&&auExits()>=2&&R.served>=FTTB_G}, + // Nobody sells transit in Tallinn here: with local transit, a network that never crossed the water won (playtest). + {id:'baltic',n:tr('common.anchors_away'),city:'tll',cash:500000,days:365,rules:{anchors:3,noTransitIn:['tll']},d:tr('scenarios.tallinn_nobody_sells_transit_anchors'),goal:tr('scenarios.90_days_in_a_row_with'),ok:()=>(S.stats.clean||0)>=90}, + {id:'pac',n:tr('common.stepping_stones'),city:'hnl',cash:5000000,days:240,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.honolulu_in_the_middle_of_the'),goal:tr('scenarios.a_path_from_los_angeles_to'),ok:()=>fastPath('lax','syd',1600)&&pathExists('lax','tok')&&R.served>=150}, + {id:'atl',n:tr('scenarios.mid_atlantic_accent'),city:'pdl',cash:5000000,days:240,rules:{},setup:()=>{S.lvl=Math.max(S.lvl||1,4);},d:tr('scenarios.ponta_delgada_azores_lisbon_lagos'),goal:tr('scenarios.1_6t_on_every_hop_from'),ok:()=>fastPath('mia','mad',1600)&&fastPath('lis','lag',1600)&&R.served>=100}, ]; const WEEK_CITIES=['fra','ams','lon','nyc','ash','sjc','sin','tok','syd','sao','jnb','bom','waw','ist','scl','hkg']; const WEEK_MODS=[{id:'pricey',n:tr('scenarios.transit_costs_30_more')},{id:'chaos',n:tr('scenarios.twice_the_failures')},{id:'poor',n:tr('scenarios.start_with_only_100k')},{id:'boom',n:tr('scenarios.eyeballs_grow_50_faster')},{id:'dk',n:tr('scenarios.every_ix_is_run_by_de')},{id:'sharks',n:tr('scenarios.shark_season_subsea_cuts_twice_as')}]; diff --git a/src/game/60-features/94-scenarios-weekly.js b/src/game/60-features/94-scenarios-weekly.js index 7d01c02..fa8c053 100644 --- a/src/game/60-features/94-scenarios-weekly.js +++ b/src/game/60-features/94-scenarios-weekly.js @@ -27,7 +27,7 @@ const WS_GOALS={ path:{p:{a:['c'],b:['c'],g:['n',10,12800],n:['n',1,120]},daily:p=>fastPath(p.a,p.b,p.g),l:N_('wkscn.goal_g_on_every_hop_from'),ok:p=>wsRun()>=p.n,m:()=>wsRun(), prog:p=>[pChk(tr('wkscn.p_path_g_a_b',{g:fmtG(p.g),a:CITY[p.a].name,b:CITY[p.b].name}),fastPath(p.a,p.b,p.g)),{l:tr('wkscn.p_days_in_a_row'),v:wsRun(),max:p.n,txt:`${wsRun()} / ${p.n}`}]}, ix:{p:{reg:['r'],n:['n',2,60]},l:N_('wkscn.goal_ports_on_n_exchanges_in'),ok:p=>wsIxN(p.reg)>=p.n,m:p=>wsIxN(p.reg),prog:p=>{const n=wsIxN(p.reg);return [{l:tr('wkscn.p_exchange_ports_in_reg',{reg:WAVE_NAME[p.reg]}),v:n,max:p.n,txt:`${n} / ${p.n}`}];}}, - pops:{p:{cs:['cs',1,8]},l:N_('wkscn.goal_a_connected_pop_in_list'),ok:p=>p.cs.every(c=>pathExists(S.scn.home,c)),m:p=>p.cs.filter(c=>pathExists(S.scn.home,c)).length,prog:p=>p.cs.map(c=>pChk(tr('progress.pop_in_city',{city:CITY[c].name}),pathExists(S.scn.home,c)))}, + pops:{p:{cs:['cs',1,8]},l:N_('wkscn.goal_a_connected_pop_in_list'),ok:p=>p.cs.every(c=>pathExists(S.scn.home,c)),m:p=>p.cs.filter(c=>pathExists(S.scn.home,c)).length,prog:p=>p.cs.map(c=>pChk(tr('progress.city_on_your_network',{city:CITY[c].name}),pathExists(S.scn.home,c)))}, event:{p:{city:['c'],g:['n',10,6400],day:['n',20,360],dur:['n',1,10]},l:N_('wkscn.goal_deliver_the_event_in_city'),ok:()=>(S.stats.evFull||0)>=1,m:()=>S.stats.evFull||0, setup:p=>S.biz.push({id:uid(),scripted:true,city:p.city,city2:null,reqs:[],name:tr('wkscn.event_name_city',{city:CITY[p.city].name}),type:'event',bw:p.g,rate:0,mood:100,since:0,start:p.day,dur:p.dur,fee:p.g*p.dur*70}), prog:p=>[pChk(tr('wkscn.p_event_delivered_in_full'),(S.stats.evFull||0)>=1),{l:tr('common.traffic_served'),v:0,max:0,txt:tr('wkscn.p_g_on_day_d',{g:fmtG(p.g),d:p.day})}]}, diff --git a/src/game/70-rules/20-exchanges.js b/src/game/70-rules/20-exchanges.js index f1332ec..7a27f83 100644 --- a/src/game/70-rules/20-exchanges.js +++ b/src/game/70-rules/20-exchanges.js @@ -5,7 +5,9 @@ Not That Telecom and Level Tree (whose real-world network lists no sites in PeeringDB at all, but sells in Sydney). Others can sit in an Australian city, like the Pacific carriers backhauling to Sydney (or Glowball Sakura Lager), but reach Australian customers only from overseas. */ -const AU_SELLERS=['tsy','voc','spl','sgt','drz','cog','ntt','lvl'],sellsAt=(n,c)=>!!n.price&&(n.pops.includes(c)||!!n.premOnly&&n.premOnly.includes(c))&&(!CITY[c].au||AU_SELLERS.includes(n.id)); +const AU_SELLERS=['tsy','voc','spl','sgt','drz','cog','ntt','lvl'],sellsAt=(n,c)=>!!n.price&&(n.pops.includes(c)||!!n.premOnly&&n.premOnly.includes(c))&&(!CITY[c].au||AU_SELLERS.includes(n.id))&&!noTransitIn(c); +// A scenario city where nobody sells transit (Anchors Away: Tallinn's internet is across the water). +const noTransitIn=c=>{const x=S&&S.scn&&S.scn.rules&&S.scn.rules.noTransitIn;return Array.isArray(x)&&x.includes(c);}; /* China Telecomet's premium crossing into China (CN-Too) is sold where its border routes start: Hong Kong, and Moscow (#195), where it rides the land route east and nothing else of theirs is on offer (premOnly). It costs the same wherever you buy it: the Hong Kong price. */ diff --git a/src/game/70-rules/70-sold-out.js b/src/game/70-rules/70-sold-out.js index 748ae49..eda5b0c 100644 --- a/src/game/70-rules/70-sold-out.js +++ b/src/game/70-rules/70-sold-out.js @@ -15,7 +15,8 @@ function peerOk(id,via,city){ if(msfNope(id,city))return {ok:false,why:tr(MSF_NOPE[hstr(ixCity(city)+S.day)%MSF_NOPE.length])}; if(via==='ix'&&city&&isRemote(city)&&noRemote(id))return {ok:false,remote:true,why:REMOTE_WHY[hstr(id)%REMOTE_WHY.length]}; if(n.pol==='open')return {ok:true}; - if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*repMul());return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};} + // In the Cogentle Spat, Goggle's peering desk wants eight times the usual traffic first, so cheap Cogentle-only transit really costs you Goggle (playtest). + if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*repMul()*(id==='ggl'&&scnRule('spat')?8:1));return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};} if(n.pol==='paid'&&paidFree(n))return via==='pni'?{ok:true,free:true}:{ok:false,why:tr('sold_out.peers_with_you_for_free_now')}; if(n.pol==='paid')return via==='pni'?{ok:true,fee:n.paidFee}:{ok:false,why:n.perG?tr('sold_out.sender_pays_a_paid_pni_only',{fee:fmt$(n.paidFee),g:fmt$(n.perG)}):tr('sold_out.paid_peering_only_over_a_pni')}; if(n.type!=='t1'){if(via!=='pni')return {ok:false,why:tr('sold_out.only_peers_over_pnis_and_only')};const need=Math.round(60*confBoost(id));return dem>=need||isTier2()?{ok:true}:{ok:false,why:tr('sold_out.wants_you_to_be_a_tier',{need,dem:dem.toFixed(1)})};} diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index db11458..79ef628 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -16,6 +16,8 @@ const borderPair=(a,b)=>CITY[a].reg==='AF'&&CITY[b].reg==='AF'&&CITY[a].cc!==CIT // fiber costs a little more again because the incumbents own it. const NULLARBOR=1.7,nullPair=(a,b)=>!!CITY[a].au&&!!CITY[b].au&&(a==='per')!==(b==='per'); const andesPair=(a,b)=>!!CITY[a].andes&&!!CITY[b].andes&&CITY[a].andes!==CITY[b].andes; +// A pair an anchor-prone cable serves (the Baltic): the map calls it overland, but the fibre lies on the seabed (Anchors Away). +let ANCHOR_P=null;const anchorPair=l=>(ANCHOR_P||(ANCHOR_P=new Set(CABLE_PAIRS.filter(p=>CAB[p.cid]&&CAB[p.cid].anchor).map(p=>edgeKey(p))))).has(edgeKey(l)); /* Overland between continents (Europe to the Middle East and Asia) crosses a dozen borders and as many carriers, each taking a cut: in real life it costs ten times the subsea route or more (#40). */ const LAND_X=45,landX=(a,b)=>!isSub(a,b)&&CITY[a].reg!==CITY[b].reg; diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index c7eaebf..dd13d16 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -1,4 +1,6 @@ -function fireFailure(){ +// Anchors Away (Baltic): a link on an anchor-prone cable, or on a pair one serves (the map calls those overland). +const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair(l); +function fireFailure(only){ const opts=[]; const live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; if(live.length){opts.push(['cut',2+Math.min(6,live.length/2)]);} @@ -17,6 +19,7 @@ function fireFailure(){ if(!opts.length)return; let tot=opts.reduce((a,o)=>a+o[1],0),r=Math.random()*tot,type=opts[0][0]; for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}} + if(only)type=only; if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(Object.keys(S.ixp).length)f.push('maxpfx');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(lit.length)f.push('roadmff');type=pick(f);} const before=R.served; if(type==='harmless'){const m=pick(HARMLESS);S.stats.incidents++;S.stats.survived++;toast(`${m[0]}
${m[1]}`,'goal');sfx('alert');return;} @@ -79,8 +82,8 @@ function fireFailure(){ const l=pick(lit),A=CITY[l.a].name,B=CITY[l.b].name,o=pick(l.ch),dur=l.spares?1:4;l.chFail={n:1,o,until:S.day+dur}; addInc({type,ref:l.id,until:S.day+dur,msg:pick([tr('failures.a_optic_on_a_b_overheated',{optic:OPT[o].n,a:A,b:B}),tr('failures.the_laser_in_a_optic_on',{optic:OPT[o].n,a:A,b:B}),tr('failures.a_optic_on_a_b_started',{optic:OPT[o].n,a:A,b:B})])+(l.spares?' '+tr('failures.swapped_from_your_spares_kit_by'):''),cost:l.spares?0:OPT[o].cost,fix:tr('failures.buy_a_replacement')}); }else if(type==='cut'){ - const mon=Math.floor((S.day%365)/30.42),monsoon=mon>=5&&mon<=8,tw=x=>x.sub&&(x.a==='tpe'||x.b==='tpe'||(x.cable&&CAB[x.cable].anchor)),vn=x=>x.sub&&(x.a==='sgn'||x.b==='sgn'),inl=x=>!x.sub&&(CITY[x.a].india||CITY[x.b].india); - const l=pick(live.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=10+Math.floor(Math.random()*8),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur)); + const mon=Math.floor((S.day%365)/30.42),monsoon=mon>=5&&mon<=8,tw=x=>(x.sub&&(x.a==='tpe'||x.b==='tpe'||(x.cable&&CAB[x.cable].anchor)))||(scnRule('anchors')&&anchorProne(x)),vn=x=>x.sub&&(x.a==='sgn'||x.b==='sgn'),inl=x=>!x.sub&&(CITY[x.a].india||CITY[x.b].india); + const pool=only&&scnRule('anchors')?live.filter(anchorProne):live;if(!pool.length)return;const l=pick(pool.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=10+Math.floor(Math.random()*8),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur)); const A=CITY[l.a].name,B=CITY[l.b].name,au=CITY[l.a].au&&CITY[l.b].au,auSummer=mon>=11||mon<=1; const en=l.sub&&(CITY[l.a].au||CITY[l.b].au)&&!(l.cable&&CAB[l.cable].fragile)&&Math.random()<0.35?pick([N_('failures.box_jellyfish_season_at_the_a'),N_('failures.a_great_white_took_an_interest')]):l.cable&&CAB[l.cable].fragile&&Math.random()<0.8?pick([N_('failures.your_a_b_cable_is_cut'),N_('failures.a_b_is_down_same_cable')]):!l.sub&&CITY[l.a].land==='nzs'&&CITY[l.b].land==='nzs'&&Math.random()<0.75?pick([N_('failures.a_kea_pulled_the_rubber_seals'),N_('failures.the_sandflies_drove_your_splicing'),N_('failures.a_farmer_s_post_hole_digger')]):l.cable==='cook'&&Math.random()<0.6?N_('failures.a_ferry_dropped_anchor_in_cook'):!l.sub&&au&&Math.random()<0.75?pick([N_('failures.a_sulphur_crested_cockatoo_chewed'),N_('failures.a_kangaroo_hit_the_fiber_hut'),N_('failures.thieves_dug_up_your_a_b'),N_('failures.a_kilometre_of_copper_went_missing'),N_('failures.a_backhoe_putting_in_a_new'),N_('failures.the_emus_won_again_a_mob'),N_('failures.a_kangaroo_boxed_your_field_tech'),N_('failures.a_drop_bear_fell_on_the'),N_('failures.an_eastern_brown_snake_moved_into'),...((S.day%365)/30.42>=8&&(S.day%365)/30.42<11?[N_('failures.magpie_swooping_season_the_field')]:[]),...(auSummer?[N_('failures.bushfire_season_the_fiber_along_a')]:[]),...(nullPair(l.a,l.b)?[N_('failures.your_a_b_fiber_broke_somewhere')]:[])]):l.sub&&(l.a==='bda'||l.b==='bda')&&Math.random()<0.7?pick([N_('failures.your_a_b_cable_went_quiet'),N_('failures.the_repair_ship_s_compass_spun')]):l.sub&&(l.a==='tbu'||l.b==='tbu')&&Math.random()<0.7?pick([N_('failures.an_undersea_volcano_erupted_next_to'),N_('failures.the_seabed_off_tonga_slid_down')]):vn(l)&&Math.random()<0.8?pick([N_('failures.another_of_vietnam_s_subsea_cables'),N_('failures.your_a_b_cable_broke_in')]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([N_('failures.a_crocodile_took_a_bite_out'),N_('failures.termites_ate_the_duct_on_a')]):tw(l)&&Math.random()<0.8?pick([N_('failures.a_cargo_ship_forgot_to_raise'),N_('failures.another_anchor_another_cut_your_a'),N_('failures.a_fishing_boat_with_an_unusually')]):l.sub&&(l.a==='oos'||l.b==='oos')&&Math.random()<0.8?pick([N_('failures.a_trawler_off_ostend_dragged_its'),N_('failures.a_wind_farm_service_vessel_dropped')]):!l.sub&&(CITY[l.a].ca||CITY[l.b].ca)&&Math.random()<0.4?pick([N_('failures.a_beaver_chewed_through_your_a'),N_('failures.your_a_b_fiber_is_down'),N_('failures.frost_heave_cracked_the_duct_on')]):!l.sub&&andesPair(l.a,l.b)?pick([N_('failures.a_landslide_in_the_andes_buried'),N_('failures.snow_closed_the_mountain_pass_and'),N_('failures.an_earthquake_shook_your_a_b'),N_('failures.a_llama_herd_trampled_the_fiber')]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([N_('failures.road_widening_near_a_cut_your'),N_('failures.the_monsoon_flooded_a_manhole_on'),N_('failures.a_digger_found_your_a_b')]):l.sub?pick([N_('failures.a_curious_shark_bit_your_subsea'),N_('failures.a_ship_dragged_its_anchor_across'),N_('failures.an_undersea_landslide_snapped_a_b')]):pick([N_('failures.a_backhoe_found_your_fiber_between'),N_('failures.squirrels_chewed_through_a_b_they'),N_('failures.road_works_cut_a_b_nobody')]); addInc({type,ref:trc,until:S.day+dur,msg:tr(en,{a:A,b:B})+(hit.length>1?' '+tr('failures.all_n_links_in_that_trench',{n:hit.length}):''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},en); @@ -166,7 +169,8 @@ function ddosAttack(recompute=true){const type='ddos',fl=scnRule('ddos');ddosExp 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=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; + // In Flood Season a terabit flood counts only when scrubbing or Flowspec took it: spare exits held some by luck (playtest). + if(ok){S.stats.ddosOk=(S.stats.ddosOk||0)+1;if(a.gbps>=1000&&(!scnRule('ddos')||hasScrub()||(DDOS_VEC[a.vec]&&DDOS_VEC[a.vec].fs&&fsAt(a.city))))S.stats.ddosOkBig=(S.stats.ddosOkBig||0)+1;}else S.stats.ddosLost=(S.stats.ddosLost||0)+1; if(scnRule('ddos')){const w=tr(FLOOD_WHO.includes(a.who)?a.who:FLOOD_WHO[0]),who=esc(w.charAt(0).toUpperCase()+w.slice(1));toast(ok?tr('failures.flood_held_g_who_gave_up',{g:fmtG(a.gbps),who}):tr('failures.that_one_got_through_g_city',{g:fmtG(a.gbps),city:esc(CITY[a.city]?CITY[a.city].name:tr('common.your_network')),p:pct(a.worst||0),who:esc(w)}),ok?'goal':'bad');}} // Flood Season: 3 to 7 days apart as before, shrinking with age, level and gamers only when attacks are spicy. const floodGap=()=>!ddosSpicy()?3+Math.floor(Math.random()*5):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))); diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index eb2c34c..4f5b445 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -11,7 +11,8 @@ function dayTick(){ 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; + // What the Great Firewall drops is not your outage: it alone kept Anchors Away's 99.5% out of reach (playtest). + if(R&&R.demand>0)S.stats.clean=(R.served+(R.gfwLost||0))/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('day_tick.the_internet_is_back_half_of'),'good'); for(const k in S.peers){const [id,c]=k.split('@'),sn=snub(id,c);if(!sn)continue;delete S.peers[k];S.stats.depeered=(S.stats.depeered||0)+1; @@ -63,6 +64,8 @@ function dayTick(){ // Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never. let dirty=false;const cm=chaosMul(); if(cm&&d>=S.nextFail){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} + // Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year). + if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} if(dirty)compute(); opsDay(d); diff --git a/src/game/94-dashboard/10-progress.js b/src/game/94-dashboard/10-progress.js index a400b8e..234cc54 100644 --- a/src/game/94-dashboard/10-progress.js +++ b/src/game/94-dashboard/10-progress.js @@ -5,13 +5,13 @@ const pSrv=g=>({l:tr('common.traffic_served'),v:R.served,max:g,txt:`${fmtG(R.ser 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.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)], + carnaval:()=>[pChk(tr('progress.carnaval_delivered_in_full'),(S.stats.evFull||0)>=1)],ixbr:()=>{const n=brIxN();return [{l:tr('progress.ix_brrr_ports_on_your_backbone'),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.city_on_your_network',{city:CITY[c].name}),pathExists('cpt',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)], atl:()=>[pChk(tr('progress.1_6t_on_every_hop_from_a90b'),fastPath('mia','mad',1600)),pChk(tr('progress.1_6t_on_every_hop_from_da01'),fastPath('lis','lag',1600)),pSrv(100)], - darien:()=>[...['bog','lim','scl','sao'].map(c=>pChk(tr('progress.pop_in_city',{city:CITY[c].name}),!!S.pops[c])),pSrv(150)], + darien:()=>[...['bog','lim','scl','sao'].map(c=>pChk(tr('progress.city_on_your_network',{city:CITY[c].name}),pathExists('pan',c))),pSrv(150)], gangnam:()=>[pReach(),pSrv(200)], - fttb:()=>[...AU_BB.map(c=>pChk(tr('progress.broadband_in_city',{city:CITY[c].name}),!!(S.pops[c]&&S.pops[c].bb))),{l:tr('common.cables_overseas'),v:Math.min(2,auExits()),max:2,txt:`${auExits()} / 2`}], + fttb:()=>[...AU_BB.map(c=>pChk(tr('progress.broadband_in_city',{city:CITY[c].name}),!!(S.pops[c]&&S.pops[c].bb))),{l:tr('common.cables_overseas'),v:Math.min(2,auExits()),max:2,txt:`${auExits()} / 2`},pSrv(FTTB_G)], flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll(); return [{l:tr('common.floods_held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('progress.terabit_floods_held'),v:big,max:5,txt:`${big} / 5`},{l:tr('progress.floods_that_got_through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('progress.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('progress.days_in_a_row_with_99'),v:S.stats.clean||0,max:90,txt:tr('progress.n_of_m',{n:S.stats.clean||0,m:90})}]}; function scnProg(){const sc=S&&S.scn;if(!sc)return null; diff --git a/src/i18n/en.js b/src/i18n/en.js index 9ff482c..41a1e3a 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2892,16 +2892,16 @@ "progress.a_port_on_ix_brrr_manaus":"A port on IX.brrr Manaus", "progress.broadband_in_city":"Broadband in {city}", "progress.carnaval_delivered_in_full":"Carnaval delivered in full", +"progress.city_on_your_network":"{city} on your network", "progress.customer_level_lv_of_max":"Customer level {lv} of {max}", "progress.days_in_a_row_at_g":"Days in a row at {g} or more", "progress.days_in_a_row_with_99":"Days in a row with 99.5% served", "progress.done_in_d_days":"Done in {d} days!", "progress.floods_that_got_through":"Floods that got through", -"progress.ix_brrr_ports":"IX.brrr ports", +"progress.ix_brrr_ports_on_your_backbone":"IX.brrr ports on your backbone", "progress.n_of_m":"{n} of {m}", "progress.next_name_unlocks_what":"Next: {name} unlocks {what}", "progress.not_tier_1_right_now_why":"Not Tier 1 right now: {why}.", -"progress.pop_in_city":"POP in {city}", "progress.terabit_floods_held":"Terabit floods held", "progress.under_attack_now":"Under attack now", "progress.your_score_peak_traffic":"Your score: peak traffic", @@ -3331,14 +3331,15 @@ "scenarios.90_days_in_a_row_with":"90 days in a row with 99.5% of demand served", "scenarios.99_reach_and_150_gbps_served":"99% reach and 150 Gbps served", "scenarios.99_reach_and_200_gbps_served":"99% reach and 200 Gbps served without going broke", -"scenarios.a_path_from_cape_town_to":"A path from Cape Town to Cairo, POPs in Lagos and Nairobi, and 150 Gbps served", +"scenarios.a_path_from_cape_town_to_cairo_lagos":"A path from Cape Town to Cairo, Lagos and Nairobi on your network too, and 150 Gbps served", "scenarios.a_path_from_los_angeles_to":"A path from Los Angeles to Sydney with 1.6T on every hop, a path from Los Angeles to Tokyo, and 150 Gbps served", "scenarios.a_path_from_marseille_to_singapore":"A path from Marseille to Singapore, and 80 Gbps between Asia and the rest of your network for 30 days in a row", "scenarios.amsterdam_hosting_capital_of_europe":"Amsterdam, hosting capital of Europe, in peak botnet season. Every smart toaster, baby monitor and unpatched fridge on Earth has picked a side, and it is not yours. A flood every few days, more and more of them in the terabits, while everything else keeps breaking too. You start with bigger gear unlocked, and you will need it.", -"scenarios.broadband_in_sydney_melbourne":"Broadband in Sydney, Melbourne, Brisbane, Adelaide and Perth, and two different cables overseas", +"scenarios.broadband_in_sydney_melbourne_served":"Broadband in Sydney, Melbourne, Brisbane, Adelaide and Perth, two different cables overseas, and 500 Gbps served", "scenarios.cape_to_cairo":"Cape to Cairo", "scenarios.cape_town_build_a_network_across":"Cape Town. Build a network across Africa: every border wants its own permit, and half the power grids are not on your side.", "scenarios.cogentle_and_goggle_are_not_speaking":"Cogentle and Goggle are not speaking, and this time it is permanent. Buy the cheap transit if you dare.", +"scenarios.connect_panama_city_to_bogota_lima":"Bogotá, Lima, Santiago and São Paulo joined up to Panama City, and 150 Gbps served", "scenarios.deliver_carnaval_in_full":"Deliver Carnaval in full", "scenarios.every_cable_through_the_red_sea":"Every cable through the Red Sea is cut, and so is the hop to Egypt. Get Marseille talking to Singapore anyway: round Africa, overland, or the other way round the planet.", "scenarios.every_ix_is_run_by_de":"Every IX is run by DE-KICKS", @@ -3350,9 +3351,8 @@ "scenarios.mid_atlantic_accent":"Mid-Atlantic Accent", "scenarios.only_spatzle_ix":"Only Spätzle-IX", "scenarios.order_and_progress":"Order and Progress", -"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.ponta_delgada_azores_lisbon_lagos":"Ponta Delgada, in the Azores, halfway across the Atlantic. Florida to Spain is just too long for a 1.6T wave: straight across, it carries 1.2T. Land on the islands in between, start the light fresh, and every hop runs at 1.6T or better. Lisbon to Lagos does 1.6T in one go, at a price: the Canaries are cheaper. You start with 1.6T gear unlocked.", +"scenarios.ports_on_15_ix_brrr_exchanges_backbone":"Ports on 15 IX.brrr exchanges your backbone joins to São Paulo, one of them in Manaus, and 200 Gbps served", "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.", @@ -3365,7 +3365,7 @@ "scenarios.start_in_stuttgart_where_nobody":"Start in Stuttgart, where nobody sells transit. Reach the internet through peering, PNIs, caches and your own fiber only. No transit anywhere, ever.", "scenarios.start_with_only_100k":"Start with only $100k", "scenarios.sydney_2013_the_toilet_paper_group":"Sydney, 2013. The Toilet Paper Group ran its own fibre into apartment basements, and the national network cried cherry-picking. Your turn: skip the Nearly Broadband Network, pay the levy, and get there first.", -"scenarios.tallinn_ships_drag_their_anchors":"Tallinn. Ships drag their anchors over Baltic cables three times as often as usual.", +"scenarios.tallinn_nobody_sells_transit_anchors":"Tallinn, where nobody sells transit: your internet is across the water. Ships drag their anchors over Baltic cables three times as often as usual.", "scenarios.the_cogentle_spat":"The Cogentle Spat", "scenarios.transit_costs_30_more":"Transit costs 30% more", "scenarios.twice_the_failures":"Twice the failures", From 68bea796f665b5daeb1a26640a884e10b689a340 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:53:38 +0100 Subject: [PATCH 125/181] Stale PNI button test: open the Tier 2 group, folded when nothing there is worth it (#175) --- tests/issues.test.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/issues.test.js b/tests/issues.test.js index da2fa5d..4758bf5 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -571,7 +571,8 @@ test('buttons behind an open modal stay quiet, and a declined PNI clears its sta 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:'mrs'});ACT.buyTransit({city:'mrs',net:'cog',tier:1});compute()"); // the PNI button was drawn while Tangerine still wanted our traffic; by the click it doesn't - ev("R.demTo.tng=50;UI.sel={type:'city',id:'mrs'};UI.tab='peer';renderAll();R.demTo.tng=0;window.__n=0;const o=toast;toast=function(h){if(/declined/.test(h))window.__n++;return o.apply(this,arguments);}"); + // Tier 2 is folded when nothing there is worth a PNI (#175): open it, as a player would. + ev("UI.pniOpen={t2:true};R.demTo.tng=50;UI.sel={type:'city',id:'mrs'};UI.tab='peer';renderAll();R.demTo.tng=0;window.__n=0;const o=toast;toast=function(h){if(/declined/.test(h))window.__n++;return o.apply(this,arguments);}"); const btn = "document.querySelector('#panel [data-act=pni][data-args*=tng]')"; assert.ok(ev(`!!${btn}`), 'a stale button to start with'); ev(`${btn}.focus();${btn}.click()`); From 0ca9ad8a95e23744bccfb2c4a7027bdbe298aa6b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:57:15 +0100 Subject: [PATCH 126/181] Scenario playtest test: a reference strategy and a failing shortcut for every scenario (C1) --- scripts/lib/scenario-ref.js | 72 ++++++++++++++++++++++++++++++++ tests/scenarios-playtest.test.js | 60 ++++++++++++++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 scripts/lib/scenario-ref.js create mode 100644 tests/scenarios-playtest.test.js diff --git a/scripts/lib/scenario-ref.js b/scripts/lib/scenario-ref.js new file mode 100644 index 0000000..2733491 --- /dev/null +++ b/scripts/lib/scenario-ref.js @@ -0,0 +1,72 @@ +// The reference player for the handmade scenarios (tests/scenarios-playtest.test.js), the sibling of scenario-bot.js +// (which plays the weekly ones). It plays inside the real game, headless, through the game's own actions, one plan +// step at a time whenever the bank allows it, plus the upkeep a careful human does every week: hot waves a size up, hot +// transit and exchange ports a LAG member, new peers at every exchange, routers before they fill. +// +// A plan is a list of steps, each [op, ...args]: +// ['bb', c] POP and broadband ['tr', c, tier] the cheapest transit there ['ix', c, tier] every exchange +// ['pop', c] a POP only ['link', a, b, tier, cable] a wave (routers upgraded first, a swap a day) +// ['hire', orders, params] the NOC intern on standing orders, as soon as the level allows +// ['wait', day] until that day ['served', g] until g Gbps are served ['prep', c, g] capacity for an event +// ['scrub', c, tier] a scrubbing center ['pnis'] a PNI with every unreached network that takes one +// ['loans'] take every loan the banks offer, from now on (the cheese plans) +const REF = String.raw`(()=>{ +const Q=window.__ref={log:[]}; +const quiet=f=>{const t=window.toast;window.toast=()=>{};try{return f();}finally{window.toast=t;}}; +Q.reserve=()=>Math.max(40000,1.3*(R.costMo||0)); +Q.can=x=>S.cash>=x+Q.reserve(); +Q.cheap=c=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!(Q.avoid||[]).includes(n.id)&&!S.transit.some(t=>t.city===c&&t.net===n.id)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0]; +Q.pop=c=>{if(!S.pops[c])ACT.buildPop({city:c});return !!S.pops[c];}; +Q.bb=c=>{Q.pop(c);if(S.pops[c]&&!S.pops[c].bb)ACT.launchBB({city:c});return !!(S.pops[c]&&S.pops[c].bb);}; +Q.tr=(c,tier=1)=>{Q.pop(c);const n=Q.cheap(c);if(!n)return true;ACT.buyTransit({city:c,net:n.id,tier});return true;}; +Q.ix=(c,tier=1)=>{if(!S.pops[c])return false;for(const x of ixIdsIn(c)){if(!ixName(x))continue;if(S.ixp[x]===undefined)ACT.buyIx({city:x,tier,signed:true});if(S.ixp[x]===undefined)continue;if(!S.rs[x])ACT.rs({city:x});ACT.peerAll({city:x});}return true;}; +// A wave: big waves need big routers at both ends, and a router swap takes a day, so the step waits (null) until they fit. +Q.link=(a,b,tier=1,via)=>{for(const c of [a,b])Q.pop(c);if(!S.pops[a]||!S.pops[b])return false; + for(const c of [a,b])for(let k=0;k<4&&!waveOk(a,b,tier);k++){const g0=S.pops[c].rgen||0;ACT.upRouter({city:c});if((S.pops[c].rgen||0)===g0)break;} + if(!waveOk(a,b,tier))return null;const n0=S.links.length;UI.via=via||null;UI.route=null;openLinkModal(a,b);ACT.buildLink({tier});closeModal();return S.links.length>n0;}; +Q.hire=(orders,par)=>{Q.wantHire=[orders||['transit','routers','repair'],par||{}];return true;}; +Q.hire0=(orders,par)=>{if(!opsCanHire()||!Q.can(20000))return false;if(!opsHired()){ACT.opsHire({id:'kevin'});closeModal();}if(!opsHired())return false; + for(const k of orders)if(!S.ops.on[k])ACT.opsToggle({k});for(const k in par)for(const [p,v] of Object.entries(par[k]))for(let i=0;i<8&&opsP(k,p)!==v;i++)ACT.opsParam({k,p});closeModal();return true;}; +Q.pnis=(tier=0)=>{for(const n of NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id])){const b=pniBatch(n.id,tier);if(!b||!b.orders.length||!Q.can(b.cost))continue;ACT.pniAll({net:n.id,tier});}return true;}; +Q.scrub=(c,tier=0)=>{ACT.buildScrub({city:c,tier});return true;}; +Q.loans=()=>{Q.loan=true;return true;}; +Q.served=g=>R.served>=g||null; +Q.wait=d=>S.day>=d||null; +// Before an event: transit for the event on top of the usual peak, and routers that can take it. +Q.prep=(c,g)=>{const need=(S.stats.peak||R.served||0)*1.2+g*1.15,cap=()=>S.transit.filter(t=>t.city===c).reduce((a,t)=>a+PORT[t.tier].g*(t.n||1),0); + for(let k=0;k<12&&cap()t.city===c).sort((a,b)=>PORT[a.tier].g*(a.n||1)-PORT[b.tier].g*(b.n||1))[0];if(!t)break;const c0=cap(); + if(t.tier=need/4&&portOk(c,t.tier+1))ACT.buyTransit({city:c,net:t.net,tier:t.tier+1});else ACT.lagT({id:t.id,d:1}); + if(cap()===c0){if(t.tier=RMAX)break;const r0=p.routers||1;ACT.addRouter({city:c});if((p.routers||1)===r0)break;}return true;}; +Q.est={pop:c=>S.pops[c]?0:popCost(c),bb:c=>(S.pops[c]?0:popCost(c))+bbCost(c),tr:()=>20000,ix:()=>25000,hire:()=>0,scrub:(c,t)=>SCRUB_TIERS[t||0].cost, + link:(a,b,t)=>(S.pops[a]?0:popCost(a))+(S.pops[b]?0:popCost(b))+waveMo(kmBetween(a,b),isSub(a,b),t)*2+20000}; +Q.upkeep=()=>{ + for(const l of S.links){if(l.kind!=='wave'||l.tier>=LT.length-1||linkDown(l)||(R.load[l.id]||0)=PORT.length-1||!portOk(t.city,t.tier+1)){if(Q.can(PORT[t.tier].setup+20000))ACT.lagT({id:t.id,d:1});if(lagCap(PORT[t.tier].g,t.n)===cap&&Q.can(80000))ACT.upRouter({city:t.city});} + else if(Q.can(PORT[t.tier+1].setup+30000))ACT.buyTransit({city:t.city,net:t.net,tier:t.tier+1});} + for(const x in S.ixp){if(S.myIx&&S.myIx[x])continue;const u=(R.useIx&&R.useIx[x])||0;if(u>=lagCap(PORT[S.ixp[x]].g,(S.ixn||{})[x])*0.75&&Q.can(30000))ACT.lagIx({city:x,d:1});} + if(!(opsHired()&&S.ops.on.routers))for(const c in S.pops){if((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1)>0.8&&Q.can(80000)){if((S.pops[c].routers||1)<2)ACT.addRouter({city:c});else ACT.upRouter({city:c});}}}; +Q.step=()=>{for(let k=0;k<6;k++){const s=Q.steps[Q.i];if(!s)return;const [op,...a]=s; + if(Q.est[op]&&!Q.can(Q.est[op](...a)))return;const ok=Q[op](...a);if(ok===null)return;Q.log.push(S.day+' '+op+' '+a.join(',')+(ok?'':' (failed)'));Q.i++;}}; +Q.day=()=>quiet(()=>{if(Q.wantHire&&Q.hire0(...Q.wantHire)){Q.log.push(S.day+' hired');Q.wantHire=null;} + if(Q.loan)for(const o of (S.loanOffers||[]).slice())ACT.takeLoan({id:o.id});closeModal(); + Q.step();if(S.day%7===0)Q.upkeep();}); +Q.start=(steps,o={})=>quiet(()=>{Q.steps=steps;Q.i=0;Q.avoid=o.avoid||[];Q.step();}); +})()`; + +// Starts scenario `id` (with `seed`, or its own), plays `plan` for up to `days` days (default: the scenario's), and +// returns the day it was won (or null), whether the network went broke, and the end state. +function play(ev, id, plan, { seed, days, avoid } = {}) { + ev(`localStorage.removeItem('sot-scn');beginGame('Ref',SCN.find(x=>x.id==='${id}').city,{scn:SCN.find(x=>x.id==='${id}')${seed ? ',seed:' + seed : ''}});if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`); + if (ev('typeof __ref') === 'undefined') ev(REF); + ev(`__ref.start(${JSON.stringify(plan)},${JSON.stringify({ avoid })})`); + const n = days || ev('S.scn.days'); + return JSON.parse(ev(`(()=>{let won=null;for(let i=0;i<${n};i++){__ref.day();dayTick();closeModal();if(S.scn.done){won=S.scn.done;break;}if(S.lost||S.scn.failed)break;} + return JSON.stringify({won,lost:!!S.lost,day:S.day,limit:S.scn.days,cash:Math.round(S.cash),served:Math.round(R.served)});})()`)); +} + +module.exports = { REF, play }; diff --git a/tests/scenarios-playtest.test.js b/tests/scenarios-playtest.test.js new file mode 100644 index 0000000..47cd222 --- /dev/null +++ b/tests/scenarios-playtest.test.js @@ -0,0 +1,60 @@ +// Rule C1, played (gameplay-rules): every handmade scenario has a reference strategy (scripts/lib/scenario-ref.js, +// the player's own actions, a plan a sensible human would follow) that wins within its days, and the obvious shortcut +// does not. The win days below were recorded in the 2.0.0 playtest; a balance change that moves them far is a change +// in how the scenario plays, so look before you re-record. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { play } = require('../scripts/lib/scenario-ref'); + +const HIRE = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix']]; +const home = (c) => [['bb', c], ['tr', c, 1], ['ix', c]]; +// ref: the reference plan; win: [earliest, latest] day it may win on; cheese: the shortcut, and `by`, the day before +// which it must not win (null: never within the scenario's days). +const PLAY = { + stg: { ref: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['link', 'fra', 'ams', 1], ['ix', 'ams'], ['bb', 'ams'], ['link', 'ams', 'lon', 1], ['ix', 'lon'], ['bb', 'lon'], ['link', 'fra', 'par', 1], ['ix', 'par'], ['bb', 'par'], ['hire', ['routers', 'repair', 'caches', 'pni', 'ix', 'sales'], { pni: { paid: true } }], ['link', 'stg', 'muc', 1], ['ix', 'muc'], ['bb', 'muc'], ['wait', 120], ['pnis'], ['link', 'lon', 'nyc', 2], ['ix', 'nyc'], ['bb', 'nyc'], ['wait', 200], ['pnis']], + win: [120, 240], cheese: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['loans'], ['hire', ['routers', 'repair']]], by: null }, + // The other way round the planet: Paris, New York, Los Angeles, Tokyo, Hong Kong, Singapore. + redsea: { ref: [...home('mrs'), ['link', 'mrs', 'par', 1], ['bb', 'par'], ['ix', 'par'], ['link', 'par', 'nyc', 1, 'amitie'], ['tr', 'nyc', 1], ['ix', 'nyc'], ['link', 'nyc', 'lax', 1], ['ix', 'lax'], ['tr', 'lax', 1], ['link', 'lax', 'tok', 1, 'jup'], ['bb', 'tok'], ['tr', 'tok', 1], ['ix', 'tok'], ['link', 'tok', 'hkg', 1, 'apg'], ['bb', 'hkg'], ['tr', 'hkg', 1], ['ix', 'hkg'], ['link', 'hkg', 'sin', 1], ['bb', 'sin'], ['tr', 'sin', 1], ['ix', 'sin'], HIRE], + win: [100, 250], cheese: [...home('mrs'), ['loans'], ['link', 'mrs', 'sin', 1], ['bb', 'sin']], by: null }, + spat: { ref: [...home('nyc'), HIRE], avoid: ['cog'], win: [50, 140], cheese: [...home('nyc'), ['hire', ['routers', 'repair']]], by: 160 }, + carnaval: { ref: [...home('rio'), ['hire'], ['wait', 69], ['prep', 'rio', 400], ['wait', 76], ['prep', 'rio', 400], ['wait', 83], ['prep', 'rio', 400]], win: [95, 95], cheese: [...home('rio'), ['loans']], by: null }, + darien: { ref: [...home('pan'), ['link', 'pan', 'bog', 1, 'pccs'], ['bb', 'bog'], ['ix', 'bog'], ['link', 'bog', 'lim', 1], ['bb', 'lim'], ['ix', 'lim'], ['link', 'lim', 'scl', 1], ['bb', 'scl'], ['ix', 'scl'], ['link', 'scl', 'sao', 1], ['bb', 'sao'], ['tr', 'sao', 1], ['ix', 'sao'], HIRE], + win: [30, 90], cheese: [...['pan', 'bog', 'lim', 'scl', 'sao'].flatMap((c) => [['bb', c], ['tr', c, 1]]), ['hire']], by: null }, + c2c: { ref: [...home('cpt'), ['link', 'cpt', 'jnb', 1], ['bb', 'jnb'], ['tr', 'jnb', 1], ['ix', 'jnb'], ['link', 'jnb', 'nbo', 1], ['bb', 'nbo'], ['ix', 'nbo'], ['link', 'nbo', 'cai', 1], ['bb', 'cai'], ['ix', 'cai'], ['link', 'jnb', 'lag', 1], ['bb', 'lag'], ['ix', 'lag'], HIRE], + win: [70, 200], cheese: [...home('cpt'), ['link', 'cpt', 'cai', 0], ['pop', 'lag'], ['pop', 'nbo'], ['hire']], by: null }, + ixbr: { ref: [...home('sao'), ...[['sao', 'rio', 1], ['sao', 'cpq', 0], ['sao', 'cwb', 0], ['cwb', 'poa', 0], ['rio', 'bhz', 0], ['bhz', 'bsb', 0], ['bsb', 'gyn', 0], ['rio', 'ssa', 0], ['ssa', 'rec', 0], ['rec', 'for', 0], ['rec', 'nat', 0], ['for', 'bel', 0], ['bel', 'mao', 0], ['bsb', 'cgb', 0], ['sao', 'vix', 0]].flatMap(([a, b, t]) => [['link', a, b, t], ['ix', b, 0]]), ['bb', 'rio'], ['tr', 'rio', 1], ['bb', 'bsb'], ['tr', 'bsb', 1], ['bb', 'for'], ['tr', 'for', 1], HIRE], + win: [40, 120], cheese: [['bb', 'sao'], ['tr', 'sao', 1], ...['sao', 'rio', 'bsb', 'bhz', 'cwb', 'poa', 'for', 'rec', 'ssa', 'cpq', 'gyn', 'bel', 'mao', 'nat', 'vix', 'cgb'].flatMap((c) => [['pop', c], ['ix', c, 0]]), ['hire']], by: null }, + // Seoul at home is enough here: the cheese is just playing, so it only must not be instant. + gangnam: { ref: [...home('icn'), ['link', 'icn', 'tok', 1], ['ix', 'tok'], ['tr', 'tok', 1], ['link', 'icn', 'hkg', 1], ['ix', 'hkg'], ['tr', 'hkg', 1], HIRE], win: [50, 120], cheese: [...home('icn'), ['loans']], by: 50 }, + // Bigger routers bring Flowspec, which also takes floods: without a scrubbing center it takes twice as long. + flood: { ref: [...home('ams'), ['scrub', 'ams', 1], ['tr', 'ams', 1], HIRE], win: [80, 200], cheese: [...home('ams'), ['tr', 'ams', 1], ['loans']], by: 180 }, + fttb: { ref: [...home('syd'), ['link', 'syd', 'akl', 0, 'tasman'], ['link', 'syd', 'nou', 0, 'gond'], ...['mel', 'bne', 'adl', 'per'].flatMap((c) => [['bb', c], ['tr', c, 1]]), ['link', 'syd', 'mel', 1], ['link', 'syd', 'bne', 1], ['link', 'mel', 'adl', 1], ['link', 'adl', 'per', 0], HIRE], + win: [80, 200], cheese: [...['syd', 'mel', 'bne', 'adl', 'per'].map((c) => ['bb', c]), ['tr', 'syd', 1], ['link', 'syd', 'akl', 0, 'tasman'], ['link', 'syd', 'nou', 0, 'gond'], ['loans']], by: 60 }, + // Tallinn has no transit: over the water to Helsinki and Stockholm on two cables each way, and round by land to Riga. + baltic: { ref: [['bb', 'tll'], ['ix', 'tll'], ['link', 'tll', 'hel', 1, 'balt'], ['tr', 'hel', 1], ['link', 'tll', 'sto', 1, 'balt'], ['tr', 'sto', 1], ['link', 'tll', 'hel', 1, 'elisa'], ['link', 'tll', 'rix', 1], ['tr', 'rix', 1], ['hire', ['transit', 'routers', 'repair', 'ix']]], + win: [90, 200], cheese: [['bb', 'tll'], ['ix', 'tll'], ['loans']], by: null }, + // The 1.6T chains: grow the traffic first, then light every hop at once (a day-0 build also gets there, just). + pac: { ref: [...home('hnl'), ...home('lax'), ...home('syd'), ['link', 'lax', 'tok', 1, 'jup'], HIRE, ['served', 145], ['link', 'lax', 'hnl', 4, 'seaus'], ['link', 'hnl', 'suv', 4, 'scx'], ['link', 'suv', 'syd', 4, 'scx']], + win: [50, 120], cheese: [...home('hnl'), ...home('lax'), ...home('syd'), ['link', 'lax', 'tok', 1, 'jup'], ['link', 'lax', 'syd', 3, 'hwk'], ['loans']], by: null }, + atl: { ref: [['bb', 'pdl'], ['tr', 'pdl', 1], ...home('mia'), ...home('mad'), ...home('lis'), HIRE, ['link', 'mia', 'bda', 4, 'sol'], ['link', 'bda', 'pdl', 4, 'sol'], ['link', 'pdl', 'mad', 4, 'sol'], ['served', 90], ['link', 'lis', 'tci', 4, 'ace'], ['link', 'tci', 'lag', 4, 'twoaf'], ['bb', 'lag']], + win: [40, 120], cheese: [['bb', 'pdl'], ['tr', 'pdl', 1], ...home('mia'), ...home('mad'), ...home('lis'), ['link', 'mia', 'mad', 3, 'col3'], ['link', 'lis', 'lag', 3, 'equi'], ['loans']], by: null }, +}; + +test('C1 played: every scenario has a reference strategy and a shortcut that fails', () => { + const g = load(); + const ids = JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))')); + assert.deepEqual(Object.keys(PLAY).sort(), ids.slice().sort(), 'C1: every scenario has a reference strategy here'); +}); + +for (const [id, P] of Object.entries(PLAY)) { + test(`${id}: the reference wins in its days, the shortcut does not`, () => { + const g = load(); + const r = play(g.ev, id, P.ref, { avoid: P.avoid }); + assert.ok(r.won !== null, `${id}: the reference does not win (${JSON.stringify(r)})`); + assert.ok(r.won >= P.win[0] && r.won <= P.win[1] && (id === 'carnaval' || r.won <= r.limit * 0.75), `${id}: won on day ${r.won}, want ${P.win.join('-')} of ${r.limit}`); + const c = play(g.ev, id, P.cheese, { days: P.by || undefined }); + assert.ok(c.won === null, `${id}: the shortcut wins on day ${c.won}${P.by ? ` (before day ${P.by})` : ''}`); + assert.deepEqual(g.errors, []); + }); +} From 97223e9d1234c1b281bf8b3eea87f79f55dc529b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 19:59:01 +0100 Subject: [PATCH 127/181] Puzzle playtest: Flash Boys' one-star reference is a one-star build; a test that each pack's idea is needed for three stars --- tests/puzzles.test.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index de3ba39..1ba9ef3 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -18,7 +18,7 @@ const REF = { downunder: { one: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1]], three: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1], ['bne', 'adl', 'land', 1]] }, edgelord: { one: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]], three: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'concerto', 2], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]] }, hubcap: { one: [['@rt', 'lon', 5, 1], ['lon', 'par', 'pasdc', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1]], three: [['@rt', 'lon', 5, 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'uly', 1]] }, - flash: { one: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]] }, + flash: { one: [['nyc', 'lon', 'hibx', 1]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]] }, baltic: { one: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['@route', 1, 'fast']], three: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['fra', 'tll', 'land', 1], ['@route', 1, 'fast']] }, fjord: { one: [['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']], three: [['par', 'svg', 'land', 1], ['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']] }, braces: { one: [['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]] }, @@ -530,3 +530,18 @@ test('a POP in a thin market costs its higher monthly rent too, and the panel sa assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo')); assert.deepEqual(errors, []); }); + +test('each pack\'s idea is needed: three stars without it fail, and the one-star builds are not secretly three', () => { + const { ev, errors } = load(); + const stars = (id, steps) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, steps); return evalP(ev).stars; }; + const packs = JSON.parse(ev('JSON.stringify(Object.fromEntries(PZ.map(p=>[p.id,p.pack])))')); + for (const id of Object.keys(REF)) { + // A ring puzzle's cheapest delivering build is a ring, which is already N-1. + if (id !== 'fire') assert.ok(stars(id, REF[id].one) < 3, `${id}: the one-star reference earns three stars`); + if (packs[id] === 'rodeo') assert.ok(stars(id, REF[id].three.filter((s) => s[0] !== '@rt')) < 3, `${id}: three stars on the starter routers`); + if (REF[id].three.some((s) => s[0] === '@route')) assert.ok(stars(id, REF[id].three.filter((s) => s[0] !== '@route')) < 3, `${id}: three stars without the routing choice`); + // N-1 Club: the brute-force answer (every one-star link doubled) is over budget or not N-1. + if (packs[id] === 'n1') assert.ok(stars(id, [...REF[id].one, ...links(REF[id].one)]) < 3, `${id}: doubling every link earns three stars`); + } + assert.deepEqual(errors, []); +}); From d309b70e0e468e00b09a3aa5d36ebd143730f290 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 20:00:50 +0100 Subject: [PATCH 128/181] CHANGELOG: scenario tuning --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e87a564..2b0dd5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. - Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. - Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price. - Take a seat on a new consortium subsea cable (#173). Capacity conferences offer them, and now and then a consortium calls from level 2: pay your share of the build, wait for the ship, then own one, two or four fiber pairs and light them with your own optics, your way onto your own subsea glass before Tier 1. A cut on that cable cuts your pairs too. From 271c562205fad79e3ac6423b7b0d6e78ba27a758 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 20:22:20 +0100 Subject: [PATCH 129/181] Tests: Mind the Gap, Order and Progress, Fibre to the Basement and Flood Season checks follow the tuned goals --- tests/modes.test.js | 10 ++++++---- tests/regions.test.js | 8 ++++++-- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/tests/modes.test.js b/tests/modes.test.js index 95ef1bd..92c56c8 100644 --- a/tests/modes.test.js +++ b/tests/modes.test.js @@ -299,12 +299,12 @@ test('#34 scenario goal, progress and customer level are always in view', () => ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderAll()"); const left = () => dom.window.document.getElementById('leftBody').textContent; assert.match(left(), /Mind the Gap/); - assert.match(left(), /POP in Bogotá/); + assert.match(left(), /Bogotá on your network/); assert.match(left(), /days left/); assert.match(left(), /Customer level 1 of 13/); assert.equal(ev("$('hScn').hidden"), false, 'scenario chip in the top bar'); const f0 = ev('scnProg().f'); - ev("S.cash=1e8;ACT.buildPop({city:'bog'});ACT.buildPop({city:'lim'});compute();renderAll()"); + ev("S.cash=1e8;UI.via='pccs';openLinkModal('pan','bog');ACT.buildLink({tier:1});closeModal();compute();renderAll()"); assert.ok(ev('scnProg().f') > f0, 'progress moves when a goal step is reached'); assert.match(ev("$('hScnVal').textContent"), /%/); assert.match(ev("$('hTier').textContent"), /Lv 1/); @@ -361,8 +361,10 @@ test('Flood Season: attacks keep coming, grow, and only count when service held' 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%+ - ev("S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,worst:0.99});ddosDone({city:'ams',gbps:20,worst:0.5});ddosDone({city:'xyz',gbps:30,worst:1})"); + // scoring: held only if service stayed at 97%+, and a terabit one only with scrubbing or Flowspec + ev("S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,vec:'http',worst:0.99})"); + assert.equal(ev('S.stats.ddosOk+S.stats.ddosOkBig'), 1, 'held, but no terabit credit without mitigation'); + ev("S.scrubs.push({city:'ams',tier:1});S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,worst:0.99});ddosDone({city:'ams',gbps:20,worst:0.5});ddosDone({city:'xyz',gbps:30,worst:1})"); assert.equal(ev('S.stats.ddosOk'), 2); assert.equal(ev('S.stats.ddosOkBig'), 1); assert.equal(ev('S.stats.ddosLost'), 1); diff --git a/tests/regions.test.js b/tests/regions.test.js index 0ae73fa..202def9 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -563,8 +563,10 @@ test('the Amazon doubles overland fiber, and there is a national-operator scenar assert.equal(ev('S.scn.id'), 'ixbr'); assert.equal(ev('brIxN()'), 0); ev("S.cash=1e9;for(const c of ['sao','rio','mao'])ACT.buildPop({city:c});S.ixp.sao=1;S.ixp.mao=1;compute()"); - assert.equal(ev('brIxN()'), 2); + assert.equal(ev('brIxN()'), 1, 'a Manaus port on a POP the backbone does not reach does not count'); assert.equal(ev("scnProg().items[1].v"), 1, 'Manaus step done'); + ev("S.links.push({id:'y1',a:'sao',b:'mao',km:2700,sub:false,kind:'wave',tier:0,mo:1});compute()"); + assert.equal(ev('brIxN()'), 2, 'joined up, it counts'); assert.deepEqual(errors, []); }); @@ -670,8 +672,10 @@ test('Fibre to the Basement: own fibre skips the wholesale cut but pays the levy assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), false, 'still needs cables overseas'); ev("S.links.push({id:'x1',a:'syd',b:'tok',km:8000,sub:true,cable:'sushi',kind:'wave',tier:1,mo:1},{id:'x2',a:'per',b:'sin',km:4000,sub:true,cable:'avo',kind:'wave',tier:1,mo:1},{id:'x3',a:'mel',b:'hba',km:600,sub:true,cable:'ferry',kind:'wave',tier:1,mo:1})"); assert.equal(ev('auExits()'), 2, 'Bass Strait does not count as overseas'); + assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), false, 'still needs the traffic'); + ev('R.served=FTTB_G'); assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), true); - assert.equal(ev("SCN_PROG.fttb().length"), 6); + assert.equal(ev("SCN_PROG.fttb().length"), 7); assert.deepEqual(errors, []); }); From 79616ead03e85075bd6d6b9174280e6845acde2f Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 20:35:18 +0100 Subject: [PATCH 130/181] Title on phones: a long Continue button wraps instead of making the card scroll sideways --- src/game/95-modals/40-title.js | 2 +- src/styles/40-modal.css | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index e285888..99dfade 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -19,7 +19,7 @@ function showTitle(){ openModal(`
${langPick('langTitle')}

Series
of Tubes

${tr('title.build_an_internet_lay_fiber_between')}

${isPhone()?installRow():''} - ${top?`
${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}
`:''} + ${top?`
${btn(tr('title.continue_name_date',{name:esc(top.name||tr('common.unnamed_network')),date:dateStr(top.day)}),'cont',{id:top.id},'pink big')}
`:''} ${many?slotsHtml():''}
${doorsHtml()} diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 4050efa..0f3265d 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -184,3 +184,5 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .presets .preset{flex-direction:row;align-items:center;gap:6px;padding:6px 10px 5px}.presets .preset i{font-size:20px}.presets .preset b{font-size:15px} .presets .preset.on::after{display:none}#presetWhat{margin:6px 0 0} .homepick{width:100%} +.tcont .b{white-space:normal;max-width:100%;overflow-wrap:anywhere;line-height:1.15} +#modalCard{overflow-x:hidden} From 8c7b7d3c6b2eaeb5baefb5f4ac87d8c9818799b5 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 20:40:13 +0100 Subject: [PATCH 131/181] A calmer in-game menu: one main button, six tiles, quiet links underneath --- src/game/90-actions/89-game-and-settings.js | 18 +++++------------- src/styles/40-modal.css | 5 +++++ 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index bbd6d2c..bff8c7e 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -25,20 +25,12 @@ Object.assign(ACT,{ // An import is a new network next to the others: the one playing here is saved and kept. try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`
AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}

${esc(S.name)}

- ${saveFailing()?`

${saveFailMsg()}

`:`

${tr('game_and_settings.your_game_saves_itself_every_few')}

`}${isPhone()?installRow():''} + ${saveFailing()?`

${saveFailMsg()}

`:`

${tr('game_and_settings.your_game_saves_itself_every_few')}

`} + +
${chatHtml()}${issueHtml()}`);}, settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();}, diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 0f3265d..3603f80 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -186,3 +186,8 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .homepick{width:100%} .tcont .b{white-space:normal;max-width:100%;overflow-wrap:anywhere;line-height:1.15} #modalCard{overflow-x:hidden} +.menu-tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-top:10px} +.mtile{border:3px solid var(--ink);border-radius:14px;background:var(--paper);box-shadow:0 3px 0 var(--ink);padding:8px 4px 7px;display:flex;flex-direction:column;align-items:center;gap:2px;cursor:pointer;font:800 13px/1.15 var(--display);color:var(--ink);text-align:center;min-height:68px;justify-content:center} +.mtile i{font-style:normal;font-size:22px;line-height:1}.mtile:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} +.menu-links{margin:12px 0 0;text-align:center;line-height:2;color:var(--ink2)} +.menu-links .lnk{background:none;border:0;padding:4px 2px;font-weight:700;font-size:14px;font-family:inherit;color:var(--ink2);text-decoration:underline;text-underline-offset:3px;cursor:pointer} From b008b3a652952f84605013d3140f45c38d9bceb6 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 20:59:13 +0100 Subject: [PATCH 132/181] Gangnam Style Peering: sender pays that bites Under the scenario's new sender rule, Seoul transit carries a sender-pays fee per Gbps, the Korean incumbents take traffic only over a paid PNI, home broadband pays less, and Korean users mind any far exit, peering included. The goal asks for 700 Gbps, Seoul 92% served well, 99% reach and a monthly profit. Korea outside the scenario is unchanged; older Gangnam saves pick up the rule. --- site/i18n/de.js | 8 ++++++-- site/i18n/es.js | 8 ++++++-- site/i18n/fr.js | 8 ++++++-- site/i18n/it.js | 8 ++++++-- site/i18n/pt.js | 8 ++++++-- src/game/10-catalog/10-economy.js | 4 ++++ src/game/60-features/20-scenarios.js | 6 +++++- src/game/80-simulation/30-compute.js | 15 +++++++++------ src/game/80-simulation/40-billing.js | 4 +++- src/game/80-simulation/50-sanitize.js | 2 +- .../80-simulation/80-geography-and-latency.js | 2 ++ src/game/80-simulation/90-sites-and-service.js | 3 ++- src/game/88-days/10-day-tick.js | 2 +- src/game/93-ui/50-city-panel.js | 6 +++--- src/game/94-dashboard/10-progress.js | 2 +- src/i18n/en.js | 8 ++++++-- 16 files changed, 67 insertions(+), 27 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 1c13625..c05ddcb 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -757,6 +757,7 @@ "city_panel.second_site_and_metro_ring":"Zweiter Standort und Metro-Ring", "city_panel.sell_internet_to_homes_here_starts":"Verkauf hier Internet an Haushalte. Startet bei etwa {start} und wächst Richtung {max}, solange der Service gut ist. Bringt jeden Monat {rate} pro ausgeliefertem Gbps.", "city_panel.sells_pnis_down_to_1g":"verkauft PNIs ab 1G", +"city_panel.sender_pays_fee_per_gbps":"Sender zahlt: +{fee} pro Gbps Transit", "city_panel.served_in_city":"Ausgeliefert in {city}", "city_panel.serving_v":"liefert {v}", "city_panel.shut_this_pop_down_its_links":"Diesen POP abschalten: Seine Links, Ports und Caches fallen mit weg, und allen Kunden, die davon abhängen, wird gekündigt. Dafür zahlst du eine Vertragsstrafe.", @@ -2928,9 +2929,11 @@ "progress.done_in_d_days":"Geschafft in {d} Tagen!", "progress.floods_that_got_through":"Fluten, die durchgekommen sind", "progress.ix_brrr_ports_on_your_backbone":"IX.brrr-Ports an deinem Backbone", +"progress.monthly_profit":"Monatsgewinn", "progress.n_of_m":"{n} von {m}", "progress.next_name_unlocks_what":"Als Nächstes: {name} schaltet {what} frei", "progress.not_tier_1_right_now_why":"Gerade nicht Tier 1: {why}.", +"progress.seoul_served_well":"Seoul gut versorgt (geliefert und schnell)", "progress.terabit_floods_held":"Abgewehrte Terabit-Fluten", "progress.under_attack_now":"Gerade unter Beschuss", "progress.your_score_peak_traffic":"Dein Ergebnis: Spitzen-Traffic", @@ -3359,7 +3362,6 @@ "scenarios.1_6t_on_every_hop_from":"1.6T auf jedem Hop von Miami nach Madrid und von Lissabon nach Lagos, und 100 Gbps bedient", "scenarios.90_days_in_a_row_with":"90 Tage am Stück mit 99,5 % der Nachfrage bedient", "scenarios.99_reach_and_150_gbps_served":"99 % Reichweite und 150 Gbps bedient", -"scenarios.99_reach_and_200_gbps_served":"99 % Reichweite und 200 Gbps bedient, ohne pleitezugehen", "scenarios.a_path_from_cape_town_to_cairo_lagos":"Ein Pfad von Kapstadt nach Kairo, Lagos und Nairobi auch in deinem Netz, und 150 Gbps bedient", "scenarios.a_path_from_los_angeles_to":"Ein Pfad von Los Angeles nach Sydney mit 1.6T auf jedem Hop, ein Pfad von Los Angeles nach Tokio, und 150 Gbps bedient", "scenarios.a_path_from_marseille_to_singapore":"Ein Pfad von Marseille nach Singapur, und 80 Gbps zwischen Asien und dem Rest deines Netzes, 30 Tage am Stück", @@ -3388,7 +3390,8 @@ "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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Sandbox-Modus
Eine Milliarde Dollar, alles freigeschaltet, und nichts geht jemals kaputt. Bau das Internet, das du schon immer wolltest.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Brasilien ist ein Kontinent: vierzig IX.brrr-Exchanges, Tausende Provedores und der Amazonas zwischen dir und dem Norden.", -"scenarios.seoul_the_fastest_hungriest_eyeballs":"Seoul. Die schnellsten, hungrigsten Privatkunden der Welt, Transit zum vierfachen Preis und drei Platzhirsche, die dir jedes Gigabit in Rechnung stellen, das du ihnen schickst.", +"scenarios.seoul_sender_pays_d":"Seoul, wo der Sender zahlt. Jedes Gbps, das ein Carrier nach Korea liefert, kostet dich zusätzlich zur Transitrechnung eine Sender-pays-Gebühr, die drei Platzhirsche reden nur über einen bezahlten PNI, Gigabit für zu Hause kostet so viel wie ein Bibimbap, und koreanische Nutzer merken jede Millisekunde. Transit in Tokio ist billig, wenn deine Kunden die Reise aushalten.", +"scenarios.seoul_sender_pays_goal":"{g} Gbps ausgeliefert, Seoul gut versorgt ({q} %), 99 % Reichweite und ein Monatsgewinn", "scenarios.shark_season_subsea_cuts_twice_as":"Haisaison: Seekabelschnitte doppelt so wahrscheinlich", "scenarios.start_in_panama_city_nothing_crosses":"Start in Panama-Stadt. Über Land kommt nichts durch den Darién Gap, und die Anden stehen allem anderen im Weg.", "scenarios.start_in_stuttgart_where_nobody":"Start in Stuttgart, wo niemand Transit verkauft. Erreiche das Internet nur über Peering, PNIs, Caches und deine eigene Glasfaser. Kein Transit, nirgends, niemals.", @@ -3448,6 +3451,7 @@ "sites_and_service.level_n":"Level {n}", "sites_and_service.n_ports":"{n} Ports", "sites_and_service.no_path_right_now":"gerade kein Pfad", +"sites_and_service.p_of_city_s_traffic_comes_from_kr":"{p} des Traffics von {city} kommt aus {to}: {ms} ms Round Trip. Koreanische Nutzer merken alles über 8 ms, und ab 40 ms gilt Breitband als schlechter Service. Liefere mehr aus Seoul: Peering, Caches und PNIs hier oder lokaler Transit, wenn du die Sender-pays-Gebühr verkraftest.", "sites_and_service.p_of_city_s_traffic_is":"{p} des Traffics von {city} läuft per Backhaul zum Transit in {to}: {ms} ms Round Trip. Nutzer merken alles über 20 ms (etwa 1.500 km), und ab 50 ms gelten Breitband und Internetdienste als schlechter Service. Kauf Transit hier oder in der Nähe oder peere lokal.", "sites_and_service.path_latency_lat":"Pfad-Latenz: {lat}", "sites_and_service.pn_routers":"{pn}-Router", diff --git a/site/i18n/es.js b/site/i18n/es.js index 03be971..c4dd964 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -755,6 +755,7 @@ "city_panel.second_site_and_metro_ring":"Segunda sede y anillo metropolitano", "city_panel.sell_internet_to_homes_here_starts":"Vende internet a hogares de aquí. Empieza en unos {start} y crece hacia {max} mientras el servicio sea bueno. Paga {rate} por Gbps servido, cada mes.", "city_panel.sells_pnis_down_to_1g":"vende PNIs desde 1G", +"city_panel.sender_pays_fee_per_gbps":"Paga quien envía: +{fee} por Gbps de tránsito", "city_panel.served_in_city":"Servido en {city}", "city_panel.serving_v":"sirviendo {v}", "city_panel.shut_this_pop_down_its_links":"Apagar este POP: sus enlaces, puertos y cachés se van con él, y todos los clientes que dependen de él se pierden, con una penalización por rescisión anticipada.", @@ -2926,9 +2927,11 @@ "progress.done_in_d_days":"¡Hecho en {d} días!", "progress.floods_that_got_through":"Inundaciones que pasaron", "progress.ix_brrr_ports_on_your_backbone":"Puertos IX.brrr en tu backbone", +"progress.monthly_profit":"Beneficio mensual", "progress.n_of_m":"{n} de {m}", "progress.next_name_unlocks_what":"Siguiente: {name} desbloquea {what}", "progress.not_tier_1_right_now_why":"Ahora no eres Tier 1: {why}.", +"progress.seoul_served_well":"Seúl bien servida (entregado y rápido)", "progress.terabit_floods_held":"Inundaciones de terabits contenidas", "progress.under_attack_now":"Bajo ataque ahora", "progress.your_score_peak_traffic":"Tu puntuación: tráfico pico", @@ -3357,7 +3360,6 @@ "scenarios.1_6t_on_every_hop_from":"1.6T en cada salto de Miami a Madrid y de Lisboa a Lagos, y 100 Gbps servidos", "scenarios.90_days_in_a_row_with":"90 días seguidos con el 99,5 % de la demanda servida", "scenarios.99_reach_and_150_gbps_served":"99 % de alcance y 150 Gbps servidos", -"scenarios.99_reach_and_200_gbps_served":"99 % de alcance y 200 Gbps servidos sin arruinarte", "scenarios.a_path_from_cape_town_to_cairo_lagos":"Un camino de Ciudad del Cabo a El Cairo, con Lagos y Nairobi también en tu red, y 150 Gbps servidos", "scenarios.a_path_from_los_angeles_to":"Un camino de Los Ángeles a Sídney con 1.6T en cada salto, un camino de Los Ángeles a Tokio, y 150 Gbps servidos", "scenarios.a_path_from_marseille_to_singapore":"Un camino de Marsella a Singapur, y 80 Gbps entre Asia y el resto de tu red durante 30 días seguidos", @@ -3386,7 +3388,8 @@ "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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Modo sandbox
Mil millones de dólares, todos los desbloqueos y nada se rompe nunca. Construye el internet que siempre quisiste.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Brasil es un continente: cuarenta intercambios IX.brrr, miles de provedores, y el Amazonas entre tú y el norte.", -"scenarios.seoul_the_fastest_hungriest_eyeballs":"Seúl. Los eyeballs más rápidos y hambrientos de la Tierra, tránsito a cuatro veces el precio, y tres operadores históricos que te facturan cada gigabit que les mandas.", +"scenarios.seoul_sender_pays_d":"Seúl, donde paga quien envía. Cada Gbps que un carrier entrega en Corea te cuesta una tasa de «paga quien envía» además de la factura de tránsito, los tres operadores históricos solo hablan por un PNI de pago, el gigabit doméstico se vende al precio de un bibimbap y los usuarios coreanos notan cada milisegundo. El tránsito en Tokio es barato, si tus clientes aguantan el viaje.", +"scenarios.seoul_sender_pays_goal":"{g} Gbps servidos, Seúl bien servida ({q} %), 99 % de alcance y beneficio mensual", "scenarios.shark_season_subsea_cuts_twice_as":"Temporada de tiburones: los cortes submarinos son el doble de probables", "scenarios.start_in_panama_city_nothing_crosses":"Empieza en Ciudad de Panamá. Nada cruza el Tapón del Darién por tierra, y los Andes se interponen en todo lo demás.", "scenarios.start_in_stuttgart_where_nobody":"Empieza en Stuttgart, donde nadie vende tránsito. Llega a internet solo por peering, PNIs, cachés y tu propia fibra. Sin tránsito en ningún sitio, nunca.", @@ -3446,6 +3449,7 @@ "sites_and_service.level_n":"Nivel {n}", "sites_and_service.n_ports":"{n} puertos", "sites_and_service.no_path_right_now":"sin ruta ahora mismo", +"sites_and_service.p_of_city_s_traffic_comes_from_kr":"El {p} del tráfico de {city} viene de {to}: {ms} ms de ida y vuelta. Los usuarios coreanos notan todo lo que pase de 8 ms, y por encima de 40 ms la banda ancha cuenta como mal servicio. Sirve más desde Seúl: peering, cachés y PNIs aquí, o tránsito local si aguantas la tasa de «paga quien envía».", "sites_and_service.p_of_city_s_traffic_is":"El {p} del tráfico de {city} se lleva por backhaul al tránsito de {to}: {ms} ms de ida y vuelta. Los usuarios notan cualquier cosa por encima de 20 ms (unos 1500 km), y pasados 50 ms la banda ancha y los servicios de internet cuentan como mal servicio. Compra tránsito aquí o cerca, o haz peering local.", "sites_and_service.path_latency_lat":"Latencia de la ruta: {lat}", "sites_and_service.pn_routers":"{pn} routers", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4f7ccad..c6c08b6 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -755,6 +755,7 @@ "city_panel.second_site_and_metro_ring":"Second site et anneau métropolitain", "city_panel.sell_internet_to_homes_here_starts":"Vends de l’Internet aux foyers d’ici. Démarre vers {start} et grimpe vers {max} tant que le service est bon. Rapporte {rate} par Gbps servi, chaque mois.", "city_panel.sells_pnis_down_to_1g":"vend des PNI dès 1G", +"city_panel.sender_pays_fee_per_gbps":"L’expéditeur paie : +{fee} par Gbps de transit", "city_panel.served_in_city":"Servi à {city}", "city_panel.serving_v":"dessert {v}", "city_panel.shut_this_pop_down_its_links":"Ferme ce POP : ses liens, ports et caches partent avec, et chaque client qui en dépend est lâché, avec une pénalité de résiliation anticipée.", @@ -2926,9 +2927,11 @@ "progress.done_in_d_days":"Fini en {d} jours !", "progress.floods_that_got_through":"Vagues passées", "progress.ix_brrr_ports_on_your_backbone":"Ports IX.brrr sur votre backbone", +"progress.monthly_profit":"Bénéfice mensuel", "progress.n_of_m":"{n} sur {m}", "progress.next_name_unlocks_what":"Prochain : {name} débloque {what}", "progress.not_tier_1_right_now_why":"Pas Tier 1 pour l’instant : {why}.", +"progress.seoul_served_well":"Séoul bien servie (livré et rapide)", "progress.terabit_floods_held":"Vagues térabit encaissées", "progress.under_attack_now":"Sous attaque", "progress.your_score_peak_traffic":"Ton score : pic de trafic", @@ -3357,7 +3360,6 @@ "scenarios.1_6t_on_every_hop_from":"1.6T sur chaque saut de Miami à Madrid et de Lisbonne à Lagos, et 100 Gbps servis", "scenarios.90_days_in_a_row_with":"90 jours d’affilée avec 99,5 % de la demande servie", "scenarios.99_reach_and_150_gbps_served":"99 % de couverture et 150 Gbps servis", -"scenarios.99_reach_and_200_gbps_served":"99 % de couverture et 200 Gbps servis sans faire faillite", "scenarios.a_path_from_cape_town_to_cairo_lagos":"Un chemin du Cap au Caire, avec Lagos et Nairobi aussi sur votre réseau, et 150 Gbps servis", "scenarios.a_path_from_los_angeles_to":"Un chemin de Los Angeles à Sydney en 1.6T sur chaque saut, un chemin de Los Angeles à Tokyo, et 150 Gbps servis", "scenarios.a_path_from_marseille_to_singapore":"Un chemin de Marseille à Singapour, et 80 Gbps entre l’Asie et le reste de ton réseau pendant 30 jours d’affilée", @@ -3386,7 +3388,8 @@ "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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Mode bac à sable
Un milliard de dollars, tout débloqué, et rien ne casse jamais. Construis l’Internet dont tu as toujours rêvé.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Le Brésil est un continent : quarante IX.brrr, des milliers de provedores, et l’Amazonie entre toi et le nord.", -"scenarios.seoul_the_fastest_hungriest_eyeballs":"Séoul. Les eyeballs les plus rapides et les plus voraces de la planète, du transit à quatre fois le prix, et trois opérateurs historiques qui te facturent chaque gigabit que tu leur envoies.", +"scenarios.seoul_sender_pays_d":"Séoul, où l’expéditeur paie. Chaque Gbps qu’un opérateur livre en Corée te coûte une taxe « l’expéditeur paie » en plus de la facture de transit, les trois opérateurs historiques ne parlent que par un PNI payant, le gigabit à la maison se vend au prix d’un bibimbap et les utilisateurs coréens remarquent chaque milliseconde. Le transit à Tokyo est bon marché, si tes clients supportent le voyage.", +"scenarios.seoul_sender_pays_goal":"{g} Gbps servis, Séoul bien servie ({q} %), 99 % de portée et un bénéfice mensuel", "scenarios.shark_season_subsea_cuts_twice_as":"Saison des requins : coupures sous-marines deux fois plus probables", "scenarios.start_in_panama_city_nothing_crosses":"Démarre à Panama City. Rien ne traverse le bouchon du Darién par voie terrestre, et les Andes barrent la route à tout le reste.", "scenarios.start_in_stuttgart_where_nobody":"Démarre à Stuttgart, où personne ne vend de transit. Atteins Internet uniquement via peering, PNI, caches et ta propre fibre. Aucun transit, nulle part, jamais.", @@ -3446,6 +3449,7 @@ "sites_and_service.level_n":"Niveau {n}", "sites_and_service.n_ports":"{n} ports", "sites_and_service.no_path_right_now":"aucun chemin pour l’instant", +"sites_and_service.p_of_city_s_traffic_comes_from_kr":"{p} du trafic de {city} vient de {to} : {ms} ms aller-retour. Les utilisateurs coréens remarquent tout ce qui dépasse 8 ms, et au-delà de 40 ms le haut débit compte comme un mauvais service. Sers davantage depuis Séoul : peering, caches et PNI ici, ou du transit local si tu supportes la taxe « l’expéditeur paie ».", "sites_and_service.p_of_city_s_traffic_is":"{p} du trafic de {city} est ramené vers le transit à {to} : {ms} ms aller-retour. Les utilisateurs le sentent au-delà de 20 ms (environ 1 500 km), et au-delà de 50 ms le haut débit et les services internet comptent comme un mauvais service. Achetez du transit ici ou à proximité, ou peerez localement.", "sites_and_service.path_latency_lat":"Latence du chemin : {lat}", "sites_and_service.pn_routers":"routeurs {pn}", diff --git a/site/i18n/it.js b/site/i18n/it.js index df570c3..f27837c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -755,6 +755,7 @@ "city_panel.second_site_and_metro_ring":"Secondo sito e anello metropolitano", "city_panel.sell_internet_to_homes_here_starts":"Vendi internet alle case di qui. Parte da circa {start} e cresce verso {max} finché il servizio è buono. Rende {rate} per Gbps servito, ogni mese.", "city_panel.sells_pnis_down_to_1g":"vende PNI anche da 1G", +"city_panel.sender_pays_fee_per_gbps":"Paga chi invia: +{fee} per Gbps di transit", "city_panel.served_in_city":"Servito a {city}", "city_panel.serving_v":"serve {v}", "city_panel.shut_this_pop_down_its_links":"Chiudi questo POP: link, porte e cache spariscono con lui, e ogni cliente che ne dipende viene lasciato andare, con una penale di recesso anticipato.", @@ -2926,9 +2927,11 @@ "progress.done_in_d_days":"Fatto in {d} giorni!", "progress.floods_that_got_through":"Ondate passate", "progress.ix_brrr_ports_on_your_backbone":"Porte IX.brrr sulla tua dorsale", +"progress.monthly_profit":"Utile mensile", "progress.n_of_m":"{n} su {m}", "progress.next_name_unlocks_what":"Prossimo: {name} sblocca {what}", "progress.not_tier_1_right_now_why":"Al momento non sei Tier 1: {why}.", +"progress.seoul_served_well":"Seul servita bene (consegnato e veloce)", "progress.terabit_floods_held":"Ondate terabit respinte", "progress.under_attack_now":"Sotto attacco ora", "progress.your_score_peak_traffic":"Il tuo punteggio: picco di traffico", @@ -3357,7 +3360,6 @@ "scenarios.1_6t_on_every_hop_from":"1.6T su ogni tratto da Miami a Madrid e da Lisbona a Lagos, e 100 Gbps serviti", "scenarios.90_days_in_a_row_with":"90 giorni di fila con il 99.5% della domanda servita", "scenarios.99_reach_and_150_gbps_served":"99% di copertura e 150 Gbps serviti", -"scenarios.99_reach_and_200_gbps_served":"99% di copertura e 200 Gbps serviti senza andare in rovina", "scenarios.a_path_from_cape_town_to_cairo_lagos":"Un percorso da Città del Capo al Cairo, con Lagos e Nairobi anche loro sulla tua rete, e 150 Gbps serviti", "scenarios.a_path_from_los_angeles_to":"Un percorso da Los Angeles a Sydney con 1.6T su ogni tratta, un percorso da Los Angeles a Tokyo e 150 Gbps serviti", "scenarios.a_path_from_marseille_to_singapore":"Un percorso da Marsiglia a Singapore, e 80 Gbps tra l’Asia e il resto della tua rete per 30 giorni di fila", @@ -3386,7 +3388,8 @@ "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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Modalità sandbox
Un miliardo di dollari, tutto sbloccato e non si rompe mai niente. Costruisci l’internet che hai sempre sognato.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Il Brasile è un continente: quaranta exchange IX.brrr, migliaia di provedores e l’Amazzonia tra te e il nord.", -"scenarios.seoul_the_fastest_hungriest_eyeballs":"Seoul. Gli eyeball più veloci e affamati della Terra, transit a quattro volte il prezzo, e tre incumbent che ti fatturano ogni gigabit che gli mandi.", +"scenarios.seoul_sender_pays_d":"Seul, dove paga chi invia. Ogni Gbps che un carrier consegna in Corea ti costa una tassa «sender pays» oltre alla bolletta del transit, i tre incumbent parlano solo tramite un PNI a pagamento, il gigabit di casa costa quanto un bibimbap e gli utenti coreani notano ogni millisecondo. Il transit a Tokyo è economico, se i tuoi clienti reggono il viaggio.", +"scenarios.seoul_sender_pays_goal":"{g} Gbps serviti, Seul servita bene ({q}%), 99% di copertura e un utile mensile", "scenarios.shark_season_subsea_cuts_twice_as":"Stagione degli squali: tagli sottomarini due volte più probabili", "scenarios.start_in_panama_city_nothing_crosses":"Parti da Panama City. Niente attraversa il Darién Gap via terra, e le Ande sono d’intralcio a tutto il resto.", "scenarios.start_in_stuttgart_where_nobody":"Parti da Stuttgart, dove nessuno vende transit. Raggiungi internet solo con peering, PNI, cache e la tua fibra. Niente transit, da nessuna parte, mai.", @@ -3446,6 +3449,7 @@ "sites_and_service.level_n":"Livello {n}", "sites_and_service.n_ports":"{n} porte", "sites_and_service.no_path_right_now":"nessun percorso al momento", +"sites_and_service.p_of_city_s_traffic_comes_from_kr":"Il {p} del traffico di {city} arriva da {to}: {ms} ms di round trip. Gli utenti coreani notano tutto sopra gli 8 ms, e oltre i 40 ms la banda larga conta come servizio scadente. Servi di più da Seul: peering, cache e PNI qui, o transit locale se reggi la tassa «sender pays».", "sites_and_service.p_of_city_s_traffic_is":"Il {p} del traffico di {city} viene riportato al transito a {to}: {ms} ms di andata e ritorno. Gli utenti se ne accorgono oltre i 20 ms (circa 1.500 km), e oltre i 50 ms banda larga e servizi internet contano come servizio scadente. Compra transito qui o vicino, o fai peering in loco.", "sites_and_service.path_latency_lat":"Latenza del percorso: {lat}", "sites_and_service.pn_routers":"router da {pn}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index e3ae318..d665af3 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -755,6 +755,7 @@ "city_panel.second_site_and_metro_ring":"Segundo site e anel metro", "city_panel.sell_internet_to_homes_here_starts":"Venda internet para as casas daqui. Começa em uns {start} e cresce até {max} enquanto o serviço for bom. Paga {rate} por Gbps servido, todo mês.", "city_panel.sells_pnis_down_to_1g":"vende PNI a partir de 1G", +"city_panel.sender_pays_fee_per_gbps":"Quem envia paga: +{fee} por Gbps de trânsito", "city_panel.served_in_city":"Servido em {city}", "city_panel.serving_v":"atendendo {v}", "city_panel.shut_this_pop_down_its_links":"Desligar este POP: links, portas e caches vão junto, e todo cliente que depende dele é dispensado, com multa por rescisão antecipada.", @@ -2926,9 +2927,11 @@ "progress.done_in_d_days":"Feito em {d} dias!", "progress.floods_that_got_through":"Enxurradas que passaram", "progress.ix_brrr_ports_on_your_backbone":"Portas no IX.brrr no seu backbone", +"progress.monthly_profit":"Lucro mensal", "progress.n_of_m":"{n} de {m}", "progress.next_name_unlocks_what":"Próximo: {name} desbloqueia {what}", "progress.not_tier_1_right_now_why":"Não é Tier 1 agora: {why}.", +"progress.seoul_served_well":"Seul bem servida (entregue e rápido)", "progress.terabit_floods_held":"Enxurradas de terabit contidas", "progress.under_attack_now":"Sob ataque agora", "progress.your_score_peak_traffic":"Sua pontuação: pico de tráfego", @@ -3357,7 +3360,6 @@ "scenarios.1_6t_on_every_hop_from":"1.6T em cada trecho de Miami a Madri e de Lisboa a Lagos, e 100 Gbps servidos", "scenarios.90_days_in_a_row_with":"90 dias seguidos com 99.5% da demanda servida", "scenarios.99_reach_and_150_gbps_served":"99% de alcance e 150 Gbps servidos", -"scenarios.99_reach_and_200_gbps_served":"99% de alcance e 200 Gbps entregues sem quebrar", "scenarios.a_path_from_cape_town_to_cairo_lagos":"Um caminho da Cidade do Cabo ao Cairo, com Lagos e Nairóbi também na sua rede, e 150 Gbps atendidos", "scenarios.a_path_from_los_angeles_to":"Um caminho de Los Angeles a Sydney com 1.6T em cada trecho, um caminho de Los Angeles a Tóquio e 150 Gbps atendidos", "scenarios.a_path_from_marseille_to_singapore":"Um caminho de Marselha a Singapura, e 80 Gbps entre a Ásia e o resto da sua rede por 30 dias seguidos", @@ -3386,7 +3388,8 @@ "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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Modo sandbox
Um bilhão de dólares, tudo desbloqueado e nada nunca quebra. Construa a internet que você sempre quis.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. O Brasil é um continente: quarenta exchanges IX.brrr, milhares de provedores e a Amazônia entre você e o norte.", -"scenarios.seoul_the_fastest_hungriest_eyeballs":"Seoul. Os eyeballs mais rápidos e famintos da Terra, transit a quatro vezes o preço, e três incumbentes que te cobram por cada gigabit que você manda.", +"scenarios.seoul_sender_pays_d":"Seul, onde quem envia paga. Cada Gbps que um carrier entrega na Coreia custa uma taxa de «quem envia paga» além da conta de trânsito, os três incumbentes só conversam por um PNI pago, o gigabit residencial sai pelo preço de um bibimbap e os usuários coreanos percebem cada milissegundo. O trânsito em Tóquio é barato, se seus clientes aguentarem a viagem.", +"scenarios.seoul_sender_pays_goal":"{g} Gbps servidos, Seul bem servida ({q}%), 99% de alcance e lucro mensal", "scenarios.shark_season_subsea_cuts_twice_as":"Temporada de tubarão: cortes submarinos duas vezes mais prováveis", "scenarios.start_in_panama_city_nothing_crosses":"Comece em Panama City. Nada atravessa o Darién Gap por terra, e os Andes atrapalham todo o resto.", "scenarios.start_in_stuttgart_where_nobody":"Comece em Stuttgart, onde ninguém vende transit. Alcance a internet só com peering, PNIs, caches e sua própria fibra. Nada de transit, em lugar nenhum, nunca.", @@ -3446,6 +3449,7 @@ "sites_and_service.level_n":"Nível {n}", "sites_and_service.n_ports":"{n} portas", "sites_and_service.no_path_right_now":"sem caminho no momento", +"sites_and_service.p_of_city_s_traffic_comes_from_kr":"{p} do tráfego de {city} vem de {to}: {ms} ms de ida e volta. Usuários coreanos percebem qualquer coisa acima de 8 ms, e acima de 40 ms a banda larga conta como serviço ruim. Sirva mais a partir de Seul: peering, caches e PNIs aqui, ou trânsito local se você aguentar a taxa de «quem envia paga».", "sites_and_service.p_of_city_s_traffic_is":"{p} do tráfego de {city} vai até o trânsito em {to}: {ms} ms de ida e volta. Os usuários percebem qualquer coisa acima de 20 ms (cerca de 1.500 km), e acima de 50 ms banda larga e serviços de internet contam como serviço ruim. Compre trânsito aqui ou perto, ou faça peering local.", "sites_and_service.path_latency_lat":"Latência do caminho: {lat}", "sites_and_service.pn_routers":"routers de {pn}", diff --git a/src/game/10-catalog/10-economy.js b/src/game/10-catalog/10-economy.js index f5f0cb5..f3c440b 100644 --- a/src/game/10-catalog/10-economy.js +++ b/src/game/10-catalog/10-economy.js @@ -6,6 +6,10 @@ const RU_BOX=40000, RU_BOX_MO=2000; const UAE_LIC=15000,KSA_LIC=25000; // Korea: "sender pays" interconnection makes transit into Seoul about four times the usual price. const KR_TRANSIT=4; +/* Gangnam Style Peering (scenario rule `sender`) turns sender pays all the way up: every Gbps a carrier delivers into + Korea is billed again as a sender-pays fee, the incumbents take traffic only over a paid PNI, home gigabit is cheap, + and users notice every millisecond of a haul to Tokyo or Hong Kong. */ +const KR_FEE=180,KR_ARPU=0.85,KR_LAT_OK=8,KR_LAT_BAD=40; /* Australia: a long way from everywhere. Every gigabit out of the country rides a long, thin subsea cable, so transit and waves cost more than almost anywhere else. IX ports are the exception: a nonprofit exchange sells 10G for about AUD 350 a month. Retail broadband is dear, but the national diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index 123bd62..49ccc82 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -10,6 +10,8 @@ const scnName=()=>S.scn.wk?wsTxt(S.scn.wk.name):S.scn.id==='weekly'?tr('scenario 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; // Ports count only on POPs your backbone joins to São Paulo: islands of POPs with a port each skipped the Amazon (playtest). const FTTB_G=500; +// Gangnam Style Peering: traffic, how well Seoul is served (delivered and fast) and a monthly profit. +const GN_G=700,GN_Q=0.92; const brIxN=()=>CITIES.filter(c=>c.br&&S.ixp[c.id]!==undefined&&(c.id==='sao'||pathExists('sao',c.id))).length; // Days and cash were tuned in the 2.0.0 playtest (tests/scenarios-playtest.test.js): a reference player wins each one in // roughly a fifth to a half of its days, and the obvious shortcut does not win. The 1.6T scenarios start with enough cash to @@ -24,7 +26,9 @@ const SCN=[ // Lagos and Nairobi on the network too: one long wave to Cairo plus two empty POPs was not a network across Africa. {id:'c2c',n:tr('scenarios.cape_to_cairo'),city:'cpt',cash:2000000,days:365,rules:{},d:tr('scenarios.cape_town_build_a_network_across'),goal:tr('scenarios.a_path_from_cape_town_to_cairo_lagos'),ok:()=>pathExists('cpt','cai')&&pathExists('cpt','lag')&&pathExists('cpt','nbo')&&R.served>=150}, {id:'ixbr',n:tr('scenarios.order_and_progress'),city:'sao',cash:600000,days:240,rules:{},d:tr('scenarios.sao_paulo_brazil_is_a_continent'),goal:tr('scenarios.ports_on_15_ix_brrr_exchanges_backbone'),ok:()=>brIxN()>=15&&S.ixp.mao!==undefined&&R.served>=200}, - {id:'gangnam',n:tr('scenarios.gangnam_style_peering'),city:'icn',cash:900000,days:240,rules:{},d:tr('scenarios.seoul_the_fastest_hungriest_eyeballs'),goal:tr('scenarios.99_reach_and_200_gbps_served'),ok:()=>R.reach>=0.99&&R.served>=200}, + // Sender pays, turned up: with Korea at the usual prices broadband swamped every bill and Seoul alone won on day 73 + // (playtest). Now Seoul transit is dear, the incumbents want a paid PNI and Korean users mind every far exit. + {id:'gangnam',n:tr('scenarios.gangnam_style_peering'),city:'icn',cash:900000,days:240,rules:{sender:true},d:tr('scenarios.seoul_sender_pays_d'),goal:tr('scenarios.seoul_sender_pays_goal',{g:GN_G,q:Math.round(GN_Q*100)}),ok:()=>R.reach>=0.99&&R.served>=GN_G&&sfOf(R,'icn')>=GN_Q&&R.revMo>=R.costMo}, {id:'flood',n:tr('common.flood_season'),city:'ams',cash:2000000,days:365,rules:{ddos:true},setup:()=>{S.lvl=Math.max(S.lvl||1,3);},d:tr('scenarios.amsterdam_hosting_capital_of_europe'),goal:tr('scenarios.hold_20_floods_5_of_them'),ok:()=>(S.stats.ddosOk||0)>=20&&(S.stats.ddosOkBig||0)>=5}, // Traffic served too: broadband in five cities and two cables were bought on day 1 and won on day 2 (playtest). {id:'fttb',n:tr('scenarios.fibre_to_the_basement'),city:'syd',cash:1500000,days:365,rules:{levy:true},d:tr('scenarios.sydney_2013_the_toilet_paper_group'),goal:tr('scenarios.broadband_in_sydney_melbourne_served'),ok:()=>AU_BB.every(c=>S.pops[c]&&S.pops[c].bb)&&auExits()>=2&&R.served>=FTTB_G}, diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index ccfb0e2..f2b08ba 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -20,10 +20,12 @@ function compute(){ const COMP=new Int32Array(NC).fill(-1);let NCOMP=0;for(const s of pops){const i=CIDX[s];if(COMP[i]>=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; + // Sender pays (Gangnam Style Peering): no carrier hands traffic to the Korean incumbents for you, only a paid PNI does. + const snd=scnRule('sender'); for(const t of S.transit){if(!popUp(t.city)||t.down>day||!liveN(t.city,t.site,t.n))continue; // AS-path prepending (#96) moves part of the port to a last-resort exit of its own. const cap=Math.min(liveCap(PORT[t.tier].g,t.city,t.site,t.n)*lagF(t),TRX&&TRX.cap[t.net]!==undefined?TRX.cap[t.net]:Infinity),pf=TRX&&TRX.prep[t.net]?PREPEND_F[TRX.prep[t.net]]:0; - const ex={k:'t',net:t.net,prem:premOn(t),pref:t.pref||'normal',lab:labOf(N_('common.net_transit'),'net',NET[t.net].name),id:t.id,city:t.city,cap:cap*(1-pf),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak}; + const ex={k:'t',net:t.net,prem:premOn(t),pref:t.pref||'normal',lab:labOf(N_('common.net_transit'),'net',NET[t.net].name),id:t.id,city:t.city,cap:cap*(1-pf),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak&&!(snd&&NET[n].kr)}; E.push(ex);if(pf)E.push({...ex,cap:cap*pf,prep:true});} // `nets`: every network ok() can say yes to, so it need not be asked about the other hundred. for(const c in S.ixp){const ct=ixCity(c);if(!(popUp(ct)||remote.includes(ct))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||!(S.myIx[c]?myIxLive(c):liveN(ct,(S.ixSite||{})[c],(S.ixn||{})[c])))continue;const set=ixSessions(c);R2.sessions+=set.size; @@ -195,11 +197,12 @@ function compute(){ e.used+=amt;f.rem-=amt; if(!f.junk){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; + 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 - // it gets worse, and past 50 ms broadband and internet services count as bad service (#…). - if(path.length){let ms=P.ms;if(ms===undefined){ms=0;for(const l of path)ms+=l.lat;P.ms=ms;}const rtt=2*ms; - if(rtt>LAT_OK){LATP[f.ci]+=ok*latLoss(rtt);if(!P.fg){P.fg=0;FARL.push(P,f.ci,e.ci);}P.fg+=ok;}}}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok; + // it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays, + // Korean users notice any exit far away, transit or not, and much sooner. + if(path.length&&(e.k==='t'||snd&&CITIES[f.ci].kr)){let ms=P.ms;if(ms===undefined){ms=0;for(const l of path)ms+=l.lat;P.ms=ms;}const rtt=2*ms,kl=snd&&CITIES[f.ci].kr; + if(rtt>(kl?KR_LAT_OK:LAT_OK)){LATP[f.ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,f.ci,e.ci);}P.fg+=ok;}}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok; // Where each flow left (the PNI list asks what a PNI here would take over, #175). if(e.k==='t'){f.gt+=ok;f.ti=e.id;}else if(e.k==='ix'){f.gi+=ok;f.ii=e.id;}else if(e.k==='p'){if(e.net===f.n&&e.city===f.c)f.gh+=ok;else f.gp+=ok;}} return amt; @@ -290,7 +293,7 @@ function compute(){ 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)+(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;}} + 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*arpuOf(c);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);} for(const c in S.myIx)V.ix+=S.myIx[c].members.length*MYIX_FEE; C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix); diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index c46efa0..f228005 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -6,7 +6,9 @@ function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);} function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);} // Monthly price of one connection; compute() sums these, the connections overview lists them. -function transitMo(t,q){const n=t.n||1;return Math.max(q,PORT[t.tier].g*n*0.2)*transitPerG(NET[t.net],t.city,premOn(t))*S.priceMul+PORT[t.tier].tmo*n+(t.clean?cleanMo(t):0);} +function transitMo(t,q){const n=t.n||1;return Math.max(q,PORT[t.tier].g*n*0.2)*transitPerG(NET[t.net],t.city,premOn(t))*S.priceMul+PORT[t.tier].tmo*n+(t.clean?cleanMo(t):0)+krFee(t,q);} +// Sender pays (Gangnam Style Peering): on top of the price, every Gbps delivered into Korea (95th percentile). +const krFee=(t,q)=>CITY[t.city].kr&&scnRule('sender')?Math.round(q*KR_FEE):0; function pniMo(p,use){if(!pniOn(p))return 0;return (p.g1?Math.round(PORT[0].pni/2):PORT[p.tier].pni)*(p.n||1)+(NET[p.net].pol==='paid'&&!paidFree(NET[p.net])?NET[p.net].paidFee:0)+(NET[p.net].perG?Math.round(NET[p.net].perG*use):0);} function ixMo(c){return S.myIx[c]?Math.round(myFab(c).mo*((S.ixSite||{})[c]==='ab'?1.5:1)):ixPortMo(c,S.ixp[c])*((S.ixn||{})[c]||1)+dkAddonMo(c);} function nniPort(c,prov){return (S.nni||[]).find(x=>x.city===c&&x.prov===prov);} diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 434d745..6ad5602 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -90,7 +90,7 @@ function migrate(s){sanitize(s); // Older saves have one contract per broker sale: fold a carrier's alien waves on one fiber into one contract. {const one=new Map();s.biz=s.biz.filter(b=>{if(b.type!=='wwave')return true;const k=b.link+'|'+b.name,a=one.get(k);if(!a){one.set(k,b);return true;} a.slots=(a.slots||0)+(b.slots||0);a.rate=(a.rate||0)+(b.rate||0);a.since=Math.min(a.since??0,b.since??0);a.mood=Math.min(a.mood??100,b.mood??100);a.folded=true;return false;}); - for(const a of one.values())if(a.folded){delete a.folded;const l=s.links.find(x=>x.id===a.link);if(l)a.what=wwWhat(l,a.slots);}}if(s.scn&&s.scn.id==='stg'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.local=true; + for(const a of one.values())if(a.folded){delete a.folded;const l=s.links.find(x=>x.id===a.link);if(l)a.what=wwWhat(l,a.slots);}}if(s.scn&&s.scn.id==='stg'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.local=true;if(s.scn&&s.scn.id==='gangnam'&&s.scn.rules&&typeof s.scn.rules==='object')s.scn.rules.sender=true; // A published weekly scenario keeps its file in the save: checked again here; a bad one plays on as the in-browser weekly. if(s.scn&&typeof s.scn==='object'&&s.scn.wk!==undefined){const d=wsValid(s.scn.wk,s.scn.key);if(d){s.scn.wk=d;s.scn.home=d.city;s.scn.run=Number.isInteger(s.scn.run)&&s.scn.run>=0?s.scn.run:0;}else{delete s.scn.wk;delete s.scn.home;delete s.scn.run;}} for(const b of [...s.biz,...s.offers])if(Array.isArray(b.reqs))b.reqs=b.reqs.filter(k=>!REQS[k]||!REQS[k].can||(isCity(b.city)&&(!b.city2||isCity(b.city2))&&REQS[k].can(b,s)));if(s.ltv!==2){for(const l of s.links)if(l.kind==='wave'&&l.tier>=3)l.tier=Math.min(LT.length-1,l.tier+1);s.ltv=2;}if(s.dk){s.dk.m=s.dk.m||{};s.dk.add=s.dk.add||{};s.dk.ret=s.dk.ret||{};s.dk.retUsed=s.dk.retUsed||{};}s.hist=s.hist||[];s.loans=s.loans||[];s.loanOffers=s.loanOffers||[];s.loanStrikes=s.loanStrikes||0;for(const l of s.links||[])if(!l.kind)l.kind='wave'; diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index 79ef628..93a9277 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -7,6 +7,8 @@ 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)); function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.au)return AU_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;} // A network's own markup on top of that, where it is far from home (Glowball Sakura Lager in Asia and New Zealand). +// What a home pays, against the usual bill. +const arpuOf=c=>CITY[c].arpu||(CITY[c].kr&&scnRule('sender')?KR_ARPU:1); const netMult=(n,c)=>regionMult(c)*((n&&n.far&&CITY[c]&&n.far[CITY[c].reg])||1); const uaePair=(a,b)=>!!CITY[a].uae&&!!CITY[b].uae; const rainPair=(a,b)=>!!(CITY[a].rain||CITY[b].rain); diff --git a/src/game/80-simulation/90-sites-and-service.js b/src/game/80-simulation/90-sites-and-service.js index 4442e36..a586f34 100644 --- a/src/game/80-simulation/90-sites-and-service.js +++ b/src/game/80-simulation/90-sites-and-service.js @@ -20,7 +20,8 @@ function routerModels(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1; function portNote(c){const p=S.pops[c];if(!p)return '';const g=p.rgen||0;return RG[g].maxP${tr('sites_and_service.your_model_here_tops_out_at',{model:esc(RG[g].n),pn:RG[g].pn})}

`:'';} // Service: what you deliver, times how it feels. Traffic backhauled far to transit is slow, and users notice. const latSlow=c=>!!(R&&R.latF&&R.latF[c]<0.97&&R.latFar[c]); -function latNote(c){if(!latSlow(c))return '';const f=R.latFar[c];return `
🐢 ${tr('sites_and_service.p_of_city_s_traffic_is',{p:pct(Math.min(1,f.share)),city:esc(CITY[c].name),to:esc(CITY[f.to].name),ms:Math.round(f.ms)})}
`;} +function latNote(c){if(!latSlow(c))return '';const f=R.latFar[c];const v={p:pct(Math.min(1,f.share)),city:esc(CITY[c].name),to:esc(CITY[f.to].name),ms:Math.round(f.ms)};return `
🐢 ${CITY[c].kr&&scnRule('sender')?tr('sites_and_service.p_of_city_s_traffic_comes_from_kr',v):tr('sites_and_service.p_of_city_s_traffic_is',v)}
`;} const LAT_OK=20,LAT_BAD=50,latLoss=rtt=>rtt<=LAT_OK?0:rtt<=LAT_BAD?0.2*(rtt-LAT_OK)/(LAT_BAD-LAT_OK):0.5; +const krLatLoss=rtt=>rtt<=KR_LAT_OK?0:rtt<=KR_LAT_BAD?0.25*(rtt-KR_LAT_OK)/(KR_LAT_BAD-KR_LAT_OK):0.5; function sfOf(r,c){const d=r.cityDem[c]||0;return d<=1e-6?1:clamp(r.citySrv[c]/d,0,1)*((r.latF&&r.latF[c])??1);} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 4f5b445..84e00f7 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -70,7 +70,7 @@ function dayTick(){ 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');} + 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-arpuOf(c));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');} checkGoals(); scnTick(d); confTick(d); diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index b8af9ba..7a57efb 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -1,7 +1,7 @@ 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(siteName(c,'a'))}

${C.name}

-
${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}${grantFact(c)}${latSlow(c)?`🐢 ${tr('city_panel.ms_ms_to_transit',{ms:Math.round(R.latFar[c].ms)})}`:''}${regionMult(c)>1?`${tr('city_panel.transit_x_pricier',{x:regionMult(c)})}`:''}${colo(c)>1?`${tr('city_panel.few_data_centers_pops_x',{x:colo(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('city_panel.underserved_users_grow_60_faster')+'':''}${ix?`${tr('city_panel.ix_ix',{ix:esc(ix)})}`:''}${p?`${tr('common.your_pop')}`:''}${down?`DOWN`:''}
+
${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}${grantFact(c)}${latSlow(c)?`🐢 ${tr('city_panel.ms_ms_to_transit',{ms:Math.round(R.latFar[c].ms)})}`:''}${regionMult(c)>1?`${tr('city_panel.transit_x_pricier',{x:regionMult(c)})}`:''}${C.kr&&scnRule('sender')?`${tr('city_panel.sender_pays_fee_per_gbps',{fee:fmt$(KR_FEE)})}`:''}${colo(c)>1?`${tr('city_panel.few_data_centers_pops_x',{x:colo(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('city_panel.underserved_users_grow_60_faster')+'':''}${ix?`${tr('city_panel.ix_ix',{ix:esc(ix)})}`:''}${p?`${tr('common.your_pop')}`:''}${down?`DOWN`:''}
`; if(!p){ h+=`
${C.note?`

${esc(C.note)}

`:''} @@ -24,11 +24,11 @@ function cityPanel(c){ if(UI.tab==='cust'){ {const nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||1;if(nl>=nc*0.95)h+=`

${tr('city_panel.router_maxed_out')}

${tr('city_panel.your_routers_here_are_forwarding',{load:fmtG(nl),cap:fmtG(nc)})}

${btn(tr('common.open_infra'),'tab',{t:'links'},'pink sm')}
`;} h+=`

${tr('common.home_broadband')}

`; - if(!p.bb){const s=bbStart(c);h+=`

${tr('city_panel.sell_internet_to_homes_here_starts',{start:fmtG(s),max:fmtG(eyeP(c)),rate:fmt$(EYE_RATE*(C.arpu||1))})}${C.au?` ${scnRule('levy')?tr('city_panel.it_runs_on_your_own_fibre',{pct:pct(AU_LEVY)}):tr('city_panel.the_nearly_broadband_network_keeps',{pct:pct(AU_WHOLESALE)})}`:''}

${btn(tr('city_panel.launch_broadband_cost',{cost:fmt$(bbCost(c))}),'launchBB',{city:c},'pink big',S.cash${tr('city_panel.sell_internet_to_homes_here_starts',{start:fmtG(s),max:fmtG(eyeP(c)),rate:fmt$(EYE_RATE*arpuOf(c))})}${C.au?` ${scnRule('levy')?tr('city_panel.it_runs_on_your_own_fibre',{pct:pct(AU_LEVY)}):tr('city_panel.the_nearly_broadband_network_keeps',{pct:pct(AU_WHOLESALE)})}`:''}

${btn(tr('city_panel.launch_broadband_cost',{cost:fmt$(bbCost(c))}),'launchBB',{city:c},'pink big',S.cash${tr('common.eyeball_demand')}${tr('city_panel.a_of_b',{a:fmtG(eye),b:fmtG(eyeP(c))})}
${tr('city_panel.served_in_city',{city:C.name})}${pct(sf)}
-
${tr('common.revenue')}${tr('common.price_mo',{price:fmt$(eye*sf*EYE_RATE*(C.arpu||1))})}
+
${tr('common.revenue')}${tr('common.price_mo',{price:fmt$(eye*sf*EYE_RATE*arpuOf(c))})}
${tr('city_panel.network_wide_peering_ratio')}${pct(R.peerShare||0)}

${tr('city_panel.more_traffic_over_peering_pnis_and')}

${sf<0.9?`

${tr('city_panel.customers_are_unhappy_and_leaving')}

`:''}
${p.boost>S.day?`${tr('city_panel.ad_campaign_n_d_left',{n:p.boost-S.day})}`:btn(tr('city_panel.run_ad_campaign_8k_2_growth'),'ad',{city:c},'',S.cash<8000)}
`;} diff --git a/src/game/94-dashboard/10-progress.js b/src/game/94-dashboard/10-progress.js index 234cc54..b6212c7 100644 --- a/src/game/94-dashboard/10-progress.js +++ b/src/game/94-dashboard/10-progress.js @@ -10,7 +10,7 @@ const SCN_PROG={stg:()=>[{l:tr('common.reach'),v:R.reach,max:0.5,txt:`${pct(R.re 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)], atl:()=>[pChk(tr('progress.1_6t_on_every_hop_from_a90b'),fastPath('mia','mad',1600)),pChk(tr('progress.1_6t_on_every_hop_from_da01'),fastPath('lis','lag',1600)),pSrv(100)], darien:()=>[...['bog','lim','scl','sao'].map(c=>pChk(tr('progress.city_on_your_network',{city:CITY[c].name}),pathExists('pan',c))),pSrv(150)], - gangnam:()=>[pReach(),pSrv(200)], + gangnam:()=>{const sf=S.pops.icn?sfOf(R,'icn'):0,pr=R.revMo-R.costMo;return [pReach(),pSrv(GN_G),{l:tr('progress.seoul_served_well'),v:sf,max:GN_Q,txt:`${pct(sf)} / ${pct(GN_Q)}`},{l:tr('progress.monthly_profit'),v:R.costMo>0?Math.min(1,R.revMo/R.costMo):1,max:1,txt:fmt$(Math.round(pr))}];}, fttb:()=>[...AU_BB.map(c=>pChk(tr('progress.broadband_in_city',{city:CITY[c].name}),!!(S.pops[c]&&S.pops[c].bb))),{l:tr('common.cables_overseas'),v:Math.min(2,auExits()),max:2,txt:`${auExits()} / 2`},pSrv(FTTB_G)], flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll(); return [{l:tr('common.floods_held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('progress.terabit_floods_held'),v:big,max:5,txt:`${big} / 5`},{l:tr('progress.floods_that_got_through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('progress.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('progress.days_in_a_row_with_99'),v:S.stats.clean||0,max:90,txt:tr('progress.n_of_m',{n:S.stats.clean||0,m:90})}]}; diff --git a/src/i18n/en.js b/src/i18n/en.js index 329113b..d273e23 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -756,6 +756,7 @@ "city_panel.second_site_and_metro_ring":"Second site and metro ring", "city_panel.sell_internet_to_homes_here_starts":"Sell internet to homes here. Starts around {start} and grows toward {max} while service is good. Pays {rate} per Gbps served, every month.", "city_panel.sells_pnis_down_to_1g":"sells PNIs down to 1G", +"city_panel.sender_pays_fee_per_gbps":"Sender pays: +{fee} per Gbps of transit", "city_panel.served_in_city":"Served in {city}", "city_panel.serving_v":"serving {v}", "city_panel.shut_this_pop_down_its_links":"Shut this POP down: its links, ports and caches go with it, and every customer that depends on it is let go, with an early-termination penalty.", @@ -2927,9 +2928,11 @@ "progress.done_in_d_days":"Done in {d} days!", "progress.floods_that_got_through":"Floods that got through", "progress.ix_brrr_ports_on_your_backbone":"IX.brrr ports on your backbone", +"progress.monthly_profit":"Monthly profit", "progress.n_of_m":"{n} of {m}", "progress.next_name_unlocks_what":"Next: {name} unlocks {what}", "progress.not_tier_1_right_now_why":"Not Tier 1 right now: {why}.", +"progress.seoul_served_well":"Seoul served well (delivered and fast)", "progress.terabit_floods_held":"Terabit floods held", "progress.under_attack_now":"Under attack now", "progress.your_score_peak_traffic":"Your score: peak traffic", @@ -3358,7 +3361,6 @@ "scenarios.1_6t_on_every_hop_from":"1.6T on every hop from Miami to Madrid and from Lisbon to Lagos, and 100 Gbps served", "scenarios.90_days_in_a_row_with":"90 days in a row with 99.5% of demand served", "scenarios.99_reach_and_150_gbps_served":"99% reach and 150 Gbps served", -"scenarios.99_reach_and_200_gbps_served":"99% reach and 200 Gbps served without going broke", "scenarios.a_path_from_cape_town_to_cairo_lagos":"A path from Cape Town to Cairo, Lagos and Nairobi on your network too, and 150 Gbps served", "scenarios.a_path_from_los_angeles_to":"A path from Los Angeles to Sydney with 1.6T on every hop, a path from Los Angeles to Tokyo, and 150 Gbps served", "scenarios.a_path_from_marseille_to_singapore":"A path from Marseille to Singapore, and 80 Gbps between Asia and the rest of your network for 30 days in a row", @@ -3387,7 +3389,8 @@ "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.", "scenarios.sandbox_mode_a_billion_dollars_every":"Sandbox mode
A billion dollars, every unlock, and nothing ever breaks. Build the internet you always wanted.", "scenarios.sao_paulo_brazil_is_a_continent":"São Paulo. Brazil is a continent: forty IX.brrr exchanges, thousands of provedores, and the Amazon between you and the north.", -"scenarios.seoul_the_fastest_hungriest_eyeballs":"Seoul. The fastest, hungriest eyeballs on Earth, transit at four times the price, and three incumbents who bill you for every gigabit you send them.", +"scenarios.seoul_sender_pays_d":"Seoul, where the sender pays. Every Gbps a carrier delivers into Korea costs you a sender-pays fee on top of the transit bill, the three incumbents only talk over a paid PNI, home gigabit sells for the price of a bibimbap, and Korean users notice every millisecond. Tokyo transit is cheap, if your customers can stand the trip.", +"scenarios.seoul_sender_pays_goal":"{g} Gbps served, Seoul served well ({q}%), 99% reach and a monthly profit", "scenarios.shark_season_subsea_cuts_twice_as":"Shark season: subsea cuts twice as likely", "scenarios.start_in_panama_city_nothing_crosses":"Start in Panama City. Nothing crosses the Darién Gap by land, and the Andes are in the way of everything else.", "scenarios.start_in_stuttgart_where_nobody":"Start in Stuttgart, where nobody sells transit. Reach the internet through peering, PNIs, caches and your own fiber only. No transit anywhere, ever.", @@ -3447,6 +3450,7 @@ "sites_and_service.level_n":"Level {n}", "sites_and_service.n_ports":"{n} ports", "sites_and_service.no_path_right_now":"no path right now", +"sites_and_service.p_of_city_s_traffic_comes_from_kr":"{p} of {city}’s traffic comes from {to}: {ms} ms round trip. Korean users notice anything over 8 ms, and past 40 ms broadband counts as bad service. Serve more from Seoul: peering, caches and PNIs here, or local transit if you can stand the sender-pays fee.", "sites_and_service.p_of_city_s_traffic_is":"{p} of {city}’s traffic is backhauled to transit in {to}: {ms} ms round trip. Users notice anything over 20 ms (about 1,500 km), and past 50 ms broadband and internet services count as bad service. Buy transit here or nearby, or peer locally.", "sites_and_service.path_latency_lat":"Path latency: {lat}", "sites_and_service.pn_routers":"{pn} routers", From 47c3674e8c4e98d568b597b729834eb948f8aa3a Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 20:59:17 +0100 Subject: [PATCH 133/181] Tests: Gangnam reference hauls from Tokyo; Seoul-only, Tokyo-only and the old plan fail The reference player learns single PNIs and last-resort transit. --- scripts/lib/scenario-ref.js | 5 ++- tests/gangnam.test.js | 54 ++++++++++++++++++++++++++++++++ tests/scenarios-playtest.test.js | 24 ++++++++++++-- 3 files changed, 80 insertions(+), 3 deletions(-) create mode 100644 tests/gangnam.test.js diff --git a/scripts/lib/scenario-ref.js b/scripts/lib/scenario-ref.js index 2733491..6164e8f 100644 --- a/scripts/lib/scenario-ref.js +++ b/scripts/lib/scenario-ref.js @@ -9,6 +9,7 @@ // ['hire', orders, params] the NOC intern on standing orders, as soon as the level allows // ['wait', day] until that day ['served', g] until g Gbps are served ['prep', c, g] capacity for an event // ['scrub', c, tier] a scrubbing center ['pnis'] a PNI with every unreached network that takes one +// ['pni', c, net, tier] one PNI with that network there ['last', c] transit there only as a last resort // ['loans'] take every loan the banks offer, from now on (the cheese plans) const REF = String.raw`(()=>{ const Q=window.__ref={log:[]}; @@ -19,6 +20,7 @@ Q.cheap=c=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!(Q.avoid||[]).includes(n.id)&& Q.pop=c=>{if(!S.pops[c])ACT.buildPop({city:c});return !!S.pops[c];}; Q.bb=c=>{Q.pop(c);if(S.pops[c]&&!S.pops[c].bb)ACT.launchBB({city:c});return !!(S.pops[c]&&S.pops[c].bb);}; Q.tr=(c,tier=1)=>{Q.pop(c);const n=Q.cheap(c);if(!n)return true;ACT.buyTransit({city:c,net:n.id,tier});return true;}; +Q.last=c=>{for(const t of S.transit)if(t.city===c)ACT.setPref({kind:'t',id:t.id,v:'low'});return true;}; Q.ix=(c,tier=1)=>{if(!S.pops[c])return false;for(const x of ixIdsIn(c)){if(!ixName(x))continue;if(S.ixp[x]===undefined)ACT.buyIx({city:x,tier,signed:true});if(S.ixp[x]===undefined)continue;if(!S.rs[x])ACT.rs({city:x});ACT.peerAll({city:x});}return true;}; // A wave: big waves need big routers at both ends, and a router swap takes a day, so the step waits (null) until they fit. Q.link=(a,b,tier=1,via)=>{for(const c of [a,b])Q.pop(c);if(!S.pops[a]||!S.pops[b])return false; @@ -28,6 +30,7 @@ Q.hire=(orders,par)=>{Q.wantHire=[orders||['transit','routers','repair'],par||{} Q.hire0=(orders,par)=>{if(!opsCanHire()||!Q.can(20000))return false;if(!opsHired()){ACT.opsHire({id:'kevin'});closeModal();}if(!opsHired())return false; for(const k of orders)if(!S.ops.on[k])ACT.opsToggle({k});for(const k in par)for(const [p,v] of Object.entries(par[k]))for(let i=0;i<8&&opsP(k,p)!==v;i++)ACT.opsParam({k,p});closeModal();return true;}; Q.pnis=(tier=0)=>{for(const n of NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id])){const b=pniBatch(n.id,tier);if(!b||!b.orders.length||!Q.can(b.cost))continue;ACT.pniAll({net:n.id,tier});}return true;}; +Q.pni=(c,net,tier=0)=>{if(!S.pni.some(p=>p.city===c&&p.net===net))ACT.pni({city:c,net,tier});closeModal();return S.pni.some(p=>p.city===c&&p.net===net);}; Q.scrub=(c,tier=0)=>{ACT.buildScrub({city:c,tier});return true;}; Q.loans=()=>{Q.loan=true;return true;}; Q.served=g=>R.served>=g||null; @@ -38,7 +41,7 @@ Q.prep=(c,g)=>{const need=(S.stats.peak||R.served||0)*1.2+g*1.15,cap=()=>S.trans if(t.tier=need/4&&portOk(c,t.tier+1))ACT.buyTransit({city:c,net:t.net,tier:t.tier+1});else ACT.lagT({id:t.id,d:1}); if(cap()===c0){if(t.tier=RMAX)break;const r0=p.routers||1;ACT.addRouter({city:c});if((p.routers||1)===r0)break;}return true;}; -Q.est={pop:c=>S.pops[c]?0:popCost(c),bb:c=>(S.pops[c]?0:popCost(c))+bbCost(c),tr:()=>20000,ix:()=>25000,hire:()=>0,scrub:(c,t)=>SCRUB_TIERS[t||0].cost, +Q.est={pop:c=>S.pops[c]?0:popCost(c),bb:c=>(S.pops[c]?0:popCost(c))+bbCost(c),tr:()=>20000,pni:()=>20000,ix:()=>25000,hire:()=>0,scrub:(c,t)=>SCRUB_TIERS[t||0].cost, link:(a,b,t)=>(S.pops[a]?0:popCost(a))+(S.pops[b]?0:popCost(b))+waveMo(kmBetween(a,b),isSub(a,b),t)*2+20000}; Q.upkeep=()=>{ for(const l of S.links){if(l.kind!=='wave'||l.tier>=LT.length-1||linkDown(l)||(R.load[l.id]||0) ev(`beginGame('T','icn',{scn:SCN.find(x=>x.id==='gangnam')});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e8`); +const seoul = "ACT.launchBB({city:'icn'});ACT.buyTransit({city:'icn',net:'cog',tier:1});compute();for(let i=0;i<20;i++)dayTick();compute()"; + +test('sender pays: fee on Seoul transit, incumbents only over a paid PNI, cheap broadband', () => { + const { ev, errors } = load(); + start(ev); + ev(seoul); + assert.ok(ev("scnRule('sender')")); + assert.equal(ev("R.reachable.ktt||R.reachable.skb||R.reachable.lgu"), false, 'transit does not carry the incumbents'); + assert.ok(ev('R.reach') < 0.99); + const t = JSON.parse(ev("(()=>{const t=S.transit[0],q=R.p95[t.id];return JSON.stringify({fee:krFee(t,q),q,mo:transitMo(t,q)})})()")); + assert.ok(t.q > 0 && t.fee === Math.round(t.q * ev('KR_FEE')), 'a sender-pays fee per Gbps of transit'); + assert.ok(ev("Math.abs(R.rev.eyeballs-R.cityEye.icn*sfOf(R,'icn')*EYE_RATE*KR_ARPU)<1")); + ev("ACT.pni({city:'icn',net:'ktt',tier:0});closeModal();for(let i=0;i<90&&!S.pni.every(pniOn);i++)dayTick();compute()"); + assert.ok(ev('R.reachable.ktt') && ev('R.reach') >= 0.99, 'a paid PNI with Kay-Tea brings the reach'); + assert.match(ev('scnCard()'), /Seoul served well/); + assert.match(ev('scnCard()'), /Monthly profit/); + assert.deepEqual(errors, []); +}); + +test('sender pays: Korean users mind a haul to Tokyo even over peering', () => { + const { ev, errors } = load(); + start(ev); + ev("ACT.launchBB({city:'icn'});UI.via=null;UI.route=null;openLinkModal('icn','tok');ACT.buildLink({tier:1});closeModal();for(const x of ixIdsIn('tok')){ACT.buyIx({city:x,tier:1,signed:true});ACT.rs({city:x});}compute()"); + assert.ok(ev('R.egT.ix') > 0 && !ev('R.egT.t'), 'only peering in Tokyo'); + assert.ok(ev('R.latF.icn') < 0.95, 'the haul costs service'); + assert.match(ev("latNote('icn')"), /Korean users notice/); + assert.deepEqual(errors, []); +}); + +test('Korea outside the scenario keeps its usual prices', () => { + const { ev, errors } = load(); + ev("UI.startCity='icn';ACT.start({});closeModal();S.cash=1e8"); + ev(seoul); + assert.ok(!ev("scnRule('sender')")); + assert.ok(ev('R.reachable.ktt'), 'transit reaches the incumbents'); + assert.equal(ev("krFee(S.transit[0],100)"), 0); + assert.ok(ev("Math.abs(R.rev.eyeballs-R.cityEye.icn*sfOf(R,'icn')*EYE_RATE)<1")); + assert.deepEqual(errors, []); +}); + +test('an older Gangnam save picks up the sender-pays rule', () => { + const { ev, errors } = load(); + start(ev); + const s = ev("(()=>{const o=JSON.parse(JSON.stringify(S));o.scn.rules={};return JSON.stringify(o);})()"); + ev(`S=migrate(JSON.parse(${JSON.stringify(s)}))`); + assert.ok(ev("S.scn.rules.sender===true")); + assert.deepEqual(errors, []); +}); diff --git a/tests/scenarios-playtest.test.js b/tests/scenarios-playtest.test.js index 47cd222..663fb11 100644 --- a/tests/scenarios-playtest.test.js +++ b/tests/scenarios-playtest.test.js @@ -9,6 +9,8 @@ const { play } = require('../scripts/lib/scenario-ref'); const HIRE = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix']]; const home = (c) => [['bb', c], ['tr', c, 1], ['ix', c]]; +const GN_H = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix', 'caches', 'pni']]; +const GN_REF = [['bb', 'icn'], ['ix', 'icn'], ['tr', 'icn', 1], ['pni', 'icn', 'ktt', 0], GN_H, ['served', 120], ['link', 'icn', 'tok', 1], ['tr', 'tok', 1], ['ix', 'tok'], ['last', 'icn'], ['pop', 'hkg']]; // ref: the reference plan; win: [earliest, latest] day it may win on; cheese: the shortcut, and `by`, the day before // which it must not win (null: never within the scenario's days). const PLAY = { @@ -25,8 +27,9 @@ const PLAY = { win: [70, 200], cheese: [...home('cpt'), ['link', 'cpt', 'cai', 0], ['pop', 'lag'], ['pop', 'nbo'], ['hire']], by: null }, ixbr: { ref: [...home('sao'), ...[['sao', 'rio', 1], ['sao', 'cpq', 0], ['sao', 'cwb', 0], ['cwb', 'poa', 0], ['rio', 'bhz', 0], ['bhz', 'bsb', 0], ['bsb', 'gyn', 0], ['rio', 'ssa', 0], ['ssa', 'rec', 0], ['rec', 'for', 0], ['rec', 'nat', 0], ['for', 'bel', 0], ['bel', 'mao', 0], ['bsb', 'cgb', 0], ['sao', 'vix', 0]].flatMap(([a, b, t]) => [['link', a, b, t], ['ix', b, 0]]), ['bb', 'rio'], ['tr', 'rio', 1], ['bb', 'bsb'], ['tr', 'bsb', 1], ['bb', 'for'], ['tr', 'for', 1], HIRE], win: [40, 120], cheese: [['bb', 'sao'], ['tr', 'sao', 1], ...['sao', 'rio', 'bsb', 'bhz', 'cwb', 'poa', 'for', 'rec', 'ssa', 'cpq', 'gyn', 'bel', 'mao', 'nat', 'vix', 'cgb'].flatMap((c) => [['pop', c], ['ix', c, 0]]), ['hire']], by: null }, - // Seoul at home is enough here: the cheese is just playing, so it only must not be instant. - gangnam: { ref: [...home('icn'), ['link', 'icn', 'tok', 1], ['ix', 'tok'], ['tr', 'tok', 1], ['link', 'icn', 'hkg', 1], ['ix', 'hkg'], ['tr', 'hkg', 1], HIRE], win: [50, 120], cheese: [...home('icn'), ['loans']], by: 50 }, + // Sender pays: Seoul transit to start (dear, but fast), one paid PNI with Kay-Tea for reach, then haul the bulk from + // Tokyo and keep Seoul transit as the last resort. Seoul alone loses money on the sender-pays fee and never wins. + gangnam: { ref: GN_REF, win: [130, 190], cheese: [...home('icn'), ['loans']], by: null }, // Bigger routers bring Flowspec, which also takes floods: without a scrubbing center it takes twice as long. flood: { ref: [...home('ams'), ['scrub', 'ams', 1], ['tr', 'ams', 1], HIRE], win: [80, 200], cheese: [...home('ams'), ['tr', 'ams', 1], ['loans']], by: 180 }, fttb: { ref: [...home('syd'), ['link', 'syd', 'akl', 0, 'tasman'], ['link', 'syd', 'nou', 0, 'gond'], ...['mel', 'bne', 'adl', 'per'].flatMap((c) => [['bb', c], ['tr', c, 1]]), ['link', 'syd', 'mel', 1], ['link', 'syd', 'bne', 1], ['link', 'mel', 'adl', 1], ['link', 'adl', 'per', 0], HIRE], @@ -58,3 +61,20 @@ for (const [id, P] of Object.entries(PLAY)) { assert.deepEqual(g.errors, []); }); } + +// Gangnam Style Peering bites every way (2.0.0 playtest): paying the sender-pays fee on everything loses money, hauling +// everything from Tokyo is too slow for Korean users, and the old plan (transit everywhere, no Kay-Tea) has neither +// the reach nor the profit. The reference's Seoul transit as first choice, not last resort, also stays in the red. +for (const [name, plan] of Object.entries({ + 'Seoul transit and Kay-Tea': [['bb', 'icn'], ['ix', 'icn'], ['tr', 'icn', 1], ['pni', 'icn', 'ktt', 0], GN_H], + 'everything from Tokyo': [['bb', 'icn'], ['link', 'icn', 'tok', 1], ['tr', 'tok', 1], ['ix', 'tok'], ['pni', 'tok', 'ktt', 0], ['pop', 'hkg'], GN_H], + 'the 1.x reference': [...home('icn'), ['link', 'icn', 'tok', 1], ['ix', 'tok'], ['tr', 'tok', 1], ['link', 'icn', 'hkg', 1], ['ix', 'hkg'], ['tr', 'hkg', 1], HIRE], + 'Tokyo haul, Seoul transit first': GN_REF.filter((s) => s[0] !== 'last'), +})) { + test(`gangnam: ${name} does not win`, () => { + const g = load(); + const r = play(g.ev, 'gangnam', plan); + assert.equal(r.won, null, `${name} won on day ${r.won}`); + assert.deepEqual(g.errors, []); + }); +} From 1b5bce7ba5c30be50aaba78d091b47c98ea80e18 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 20:59:24 +0100 Subject: [PATCH 134/181] CHANGELOG: Gangnam Style Peering redesign --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b0dd5a..4c98686 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 -- Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. +- Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. - Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. - Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price. - Take a seat on a new consortium subsea cable (#173). Capacity conferences offer them, and now and then a consortium calls from level 2: pay your share of the build, wait for the ship, then own one, two or four fiber pairs and light them with your own optics, your way onto your own subsea glass before Tier 1. A cut on that cable cuts your pairs too. From 62d6ece5dcf1947f765d6965a890fcffc2c4cfc5 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 21:00:46 +0100 Subject: [PATCH 135/181] Menu: the NOC chat and bug-report cards become two small links --- src/game/90-actions/89-game-and-settings.js | 2 +- src/styles/40-modal.css | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index bff8c7e..201f4f1 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -31,7 +31,7 @@ Object.assign(ACT,{
-
${chatHtml()}${issueHtml()}`);}, +
`);}, settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();}, prefSet:({v})=>{const [k,b]=String(v).split(':');if(!own(PREF_DEF,k))return;setPref(k,b==='1');sfx('click');refreshSettings();}, diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 3603f80..5a27215 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -191,3 +191,5 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .mtile i{font-style:normal;font-size:22px;line-height:1}.mtile:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} .menu-links{margin:12px 0 0;text-align:center;line-height:2;color:var(--ink2)} .menu-links .lnk{background:none;border:0;padding:4px 2px;font-weight:700;font-size:14px;font-family:inherit;color:var(--ink2);text-decoration:underline;text-underline-offset:3px;cursor:pointer} +.menu-plugs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:12px} +.mplug{border:2px solid var(--line);border-radius:12px;padding:8px 10px;font-weight:700;font-size:13px;line-height:1.25;color:var(--ink);text-decoration:none;background:var(--soft);display:flex;align-items:center} From 81ad85cb035fad39cac717dd5775b3af5f2e73bd Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 21:36:44 +0100 Subject: [PATCH 136/181] The NOC tab shows no numbers: a red dot only while something is broken; drop five unused labels --- 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/93-ui/20-phone.js | 4 ++-- src/game/93-ui/40-hud-and-panels.js | 4 ++-- src/i18n/en.js | 5 ----- src/styles/20-drawers.css | 2 ++ src/styles/60-phone.css | 1 + tests/game.test.js | 12 +++++++----- 11 files changed, 14 insertions(+), 39 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index c05ddcb..6405f07 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1796,11 +1796,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Dein POP · braucht dort einen Fabric-Port", "game_and_settings.delete_and_start_over":"Löschen und neu anfangen", "game_and_settings.export_save_download_a_file":"Spielstand exportieren Datei herunterladen", -"game_and_settings.import_a_save_from_a_file":"Spielstand importieren aus einer Datei", "game_and_settings.import_failed_that_save_is_damaged":"Import fehlgeschlagen.
Dieser Spielstand ist beschädigt und konnte nicht geladen werden. Dein aktuelles Spiel ist unberührt.", "game_and_settings.name_and_everything_it_owns_will":"{name} und alles, was dazugehört, wird gelöscht. Das lässt sich nicht rückgängig machen.", -"game_and_settings.scenarios_amp_weekly_challenge":"Szenarien & Wochen-Challenge", -"game_and_settings.share_your_network_image_card":"Dein Netz teilen Bildkarte", "game_and_settings.start_a_new_network":"Ein neues Netz starten?", "game_and_settings.welcome_back_name_imported_and_saved":"Willkommen zurück, {name}.
Importiert und auf diesem Gerät gespeichert.", "game_and_settings.your_game_saves_itself_every_few":"Dein Spiel speichert sich alle paar Sekunden auf diesem Gerät.", @@ -2016,7 +2013,6 @@ "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} Nachricht wartet auf eine Antwort.","other":"{n} Nachrichten warten auf eine Antwort."}, "hud_and_panels.n_more_networks":{"one":"+{n} weiteres Netz","other":"+{n} weitere Netze"}, "hud_and_panels.n_networks_d_days_left":"{n} Netze · noch {d} Tage", -"hud_and_panels.n_new_notification":{"one":"{n} neue Benachrichtigung","other":"{n} neue Benachrichtigungen"}, "hud_and_panels.n_rules_live":"{n} Regeln aktiv", "hud_and_panels.n_session_is_down_on_its":{"one":"{n} Session ist wegen ihres Max-Prefix-Limits down.","other":"{n} Sessions sind wegen ihres Max-Prefix-Limits down."}, "hud_and_panels.n_small_networks":"{n} kleine Netze", @@ -3521,7 +3517,6 @@ "slots.this_window_stopped_saving_so_it":"In einem anderen Fenster wurde eine neuere Version gespeichert, also speichert dieses nicht mehr, statt sie zu überschreiben.", "slots.two_windows_one_network":"Zwei Fenster, ein Netz", "slots.your_networks":"Deine Netze", -"slots.your_networks_switch_or_start_another":"Deine Netze wechseln oder ein neues starten", "slots.your_other_networks_share_this_browser":"Deine anderen Netze teilen sich den Speicher dieses Browsers. Exportiere die, die du behalten willst, und lösche sie dann hier, um Platz zu schaffen.", "sold_out.a_hyperscaler_bought_every_wave_of":"Ein Hyperscaler hat letzte Woche jede Wave dieser Größe auf dieser Route gekauft.", "sold_out.not_big_enough_yet_list":"Noch nicht groß genug: {list}", diff --git a/site/i18n/es.js b/site/i18n/es.js index c4dd964..49db76a 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1794,11 +1794,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Tu POP · necesita un puerto de fabric allí", "game_and_settings.delete_and_start_over":"Borrar y empezar de nuevo", "game_and_settings.export_save_download_a_file":"Exportar partida descargar un archivo", -"game_and_settings.import_a_save_from_a_file":"Importar una partida desde un archivo", "game_and_settings.import_failed_that_save_is_damaged":"Falló la importación.
Esa partida está dañada y no se pudo cargar. Tu partida actual sigue intacta.", "game_and_settings.name_and_everything_it_owns_will":"{name} y todo lo que posee se borrarán. No se puede deshacer.", -"game_and_settings.scenarios_amp_weekly_challenge":"Escenarios y desafío semanal", -"game_and_settings.share_your_network_image_card":"Comparte tu red tarjeta de imagen", "game_and_settings.start_a_new_network":"¿Empezar una red nueva?", "game_and_settings.welcome_back_name_imported_and_saved":"Bienvenido de nuevo, {name}.
Importada y guardada en este dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"Tu partida se guarda sola cada pocos segundos en este dispositivo.", @@ -2014,7 +2011,6 @@ "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} mensaje esperando respuesta.","other":"{n} mensajes esperando respuesta."}, "hud_and_panels.n_more_networks":{"one":"+{n} red más","other":"+{n} redes más"}, "hud_and_panels.n_networks_d_days_left":"{n} redes · quedan {d} días", -"hud_and_panels.n_new_notification":{"one":"{n} notificación nueva","other":"{n} notificaciones nuevas"}, "hud_and_panels.n_rules_live":"{n} reglas activas", "hud_and_panels.n_session_is_down_on_its":{"one":"{n} sesión está caída por su límite de max-prefix.","other":"{n} sesiones están caídas por su límite de max-prefix."}, "hud_and_panels.n_small_networks":"{n} redes pequeñas", @@ -3519,7 +3515,6 @@ "slots.this_window_stopped_saving_so_it":"Se guardó una versión más nueva en otra ventana, así que esta dejó de guardar en vez de sobrescribirla.", "slots.two_windows_one_network":"Dos ventanas, una red", "slots.your_networks":"Tus redes", -"slots.your_networks_switch_or_start_another":"Tus redes cambia o empieza otra", "slots.your_other_networks_share_this_browser":"Tus otras redes comparten el almacenamiento de este navegador. Exporta las que quieras conservar y bórralas aquí para hacer sitio.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hiperescalador compró la semana pasada todas las ondas de ese tamaño en esta ruta.", "sold_out.not_big_enough_yet_list":"Aún no es lo bastante grande: {list}", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c6c08b6..cc5ee06 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1794,11 +1794,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Ton POP · il y faut un port fabric", "game_and_settings.delete_and_start_over":"Supprimer et recommencer", "game_and_settings.export_save_download_a_file":"Exporter la sauvegarde télécharger un fichier", -"game_and_settings.import_a_save_from_a_file":"Importer une sauvegarde depuis un fichier", "game_and_settings.import_failed_that_save_is_damaged":"Échec de l’import.
Cette sauvegarde est endommagée et n’a pas pu être chargée. Ta partie en cours est intacte.", "game_and_settings.name_and_everything_it_owns_will":"{name} et tout ce qu’il possède seront supprimés. Impossible de revenir en arrière.", -"game_and_settings.scenarios_amp_weekly_challenge":"Scénarios & défi de la semaine", -"game_and_settings.share_your_network_image_card":"Partager ton réseau carte image", "game_and_settings.start_a_new_network":"Créer un nouveau réseau ?", "game_and_settings.welcome_back_name_imported_and_saved":"Bon retour, {name}.
Partie importée et sauvegardée sur cet appareil.", "game_and_settings.your_game_saves_itself_every_few":"Ta partie se sauvegarde toute seule sur cet appareil, toutes les quelques secondes.", @@ -2014,7 +2011,6 @@ "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} message attend une réponse.","other":"{n} messages attendent une réponse."}, "hud_and_panels.n_more_networks":{"one":"+{n} autre réseau","other":"+{n} autres réseaux"}, "hud_and_panels.n_networks_d_days_left":"{n} réseaux · {d} j restants", -"hud_and_panels.n_new_notification":{"one":"{n} nouvelle notification","other":"{n} nouvelles notifications"}, "hud_and_panels.n_rules_live":"{n} règles actives", "hud_and_panels.n_session_is_down_on_its":{"one":"{n} session est coupée par sa limite max-prefix.","other":"{n} sessions sont coupées par leur limite max-prefix."}, "hud_and_panels.n_small_networks":"{n} petits réseaux", @@ -3519,7 +3515,6 @@ "slots.this_window_stopped_saving_so_it":"Une version plus récente a été sauvegardée dans une autre fenêtre, alors celle-ci a arrêté de sauvegarder au lieu de l'écraser.", "slots.two_windows_one_network":"Deux fenêtres, un réseau", "slots.your_networks":"Tes réseaux", -"slots.your_networks_switch_or_start_another":"Tes réseaux changer, ou en lancer un autre", "slots.your_other_networks_share_this_browser":"Tes autres réseaux partagent le stockage de ce navigateur. Exporte ceux que tu veux garder, puis supprime-les ici pour faire de la place.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hyperscaler a acheté la semaine dernière toutes les ondes de cette taille sur cette route.", "sold_out.not_big_enough_yet_list":"Pas encore assez gros : {list}", diff --git a/site/i18n/it.js b/site/i18n/it.js index f27837c..dd1886c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1794,11 +1794,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Il tuo POP · serve una porta fabric lì", "game_and_settings.delete_and_start_over":"Cancella e ricomincia", "game_and_settings.export_save_download_a_file":"Esporta salvataggio scarica un file", -"game_and_settings.import_a_save_from_a_file":"Importa un salvataggio da un file", "game_and_settings.import_failed_that_save_is_damaged":"Importazione fallita.
Quel salvataggio è danneggiato e non si può caricare. La partita in corso non è stata toccata.", "game_and_settings.name_and_everything_it_owns_will":"{name} e tutto ciò che possiede verranno cancellati. Non si torna indietro.", -"game_and_settings.scenarios_amp_weekly_challenge":"Scenari e sfida settimanale", -"game_and_settings.share_your_network_image_card":"Condividi la tua rete come immagine", "game_and_settings.start_a_new_network":"Vuoi creare una nuova rete?", "game_and_settings.welcome_back_name_imported_and_saved":"Bentornato, {name}.
Importato e salvato su questo dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"La partita si salva da sola ogni pochi secondi su questo dispositivo.", @@ -2014,7 +2011,6 @@ "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} messaggio aspetta una risposta.","other":"{n} messaggi aspettano una risposta."}, "hud_and_panels.n_more_networks":{"one":"+{n} altra rete","other":"+{n} altre reti"}, "hud_and_panels.n_networks_d_days_left":"{n} reti · {d} giorni rimasti", -"hud_and_panels.n_new_notification":{"one":"{n} nuova notifica","other":"{n} nuove notifiche"}, "hud_and_panels.n_rules_live":"{n} regole attive", "hud_and_panels.n_session_is_down_on_its":{"one":"{n} sessione è giù per il limite max-prefix.","other":"{n} sessioni sono giù per il limite max-prefix."}, "hud_and_panels.n_small_networks":"{n} piccole reti", @@ -3519,7 +3515,6 @@ "slots.this_window_stopped_saving_so_it":"In un'altra finestra è stata salvata una versione più recente, quindi questa ha smesso di salvare invece di sovrascriverla.", "slots.two_windows_one_network":"Due finestre, una rete", "slots.your_networks":"Le tue reti", -"slots.your_networks_switch_or_start_another":"Le tue reti cambia o iniziane un'altra", "slots.your_other_networks_share_this_browser":"Le tue altre reti condividono lo spazio di questo browser. Esporta quelle che vuoi tenere, poi eliminale qui per fare posto.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hyperscaler ha comprato la settimana scorsa ogni onda di questa misura su questa tratta.", "sold_out.not_big_enough_yet_list":"Non sei ancora abbastanza grande: {list}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index d665af3..ffba098 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1794,11 +1794,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Seu POP · precisa de uma porta de fabric lá", "game_and_settings.delete_and_start_over":"Apagar e recomeçar", "game_and_settings.export_save_download_a_file":"Exportar save baixar um arquivo", -"game_and_settings.import_a_save_from_a_file":"Importar um save de um arquivo", "game_and_settings.import_failed_that_save_is_damaged":"Falha na importação.
Esse save está corrompido e não pôde ser carregado. Seu jogo atual não foi mexido.", "game_and_settings.name_and_everything_it_owns_will":"{name} e tudo o que ela possui serão apagados. Não dá para desfazer.", -"game_and_settings.scenarios_amp_weekly_challenge":"Cenários & desafio semanal", -"game_and_settings.share_your_network_image_card":"Compartilhar sua rede card de imagem", "game_and_settings.start_a_new_network":"Começar uma nova rede?", "game_and_settings.welcome_back_name_imported_and_saved":"Bem-vindo de volta, {name}.
Importado e salvo neste dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"Seu jogo se salva sozinho a cada poucos segundos neste dispositivo.", @@ -2014,7 +2011,6 @@ "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} mensagem esperando resposta.","other":"{n} mensagens esperando resposta."}, "hud_and_panels.n_more_networks":{"one":"+{n} rede a mais","other":"+{n} redes a mais"}, "hud_and_panels.n_networks_d_days_left":"{n} redes · faltam {d} dias", -"hud_and_panels.n_new_notification":{"one":"{n} notificação nova","other":"{n} notificações novas"}, "hud_and_panels.n_rules_live":"{n} regras ativas", "hud_and_panels.n_session_is_down_on_its":{"one":"{n} sessão está fora pelo limite de max-prefix.","other":"{n} sessões estão fora pelo limite de max-prefix."}, "hud_and_panels.n_small_networks":"{n} redes pequenas", @@ -3519,7 +3515,6 @@ "slots.this_window_stopped_saving_so_it":"Uma versão mais nova foi salva em outra janela, então esta parou de salvar em vez de sobrescrevê-la.", "slots.two_windows_one_network":"Duas janelas, uma rede", "slots.your_networks":"Suas redes", -"slots.your_networks_switch_or_start_another":"Suas redes trocar ou começar outra", "slots.your_other_networks_share_this_browser":"Suas outras redes dividem o armazenamento deste navegador. Exporte as que quiser manter e apague-as aqui para abrir espaço.", "sold_out.a_hyperscaler_bought_every_wave_of":"Um hyperscaler comprou semana passada todas as ondas desse tamanho nesta rota.", "sold_out.not_big_enough_yet_list":"Você ainda não é grande o bastante: {list}", diff --git a/src/game/93-ui/20-phone.js b/src/game/93-ui/20-phone.js index f1b6d32..3b7339b 100644 --- a/src/game/93-ui/20-phone.js +++ b/src/game/93-ui/20-phone.js @@ -3,10 +3,10 @@ const isPhone=()=>innerWidth<=760||(innerHeight<=500&&matchMedia('(pointer:coars const SPEEDS=[0.5,1,2,4,8]; function renderTabbar(){const tb=$('tabbar');if(!tb||(pressing&&UI.ticking))return;if(!isPhone()||!S||!UI.started||pzOn()){tb.hidden=true;document.body.classList.toggle('sheet-open',pzOn()&&isPhone()&&!!UI.sel);return;}tb.hidden=false; const open=UI.leftOpen&&!UI.sel,cur=UI.left||'goals',ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length; - const tab=(k,ic,l,cnt,red)=>``; + const tab=(k,ic,l,cnt,red)=>``; const h=(rule('clock')?``+ ``:'')+ - (()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length||(UI.left==='noc'&&UI.leftOpen?'':logUnread())||'',S.inc.length>0)+tab('nets','🌐',tr('common.networks'),ibxOpen()||'',ibxUrgent()>0); + (()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length?' ':'',true)+tab('nets','🌐',tr('common.networks'),ibxOpen()||'',ibxUrgent()>0); if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;} document.body.classList.toggle('sheet-open',!!(UI.sel||UI.leftOpen));} function haptic(ms){if(UI.muted)return;try{navigator.vibrate&&navigator.vibrate(ms||12);}catch(e){}} diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index c2be442..7a32ef7 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -20,7 +20,7 @@ function renderHUD(){ $('hDate').textContent=dateStr(S.day); {const bo=(S.loanOffers||[]).length,hb=$('hBank');hb.hidden=!bo;hb.textContent=bo;} {const st=custStats(),hc=$('hCust');hc.hidden=!st.n;if(st.n){$('hCustVal').innerHTML=`${st.avg>=80?'😀':st.avg>=60?'🙂':st.avg>=30?'😟':'😡'} ${Math.round(st.avg)}%${st.unhappy?` ${st.unhappy}`:''}`;hc.classList.toggle('hot',st.furious>0);}} - const n=S.inc.length;$('hNoc').classList.toggle('hot',n>0);{const u=UI.left==='noc'&&UI.leftOpen?0:logUnread(),b=$('hNocNew');if(b){b.hidden=!u;b.textContent=u>99?'99+':String(u);b.title=trn('hud_and_panels.n_new_notification',u);}}$('hNocVal').textContent=n?trn('hud_and_panels.n_incident',n):tr('common.all_quiet'); + const n=S.inc.length;$('hNoc').classList.toggle('hot',n>0);{const b=$('hNocNew');if(b)b.hidden=true;}$('hNocVal').textContent=n?trn('hud_and_panels.n_incident',n):tr('common.all_quiet'); if(!window.__TUBES_TEST__)fitHud(); renderTabbar(); } @@ -31,7 +31,7 @@ function renderLeft(){checkLayer(); renderTabbar(); if(!S||pzOn()){L.hidden=true;return;}L.hidden=false; const ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length; - const tabs=[['goals',`${tr('common.goals')}${ndone}/${GOALS.length}`],['deals',`${tr('common.deals')}${S.offers.length?`${S.offers.length}`:''}`],['noc',`NOC${S.inc.length?`${S.inc.length}`:''}`],['nets',`${tr('common.networks')}${ibxOpen()?`${ibxOpen()}`:''}`]]; + const tabs=[['goals',`${tr('common.goals')}${ndone}/${GOALS.length}`],['deals',`${tr('common.deals')}${S.offers.length?`${S.offers.length}`:''}`],['noc',`NOC${S.inc.length?``:''}`],['nets',`${tr('common.networks')}${ibxOpen()?`${ibxOpen()}`:''}`]]; $('leftTabs').innerHTML=tabs.map(([k,l])=>``).join('')+(innerWidth<760?``:''); let h=''; if(UI.left==='goals'){ diff --git a/src/i18n/en.js b/src/i18n/en.js index d273e23..5c158d7 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1795,11 +1795,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Your POP · needs a fabric port there", "game_and_settings.delete_and_start_over":"Delete and start over", "game_and_settings.export_save_download_a_file":"Export save download a file", -"game_and_settings.import_a_save_from_a_file":"Import a save from a file", "game_and_settings.import_failed_that_save_is_damaged":"Import failed.
That save is damaged and could not be loaded. Your current game is untouched.", "game_and_settings.name_and_everything_it_owns_will":"{name} and everything it owns will be deleted. This cannot be undone.", -"game_and_settings.scenarios_amp_weekly_challenge":"Scenarios & weekly challenge", -"game_and_settings.share_your_network_image_card":"Share your network image card", "game_and_settings.start_a_new_network":"Start a new network?", "game_and_settings.welcome_back_name_imported_and_saved":"Welcome back, {name}.
Imported and saved on this device.", "game_and_settings.your_game_saves_itself_every_few":"Your game saves itself every few seconds on this device.", @@ -2015,7 +2012,6 @@ "hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} message waiting for an answer.","other":"{n} messages waiting for an answer."}, "hud_and_panels.n_more_networks":{"one":"+{n} more network","other":"+{n} more networks"}, "hud_and_panels.n_networks_d_days_left":"{n} networks · {d} days left", -"hud_and_panels.n_new_notification":{"one":"{n} new notification","other":"{n} new notifications"}, "hud_and_panels.n_rules_live":"{n} rules live", "hud_and_panels.n_session_is_down_on_its":{"one":"{n} session is down on its max-prefix limit.","other":"{n} sessions are down on their max-prefix limit."}, "hud_and_panels.n_small_networks":"{n} small networks", @@ -3520,7 +3516,6 @@ "slots.this_window_stopped_saving_so_it":"A newer version was saved in another window, so this one stopped saving instead of overwriting it.", "slots.two_windows_one_network":"Two windows, one network", "slots.your_networks":"Your networks", -"slots.your_networks_switch_or_start_another":"Your networks switch, or start another", "slots.your_other_networks_share_this_browser":"Your other networks share this browser's storage. Export the ones you want to keep, then delete them here to make room.", "sold_out.a_hyperscaler_bought_every_wave_of":"A hyperscaler bought every wave of that size on this route last week.", "sold_out.not_big_enough_yet_list":"Not big enough yet: {list}", diff --git a/src/styles/20-drawers.css b/src/styles/20-drawers.css index bd9b547..5f510ec 100644 --- a/src/styles/20-drawers.css +++ b/src/styles/20-drawers.css @@ -83,3 +83,5 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .inc .nm{font-weight:900} .inc .meta{font-size:12px;color:var(--ink2);margin-top:2px;line-height:1.35} +/* The NOC tab only says whether something is broken, never how many notifications wait (2.0). */ +.cnt.dot{min-width:0;width:9px;height:9px;padding:0;border-radius:50%;vertical-align:middle} diff --git a/src/styles/60-phone.css b/src/styles/60-phone.css index 6bccadf..39cbe7f 100644 --- a/src/styles/60-phone.css +++ b/src/styles/60-phone.css @@ -35,6 +35,7 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #tabbar button.play.paused{background:#FFE3F0} #tabbar .cnt{position:absolute;top:2px;right:calc(50% - 22px);min-width:16px;height:16px;padding:0 4px;border-radius:8px;background:var(--me);color:#fff;font-size:10px;line-height:16px;box-sizing:border-box} #tabbar .cnt.red{background:var(--bad)} + #tabbar .cnt.dot{min-width:0;width:10px;height:10px;padding:0;top:6px;right:calc(50% - 16px)} #left,#panel{top:auto !important;left:0 !important;right:0 !important;width:auto !important;bottom:var(--tabbar) !important;max-height:min(62%,calc(100% - var(--tabbar) - 70px)) !important;border-radius:20px 20px 0 0 !important;border-bottom:0 !important;box-shadow:0 -3px 0 var(--ink) !important;transition:max-height .22s ease,transform .22s ease;z-index:7} #left.full,#panel.full{max-height:calc(100% - var(--tabbar) - 56px - env(safe-area-inset-top,0px)) !important} #left.closed{display:none} diff --git a/tests/game.test.js b/tests/game.test.js index 13e085a..6f5d817 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -483,14 +483,13 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens assert.equal(ev("S.log.length"), 6, 'a minute later it starts a new line'); // the NOC shows them right after the incidents, with Open where there is something to open assert.equal(ev("logUnread()"), 6); - ev("renderHUD()"); assert.equal(doc.getElementById('hNocNew').hidden, false); assert.equal(doc.getElementById('hNocNew').textContent, '6'); + ev("renderHUD()"); assert.equal(doc.getElementById('hNocNew').hidden, true, 'no unread count on the NOC button (2.0)'); ev("UI.left='noc';UI.leftOpen=true;UI.sel=null;renderLeft();renderHUD()"); const body = doc.getElementById('leftBody').textContent; assert.match(body, /Notifications\s*last 10 minutes/); assert.ok(body.indexOf('Notifications') < body.indexOf('DDoS scrubbing'), 'near the top, not at the bottom'); assert.match(body, /×5/); assert.match(body, /just now/); assert.equal(doc.querySelectorAll('#leftBody [data-act=logOpen]').length, 2, 'Open only where it leads somewhere (2 of the 5 shown)'); - assert.equal(doc.getElementById('hNocNew').hidden, true, 'read once the NOC is open'); assert.equal(ev("logUnread()"), 0); ev("ACT.logAll()"); assert.equal(doc.querySelectorAll('#leftBody .note').length, 6); assert.equal(doc.querySelectorAll('#leftBody [data-act=logOpen]').length, 3); // Open goes there @@ -506,12 +505,15 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens ev("S.log.push({t:'old',k:'weird',o:{a:'city',v:'atlantis'},n:'many'},{t:5},{t:'x',o:{a:'tab',v:'evil'}},{t:'y',o:{a:'link',v:'l1'},at:'soon'});S=sanitize(S)"); const tail = JSON.parse(ev("JSON.stringify(S.log.slice(-3))")); assert.deepEqual(tail.map(e => [e.t, e.k, e.o, e.n, e.at]), [['old', '', null, 1, 0], ['x', '', null, 1, 0], ['y', '', { a: 'link', v: 'l1' }, 1, 0]]); - // phones: the NOC tab carries the count + // phones: the NOC tab shows no numbers, only a red dot while something is broken ev("__tick(1000);toast('Router crashed
Your router in London is rebooting.','bad');UI.left='goals';UI.leftOpen=false"); dom.window.innerWidth = 360; ev("renderAll&&renderAll()"); const nocTab = [...doc.querySelectorAll('#tabbar [data-act=phoneTab]')].find(b => JSON.parse(b.dataset.args).t === 'noc'); - assert.equal(nocTab.querySelector('.cnt').textContent, '1', 'one unread notification on the NOC tab'); - assert.equal(nocTab.querySelector('.cnt').classList.contains('red'), false, 'not red: red is for incidents'); + assert.equal(nocTab.querySelector('.cnt'), null, 'no number for unread notifications on the NOC tab'); + ev("S.inc.push({id:'x1',type:'crash',city:'lon',msg:'',until:S.day+3});renderAll()"); + const nocTab2 = [...doc.querySelectorAll('#tabbar [data-act=phoneTab]')].find(b => JSON.parse(b.dataset.args).t === 'noc'); + assert.ok(nocTab2.querySelector('.cnt.dot.red'), 'a live incident shows a red dot'); + assert.equal(nocTab2.querySelector('.cnt').textContent, '', 'and no number'); assert.deepEqual(errors, []); }); From 4ebe8418a0ca9af6ee962902aaa4155bdc61ff9b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 21:37:05 +0100 Subject: [PATCH 137/181] Peering desk: incoming requests answered by policy; inbox, max-prefix and the Large Peering Model removed --- site/i18n/de.js | 100 +++--------------- site/i18n/es.js | 100 +++--------------- site/i18n/fr.js | 100 +++--------------- site/i18n/it.js | 100 +++--------------- site/i18n/pt.js | 100 +++--------------- src/game/40-progress/30-rules.js | 16 +-- src/game/60-features/80-new-game.js | 2 +- src/game/70-rules/20-exchanges.js | 2 +- src/game/70-rules/40-peering-desk.js | 30 ++++++ src/game/70-rules/40-peering-inbox.js | 83 --------------- src/game/70-rules/70-sold-out.js | 2 +- src/game/80-simulation/30-compute.js | 2 +- src/game/80-simulation/50-sanitize.js | 14 ++- src/game/85-incidents/20-failures.js | 9 +- src/game/88-days/10-day-tick.js | 2 +- src/game/90-actions/10-interface.js | 2 +- .../90-actions/40-sites-peering-caches.js | 8 +- src/game/93-ui/20-phone.js | 2 +- src/game/93-ui/40-hud-and-panels.js | 4 +- src/game/93-ui/55-utilities.js | 2 +- src/game/93-ui/57-ops-panel.js | 3 +- src/game/95-modals/20-notifications.js | 4 +- src/game/95-modals/45-slots.js | 2 +- src/game/95-modals/60-help.js | 4 +- src/i18n/en.js | 100 +++--------------- src/styles/40-modal.css | 2 +- tests/i18n.test.js | 4 +- 27 files changed, 151 insertions(+), 648 deletions(-) create mode 100644 src/game/70-rules/40-peering-desk.js delete mode 100644 src/game/70-rules/40-peering-inbox.js diff --git a/site/i18n/de.js b/site/i18n/de.js index c05ddcb..cafa5db 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -809,7 +809,6 @@ "common.aug":"Aug", "common.auto":"Auto", "common.auto_enrolled":"automatisch gebucht", -"common.average":"Durchschnitt", "common.avoid":"Meiden", "common.back":"Zurück", "common.back_to_the_map":"Zurück zur Karte", @@ -825,7 +824,6 @@ "common.bgp_hijack":"BGP-Hijack", "common.bgp_sessions":"BGP-Sessions", "common.big_league":"Erste Liga", -"common.black_hole":"Schwarzes Loch", "common.blitz":"Blitz", "common.boot_time":"Bootzeit", "common.boot_times":"Bootzeiten", @@ -833,7 +831,6 @@ "common.box_6ee3":"− Box", "common.build_time":"Bauzeit", "common.building":"im Bau", -"common.bumped":"verdrängt", "common.bunker_two":"Bunker Zwei", "common.busiest_links":"Meistgenutzte Links", "common.business_customers":"Geschäftskunden", @@ -995,8 +992,6 @@ "common.import_a_save":"Spielstand importieren", "common.in_progress":"läuft", "common.in_use":"Belegt", -"common.inbox":"Posteingang", -"common.inbox_zero":"Inbox Zero.", "common.incident":"Störung", "common.incidents":"Störungen", "common.incidents_survived":"Überstandene Störungen", @@ -1124,7 +1119,6 @@ "common.oops":"Hoppla", "common.open":"Öffnen", "common.open_bank":"Bank öffnen", -"common.open_inbox":"Posteingang öffnen", "common.open_infra":"Infra öffnen", "common.open_lease":"Miete öffnen", "common.open_noc":"NOC öffnen", @@ -1149,7 +1143,6 @@ "common.peered_ce2f":"Gepeert ✓", "common.peering":"Peering", "common.peering_first":"Peering First", -"common.peering_inbox":"Peering-Posteingang", "common.peering_policy":"Peering-Policy", "common.peering_ratio":"Peering-Quote", "common.peering_spat":"Peering-Streit", @@ -1198,7 +1191,6 @@ "common.remove_port":"Port entfernen", "common.remove_script":"Skript entfernen", "common.request":"Anfragen", -"common.responsive":"Reagiert", "common.resume":"Fortsetzen", "common.retention_offer":"Halteangebot", "common.revenue":"Umsatz", @@ -1304,7 +1296,6 @@ "common.to":"Nach", "common.toaster_wrangler":"Toaster-Bändiger", "common.today":"Heute", -"common.today_4203":"heute", "common.toggle_sound":"Sound an/aus", "common.too_far_for_this_cable":"zu weit für dieses Kabel", "common.traceroute":"Traceroute", @@ -1366,7 +1357,6 @@ "common.your_network":"Dein Netz", "common.your_pop":"Dein POP", "common.your_pops":"Deine POPs", -"common.your_reputation":"Dein Ruf", "common.zombie_route":"Zombie-Route", "compute.attack_hauled_to_scrubbing_in_city":"Angriff zum Scrubbing nach {city} geschleppt", "compute.courtesy_route_to_new_networks":"Gefälligkeits-Route zu neuen Netzen", @@ -1613,8 +1603,6 @@ "failures.a_kilometre_of_copper_went_missing":"Ein Kilometer „Kupfer“ ist aus deinem Graben {a}–{b} verschwunden. Es war deine Glasfaser. Der Schrotthändler hat sie mit einem Zettel zurückgeschickt.", "failures.a_landslide_in_the_andes_buried":"Ein Erdrutsch in den Anden hat deine Glasfaser {a}–{b} verschüttet.", "failures.a_llama_herd_trampled_the_fiber":"Eine Lamaherde hat die Glasfasermarkierung an {a}–{b} niedergetrampelt. Dann hat ein Bagger die Glasfaser gefunden.", -"failures.a_member_at_ix_leaked_the":"Ein Mitglied am {ix} hat die komplette Routing-Tabelle in den Route Server geleakt. Überall haben Max-Prefix-Limits ausgelöst. Dein Peering dort ist down.", -"failures.a_member_at_ix_leaked_the_5563":"Ein Mitglied am {ix} hat die komplette Routing-Tabelle in den Route Server geleakt. Überall haben Max-Prefix-Limits ausgelöst. Dein Peering dort, in {city}, ist down.", "failures.a_new_tech_in_a_tidied":"Ein neuer Techniker in {a} hat das Kabelchaos „aufgeräumt“. Dein Link {a}–{b} gehörte zum Chaos.", "failures.a_new_tech_in_city_used":"Ein neuer Techniker in {city} hat Vegemite als Wärmeleitpaste benutzt. Es leitet Geschmack, nicht Wärme, und dein Router ist gar geworden.", "failures.a_optic_on_a_b_overheated":"Eine {optic} auf {a}–{b} ist überhitzt und jetzt ein sehr teurer Schlüsselanhänger.", @@ -1681,7 +1669,6 @@ "failures.load_shedding_stage_n_in_city":"Lastabwurf Stufe {n} in {city}, und du hast keinen Generator. Kauf einen: Hier ist das nicht optional.", "failures.load_shedding_took_out_site_in":"Lastabwurf hat {site} in {city} lahmgelegt. {other} lief weiter, also arbeitet der POP mit halber Kapazität. Alles, was nur am dunklen Standort angeschlossen ist, ist offline.", "failures.magpie_swooping_season_the_field":"Elstern-Angriffssaison: Die Techniker an {a}–{b} verlassen den Transporter nicht, und deine Glasfaser bleibt durchtrennt.", -"failures.max_prefix_meltdown":"Max-Prefix-Kernschmelze", "failures.metro_ring_cut":"Metro-Ring gekappt", "failures.microbursts_on_a_b_overflow_shallow":"Microbursts auf {a}–{b} lassen flache Router-Buffer überlaufen: 0,5 % Verlust zur Spitzenzeit, und jeder Videocall merkt es.", "failures.microbursts_on_a_b_your_deep":"Microbursts auf {a}–{b}.
Deine Router mit tiefen Buffern haben sie aufgesaugt. Niemand hat was gemerkt.", @@ -1796,11 +1783,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Dein POP · braucht dort einen Fabric-Port", "game_and_settings.delete_and_start_over":"Löschen und neu anfangen", "game_and_settings.export_save_download_a_file":"Spielstand exportieren Datei herunterladen", -"game_and_settings.import_a_save_from_a_file":"Spielstand importieren aus einer Datei", "game_and_settings.import_failed_that_save_is_damaged":"Import fehlgeschlagen.
Dieser Spielstand ist beschädigt und konnte nicht geladen werden. Dein aktuelles Spiel ist unberührt.", "game_and_settings.name_and_everything_it_owns_will":"{name} und alles, was dazugehört, wird gelöscht. Das lässt sich nicht rückgängig machen.", -"game_and_settings.scenarios_amp_weekly_challenge":"Szenarien & Wochen-Challenge", -"game_and_settings.share_your_network_image_card":"Dein Netz teilen Bildkarte", "game_and_settings.start_a_new_network":"Ein neues Netz starten?", "game_and_settings.welcome_back_name_imported_and_saved":"Willkommen zurück, {name}.
Importiert und auf diesem Gerät gespeichert.", "game_and_settings.your_game_saves_itself_every_few":"Dein Spiel speichert sich alle paar Sekunden auf diesem Gerät.", @@ -1871,7 +1855,7 @@ "help.each_pop_s_router_model_caps":"Das Router-Modell eines POPs begrenzt seinen schnellsten Port (100G, 400G, 800G, 1.6T) und wie viel er weiterleiten kann. Größere Waves und Ports brauchen an beiden Enden bessere Router. Bessere Modelle werden mit deinem Kundenlevel freigeschaltet. Mit nur einem Router heißen Upgrades einen Tag Ausfallzeit.", "help.event_networks_a_final_a_festival":"Event-Netze (ein Finale, ein Festival, eine Keynote) brauchen für ein paar Tage einen Kapazitätsschub in einer Stadt und zahlen einmal am Ende, anteilig danach, wie viel der Menge du bedient hast; unter 70 % zahlst du eine Vertragsstrafe. SD-WAN-Ketten verbinden 3–6 deiner POPs als Hub-and-Spoke, also verärgert eine kaputte Speiche den ganzen Vertrag. Sobald du eigene Dark Fiber betreibst, wollen Carrier freie Kanäle als Alien Waves mieten, und auf selbst gebauter Glasfaser ein freies Paar.", "help.events_chains_and_wholesale":"Events, Ketten und Wholesale", -"help.every_ix_port_brings_peering":"Jeder IX-Port bringt Peering-Anfragen und Max-Prefix-Alarme mit, im Tab Netze. Eine Session, die ihr Limit sprengt, bleibt down, bis du nachsiehst: Heb das Limit bei Wachstum an, lass sie bei einem Leak down. Ignorierst du deine Post, werden selektive Netze wählerischer.", +"help.every_ix_port_brings_requests":"Jeder IX-Port bringt Peering-Anfragen, und deine Peering-Policy im Netze-Tab beantwortet sie: Offen nimmt alle an, Selektiv nimmt die Netze, mit denen sich Peering lohnt, und lehnt den Rest still ab, Geschlossen lehnt alle ab. Einmal pro Woche fasst das NOC-Log es zusammen.", "help.every_link_has_latency_high":"Jeder Link hat Latenz. Hochfrequenzhändler zahlen ein Vermögen für eine Verbindung innerhalb ihres Latenzbudgets; route sie über „Niedrigste Latenz“. Backup-Kunden ist das egal, also route sie „Landschaftlich“ über deine ruhigen Links, damit die vollen frei bleiben.", "help.home_broadband_users_they_mostly":"Heim-Breitband-Nutzer. Sie laden meist von CDNs herunter und zahlen dir pro ausgeliefertem Gbps. Bedien sie gut, und sie vermehren sich.", "help.how_the_internet_works_here":"So funktioniert das Internet hier", @@ -1885,7 +1869,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) ist transitfrei. Du peerst mit jedem Riesen auf dem Planeten und zahlst niemandem etwas, um das Internet zu erreichen. Hat dich {days} Tage und {n} Störungen gekostet.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG und Co. kommen jedes Jahr vorbei. Melde dich im Tab Deals für $8k an. In den 45 Tagen danach brauchen selektive Netze mit Präsenz in dieser Region nur halb so viel Traffic wie sonst, bevor sie mit dir peeren. Manchmal gewinnst du auch die Tombola.", "help.once_auto_te_is_installed_you":"Sobald Auto-TE installiert ist, kannst du es im Tab NOC programmieren. Zu den Regeln gehören spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams und blackhole ddos. Prüfen spielt einen Probelauf mit dem Live-Traffic durch; Deployen macht es echt, Fehler inklusive.", -"help.one_game_four_doors_puzzles_are":"Ein Spiel, vier Türen, und die Regeln wählst du beim Start eines Netzes, danach sind sie festgelegt. Rätsel sind kleine Knoten zum Entwirren, ohne Uhr. Sandbox gibt dir eine Milliarde Dollar, alle Freischaltungen (dein eigenes Seekabel inklusive) und so viel Chaos, wie du willst, aber keine Abzeichen. Normal gibt es dreifach: Change Freeze (wenige Ausfälle, Lieferungen in Tagen, kein Postfach, keine Engpässe), Rufbereitschaft (das klassische Spiel) und BGP um 3 Uhr nachts (mehr und längere Ausfälle, mehr DDoS). Szenarien sind handgebaute Herausforderungen mit Ziel und Frist, und die Wochen-Challenge gibt allen eine Woche lang dieselbe Welt. Teile dein Ergebnis mit der Karte im Menü.", +"help.one_game_four_doors_and_the":"Ein Spiel, vier Türen, und die Regeln wählst du beim Start eines Netzes, danach sind sie festgelegt. Rätsel sind kleine Knoten zum Entwirren, ohne Uhr. Sandbox gibt dir eine Milliarde Dollar, alle Freischaltungen (dein eigenes Seekabel inklusive) und so viel Chaos, wie du willst, aber keine Abzeichen. Normal gibt es dreifach: Change Freeze (wenige Ausfälle, Lieferungen in Tagen, keine Engpässe), Rufbereitschaft (das klassische Spiel) und BGP um 3 Uhr nachts (mehr und längere Ausfälle, mehr DDoS). Szenarien sind handgebaute Herausforderungen mit Ziel und Frist, und die Wochen-Challenge gibt allen eine Woche lang dieselbe Welt. Teile dein Ergebnis mit der Karte im Menü.", "help.open_peers_with_anyone_selective":"Offene Netze peeren mit allen. Selektive wollen erst Traffic sehen. Restriktive (Tier 1s) peeren nur mit Riesen, über PNIs. Paid Peering heißt genau das: Du zahlst. Große selektive Netze haben auch Launen: In manchen Städten lehnen sie ein paar Monate lang neue Peers ab oder nehmen nur PNIs, und ab und zu bauen sie eine Session ab, die du schon hattest. Versuch es in einer anderen Stadt oder mit einem PNI und frag später nochmal.", "help.out_of_port_speed_bundle_up":"Port zu langsam? Bündle bis zu 8 identische Ports zum selben Transit-Anbieter, IX oder PNI zu einem LAG. Jedes Mitglied kostet einen vollen Port; Flow-Hashing ist nie perfekt gleichmäßig, also trägt ein Bündel etwa 95 % der Summe.", "help.pni_lead_times":"PNI-Lieferzeiten", @@ -2010,15 +1994,12 @@ "hud_and_panels.has_errors_not_running":"hat Fehler, läuft nicht", "hud_and_panels.incidents_so_far":"Bisherige Störungen", "hud_and_panels.install_auto_te_cost_mo_mo":"Auto-TE installieren {cost} + {mo}/Monat", -"hud_and_panels.large_peering_model_is_on_it":"Das Large Peering Model kümmert sich drum.", "hud_and_panels.lv_n":"Lv {n}", "hud_and_panels.n_incident":{"one":"{n} Störung","other":"{n} Störungen"}, -"hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} Nachricht wartet auf eine Antwort.","other":"{n} Nachrichten warten auf eine Antwort."}, "hud_and_panels.n_more_networks":{"one":"+{n} weiteres Netz","other":"+{n} weitere Netze"}, "hud_and_panels.n_networks_d_days_left":"{n} Netze · noch {d} Tage", "hud_and_panels.n_new_notification":{"one":"{n} neue Benachrichtigung","other":"{n} neue Benachrichtigungen"}, "hud_and_panels.n_rules_live":"{n} Regeln aktiv", -"hud_and_panels.n_session_is_down_on_its":{"one":"{n} Session ist wegen ihres Max-Prefix-Limits down.","other":"{n} Sessions sind wegen ihres Max-Prefix-Limits down."}, "hud_and_panels.n_small_networks":"{n} kleine Netze", "hud_and_panels.n_special_requirement":{"one":"{n} Sonderwunsch","other":"{n} Sonderwünsche"}, "hud_and_panels.n_unhappy_customer_price_mo_at":{"one":"{n} unzufriedener Kunde, {price}/Monat gefährdet","other":"{n} unzufriedene Kunden, {price}/Monat gefährdet"}, @@ -2594,6 +2575,7 @@ "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.day_d":"Tag {d}", "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.", @@ -2632,8 +2614,6 @@ "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.", -"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.", @@ -2746,61 +2726,14 @@ "page.series_of_tubes_build_the_internet":"Series of Tubes: Bau das Internet, eine Röhre nach der anderen", "page.world_map_of_your_network":"Weltkarte deines Netzes", "page.x":"", -"peering_inbox.accept_all_requests":"Alle Anfragen annehmen", -"peering_inbox.an_ai_agent_that_answers_every":"Ein KI-Agent, der jeden Tag jede Peering-Anfrage und jeden Max-Prefix-Alarm für dich beantwortet. {price}/Jahr. Trainiert mit zwanzig Jahren Peering-Mailinglisten.", -"peering_inbox.answered_your_mail_a_accepted_d":"Hat deine Mails beantwortet: {a} angenommen, {d} abgelehnt.", -"peering_inbox.asked_netchill_s_peering_team_to":"Hat das Peering-Team von NetChill gebeten, „bitte mehr Netchill bereitzustellen“.", -"peering_inbox.configured_lim_prefixes_received_got":"Konfiguriert: {lim} Präfixe. Empfangen: {got}.", -"peering_inbox.day_d":"Tag {d}", -"peering_inbox.dear_sir_or_madam_please_peer":"Sehr geehrte Damen und Herren, bitte peeren Sie. Wir haben drei Präfixe und sehr große Pläne.", -"peering_inbox.decline_all_requests":"Alle Anfragen ablehnen", -"peering_inbox.declined_who_at_ix_not_a":"{who} am {ix} abgelehnt: „passt strategisch nicht“. Hat es aber.", -"peering_inbox.every_exchange_port_brings_mail":"Jeder Exchange-Port bringt Post. Beantworte Peering-Anfragen und sieh dir Sessions an, die ihr Max-Prefix-Limit erreicht haben: Ist das Wachstum oder ein Route Leak? Unbeantwortete Mails bringen dir einen schlechten Ruf ein, und selektive Netze bekommen das mit.", -"peering_inbox.everyone_who_asks_gets_a_session":"Jeder, der fragt, bekommt eine Session, und die Route Server laufen. Viele winzige Peers und viele Max-Prefix-Alarme.", -"peering_inbox.fewer_requests_and_you_answer_them":"Weniger Anfragen, und du beantwortest sie selbst. Keine Route Server: Geh zu jedem Exchange und frag die Netze an, die du willst.", -"peering_inbox.fire_the_ai":"KI feuern", -"peering_inbox.good_call_it_was_a_route":"Gut erkannt: Es war ein Route Leak.
{who} hat eine vertippte Route-Map gefunden. Die Session kommt in ein paar Tagen von selbst zurück.", -"peering_inbox.greetings_we_are_a_fast_growing":"Grüße. Wir sind ein schnell wachsendes Netz. Letztes Jahr hatten wir einen Kunden, dieses Jahr sind es zwei.", -"peering_inbox.hello_please_find_attached_our":"Hallo, anbei unsere Peering-Anfrage als Word-Dokument, eingescannt von einem Ausdruck.", -"peering_inbox.hey_quick_one_can_you_peer":"Hey, kurze Frage: Kannst du mit uns am {ix} peeren? Wir haben einen sehr wichtigen Minecraft-Server.", -"peering_inbox.hi_we_would_like_to_peer":"Hi! Wir würden gern mit dir am {ix} peeren. Unser PeeringDB-Eintrag ist aktuell.", -"peering_inbox.hire_it_mo_mo":"Anheuern {mo}/Monat", -"peering_inbox.inbox_zero_enjoy_it_while_it":"Inbox Zero. Genieß es, solange es anhält.", -"peering_inbox.keep_it_down":"Down lassen", -"peering_inbox.kept_who_down_at_ix_for":"{who} am {ix} wegen „verdächtigen Wachstums“ down gelassen. Sie waren um einen Kunden gewachsen.", -"peering_inbox.kept_who_down_at_ix_it":"{who} am {ix} down gelassen: Es war ein Route Leak. Volltreffer.", -"peering_inbox.large_peering_model":"Large Peering Model", -"peering_inbox.large_peering_model_is_answering":"Das Large Peering Model beantwortet deine Mails", -"peering_inbox.max_prefix_limit_hit_who_at":"Max-Prefix-Limit erreicht: {who} am {ix}.
Die Session bleibt down, bis du sie dir ansiehst.", -"peering_inbox.max_prefix_limit_hit_who_at_5c56":"Max-Prefix-Limit erreicht: {who} am {ix}", -"peering_inbox.mostly_ignores_email":"Ignoriert Mails meistens", -"peering_inbox.n_day_ago":{"one":"vor {n} Tag","other":"vor {n} Tagen"}, -"peering_inbox.n_unanswered":{"one":"{n} unbeantwortet","other":"{n} unbeantwortet"}, -"peering_inbox.no_mail_yet_buy_an_ix":"Noch keine Post. Kauf einen IX-Port, dann kommt sie.", -"peering_inbox.nobody_asks_and_no_route_servers":"Niemand fragt, und keine Route Server. Kunden hören, dass du schwer erreichbar bist, also rufen weniger an, und dein Ruf sinkt.", -"peering_inbox.open_to_all":"Offen für alle", -"peering_inbox.opened_a_ticket_with_itself_to":"Hat bei sich selbst ein Ticket eröffnet, um die eigenen Entscheidungen zu prüfen. Es hat sie genehmigt.", -"peering_inbox.peering_request_fifth_attempt_is":"Peering-Anfrage, fünfter Versuch. Ist da jemand?", -"peering_inbox.peeringdb_last_updated_n_year_ago":{"one":"PeeringDB zuletzt vor {n} Jahr aktualisiert","other":"PeeringDB zuletzt vor {n} Jahren aktualisiert"}, -"peering_inbox.peeringdb_updated_last_month":"PeeringDB letzten Monat aktualisiert", -"peering_inbox.please_configure_sessions_with_us_at":"Bitte konfiguriere Sessions mit uns am {ix}. Wir machen unsere nächste Woche, oder die Woche danach.", -"peering_inbox.price_year_it_never_sleeps_never":"{price}/Jahr. Schläft nie, beschwert sich nie und liegt oft falsch.", -"peering_inbox.raise_all_max_prefix_limits":"Alle Max-Prefix-Limits anheben", -"peering_inbox.raise_the_limit":"Limit anheben", -"peering_inbox.raised_the_max_prefix_limit_for":"Hat das Max-Prefix-Limit für {who} am {ix} auf {n} angehoben. Sie wirkten nett.", -"peering_inbox.raised_the_max_prefix_limit_for_7b4b":"Hat das Max-Prefix-Limit für {who} am {ix} angehoben. Diesmal zu Recht.", -"peering_inbox.replied_to_a_peering_request_with":"Hat eine Peering-Anfrage mit einem Haiku über BGP beantwortet. Noch keine Antwort.", -"peering_inbox.session_with_who_is_back_up":"Die Session mit {who} ist wieder up.
Neues Limit: {n} Präfixe. Sie versprechen, PeeringDB zu aktualisieren.", -"peering_inbox.signed_you_up_for_a_webinar":"Hat dich für ein Webinar über „Peering im Zeitalter der KI“ angemeldet.", -"peering_inbox.that_was_a_route_leak_who":"Das war ein Route Leak.
{who} hat {n} Präfixe announced: eine volle Tabelle. Lass die Session nächstes Mal down.", -"peering_inbox.the_session_stays_down_who_will":"Die Session bleibt down.
{who} aktualisiert PeeringDB und fragt nochmal. Irgendwann.", -"peering_inbox.their_peeringdb_says_lim_last":{"one":"Laut ihrer PeeringDB {lim}, zuletzt vor {n} Jahr aktualisiert.","other":"Laut ihrer PeeringDB {lim}, zuletzt vor {n} Jahren aktualisiert."}, -"peering_inbox.tidied_up_a_session_it_decided":"Hat eine Session aufgeräumt, die es für ungenutzt hielt: {who} am {ix} de-peert.", -"peering_inbox.updated_your_peeringdb_record_your":"Hat deinen PeeringDB-Eintrag aktualisiert. Deine NOC-Telefonnummer gehört jetzt einer Pizzeria.", -"peering_inbox.we_noticed_you_are_at_ix":"Wir haben gesehen, dass du am {ix} bist. Wir auch. Wollen wir?", -"peering_inbox.who_asked_a_mailing_list_whether":"{who} hat auf einer Mailingliste gefragt, ob jemand einen funktionierenden Kontakt bei {me} hat.
Ihre Peering-Anfrage lag einen Monat in deinem Postfach.", -"peering_inbox.who_at_ix_was_sending_a":"{who} am {ix} hat eine volle Tabelle geschickt, und das Max-Prefix-Limit war das Einzige, was das aufgehalten hat. Mit angehobenem Limit zeigen die Präfixe von {net} jetzt in deren Keller. Traffic zu {net} über Transit wird ein paar Tage lang geblackholt.", -"peering_inbox.wrote_a_thousand_word_apology_to":"Hat eine tausend Wörter lange Entschuldigung an ein Netz geschrieben, mit dem du nie gepeert hast.", +"peering_desk.closed_desc":"Jede Peering-Anfrage wird abgelehnt, und keine Route Server. Kunden hören, dass du schwer erreichbar bist, also rufen weniger an.", +"peering_desk.n_more_exchanges":{"one":"{n} weiterer Exchange","other":"{n} weitere Exchanges"}, +"peering_desk.n_new_sessions_at_ix":{"one":"Peering-Desk: {n} neue Session an {ix} ({pol}).","other":"Peering-Desk: {n} neue Sessions an {ix} ({pol})."}, +"peering_desk.n_new_sessions_at_ix_declined":{"one":"Peering-Desk: {n} neue Session an {ix}, {d} abgelehnt ({pol}).","other":"Peering-Desk: {n} neue Sessions an {ix}, {d} abgelehnt ({pol})."}, +"peering_desk.n_requests_declined":{"one":"Peering-Desk: {n} Anfrage abgelehnt ({pol}).","other":"Peering-Desk: {n} Anfragen abgelehnt ({pol})."}, +"peering_desk.open_desc":"Jedes Netz, das fragt, bekommt eine Session, und die Route Server laufen.", +"peering_desk.open_to_all":"Offen für alle", +"peering_desk.selective_desc":"Kleine Netze am Exchange und Neulinge mit aktueller PeeringDB bekommen eine Session, der Rest wird still abgelehnt. Keine Route Server: Frag an jedem Exchange die Netze an, die du willst.", "peering_policy.a_new_vp_wants_to_monetise":"Ein neuer VP will in diesem Markt „Interconnection monetarisieren“.", "peering_policy.already_reach_you_through_your":"Erreichen dich hier schon über deinen Transit-Provider und finden das in Ordnung.", "peering_policy.moved_everything_in_this_city_to":"Haben in dieser Stadt alles auf PNIs umgestellt. Bitte lies ihre PearingDB-Seite, alle 40 Seiten davon.", @@ -3311,7 +3244,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Steck zuerst etwas aus.
{used} Ports sind belegt, und mit einem Router weniger gibt es nur {max}.", "rules.a_billion_dollars_every_unlock_your":"Eine Milliarde Dollar, alles freigeschaltet, dein eigenes Seekabel.", "rules.a_cut_now_and_then":"Ab und zu ein Bagger.", -"rules.a_third_of_the_outages_no_ddos":"Ein Drittel der Ausfälle, kein DDoS. PNIs und Bauten in Tagen. Kein Postfach, keine Lieferengpässe, keine ausverkauften Routen, kein De-Peering.", +"rules.a_third_of_the_outages_no_ddos_pnis":"Ein Drittel der Ausfälle, kein DDoS. PNIs und Bauten in Tagen. Keine Lieferengpässe, keine ausverkauften Routen, kein De-Peering.", "rules.bgp_at_3_a_m":"BGP um 3 Uhr nachts", "rules.change_freeze":"Change Freeze", "rules.chaos_calm":"Ruhig", @@ -3328,7 +3261,7 @@ "rules.on_call":"Rufbereitschaft", "rules.one_small_network_one_tricky_goal":"Ein kleines Netz, ein kniffliges Ziel.", "rules.puzzle":"Rätsel", -"rules.real_lead_times_real_outages_a":"Echte Lieferzeiten, echte Ausfälle, ein volles Peering-Postfach. Das klassische Spiel.", +"rules.real_lead_times_real_outages_a_real":"Echte Lieferzeiten, echte Ausfälle, ein echter Markt. Das klassische Spiel.", "rules.rules_are_locked_for_this_network":"{rules}: Die Regeln sind für dieses Netz festgelegt.", "rules.the_real_thing_your_pager_has":"Das echte Spiel. Dein Pager hat Meinungen.", "rules.your_pager_never_sleeps":"Dein Pager schläft nie.", @@ -3462,9 +3395,7 @@ "sites_peering_caches.bgp_session_established":"BGP-Session aufgebaut.", "sites_peering_caches.cache_installed_in_city_net_shipped":"{cache} in {city} installiert!
{net} hat ihn kostenlos geliefert. Du zahlst {mo}/Monat für Strom.", "sites_peering_caches.could_you_resend_the_loa_you":"„Könntest du die LOA nochmal schicken?“
Du hast sie schon viermal geschickt.", -"sites_peering_caches.hello_i_am_large_peering_model":"Hallo! Ich bin das Large Peering Model. Ich habe dein Postfach gelesen und habe schon eine Meinung dazu.", "sites_peering_caches.it_is_with_the_provisioning_team":"„Das liegt beim Provisioning-Team.“
Niemand hat das Provisioning-Team je getroffen.", -"sites_peering_caches.large_peering_model_is_hired_your":"Das Large Peering Model ist angeheuert.
Dein Postfach ist jetzt sein Problem. {price} pro Jahr, monatlich abgerechnet.", "sites_peering_caches.n_new_session_at_ix_small":{"one":"{n} neue Session am {ix}.
Kleine Netze, aber das summiert sich, und alle zählen für den Club.","other":"{n} neue Sessions am {ix}.
Kleine Netze, aber das summiert sich, und alle zählen für den Club."}, "sites_peering_caches.net_accepted":"{net} hat angenommen!", "sites_peering_caches.net_declined_the_pni_why":"{net} hat den PNI abgelehnt.
{why}", @@ -3472,11 +3403,8 @@ "sites_peering_caches.net_does_not_do_port_pnis":"{net} macht keine {port}-PNIs.
Nichts unter 100G. Komm mit mehr Traffic wieder, oder mit einer größeren Optik.", "sites_peering_caches.net_says_not_yet_send_them":"{net} sagt: noch nicht.
Schick ihnen erst {min}+ Gbps.", "sites_peering_caches.pni_with_net_ordered_eta_a":"PNI mit {net} bestellt.
{eta}. Ein Cross-Connect im {dc}, sobald jemand die LOA findet.", -"sites_peering_caches.raised_n_max_prefix_limits_all":"{n} Max-Prefix-Limits angehoben.
Alles Wachstum, keine Leaks. Glück gehabt.", -"sites_peering_caches.raised_n_max_prefix_limits_one":{"one":"{n} Max-Prefix-Limits angehoben.
Eines davon war ein Route Leak. Das liegt jetzt im NOC.","other":"{n} Max-Prefix-Limits angehoben.
{k} davon waren Route Leaks. Die liegen jetzt im NOC."}, "sites_peering_caches.second_lag_member_added_one_member":"Zweites LAG-Mitglied hinzugefügt.
Jetzt ein Mitglied in jedem Gebäude, also legt ein dunkles Gebäude nur den halben Port lahm.", "sites_peering_caches.second_site_live_in_city_b":"Zweiter Standort in {city} live.
{b} ist über deinen eigenen Metro-Ring mit {a} verbunden. Verschieb ein paar Uplinks in den Tabs Transit und Peering dorthin.", -"sites_peering_caches.the_ai_is_gone_it_left":"Die KI ist weg.
Sie hat ein 40-seitiges Übergabedokument hinterlassen. Es geht hauptsächlich um sie selbst.", "sites_peering_caches.they_checked_your_pearingdb_page_and":"Sie haben sich deine PearingDB-Seite angesehen und mochten die Traffic-Zahlen.", "sites_peering_caches.we_are_waiting_on_the_colo":"„Wir warten beim Colo auf den Cross-Connect.“
Das Colo sagt, es wartet auf sie.", "sites_peering_caches.your_account_manager_found_the_order":"Dein Account Manager hat die Bestellung unter einem Schreibtisch gefunden.
Die Lieferung rückt einen Monat näher.", @@ -3498,6 +3426,7 @@ "slots.last_played_ago":"Zuletzt gespielt: {ago}", "slots.load_the_newest_version":"Neueste Version laden", "slots.more_for_name":"Mehr zu {name}", +"slots.n_day_ago":{"one":"vor {n} Tag","other":"vor {n} Tagen"}, "slots.n_h_ago":{"one":"vor {n} Std.","other":"vor {n} Std."}, "slots.name_is_open_in_another_window":"{name} ist in einem anderen Fenster offen", "slots.name_is_waiting_in_your_other":"{name} wartet in deinem anderen Fenster.
Wechsle dorthin, um weiterzuspielen.", @@ -3521,7 +3450,6 @@ "slots.this_window_stopped_saving_so_it":"In einem anderen Fenster wurde eine neuere Version gespeichert, also speichert dieses nicht mehr, statt sie zu überschreiben.", "slots.two_windows_one_network":"Zwei Fenster, ein Netz", "slots.your_networks":"Deine Netze", -"slots.your_networks_switch_or_start_another":"Deine Netze wechseln oder ein neues starten", "slots.your_other_networks_share_this_browser":"Deine anderen Netze teilen sich den Speicher dieses Browsers. Exportiere die, die du behalten willst, und lösche sie dann hier, um Platz zu schaffen.", "sold_out.a_hyperscaler_bought_every_wave_of":"Ein Hyperscaler hat letzte Woche jede Wave dieser Größe auf dieser Route gekauft.", "sold_out.not_big_enough_yet_list":"Noch nicht groß genug: {list}", diff --git a/site/i18n/es.js b/site/i18n/es.js index c4dd964..00fd43e 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -807,7 +807,6 @@ "common.aug":"Ago", "common.auto":"Auto", "common.auto_enrolled":"alta automática", -"common.average":"Media", "common.avoid":"Evitar", "common.back":"Atrás", "common.back_to_the_map":"Volver al mapa", @@ -823,7 +822,6 @@ "common.bgp_hijack":"Secuestro de BGP", "common.bgp_sessions":"Sesiones BGP", "common.big_league":"Primera división", -"common.black_hole":"Agujero negro", "common.blitz":"Blitz", "common.boot_time":"Tiempo de arranque", "common.boot_times":"Tiempos de arranque", @@ -831,7 +829,6 @@ "common.box_6ee3":"− caja", "common.build_time":"Tiempo de construcción", "common.building":"construyendo", -"common.bumped":"desplazado", "common.bunker_two":"Búnker Dos", "common.busiest_links":"Enlaces más ocupados", "common.business_customers":"Clientes empresariales", @@ -993,8 +990,6 @@ "common.import_a_save":"Importar una partida", "common.in_progress":"en curso", "common.in_use":"En uso", -"common.inbox":"Bandeja de entrada", -"common.inbox_zero":"Bandeja a cero.", "common.incident":"Incidente", "common.incidents":"Incidentes", "common.incidents_survived":"Incidentes superados", @@ -1122,7 +1117,6 @@ "common.oops":"Ups", "common.open":"Abrir", "common.open_bank":"Abrir banco", -"common.open_inbox":"Abrir bandeja", "common.open_infra":"Abrir Infra", "common.open_lease":"Abrir alquiler", "common.open_noc":"Abrir NOC", @@ -1147,7 +1141,6 @@ "common.peered_ce2f":"Con peering ✓", "common.peering":"Peering", "common.peering_first":"Peering primero", -"common.peering_inbox":"Bandeja de peering", "common.peering_policy":"Política de peering", "common.peering_ratio":"Ratio de peering", "common.peering_spat":"Riña de peering", @@ -1196,7 +1189,6 @@ "common.remove_port":"Quitar puerto", "common.remove_script":"Quitar script", "common.request":"Solicitar", -"common.responsive":"Responsivo", "common.resume":"Reanudar", "common.retention_offer":"Oferta de retención", "common.revenue":"Ingresos", @@ -1302,7 +1294,6 @@ "common.to":"Hasta", "common.toaster_wrangler":"Domador de tostadoras", "common.today":"Hoy", -"common.today_4203":"hoy", "common.toggle_sound":"Alternar sonido", "common.too_far_for_this_cable":"demasiado lejos para este cable", "common.traceroute":"Traceroute", @@ -1364,7 +1355,6 @@ "common.your_network":"Tu red", "common.your_pop":"Tu POP", "common.your_pops":"Tus POPs", -"common.your_reputation":"Tu reputación", "common.zombie_route":"Ruta zombi", "compute.attack_hauled_to_scrubbing_in_city":"Ataque desviado a depuración en {city}", "compute.courtesy_route_to_new_networks":"Ruta de cortesía a redes nuevas", @@ -1611,8 +1601,6 @@ "failures.a_kilometre_of_copper_went_missing":"Desapareció un kilómetro de «cobre» de tu zanja {a}–{b}. Era tu fibra. El desguace la devolvió con una nota.", "failures.a_landslide_in_the_andes_buried":"Un deslizamiento de tierra en los Andes enterró tu fibra {a}–{b}.", "failures.a_llama_herd_trampled_the_fiber":"Una manada de llamas pisoteó el hito de la fibra en {a}–{b}. Luego una retroexcavadora encontró la fibra.", -"failures.a_member_at_ix_leaked_the":"Un miembro de {ix} filtró la tabla de rutas completa al route server. Los límites de max-prefix saltaron por todas partes. Tu peering allí está caído.", -"failures.a_member_at_ix_leaked_the_5563":"Un miembro de {ix} filtró la tabla de rutas completa al route server. Los límites de max-prefix saltaron por todas partes. Tu peering allí, en {city}, está caído.", "failures.a_new_tech_in_a_tidied":"Un técnico nuevo en {a} «ordenó» el lío de cables. Tu enlace {a}–{b} era parte del lío.", "failures.a_new_tech_in_city_used":"Un técnico nuevo en {city} usó Vegemite como pasta térmica. Conduce sabor, no calor, y tu router se cocinó.", "failures.a_optic_on_a_b_overheated":"Una {optic} en {a}–{b} se sobrecalentó y ahora es un llavero muy caro.", @@ -1679,7 +1667,6 @@ "failures.load_shedding_stage_n_in_city":"Cortes programados de fase {n} en {city}, y no tienes generador. Compra uno: aquí no es opcional.", "failures.load_shedding_took_out_site_in":"Los cortes programados tumbaron {site} en {city}. {other} siguió funcionando, así que el POP trabaja a media capacidad. Lo que solo esté conectado en la sede a oscuras está fuera de línea.", "failures.magpie_swooping_season_the_field":"Temporada de urracas en picado: los técnicos de campo de {a}–{b} no salen de la furgoneta, y tu corte sigue cortado.", -"failures.max_prefix_meltdown":"Colapso de max-prefix", "failures.metro_ring_cut":"Anillo metropolitano cortado", "failures.microbursts_on_a_b_overflow_shallow":"Microrráfagas en {a}–{b} desbordan los buffers poco profundos del router: 0,5 % de pérdida en hora punta, y todas las videollamadas lo notan.", "failures.microbursts_on_a_b_your_deep":"Microrráfagas en {a}–{b}.
Tus routers de buffer profundo las absorbieron. Nadie lo notó.", @@ -1794,11 +1781,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Tu POP · necesita un puerto de fabric allí", "game_and_settings.delete_and_start_over":"Borrar y empezar de nuevo", "game_and_settings.export_save_download_a_file":"Exportar partida descargar un archivo", -"game_and_settings.import_a_save_from_a_file":"Importar una partida desde un archivo", "game_and_settings.import_failed_that_save_is_damaged":"Falló la importación.
Esa partida está dañada y no se pudo cargar. Tu partida actual sigue intacta.", "game_and_settings.name_and_everything_it_owns_will":"{name} y todo lo que posee se borrarán. No se puede deshacer.", -"game_and_settings.scenarios_amp_weekly_challenge":"Escenarios y desafío semanal", -"game_and_settings.share_your_network_image_card":"Comparte tu red tarjeta de imagen", "game_and_settings.start_a_new_network":"¿Empezar una red nueva?", "game_and_settings.welcome_back_name_imported_and_saved":"Bienvenido de nuevo, {name}.
Importada y guardada en este dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"Tu partida se guarda sola cada pocos segundos en este dispositivo.", @@ -1869,7 +1853,7 @@ "help.each_pop_s_router_model_caps":"El modelo de router de cada POP limita su puerto más rápido (100G, 400G, 800G, 1.6T) y cuánto puede reenviar. Las ondas y puertos mayores necesitan mejores routers en ambos extremos. Los mejores modelos se desbloquean con tu nivel de cliente. Con un solo router, mejorar implica un día de inactividad.", "help.event_networks_a_final_a_festival":"Las redes de eventos (una final, un festival, una keynote) necesitan una ráfaga de capacidad en una ciudad durante unos días y pagan una vez al final, prorrateado según cuánto de la multitud serviste; por debajo del 70 % pagas una penalización. Las cadenas SD-WAN conectan 3–6 de tus POPs en hub-and-spoke, así que un radio roto altera todo el contrato. Cuando operes tu propia fibra oscura, los operadores querrán alquilar canales libres como ondas alien, y en la fibra que construiste tú, un par libre.", "help.events_chains_and_wholesale":"Eventos, cadenas y mayorista", -"help.every_ix_port_brings_peering":"Cada puerto IX trae solicitudes de peering y alertas de max-prefix, en la pestaña Redes. Una sesión que supera su límite está caída hasta que la mires: sube el límite si es por crecimiento, déjala caída si es una fuga. Si ignoras el correo, las redes selectivas se ponen más quisquillosas.", +"help.every_ix_port_brings_requests":"Cada puerto de IX trae solicitudes de peering, y tu política de peering, en la pestaña Redes, las responde: Abierta acepta a todos, Selectiva acepta las redes con las que vale la pena hacer peering y rechaza en silencio al resto, Cerrada las rechaza todas. Una vez por semana el registro del NOC lo resume.", "help.every_link_has_latency_high":"Cada enlace tiene latencia. Los traders de alta frecuencia pagan una fortuna por un circuito dentro de su presupuesto de latencia; enrútalos con «Menor latencia». A los clientes de copias masivas no les importa, así que enrútalos por «Panorámica» sobre tus enlaces tranquilos para dejar libres los ocupados.", "help.home_broadband_users_they_mostly":"Usuarios de banda ancha doméstica. Sobre todo descargan de CDN y te pagan por cada Gbps que entregas. Sírvelos bien y se multiplican.", "help.how_the_internet_works_here":"Cómo funciona internet aquí", @@ -1883,7 +1867,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) es libre de tránsito. Haces peering con todos los gigantes del planeta y no pagas a nadie por llegar a internet. Te llevó {days} días y {n} incidentes.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG y compañía vienen cada año. Regístrate en la pestaña Tratos por $8k. Durante 45 días después, las redes selectivas con presencia en esa región solo piden la mitad del tráfico habitual antes de hacer peering contigo. A veces también ganas la rifa.", "help.once_auto_te_is_installed_you":"Una vez instalado Auto-TE, puedes programarlo desde la pestaña NOC. Las reglas incluyen spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams y blackhole ddos. Check hace una prueba en seco con tráfico real; Deploy lo hace de verdad, errores incluidos.", -"help.one_game_four_doors_puzzles_are":"Un juego, cuatro puertas, y las reglas se eligen al empezar una red y quedan fijadas después. Los puzles son pequeños nudos que deshacer, sin reloj. Sandbox te da mil millones de dólares, todo desbloqueado (tu propio cable submarino incluido) y el caos que elijas, pero sin insignias. Normal viene de tres maneras: Congelación de cambios (pocas caídas, entregas en días, sin bandeja ni escasez), De guardia (el juego clásico) y BGP a las 3 de la mañana (más caídas y más largas, más DDoS). Los escenarios son retos hechos a mano con un objetivo y un plazo, y el reto semanal da a todos el mismo mundo durante una semana. Comparte tu resultado con la tarjeta del menú.", +"help.one_game_four_doors_and_the":"Un juego, cuatro puertas, y las reglas se eligen al empezar una red y quedan fijadas después. Los puzles son pequeños nudos que deshacer, sin reloj. Sandbox te da mil millones de dólares, todo desbloqueado (tu propio cable submarino incluido) y el caos que elijas, pero sin insignias. Normal viene de tres maneras: Congelación de cambios (pocas caídas, entregas en días, sin escasez), De guardia (el juego clásico) y BGP a las 3 de la mañana (más caídas y más largas, más DDoS). Los escenarios son retos hechos a mano con un objetivo y un plazo, y el reto semanal da a todos el mismo mundo durante una semana. Comparte tu resultado con la tarjeta del menú.", "help.open_peers_with_anyone_selective":"Open hace peering con cualquiera. Selective quiere ver tráfico primero. Restrictive (los Tier 1) solo hace peering con gigantes, por PNIs. Paid significa justo eso. Las grandes redes selectivas también tienen sus rachas: en algunas ciudades rechazan peers nuevos durante unos meses, o solo aceptan PNIs, y de vez en cuando tumban una sesión que ya tenías. Prueba otra ciudad o un PNI, y vuelve a preguntar más tarde.", "help.out_of_port_speed_bundle_up":"¿Te quedas sin velocidad de puerto? Agrupa hasta 8 puertos idénticos al mismo proveedor de tránsito, IX o PNI en un LAG. Cada miembro cuesta un puerto entero; el hash de flujos nunca es perfectamente uniforme, así que un paquete transporta cerca del 95 % de la suma.", "help.pni_lead_times":"Plazos de los PNI", @@ -2008,15 +1992,12 @@ "hud_and_panels.has_errors_not_running":"tiene errores, no funciona", "hud_and_panels.incidents_so_far":"Incidentes hasta ahora", "hud_and_panels.install_auto_te_cost_mo_mo":"Instalar Auto-TE {cost} + {mo}/mes", -"hud_and_panels.large_peering_model_is_on_it":"El Gran Modelo de Peering está en ello.", "hud_and_panels.lv_n":"Nv {n}", "hud_and_panels.n_incident":{"one":"{n} incidente","other":"{n} incidentes"}, -"hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} mensaje esperando respuesta.","other":"{n} mensajes esperando respuesta."}, "hud_and_panels.n_more_networks":{"one":"+{n} red más","other":"+{n} redes más"}, "hud_and_panels.n_networks_d_days_left":"{n} redes · quedan {d} días", "hud_and_panels.n_new_notification":{"one":"{n} notificación nueva","other":"{n} notificaciones nuevas"}, "hud_and_panels.n_rules_live":"{n} reglas activas", -"hud_and_panels.n_session_is_down_on_its":{"one":"{n} sesión está caída por su límite de max-prefix.","other":"{n} sesiones están caídas por su límite de max-prefix."}, "hud_and_panels.n_small_networks":"{n} redes pequeñas", "hud_and_panels.n_special_requirement":{"one":"{n} requisito especial","other":"{n} requisitos especiales"}, "hud_and_panels.n_unhappy_customer_price_mo_at":{"one":"{n} cliente descontento, {price}/mes en riesgo","other":"{n} clientes descontentos, {price}/mes en riesgo"}, @@ -2592,6 +2573,7 @@ "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.day_d":"Día {d}", "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.", @@ -2630,8 +2612,6 @@ "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.", -"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.", @@ -2744,61 +2724,14 @@ "page.series_of_tubes_build_the_internet":"Series of Tubes: construye internet, un tubo a la vez", "page.world_map_of_your_network":"Mapa del mundo de tu red", "page.x":"", -"peering_inbox.accept_all_requests":"Aceptar todas las solicitudes", -"peering_inbox.an_ai_agent_that_answers_every":"Un agente de IA que responde por ti todas las solicitudes de peering y alertas de max-prefix, todos los días. {price}/año. Entrenado con veinte años de listas de correo de peering.", -"peering_inbox.answered_your_mail_a_accepted_d":"Respondió tu correo: {a} aceptadas, {d} rechazadas.", -"peering_inbox.asked_netchill_s_peering_team_to":"Pidió al equipo de peering de NetChill que «por favor aporte más Netchill».", -"peering_inbox.configured_lim_prefixes_received_got":"Configurado: {lim} prefijos. Recibido: {got}.", -"peering_inbox.day_d":"Día {d}", -"peering_inbox.dear_sir_or_madam_please_peer":"Estimado señor o señora: por favor, hagamos peering. Tenemos tres prefijos y planes muy grandes.", -"peering_inbox.decline_all_requests":"Rechazar todas las solicitudes", -"peering_inbox.declined_who_at_ix_not_a":"Rechazó a {who} en {ix}: «no encaja estratégicamente». Sí encajaba.", -"peering_inbox.every_exchange_port_brings_mail":"Cada puerto de intercambio trae correo. Responde las solicitudes de peering y mira las sesiones que alcanzan su límite de max-prefix: ¿es crecimiento o una fuga de rutas? El correo sin responder te da fama, y las redes selectivas se enteran.", -"peering_inbox.everyone_who_asks_gets_a_session":"Todo el que pregunta recibe una sesión, y los route servers funcionan. Muchos peers diminutos y muchas alertas de max-prefix.", -"peering_inbox.fewer_requests_and_you_answer_them":"Menos solicitudes, y las respondes tú mismo. Sin route servers: ve a cada intercambio y solicita las redes que quieras.", -"peering_inbox.fire_the_ai":"Despedir a la IA", -"peering_inbox.good_call_it_was_a_route":"Buena decisión: era una fuga de rutas.
{who} encontró un route-map con un dedazo. La sesión vuelve sola en unos días.", -"peering_inbox.greetings_we_are_a_fast_growing":"Saludos. Somos una red en rápido crecimiento. El año pasado teníamos un cliente; este año tenemos dos.", -"peering_inbox.hello_please_find_attached_our":"Hola, adjuntamos nuestra solicitud de peering como documento de Word, escaneado de una impresión.", -"peering_inbox.hey_quick_one_can_you_peer":"Hola, una rápida: ¿podéis hacer peering con nosotros en {ix}? Tenemos un servidor de Minecraft importantísimo.", -"peering_inbox.hi_we_would_like_to_peer":"¡Hola! Nos gustaría hacer peering contigo en {ix}. Nuestro registro de PeeringDB está al día.", -"peering_inbox.hire_it_mo_mo":"Contratarla {mo}/mes", -"peering_inbox.inbox_zero_enjoy_it_while_it":"Bandeja a cero. Disfrútalo mientras dure.", -"peering_inbox.keep_it_down":"Mantenerla caída", -"peering_inbox.kept_who_down_at_ix_for":"Mantuvo caído a {who} en {ix} por «crecimiento sospechoso». Había crecido en un cliente.", -"peering_inbox.kept_who_down_at_ix_it":"Mantuvo caído a {who} en {ix}: era una fuga de rutas. Acertó de lleno.", -"peering_inbox.large_peering_model":"Gran Modelo de Peering", -"peering_inbox.large_peering_model_is_answering":"El Gran Modelo de Peering está respondiendo tu correo", -"peering_inbox.max_prefix_limit_hit_who_at":"Límite de max-prefix alcanzado: {who} en {ix}.
La sesión está caída hasta que la mires.", -"peering_inbox.max_prefix_limit_hit_who_at_5c56":"Límite de max-prefix alcanzado: {who} en {ix}", -"peering_inbox.mostly_ignores_email":"Casi nunca contesta el correo", -"peering_inbox.n_day_ago":{"one":"hace {n} día","other":"hace {n} días"}, -"peering_inbox.n_unanswered":{"one":"{n} sin responder","other":"{n} sin responder"}, -"peering_inbox.no_mail_yet_buy_an_ix":"Aún no hay correo. Compra un puerto IX y llegará.", -"peering_inbox.nobody_asks_and_no_route_servers":"Nadie pregunta, y no hay route servers. Los clientes oyen que eres difícil de contactar, así que te llaman menos, y tu reputación se hunde.", -"peering_inbox.open_to_all":"Abierto a todos", -"peering_inbox.opened_a_ticket_with_itself_to":"Abrió un ticket consigo mismo para revisar sus propias decisiones. Las aprobó.", -"peering_inbox.peering_request_fifth_attempt_is":"Solicitud de peering, quinto intento. ¿Hay alguien ahí?", -"peering_inbox.peeringdb_last_updated_n_year_ago":{"one":"PeeringDB actualizado por última vez hace {n} año","other":"PeeringDB actualizado por última vez hace {n} años"}, -"peering_inbox.peeringdb_updated_last_month":"PeeringDB actualizado el mes pasado", -"peering_inbox.please_configure_sessions_with_us_at":"Por favor, configura sesiones con nosotros en {ix}. Nosotros haremos las nuestras la semana que viene, o la otra.", -"peering_inbox.price_year_it_never_sleeps_never":"{price}/año. Nunca duerme, nunca se queja y a menudo se equivoca.", -"peering_inbox.raise_all_max_prefix_limits":"Subir todos los límites de max-prefix", -"peering_inbox.raise_the_limit":"Subir el límite", -"peering_inbox.raised_the_max_prefix_limit_for":"Subió el límite de max-prefix de {who} en {ix} a {n}. Parecían simpáticos.", -"peering_inbox.raised_the_max_prefix_limit_for_7b4b":"Subió el límite de max-prefix de {who} en {ix}. Bien, esta vez.", -"peering_inbox.replied_to_a_peering_request_with":"Respondió a una solicitud de peering con un haiku sobre BGP. Aún sin respuesta.", -"peering_inbox.session_with_who_is_back_up":"La sesión con {who} vuelve a estar activa.
Nuevo límite: {n} prefijos. Prometen actualizar PeeringDB.", -"peering_inbox.signed_you_up_for_a_webinar":"Te apuntó a un seminario web sobre «El peering en la era de la IA».", -"peering_inbox.that_was_a_route_leak_who":"Era una fuga de rutas.
{who} anunciaba {n} prefijos: una tabla completa. La próxima vez, mantenla caída.", -"peering_inbox.the_session_stays_down_who_will":"La sesión sigue caída.
{who} actualizará PeeringDB y volverá a preguntar. Con el tiempo.", -"peering_inbox.their_peeringdb_says_lim_last":{"one":"Su PeeringDB dice {lim}, actualizado por última vez hace {n} año.","other":"Su PeeringDB dice {lim}, actualizado por última vez hace {n} años."}, -"peering_inbox.tidied_up_a_session_it_decided":"Ordenó una sesión que decidió que estaba sin uso: quitó el peering a {who} en {ix}.", -"peering_inbox.updated_your_peeringdb_record_your":"Actualizó tu registro de PeeringDB. Tu teléfono del NOC ahora es una pizzería.", -"peering_inbox.we_noticed_you_are_at_ix":"Notamos que estás en {ix}. Nosotros también. ¿Probamos?", -"peering_inbox.who_asked_a_mailing_list_whether":"{who} preguntó en una lista de correo si alguien tiene un contacto que funcione en {me}.
Su solicitud de peering lleva un mes en tu bandeja.", -"peering_inbox.who_at_ix_was_sending_a":"{who} en {ix} enviaba una tabla completa, y el límite de max-prefix era lo único que lo frenaba. Con el límite subido, los prefijos de {net} apuntan a su sótano. El tráfico hacia {net} por tránsito cae en un agujero negro unos días.", -"peering_inbox.wrote_a_thousand_word_apology_to":"Escribió una disculpa de mil palabras a una red con la que nunca hiciste peering.", +"peering_desk.closed_desc":"Se rechaza toda solicitud de peering, y no hay route servers. Los clientes oyen que eres difícil de contactar, así que te llaman menos.", +"peering_desk.n_more_exchanges":{"one":"{n} intercambio más","other":"{n} intercambios más"}, +"peering_desk.n_new_sessions_at_ix":{"one":"Mesa de peering: {n} sesión nueva en {ix} ({pol}).","other":"Mesa de peering: {n} sesiones nuevas en {ix} ({pol})."}, +"peering_desk.n_new_sessions_at_ix_declined":{"one":"Mesa de peering: {n} sesión nueva en {ix}, {d} rechazadas ({pol}).","other":"Mesa de peering: {n} sesiones nuevas en {ix}, {d} rechazadas ({pol})."}, +"peering_desk.n_requests_declined":{"one":"Mesa de peering: {n} solicitud rechazada ({pol}).","other":"Mesa de peering: {n} solicitudes rechazadas ({pol})."}, +"peering_desk.open_desc":"Toda red que lo pide recibe una sesión, y los route servers funcionan.", +"peering_desk.open_to_all":"Abierto a todos", +"peering_desk.selective_desc":"Las redes pequeñas del intercambio y los recién llegados con PeeringDB al día reciben una sesión; el resto se rechaza en silencio. Sin route servers: solicita las redes que quieras en cada intercambio.", "peering_policy.a_new_vp_wants_to_monetise":"Un nuevo vicepresidente quiere «monetizar la interconexión» en este mercado.", "peering_policy.already_reach_you_through_your":"Ya llegan a ti a través de tu proveedor de tránsito aquí y creen que eso está bien.", "peering_policy.moved_everything_in_this_city_to":"Movieron todo en esta ciudad a PNIs. Lee su página de PearingDB, las 40 páginas.", @@ -3309,7 +3242,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Desconecta algo primero.
Hay {used} puertos en uso, y con un router menos solo hay {max}.", "rules.a_billion_dollars_every_unlock_your":"Mil millones de dólares, todo desbloqueado, tu propio cable submarino.", "rules.a_cut_now_and_then":"Algún corte de vez en cuando.", -"rules.a_third_of_the_outages_no_ddos":"Un tercio de las caídas, sin DDoS. PNI y obras en días. Sin bandeja de entrada, sin escasez, sin rutas agotadas, sin de-peering.", +"rules.a_third_of_the_outages_no_ddos_pnis":"Un tercio de las caídas, sin DDoS. PNI y obras en días. Sin escasez, sin rutas agotadas, sin de-peering.", "rules.bgp_at_3_a_m":"BGP a las 3 de la mañana", "rules.change_freeze":"Congelación de cambios", "rules.chaos_calm":"Tranquilo", @@ -3326,7 +3259,7 @@ "rules.on_call":"De guardia", "rules.one_small_network_one_tricky_goal":"Una red pequeña, un objetivo con truco.", "rules.puzzle":"Puzle", -"rules.real_lead_times_real_outages_a":"Plazos reales, caídas reales, una bandeja de peering llena. El juego clásico.", +"rules.real_lead_times_real_outages_a_real":"Plazos reales, caídas reales, un mercado real. El juego clásico.", "rules.rules_are_locked_for_this_network":"{rules}: las reglas están fijadas para esta red.", "rules.the_real_thing_your_pager_has":"El juego de verdad. Tu busca tiene opiniones.", "rules.your_pager_never_sleeps":"Tu busca no duerme nunca.", @@ -3460,9 +3393,7 @@ "sites_peering_caches.bgp_session_established":"Sesión BGP establecida.", "sites_peering_caches.cache_installed_in_city_net_shipped":"¡{cache} instalada en {city}!
{net} la envió gratis. Pagas {mo}/mes de energía.", "sites_peering_caches.could_you_resend_the_loa_you":"«¿Podrías reenviar la LOA?»
Ya la has enviado cuatro veces.", -"sites_peering_caches.hello_i_am_large_peering_model":"¡Hola! Soy el Gran Modelo de Peering. He leído tu bandeja de entrada y ya tengo opiniones.", "sites_peering_caches.it_is_with_the_provisioning_team":"«Está con el equipo de aprovisionamiento.»
Nadie ha conocido nunca al equipo de aprovisionamiento.", -"sites_peering_caches.large_peering_model_is_hired_your":"El Gran Modelo de Peering está contratado.
Tu bandeja de entrada es ahora problema suyo. {price} al año, facturado mensualmente.", "sites_peering_caches.n_new_session_at_ix_small":{"one":"{n} sesión nueva en {ix}.
Redes pequeñas, pero suman, y todas cuentan para el club.","other":"{n} sesiones nuevas en {ix}.
Redes pequeñas, pero suman, y todas cuentan para el club."}, "sites_peering_caches.net_accepted":"¡{net} aceptó!", "sites_peering_caches.net_declined_the_pni_why":"{net} rechazó el PNI.
{why}", @@ -3470,11 +3401,8 @@ "sites_peering_caches.net_does_not_do_port_pnis":"{net} no hace PNIs de {port}.
Nada menor de 100G. Vuelve con más tráfico, o una óptica mayor.", "sites_peering_caches.net_says_not_yet_send_them":"{net} dice que todavía no.
Mándale primero {min}+ Gbps.", "sites_peering_caches.pni_with_net_ordered_eta_a":"PNI con {net} pedido.
{eta}. Una interconexión cruzada en {dc}, cuando alguien encuentre la LOA.", -"sites_peering_caches.raised_n_max_prefix_limits_all":"Subidos {n} límites de max-prefix.
Todo crecimiento, ninguna fuga. Qué suerte.", -"sites_peering_caches.raised_n_max_prefix_limits_one":{"one":"Subidos {n} límites de max-prefix.
Uno de ellos era una fuga de rutas. Ahora está en el NOC.","other":"Subidos {n} límites de max-prefix.
{k} de ellos eran fugas de rutas. Ahora están en el NOC."}, "sites_peering_caches.second_lag_member_added_one_member":"Segundo miembro LAG añadido.
Ahora hay un miembro en cada edificio, así que un edificio a oscuras solo tumba la mitad del puerto.", "sites_peering_caches.second_site_live_in_city_b":"Segunda sede activa en {city}.
{b} está unida a {a} por tu propio anillo metropolitano. Mueve algunos uplinks allí desde las pestañas Tránsito y Peering.", -"sites_peering_caches.the_ai_is_gone_it_left":"La IA se fue.
Dejó un documento de traspaso de 40 páginas. Trata sobre todo de sí misma.", "sites_peering_caches.they_checked_your_pearingdb_page_and":"Revisaron tu página de PearingDB y les gustaron las cifras de tráfico.", "sites_peering_caches.we_are_waiting_on_the_colo":"«Estamos esperando al colo para la interconexión cruzada.»
El colo dice que está esperando por ellos.", "sites_peering_caches.your_account_manager_found_the_order":"Tu gestor de cuenta encontró el pedido bajo un escritorio.
Está un mes más cerca.", @@ -3496,6 +3424,7 @@ "slots.last_played_ago":"Última partida: {ago}", "slots.load_the_newest_version":"Cargar la versión más nueva", "slots.more_for_name":"Más de {name}", +"slots.n_day_ago":{"one":"hace {n} día","other":"hace {n} días"}, "slots.n_h_ago":{"one":"hace {n} h","other":"hace {n} h"}, "slots.name_is_open_in_another_window":"{name} está abierta en otra ventana", "slots.name_is_waiting_in_your_other":"{name} te espera en tu otra ventana.
Cambia a ella para seguir jugando.", @@ -3519,7 +3448,6 @@ "slots.this_window_stopped_saving_so_it":"Se guardó una versión más nueva en otra ventana, así que esta dejó de guardar en vez de sobrescribirla.", "slots.two_windows_one_network":"Dos ventanas, una red", "slots.your_networks":"Tus redes", -"slots.your_networks_switch_or_start_another":"Tus redes cambia o empieza otra", "slots.your_other_networks_share_this_browser":"Tus otras redes comparten el almacenamiento de este navegador. Exporta las que quieras conservar y bórralas aquí para hacer sitio.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hiperescalador compró la semana pasada todas las ondas de ese tamaño en esta ruta.", "sold_out.not_big_enough_yet_list":"Aún no es lo bastante grande: {list}", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c6c08b6..3cf10fb 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -807,7 +807,6 @@ "common.aug":"août", "common.auto":"Auto", "common.auto_enrolled":"inscrit d’office", -"common.average":"Dans la moyenne", "common.avoid":"Éviter", "common.back":"Retour", "common.back_to_the_map":"Retour à la carte", @@ -823,7 +822,6 @@ "common.bgp_hijack":"Détournement BGP", "common.bgp_sessions":"Sessions BGP", "common.big_league":"Cour des grands", -"common.black_hole":"Trou noir", "common.blitz":"Blitz", "common.boot_time":"Temps de boot", "common.boot_times":"Temps de boot", @@ -831,7 +829,6 @@ "common.box_6ee3":"− cache", "common.build_time":"Durée des travaux", "common.building":"en construction", -"common.bumped":"relancé", "common.bunker_two":"Bunker 2", "common.busiest_links":"Liens les plus chargés", "common.business_customers":"Clients entreprises", @@ -993,8 +990,6 @@ "common.import_a_save":"Importer une sauvegarde", "common.in_progress":"en cours", "common.in_use":"Utilisé", -"common.inbox":"Boîte", -"common.inbox_zero":"Inbox zéro.", "common.incident":"Incident", "common.incidents":"Incidents", "common.incidents_survived":"Incidents surmontés", @@ -1122,7 +1117,6 @@ "common.oops":"Oups", "common.open":"Ouvrir", "common.open_bank":"Ouvrir la banque", -"common.open_inbox":"Ouvrir la boîte", "common.open_infra":"Ouvrir Infra", "common.open_lease":"Voir la location", "common.open_noc":"Ouvrir le NOC", @@ -1147,7 +1141,6 @@ "common.peered_ce2f":"En peering ✓", "common.peering":"Peering", "common.peering_first":"Le peering d’abord", -"common.peering_inbox":"Boîte de peering", "common.peering_policy":"Politique de peering", "common.peering_ratio":"Ratio de peering", "common.peering_spat":"Brouille de peering", @@ -1196,7 +1189,6 @@ "common.remove_port":"Retirer le port", "common.remove_script":"Supprimer le script", "common.request":"Demander", -"common.responsive":"Réactif", "common.resume":"Reprendre", "common.retention_offer":"Offre de fidélisation", "common.revenue":"Chiffre d’affaires", @@ -1302,7 +1294,6 @@ "common.to":"Vers", "common.toaster_wrangler":"Dompteur de grille-pain", "common.today":"Aujourd’hui", -"common.today_4203":"aujourd’hui", "common.toggle_sound":"Activer/couper le son", "common.too_far_for_this_cable":"trop loin pour ce câble", "common.traceroute":"Traceroute", @@ -1364,7 +1355,6 @@ "common.your_network":"Ton réseau", "common.your_pop":"Ton POP", "common.your_pops":"Tes POP", -"common.your_reputation":"Votre réputation", "common.zombie_route":"Route zombie", "compute.attack_hauled_to_scrubbing_in_city":"Attaque acheminée vers le scrubbing de {city}", "compute.courtesy_route_to_new_networks":"Route de courtoisie vers les nouveaux réseaux", @@ -1611,8 +1601,6 @@ "failures.a_kilometre_of_copper_went_missing":"Un kilomètre de « cuivre » a disparu de ta tranchée {a}–{b}. C’était ta fibre. Le ferrailleur l’a renvoyée avec un petit mot.", "failures.a_landslide_in_the_andes_buried":"Un glissement de terrain dans les Andes a enseveli ta fibre {a}–{b}.", "failures.a_llama_herd_trampled_the_fiber":"Un troupeau de lamas a piétiné la balise de fibre sur {a}–{b}. Puis un tractopelle a trouvé la fibre.", -"failures.a_member_at_ix_leaked_the":"Un membre de {ix} a fait fuiter la table de routage complète dans le route server. Les limites max-prefix ont sauté partout. Ton peering là-bas est tombé.", -"failures.a_member_at_ix_leaked_the_5563":"Un membre de {ix} a fait fuiter la table de routage complète dans le route server. Les limites max-prefix ont sauté partout. Ton peering là-bas, à {city}, est tombé.", "failures.a_new_tech_in_a_tidied":"Un nouveau technicien à {a} a « rangé » le sac de nœuds de câbles. Ton lien {a}–{b} faisait partie du sac de nœuds.", "failures.a_new_tech_in_city_used":"Un nouveau technicien à {city} a utilisé de la Vegemite comme pâte thermique. Elle conduit le goût, pas la chaleur, et ton routeur a cuit.", "failures.a_optic_on_a_b_overheated":"Une optique {optic} sur {a}–{b} a surchauffé et n’est plus qu’un porte-clés hors de prix.", @@ -1679,7 +1667,6 @@ "failures.load_shedding_stage_n_in_city":"Délestage niveau {n} à {city}, et tu n’as pas de groupe électrogène. Achètes-en un : ici, ce n’est pas optionnel.", "failures.load_shedding_took_out_site_in":"Le délestage a mis {site} hors service à {city}. {other} a tenu, donc le POP tourne à mi-capacité. Tout ce qui n’est branché que sur le site éteint est hors ligne.", "failures.magpie_swooping_season_the_field":"Saison des attaques de pies : les techniciens sur {a}–{b} refusent de sortir de la camionnette, et ta coupure reste coupée.", -"failures.max_prefix_meltdown":"Max-prefix en vrac", "failures.metro_ring_cut":"Anneau métro coupé", "failures.microbursts_on_a_b_overflow_shallow":"Les microbursts sur {a}–{b} débordent les buffers peu profonds des routeurs : 0,5 % de perte en pointe, et chaque visio le remarque.", "failures.microbursts_on_a_b_your_deep":"Microbursts sur {a}–{b}.
Tes routeurs à buffers profonds les ont absorbés. Personne n’a rien remarqué.", @@ -1794,11 +1781,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Ton POP · il y faut un port fabric", "game_and_settings.delete_and_start_over":"Supprimer et recommencer", "game_and_settings.export_save_download_a_file":"Exporter la sauvegarde télécharger un fichier", -"game_and_settings.import_a_save_from_a_file":"Importer une sauvegarde depuis un fichier", "game_and_settings.import_failed_that_save_is_damaged":"Échec de l’import.
Cette sauvegarde est endommagée et n’a pas pu être chargée. Ta partie en cours est intacte.", "game_and_settings.name_and_everything_it_owns_will":"{name} et tout ce qu’il possède seront supprimés. Impossible de revenir en arrière.", -"game_and_settings.scenarios_amp_weekly_challenge":"Scénarios & défi de la semaine", -"game_and_settings.share_your_network_image_card":"Partager ton réseau carte image", "game_and_settings.start_a_new_network":"Créer un nouveau réseau ?", "game_and_settings.welcome_back_name_imported_and_saved":"Bon retour, {name}.
Partie importée et sauvegardée sur cet appareil.", "game_and_settings.your_game_saves_itself_every_few":"Ta partie se sauvegarde toute seule sur cet appareil, toutes les quelques secondes.", @@ -1869,7 +1853,7 @@ "help.each_pop_s_router_model_caps":"Le modèle de routeur de chaque POP plafonne son port le plus rapide (100G, 400G, 800G, 1.6T) et ce qu’il peut acheminer. Des longueurs d’onde et des ports plus gros exigent de meilleurs routeurs aux deux bouts. Les meilleurs modèles se débloquent avec ton niveau clients. Avec un seul routeur, chaque upgrade coûte une journée d’indisponibilité.", "help.event_networks_a_final_a_festival":"Les réseaux événementiels (une finale, un festival, une keynote) veulent un pic de capacité dans une ville pendant quelques jours et paient en une fois à la fin, au prorata de la part du public servie ; en dessous de 70 %, tu paies une pénalité. Les chaînes SD-WAN relient 3–6 de tes POP en hub-and-spoke, donc un seul spoke cassé fâche tout le contrat. Dès que tu exploites ta propre fibre noire, les opérateurs veulent louer tes canaux libres en alien waves et, sur la fibre que tu as construite toi-même, une paire libre.", "help.events_chains_and_wholesale":"Événements, chaînes et vente en gros", -"help.every_ix_port_brings_peering":"Chaque port IX amène des demandes de peering et des alertes max-prefix, dans l’onglet Réseaux. Une session qui dépasse sa limite reste coupée tant que vous n’y regardez pas : relevez la limite si c’est de la croissance, laissez-la coupée si c’est une fuite. Ignorez votre courrier et les réseaux sélectifs deviennent plus exigeants.", +"help.every_ix_port_brings_requests":"Chaque port d’IX apporte des demandes de peering, et ta politique de peering, dans l’onglet Réseaux, y répond : Ouverte accepte tout le monde, Sélective accepte les réseaux qui valent le coup et décline discrètement les autres, Fermée les décline toutes. Une fois par semaine, le journal du NOC fait le bilan.", "help.every_link_has_latency_high":"Chaque lien a une latence. Les traders haute fréquence paient une fortune pour un circuit qui tient dans leur budget de latence ; achemine-les en « Latence minimale ». Les clients de sauvegarde en masse s’en fichent, alors achemine-les en « Chemin des écoliers » sur tes liens calmes pour garder les chargés libres.", "help.home_broadband_users_they_mostly":"Abonnés haut débit résidentiels. Ils téléchargent surtout depuis des CDN et te paient par Gbps livré. Sers-les bien et ils se multiplient.", "help.how_the_internet_works_here":"Comment marche Internet ici", @@ -1883,7 +1867,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) est transit-free. Tu fais du peering avec tous les géants de la planète et tu ne paies personne pour atteindre Internet. Il t’a fallu {days} jours et {n} incidents.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG et compagnie reviennent chaque année. Inscris-toi dans l’onglet Offres pour $8k. Pendant les 45 jours suivants, les réseaux sélectifs présents dans cette région ne demandent que la moitié du trafic habituel avant de faire du peering avec toi. Parfois, tu gagnes aussi la tombola.", "help.once_auto_te_is_installed_you":"Une fois Auto-TE installé, tu peux le programmer depuis l’onglet NOC. Parmi les règles : spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams et blackhole ddos. Vérifier fait un essai à blanc sur le trafic réel ; Déployer le rend réel, erreurs comprises.", -"help.one_game_four_doors_puzzles_are":"Un jeu, quatre portes, et les règles se choisissent au démarrage d’un réseau puis restent verrouillées. Les casse-têtes sont de petits nœuds à défaire, sans horloge. Le bac à sable te donne un milliard de dollars, tout débloqué (ton propre câble sous-marin compris) et autant de chaos que tu veux, mais pas de badges. Normal existe en trois versions : Gel des changements (peu de pannes, livraisons en quelques jours, ni boîte de réception ni pénurie), D’astreinte (le jeu classique) et BGP à 3 h du matin (plus de pannes, plus longues, plus de DDoS). Les scénarios sont des défis faits main avec un objectif et une échéance, et le défi de la semaine donne à tous le même monde pendant une semaine. Partage ton résultat avec la carte du menu.", +"help.one_game_four_doors_and_the":"Un jeu, quatre portes, et les règles se choisissent au démarrage d’un réseau puis restent verrouillées. Les casse-têtes sont de petits nœuds à défaire, sans horloge. Le bac à sable te donne un milliard de dollars, tout débloqué (ton propre câble sous-marin compris) et autant de chaos que tu veux, mais pas de badges. Normal existe en trois versions : Gel des changements (peu de pannes, livraisons en quelques jours, pas de pénurie), D’astreinte (le jeu classique) et BGP à 3 h du matin (plus de pannes, plus longues, plus de DDoS). Les scénarios sont des défis faits main avec un objectif et une échéance, et le défi de la semaine donne à tous le même monde pendant une semaine. Partage ton résultat avec la carte du menu.", "help.open_peers_with_anyone_selective":"Ouverte : peering avec tout le monde. Sélective : veut d’abord voir du trafic. Restrictive (les Tier 1) : peering uniquement avec les géants, via PNI. Payante : tout est dans le nom. Les gros réseaux sélectifs ont aussi leurs humeurs : dans certaines villes, ils refusent les nouveaux peers pendant quelques mois, ou n’acceptent que des PNI, et de temps en temps ils coupent une session que tu avais déjà. Essaie une autre ville ou un PNI, et redemande plus tard.", "help.out_of_port_speed_bundle_up":"Port trop petit ? Regroupe jusqu’à 8 ports identiques vers le même fournisseur de transit, IX ou PNI en un LAG. Chaque membre coûte un port complet ; le hachage des flux n’est jamais parfaitement équilibré, donc un bundle transporte environ 95 % de la somme.", "help.pni_lead_times":"Délais des PNI", @@ -2008,15 +1992,12 @@ "hud_and_panels.has_errors_not_running":"contient des erreurs, à l’arrêt", "hud_and_panels.incidents_so_far":"Incidents jusqu’ici", "hud_and_panels.install_auto_te_cost_mo_mo":"Installer Auto-TE {cost} + {mo}/mois", -"hud_and_panels.large_peering_model_is_on_it":"Large Peering Model s’en occupe.", "hud_and_panels.lv_n":"Niv. {n}", "hud_and_panels.n_incident":{"one":"{n} incident","other":"{n} incidents"}, -"hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} message attend une réponse.","other":"{n} messages attendent une réponse."}, "hud_and_panels.n_more_networks":{"one":"+{n} autre réseau","other":"+{n} autres réseaux"}, "hud_and_panels.n_networks_d_days_left":"{n} réseaux · {d} j restants", "hud_and_panels.n_new_notification":{"one":"{n} nouvelle notification","other":"{n} nouvelles notifications"}, "hud_and_panels.n_rules_live":"{n} règles actives", -"hud_and_panels.n_session_is_down_on_its":{"one":"{n} session est coupée par sa limite max-prefix.","other":"{n} sessions sont coupées par leur limite max-prefix."}, "hud_and_panels.n_small_networks":"{n} petits réseaux", "hud_and_panels.n_special_requirement":{"one":"{n} exigence spéciale","other":"{n} exigences spéciales"}, "hud_and_panels.n_unhappy_customer_price_mo_at":{"one":"{n} client mécontent, {price}/mois en jeu","other":"{n} clients mécontents, {price}/mois en jeu"}, @@ -2592,6 +2573,7 @@ "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.day_d":"Jour {d}", "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.", @@ -2630,8 +2612,6 @@ "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.", -"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.", @@ -2744,61 +2724,14 @@ "page.series_of_tubes_build_the_internet":"Series of Tubes : construis Internet, un tuyau à la fois", "page.world_map_of_your_network":"Carte du monde de ton réseau", "page.x":"", -"peering_inbox.accept_all_requests":"Accepter toutes les demandes", -"peering_inbox.an_ai_agent_that_answers_every":"Un agent IA qui répond pour vous à chaque demande de peering et à chaque alerte max-prefix, tous les jours. {price}/an. Entraîné sur vingt ans de listes de diffusion sur le peering.", -"peering_inbox.answered_your_mail_a_accepted_d":"A répondu à votre courrier : {a} acceptées, {d} refusées.", -"peering_inbox.asked_netchill_s_peering_team_to":"A demandé à l’équipe peering de NetChill de « fournir plus de Netchill, svp ».", -"peering_inbox.configured_lim_prefixes_received_got":"Configuré : {lim} préfixes. Reçus : {got}.", -"peering_inbox.day_d":"Jour {d}", -"peering_inbox.dear_sir_or_madam_please_peer":"Madame, Monsieur, merci de bien vouloir peerer. Nous avons trois préfixes et de très grands projets.", -"peering_inbox.decline_all_requests":"Refuser toutes les demandes", -"peering_inbox.declined_who_at_ix_not_a":"A refusé {who} à {ix} : « pas stratégique ». Ils l’étaient.", -"peering_inbox.every_exchange_port_brings_mail":"Chaque port IX amène du courrier. Répondez aux demandes de peering et regardez les sessions qui dépassent leur limite max-prefix : croissance ou fuite de routes ? Le courrier sans réponse vous fait une réputation, et les réseaux sélectifs en entendent parler.", -"peering_inbox.everyone_who_asks_gets_a_session":"Quiconque demande obtient une session, et les route servers fonctionnent. Beaucoup de minuscules peers, et beaucoup d’alertes max-prefix.", -"peering_inbox.fewer_requests_and_you_answer_them":"Moins de demandes, et vous y répondez vous-même. Pas de route servers : allez sur chaque exchange demander les réseaux que vous voulez.", -"peering_inbox.fire_the_ai":"Licencier l’IA", -"peering_inbox.good_call_it_was_a_route":"Bien vu : c’était une fuite de routes.
{who} a trouvé une route-map mal tapée. La session revient toute seule dans quelques jours.", -"peering_inbox.greetings_we_are_a_fast_growing":"Salutations. Nous sommes un réseau en pleine croissance. L’an dernier nous avions un client ; cette année, deux.", -"peering_inbox.hello_please_find_attached_our":"Bonjour, veuillez trouver ci-joint notre demande de peering au format Word, scannée depuis une impression.", -"peering_inbox.hey_quick_one_can_you_peer":"Salut, petite question : vous pouvez peerer avec nous à {ix} ? On a un serveur Minecraft très important.", -"peering_inbox.hi_we_would_like_to_peer":"Bonjour ! Nous aimerions faire du peering avec vous à {ix}. Notre fiche PeeringDB est à jour.", -"peering_inbox.hire_it_mo_mo":"L’embaucher {mo}/mois", -"peering_inbox.inbox_zero_enjoy_it_while_it":"Inbox zéro. Profitez-en tant que ça dure.", -"peering_inbox.keep_it_down":"La laisser coupée", -"peering_inbox.kept_who_down_at_ix_for":"A laissé {who} coupé à {ix} pour « croissance suspecte ». Ils avaient gagné un client.", -"peering_inbox.kept_who_down_at_ix_it":"A laissé {who} coupé à {ix} : c’était une fuite de routes. Dans le mille.", -"peering_inbox.large_peering_model":"Large Peering Model", -"peering_inbox.large_peering_model_is_answering":"Large Peering Model répond à votre courrier", -"peering_inbox.max_prefix_limit_hit_who_at":"Limite max-prefix atteinte : {who} à {ix}.
La session reste coupée tant que vous n’y avez pas regardé.", -"peering_inbox.max_prefix_limit_hit_who_at_5c56":"Limite max-prefix atteinte : {who} à {ix}", -"peering_inbox.mostly_ignores_email":"Ignore presque tous les e-mails", -"peering_inbox.n_day_ago":{"one":"il y a {n} jour","other":"il y a {n} jours"}, -"peering_inbox.n_unanswered":{"one":"{n} sans réponse","other":"{n} sans réponse"}, -"peering_inbox.no_mail_yet_buy_an_ix":"Pas encore de courrier. Achetez un port IX, il viendra.", -"peering_inbox.nobody_asks_and_no_route_servers":"Personne ne demande, et pas de route servers. Les clients entendent dire que vous êtes difficile à joindre, donc moins d’entre eux appellent, et votre réputation coule.", -"peering_inbox.open_to_all":"Ouverte à tous", -"peering_inbox.opened_a_ticket_with_itself_to":"S’est ouvert un ticket pour revoir ses propres décisions. Il les a approuvées.", -"peering_inbox.peering_request_fifth_attempt_is":"Demande de peering, cinquième tentative. Il y a quelqu’un ?", -"peering_inbox.peeringdb_last_updated_n_year_ago":{"one":"PeeringDB mis à jour il y a {n} an","other":"PeeringDB mis à jour il y a {n} ans"}, -"peering_inbox.peeringdb_updated_last_month":"PeeringDB mis à jour le mois dernier", -"peering_inbox.please_configure_sessions_with_us_at":"Merci de configurer les sessions avec nous à {ix}. Nous ferons les nôtres la semaine prochaine, ou celle d’après.", -"peering_inbox.price_year_it_never_sleeps_never":"{price}/an. Ne dort jamais, ne se plaint jamais et se trompe souvent.", -"peering_inbox.raise_all_max_prefix_limits":"Relever toutes les limites max-prefix", -"peering_inbox.raise_the_limit":"Relever la limite", -"peering_inbox.raised_the_max_prefix_limit_for":"A relevé la limite max-prefix de {who} à {ix} à {n}. Ils avaient l’air sympas.", -"peering_inbox.raised_the_max_prefix_limit_for_7b4b":"A relevé la limite max-prefix de {who} à {ix}. À raison, cette fois.", -"peering_inbox.replied_to_a_peering_request_with":"A répondu à une demande de peering par un haïku sur BGP. Pas de réponse pour l’instant.", -"peering_inbox.session_with_who_is_back_up":"La session avec {who} est rétablie.
Nouvelle limite : {n} préfixes. Ils promettent de mettre PeeringDB à jour.", -"peering_inbox.signed_you_up_for_a_webinar":"Vous a inscrit à un webinaire sur « Le peering à l’ère de l’IA ».", -"peering_inbox.that_was_a_route_leak_who":"C’était une fuite de routes.
{who} annonçait {n} préfixes : une table complète. La prochaine fois, laissez-la coupée.", -"peering_inbox.the_session_stays_down_who_will":"La session reste coupée.
{who} va mettre PeeringDB à jour et redemander. Un jour.", -"peering_inbox.their_peeringdb_says_lim_last":{"one":"Leur PeeringDB indique {lim}, mis à jour il y a {n} an.","other":"Leur PeeringDB indique {lim}, mis à jour il y a {n} ans."}, -"peering_inbox.tidied_up_a_session_it_decided":"A fait le ménage dans les sessions qu’il jugeait inutiles : a dépeeré {who} à {ix}.", -"peering_inbox.updated_your_peeringdb_record_your":"A mis à jour votre fiche PeeringDB. Le numéro de votre NOC est maintenant celui d’une pizzeria.", -"peering_inbox.we_noticed_you_are_at_ix":"Nous avons remarqué que vous êtes à {ix}. Nous aussi. On y va ?", -"peering_inbox.who_asked_a_mailing_list_whether":"{who} a demandé sur une liste de diffusion si quelqu’un avait un contact qui marche chez {me}.
Leur demande de peering a dormi un mois dans votre boîte.", -"peering_inbox.who_at_ix_was_sending_a":"{who} à {ix} envoyait une table complète, et la limite max-prefix était la seule chose qui la retenait. Limite relevée, les préfixes de {net} pointent vers leur cave. Le trafic vers {net} via le transit part dans un trou noir pendant quelques jours.", -"peering_inbox.wrote_a_thousand_word_apology_to":"A écrit mille mots d’excuses à un réseau avec qui vous n’avez jamais peeré.", +"peering_desk.closed_desc":"Toute demande de peering est déclinée, et pas de route servers. Les clients entendent dire que tu es difficile à joindre, donc moins d’entre eux appellent.", +"peering_desk.n_more_exchanges":{"one":"{n} autre exchange","other":"{n} autres exchanges"}, +"peering_desk.n_new_sessions_at_ix":{"one":"Bureau du peering : {n} nouvelle session à {ix} ({pol}).","other":"Bureau du peering : {n} nouvelles sessions à {ix} ({pol})."}, +"peering_desk.n_new_sessions_at_ix_declined":{"one":"Bureau du peering : {n} nouvelle session à {ix}, {d} déclinées ({pol}).","other":"Bureau du peering : {n} nouvelles sessions à {ix}, {d} déclinées ({pol})."}, +"peering_desk.n_requests_declined":{"one":"Bureau du peering : {n} demande déclinée ({pol}).","other":"Bureau du peering : {n} demandes déclinées ({pol})."}, +"peering_desk.open_desc":"Tout réseau qui demande obtient une session, et les route servers fonctionnent.", +"peering_desk.open_to_all":"Ouverte à tous", +"peering_desk.selective_desc":"Les petits réseaux de l’exchange et les nouveaux venus avec un PeeringDB à jour obtiennent une session ; les autres sont discrètement déclinés. Pas de route servers : va demander les réseaux que tu veux sur chaque exchange.", "peering_policy.a_new_vp_wants_to_monetise":"Un nouveau VP veut « monétiser l’interconnexion » sur ce marché.", "peering_policy.already_reach_you_through_your":"Te joignent déjà via ton fournisseur de transit ici et trouvent que ça suffit.", "peering_policy.moved_everything_in_this_city_to":"Ont tout migré en PNI dans cette ville. Merci de lire leur page PearingDB, les 40 pages.", @@ -3309,7 +3242,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Débranche d’abord quelque chose.
{used} ports sont utilisés, et avec un routeur de moins tu n’en aurais que {max}.", "rules.a_billion_dollars_every_unlock_your":"Un milliard de dollars, tout débloqué, ton propre câble sous-marin.", "rules.a_cut_now_and_then":"Une coupure de temps en temps.", -"rules.a_third_of_the_outages_no_ddos":"Un tiers des pannes, pas de DDoS. PNI et chantiers en quelques jours. Pas de boîte de réception, pas de pénurie, pas de routes épuisées, pas de dépeering.", +"rules.a_third_of_the_outages_no_ddos_pnis":"Un tiers des pannes, pas de DDoS. PNI et chantiers en quelques jours. Pas de pénurie, pas de routes épuisées, pas de dépeering.", "rules.bgp_at_3_a_m":"BGP à 3 h du matin", "rules.change_freeze":"Gel des changements", "rules.chaos_calm":"Calme", @@ -3326,7 +3259,7 @@ "rules.on_call":"D’astreinte", "rules.one_small_network_one_tricky_goal":"Un petit réseau, un objectif retors.", "rules.puzzle":"Casse-tête", -"rules.real_lead_times_real_outages_a":"De vrais délais, de vraies pannes, une boîte de peering pleine. Le jeu classique.", +"rules.real_lead_times_real_outages_a_real":"De vrais délais, de vraies pannes, un vrai marché. Le jeu classique.", "rules.rules_are_locked_for_this_network":"{rules} : les règles sont verrouillées pour ce réseau.", "rules.the_real_thing_your_pager_has":"Le vrai jeu. Ton bipeur a des opinions.", "rules.your_pager_never_sleeps":"Ton bipeur ne dort jamais.", @@ -3460,9 +3393,7 @@ "sites_peering_caches.bgp_session_established":"Session BGP établie.", "sites_peering_caches.cache_installed_in_city_net_shipped":"{cache} installé à {city} !
{net} te l’a envoyé gratuitement. Tu paies {mo}/mois d’électricité.", "sites_peering_caches.could_you_resend_the_loa_you":"« Pourriez-vous renvoyer la LOA ? »
Vous l’avez envoyée quatre fois.", -"sites_peering_caches.hello_i_am_large_peering_model":"Bonjour ! Je suis Large Peering Model. J’ai lu votre boîte et j’ai déjà des avis.", "sites_peering_caches.it_is_with_the_provisioning_team":"« C’est chez l’équipe de provisioning. »
Personne n’a jamais rencontré l’équipe de provisioning.", -"sites_peering_caches.large_peering_model_is_hired_your":"Large Peering Model est embauché.
Votre boîte, c’est son problème maintenant. {price} par an, facturés chaque mois.", "sites_peering_caches.n_new_session_at_ix_small":{"one":"{n} nouvelle session sur {ix}.
Des petits réseaux, mais ça s’additionne, et tout compte pour le club.","other":"{n} nouvelles sessions sur {ix}.
Des petits réseaux, mais ça s’additionne, et tout compte pour le club."}, "sites_peering_caches.net_accepted":"{net} a accepté !", "sites_peering_caches.net_declined_the_pni_why":"{net} a refusé le PNI.
{why}", @@ -3470,11 +3401,8 @@ "sites_peering_caches.net_does_not_do_port_pnis":"{net} ne fait pas de PNI en {port}.
Rien en dessous de 100G. Revenez avec plus de trafic, ou une optique plus grosse.", "sites_peering_caches.net_says_not_yet_send_them":"{net} dit : pas encore.
Envoie-leur d’abord {min}+ Gbps.", "sites_peering_caches.pni_with_net_ordered_eta_a":"PNI avec {net} commandée.
{eta}. Un cross-connect chez {dc}, dès que quelqu’un aura retrouvé la LOA.", -"sites_peering_caches.raised_n_max_prefix_limits_all":"{n} limites max-prefix relevées.
Que de la croissance, aucune fuite. Chanceux.", -"sites_peering_caches.raised_n_max_prefix_limits_one":{"one":"{n} limites max-prefix relevées.
L’une d’elles était une fuite de routes. Elle est dans le NOC maintenant.","other":"{n} limites max-prefix relevées.
{k} d’entre elles étaient des fuites de routes. Elles sont dans le NOC maintenant."}, "sites_peering_caches.second_lag_member_added_one_member":"Second membre de LAG ajouté.
Un membre dans chaque bâtiment désormais : un bâtiment éteint ne coupe plus que la moitié du port.", "sites_peering_caches.second_site_live_in_city_b":"Second site actif à {city}.
{b} est relié à {a} par ton propre anneau métropolitain. Déplaces-y quelques uplinks depuis les onglets Transit et Peering.", -"sites_peering_caches.the_ai_is_gone_it_left":"L’IA est partie.
Elle a laissé un document de passation de 40 pages. Il parle surtout d’elle.", "sites_peering_caches.they_checked_your_pearingdb_page_and":"Ils ont consulté ta page PearingDB et ont aimé tes chiffres de trafic.", "sites_peering_caches.we_are_waiting_on_the_colo":"« Nous attendons le colo pour le cross-connect. »
Le colo dit qu’il les attend.", "sites_peering_caches.your_account_manager_found_the_order":"Votre account manager a retrouvé la commande sous un bureau.
Elle a un mois d’avance.", @@ -3496,6 +3424,7 @@ "slots.last_played_ago":"Dernière partie : {ago}", "slots.load_the_newest_version":"Charger la version la plus récente", "slots.more_for_name":"Plus pour {name}", +"slots.n_day_ago":{"one":"il y a {n} jour","other":"il y a {n} jours"}, "slots.n_h_ago":{"one":"il y a {n} h","other":"il y a {n} h"}, "slots.name_is_open_in_another_window":"{name} est ouvert dans une autre fenêtre", "slots.name_is_waiting_in_your_other":"{name} t'attend dans ton autre fenêtre.
Passe dessus pour continuer à jouer.", @@ -3519,7 +3448,6 @@ "slots.this_window_stopped_saving_so_it":"Une version plus récente a été sauvegardée dans une autre fenêtre, alors celle-ci a arrêté de sauvegarder au lieu de l'écraser.", "slots.two_windows_one_network":"Deux fenêtres, un réseau", "slots.your_networks":"Tes réseaux", -"slots.your_networks_switch_or_start_another":"Tes réseaux changer, ou en lancer un autre", "slots.your_other_networks_share_this_browser":"Tes autres réseaux partagent le stockage de ce navigateur. Exporte ceux que tu veux garder, puis supprime-les ici pour faire de la place.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hyperscaler a acheté la semaine dernière toutes les ondes de cette taille sur cette route.", "sold_out.not_big_enough_yet_list":"Pas encore assez gros : {list}", diff --git a/site/i18n/it.js b/site/i18n/it.js index f27837c..cd54bf0 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -807,7 +807,6 @@ "common.aug":"ago", "common.auto":"Auto", "common.auto_enrolled":"iscritto d’ufficio", -"common.average":"Nella media", "common.avoid":"Evita", "common.back":"Indietro", "common.back_to_the_map":"Torna alla mappa", @@ -823,7 +822,6 @@ "common.bgp_hijack":"BGP hijack", "common.bgp_sessions":"Sessioni BGP", "common.big_league":"Serie A", -"common.black_hole":"Buco nero", "common.blitz":"Blitz", "common.boot_time":"Tempo di boot", "common.boot_times":"Tempi di boot", @@ -831,7 +829,6 @@ "common.box_6ee3":"− box", "common.build_time":"Tempo di costruzione", "common.building":"in costruzione", -"common.bumped":"sollecitata", "common.bunker_two":"Bunker Due", "common.busiest_links":"Link più carichi", "common.business_customers":"Clienti aziendali", @@ -993,8 +990,6 @@ "common.import_a_save":"Importa un salvataggio", "common.in_progress":"in corso", "common.in_use":"In uso", -"common.inbox":"Posta", -"common.inbox_zero":"Inbox zero.", "common.incident":"Incidente", "common.incidents":"Incidenti", "common.incidents_survived":"Incidenti superati", @@ -1122,7 +1117,6 @@ "common.oops":"Ops", "common.open":"Apri", "common.open_bank":"Apri la banca", -"common.open_inbox":"Apri la casella", "common.open_infra":"Apri Infra", "common.open_lease":"Apri l’affitto", "common.open_noc":"Apri il NOC", @@ -1147,7 +1141,6 @@ "common.peered_ce2f":"In peering ✓", "common.peering":"Peering", "common.peering_first":"Prima il peering", -"common.peering_inbox":"Casella di peering", "common.peering_policy":"Policy di peering", "common.peering_ratio":"Quota peering", "common.peering_spat":"Lite di peering", @@ -1196,7 +1189,6 @@ "common.remove_port":"Rimuovi porta", "common.remove_script":"Rimuovi script", "common.request":"Richiedi", -"common.responsive":"Reattivo", "common.resume":"Riprendi", "common.retention_offer":"Offerta di fidelizzazione", "common.revenue":"Ricavi", @@ -1302,7 +1294,6 @@ "common.to":"A", "common.toaster_wrangler":"Domatore di tostapane", "common.today":"Oggi", -"common.today_4203":"oggi", "common.toggle_sound":"Attiva/disattiva suono", "common.too_far_for_this_cable":"troppo lontano per questo cavo", "common.traceroute":"Traceroute", @@ -1364,7 +1355,6 @@ "common.your_network":"La tua rete", "common.your_pop":"Il tuo POP", "common.your_pops":"I tuoi POP", -"common.your_reputation":"La tua reputazione", "common.zombie_route":"Route zombie", "compute.attack_hauled_to_scrubbing_in_city":"Attacco portato allo scrubbing di {city}", "compute.courtesy_route_to_new_networks":"Percorso di cortesia verso le nuove reti", @@ -1611,8 +1601,6 @@ "failures.a_kilometre_of_copper_went_missing":"Un chilometro di “rame” è sparito dal tuo scavo {a}–{b}. Era la tua fibra. Lo sfasciacarrozze l’ha rispedita indietro con un biglietto.", "failures.a_landslide_in_the_andes_buried":"Una frana nelle Ande ha sepolto la tua fibra {a}–{b}.", "failures.a_llama_herd_trampled_the_fiber":"Una mandria di lama ha calpestato il segnalatore della fibra su {a}–{b}. Poi una ruspa ha trovato la fibra.", -"failures.a_member_at_ix_leaked_the":"Un membro di {ix} ha fatto leak dell’intera tabella di routing nel route server. I limiti max-prefix sono scattati ovunque. Il tuo peering lì è giù.", -"failures.a_member_at_ix_leaked_the_5563":"Un membro di {ix} ha fatto leak dell’intera tabella di routing nel route server. I limiti max-prefix sono scattati ovunque. Il tuo peering lì, a {city}, è giù.", "failures.a_new_tech_in_a_tidied":"Un nuovo tecnico a {a} ha “messo in ordine” il groviglio di cavi. Il tuo link {a}–{b} faceva parte del groviglio.", "failures.a_new_tech_in_city_used":"Un nuovo tecnico a {city} ha usato la Vegemite come pasta termica. Conduce il sapore, non il calore, e il tuo router si è cotto.", "failures.a_optic_on_a_b_overheated":"Un {optic} su {a}–{b} si è surriscaldato e ora è un portachiavi molto costoso.", @@ -1679,7 +1667,6 @@ "failures.load_shedding_stage_n_in_city":"Distacchi a rotazione stage {n} a {city}, e non hai un generatore. Compralo: qui non è facoltativo.", "failures.load_shedding_took_out_site_in":"I distacchi a rotazione hanno spento {site} a {city}. {other} ha retto, quindi il POP gira a metà capacità. Tutto ciò che è collegato solo al sito al buio è offline.", "failures.magpie_swooping_season_the_field":"Stagione delle gazze in picchiata: i tecnici su {a}–{b} non escono dal furgone, e il tuo taglio resta tagliato.", -"failures.max_prefix_meltdown":"Max-prefix in tilt", "failures.metro_ring_cut":"Anello metro tagliato", "failures.microbursts_on_a_b_overflow_shallow":"I microburst su {a}–{b} riempiono i buffer poco profondi dei router: 0,5% di perdita al picco, e ogni videochiamata se ne accorge.", "failures.microbursts_on_a_b_your_deep":"Microburst su {a}–{b}.
I tuoi router con buffer profondi li hanno assorbiti. Nessuno se n’è accorto.", @@ -1794,11 +1781,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Il tuo POP · serve una porta fabric lì", "game_and_settings.delete_and_start_over":"Cancella e ricomincia", "game_and_settings.export_save_download_a_file":"Esporta salvataggio scarica un file", -"game_and_settings.import_a_save_from_a_file":"Importa un salvataggio da un file", "game_and_settings.import_failed_that_save_is_damaged":"Importazione fallita.
Quel salvataggio è danneggiato e non si può caricare. La partita in corso non è stata toccata.", "game_and_settings.name_and_everything_it_owns_will":"{name} e tutto ciò che possiede verranno cancellati. Non si torna indietro.", -"game_and_settings.scenarios_amp_weekly_challenge":"Scenari e sfida settimanale", -"game_and_settings.share_your_network_image_card":"Condividi la tua rete come immagine", "game_and_settings.start_a_new_network":"Vuoi creare una nuova rete?", "game_and_settings.welcome_back_name_imported_and_saved":"Bentornato, {name}.
Importato e salvato su questo dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"La partita si salva da sola ogni pochi secondi su questo dispositivo.", @@ -1869,7 +1853,7 @@ "help.each_pop_s_router_model_caps":"Il modello di router di ogni POP limita la sua porta più veloce (100G, 400G, 800G, 1.6T) e quanto traffico può inoltrare. Wave e porte più grandi richiedono router migliori a entrambe le estremità. I modelli migliori si sbloccano con il tuo livello clienti. Con un solo router, ogni upgrade vuol dire un giorno di downtime.", "help.event_networks_a_final_a_festival":"Le reti per eventi (una finale, un festival, un keynote) vogliono un picco di capacità in una città per qualche giorno e pagano una volta sola alla fine, in proporzione a quanta folla hai servito; sotto il 70% paghi una penale. Le catene SD-WAN collegano 3–6 dei tuoi POP in hub-and-spoke, quindi uno spoke rotto fa arrabbiare tutto il contratto. Quando gestisci la tua dark fiber, i carrier vogliono affittare i canali liberi come alien wave e, sulla fibra che hai costruito tu, una coppia libera.", "help.events_chains_and_wholesale":"Eventi, catene e wholesale", -"help.every_ix_port_brings_peering":"Ogni porta IX porta richieste di peering e allarmi max-prefix, nella scheda Reti. Una sessione che supera il limite resta giù finché non ci guardi: alza il limite se è crescita, tienila giù se è un leak. Ignora la posta e le reti selettive diventano più esigenti.", +"help.every_ix_port_brings_requests":"Ogni porta IX porta richieste di peering, e la tua policy di peering, nella scheda Reti, risponde per te: Aperta accetta tutti, Selettiva accetta le reti con cui conviene fare peering e declina in silenzio le altre, Chiusa le declina tutte. Una volta a settimana il log del NOC fa il riassunto.", "help.every_link_has_latency_high":"Ogni link ha una latenza. I trader HFT pagano una fortuna per un circuito dentro il loro budget di latenza: instradali su “Latenza minima”. Ai clienti di backup massivo non importa, quindi instradali sul “Panoramico” lungo i tuoi link tranquilli, per lasciare liberi quelli trafficati.", "help.home_broadband_users_they_mostly":"Utenti di banda larga domestica. Scaricano soprattutto dalle CDN e ti pagano per ogni Gbps che consegni. Servili bene e si moltiplicano.", "help.how_the_internet_works_here":"Come funziona internet qui", @@ -1883,7 +1867,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) è transit-free. Fai peering con ogni gigante del pianeta e non paghi nessuno per raggiungere internet. Ci hai messo {days} giorni e {n} incidenti.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG e compagnia tornano ogni anno. Iscriviti nella scheda Offerte per $8k. Nei 45 giorni successivi, le reti selective presenti in quella regione chiedono solo metà del traffico abituale prima di fare peering con te. A volte vinci pure la lotteria.", "help.once_auto_te_is_installed_you":"Una volta installato Auto-TE, puoi programmarlo dalla scheda NOC. Tra le regole ci sono spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams e blackhole ddos. Check fa una prova a secco sul traffico reale; Deploy la rende vera, errori compresi.", -"help.one_game_four_doors_puzzles_are":"Un gioco, quattro porte, e le regole si scelgono quando nasce una rete e poi restano bloccate. I rompicapi sono piccoli nodi da sciogliere, senza orologio. La sandbox ti dà un miliardo di dollari, tutto sbloccato (compreso il tuo cavo sottomarino) e tutto il caos che scegli, ma niente medaglie. Normale ha tre varianti: Change freeze (pochi guasti, consegne in pochi giorni, niente posta né carenze), Reperibile (il gioco classico) e BGP alle 3 di notte (guasti più frequenti e più lunghi, più DDoS). Gli scenari sono sfide fatte a mano con un obiettivo e una scadenza, e la sfida settimanale dà a tutti lo stesso mondo per una settimana. Condividi il risultato con la scheda nel menu.", +"help.one_game_four_doors_and_the":"Un gioco, quattro porte, e le regole si scelgono quando nasce una rete e poi restano bloccate. I rompicapi sono piccoli nodi da sciogliere, senza orologio. La sandbox ti dà un miliardo di dollari, tutto sbloccato (compreso il tuo cavo sottomarino) e tutto il caos che scegli, ma niente medaglie. Normale ha tre varianti: Change freeze (pochi guasti, consegne in pochi giorni, niente carenze), Reperibile (il gioco classico) e BGP alle 3 di notte (guasti più frequenti e più lunghi, più DDoS). Gli scenari sono sfide fatte a mano con un obiettivo e una scadenza, e la sfida settimanale dà a tutti lo stesso mondo per una settimana. Condividi il risultato con la scheda nel menu.", "help.open_peers_with_anyone_selective":"Open: fa peering con chiunque. Selective: vuole prima vedere traffico. Restrictive (i Tier 1): fa peering solo con i giganti, tramite PNI. Paid: esattamente quello che sembra, si paga. Le grandi reti selective hanno anche i loro umori: in certe città rifiutano nuovi peer per qualche mese, o accettano solo PNI, e ogni tanto abbattono una sessione che avevi già. Prova un’altra città o un PNI, e richiedi più avanti.", "help.out_of_port_speed_bundle_up":"Porte al limite? Raggruppa fino a 8 porte identiche verso lo stesso provider di transit, IX o PNI in un LAG. Ogni membro costa una porta intera; il flow hashing non è mai perfettamente uniforme, quindi un bundle trasporta circa il 95% della somma.", "help.pni_lead_times":"Tempi di consegna delle PNI", @@ -2008,15 +1992,12 @@ "hud_and_panels.has_errors_not_running":"ha errori, non gira", "hud_and_panels.incidents_so_far":"Incidenti finora", "hud_and_panels.install_auto_te_cost_mo_mo":"Installa Auto-TE {cost} + {mo}/mese", -"hud_and_panels.large_peering_model_is_on_it":"Ci pensa Large Peering Model.", "hud_and_panels.lv_n":"Liv. {n}", "hud_and_panels.n_incident":{"one":"{n} incidente","other":"{n} incidenti"}, -"hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} messaggio aspetta una risposta.","other":"{n} messaggi aspettano una risposta."}, "hud_and_panels.n_more_networks":{"one":"+{n} altra rete","other":"+{n} altre reti"}, "hud_and_panels.n_networks_d_days_left":"{n} reti · {d} giorni rimasti", "hud_and_panels.n_new_notification":{"one":"{n} nuova notifica","other":"{n} nuove notifiche"}, "hud_and_panels.n_rules_live":"{n} regole attive", -"hud_and_panels.n_session_is_down_on_its":{"one":"{n} sessione è giù per il limite max-prefix.","other":"{n} sessioni sono giù per il limite max-prefix."}, "hud_and_panels.n_small_networks":"{n} piccole reti", "hud_and_panels.n_special_requirement":{"one":"{n} requisito speciale","other":"{n} requisiti speciali"}, "hud_and_panels.n_unhappy_customer_price_mo_at":{"one":"{n} cliente scontento, {price}/mese a rischio","other":"{n} clienti scontenti, {price}/mese a rischio"}, @@ -2592,6 +2573,7 @@ "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.day_d":"Giorno {d}", "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.", @@ -2630,8 +2612,6 @@ "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.", -"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.", @@ -2744,61 +2724,14 @@ "page.series_of_tubes_build_the_internet":"Series of Tubes: costruisci internet, un tubo alla volta", "page.world_map_of_your_network":"Mappa del mondo della tua rete", "page.x":"", -"peering_inbox.accept_all_requests":"Accetta tutte le richieste", -"peering_inbox.an_ai_agent_that_answers_every":"Un agente IA che risponde per te a ogni richiesta di peering e allarme max-prefix, ogni giorno. {price}/anno. Addestrato su vent’anni di mailing list sul peering.", -"peering_inbox.answered_your_mail_a_accepted_d":"Ha risposto alla tua posta: {a} accettate, {d} rifiutate.", -"peering_inbox.asked_netchill_s_peering_team_to":"Ha chiesto al team di peering di NetChill di “fornire più Netchill, per favore”.", -"peering_inbox.configured_lim_prefixes_received_got":"Configurato: {lim} prefissi. Ricevuti: {got}.", -"peering_inbox.day_d":"Giorno {d}", -"peering_inbox.dear_sir_or_madam_please_peer":"Gentile Signore o Signora, per favore fate peering. Abbiamo tre prefissi e progetti molto grandi.", -"peering_inbox.decline_all_requests":"Rifiuta tutte le richieste", -"peering_inbox.declined_who_at_ix_not_a":"Ha rifiutato {who} a {ix}: “non strategico”. Lo era.", -"peering_inbox.every_exchange_port_brings_mail":"Ogni porta IX porta posta. Rispondi alle richieste di peering e guarda le sessioni che superano il limite max-prefix: è crescita o un route leak? La posta senza risposta ti fa una reputazione, e le reti selettive lo vengono a sapere.", -"peering_inbox.everyone_who_asks_gets_a_session":"Chiunque chieda ottiene una sessione, e i route server funzionano. Tanti peer minuscoli, e tanti allarmi max-prefix.", -"peering_inbox.fewer_requests_and_you_answer_them":"Meno richieste, e rispondi tu. Niente route server: vai su ogni exchange e chiedi le reti che vuoi.", -"peering_inbox.fire_the_ai":"Licenzia l’IA", -"peering_inbox.good_call_it_was_a_route":"Ben fatto: era un route leak.
{who} ha trovato una route map scritta male. La sessione torna da sola tra qualche giorno.", -"peering_inbox.greetings_we_are_a_fast_growing":"Saluti. Siamo una rete in rapida crescita. L’anno scorso avevamo un cliente; quest’anno ne abbiamo due.", -"peering_inbox.hello_please_find_attached_our":"Salve, in allegato la nostra richiesta di peering come documento Word, scansionato da una stampa.", -"peering_inbox.hey_quick_one_can_you_peer":"Ehi, domanda veloce: potete fare peering con noi a {ix}? Abbiamo un server Minecraft molto importante.", -"peering_inbox.hi_we_would_like_to_peer":"Ciao! Vorremmo fare peering con voi a {ix}. Il nostro record su PeeringDB è aggiornato.", -"peering_inbox.hire_it_mo_mo":"Assumilo {mo}/mese", -"peering_inbox.inbox_zero_enjoy_it_while_it":"Inbox zero. Goditela finché dura.", -"peering_inbox.keep_it_down":"Tienila giù", -"peering_inbox.kept_who_down_at_ix_for":"Ha tenuto giù {who} a {ix} per “crescita sospetta”. Erano cresciuti di un cliente.", -"peering_inbox.kept_who_down_at_ix_it":"Ha tenuto giù {who} a {ix}: era un route leak. Centrato.", -"peering_inbox.large_peering_model":"Large Peering Model", -"peering_inbox.large_peering_model_is_answering":"Large Peering Model risponde alla tua posta", -"peering_inbox.max_prefix_limit_hit_who_at":"Limite max-prefix superato: {who} a {ix}.
La sessione resta giù finché non ci guardi.", -"peering_inbox.max_prefix_limit_hit_who_at_5c56":"Limite max-prefix superato: {who} a {ix}", -"peering_inbox.mostly_ignores_email":"Ignora quasi tutte le email", -"peering_inbox.n_day_ago":{"one":"{n} giorno fa","other":"{n} giorni fa"}, -"peering_inbox.n_unanswered":{"one":"{n} senza risposta","other":"{n} senza risposta"}, -"peering_inbox.no_mail_yet_buy_an_ix":"Ancora niente posta. Compra una porta IX e arriverà.", -"peering_inbox.nobody_asks_and_no_route_servers":"Nessuno chiede, e niente route server. I clienti sentono dire che sei difficile da raggiungere, quindi ne chiamano meno, e la tua reputazione affonda.", -"peering_inbox.open_to_all":"Aperta a tutti", -"peering_inbox.opened_a_ticket_with_itself_to":"Ha aperto un ticket a se stesso per rivedere le proprie decisioni. Le ha approvate.", -"peering_inbox.peering_request_fifth_attempt_is":"Richiesta di peering, quinto tentativo. C’è qualcuno?", -"peering_inbox.peeringdb_last_updated_n_year_ago":{"one":"PeeringDB aggiornato {n} anno fa","other":"PeeringDB aggiornato {n} anni fa"}, -"peering_inbox.peeringdb_updated_last_month":"PeeringDB aggiornato il mese scorso", -"peering_inbox.please_configure_sessions_with_us_at":"Per favore configurate le sessioni con noi a {ix}. Noi faremo le nostre la settimana prossima, o quella dopo.", -"peering_inbox.price_year_it_never_sleeps_never":"{price}/anno. Non dorme mai, non si lamenta mai e sbaglia spesso.", -"peering_inbox.raise_all_max_prefix_limits":"Alza tutti i limiti max-prefix", -"peering_inbox.raise_the_limit":"Alza il limite", -"peering_inbox.raised_the_max_prefix_limit_for":"Ha alzato il limite max-prefix per {who} a {ix} a {n}. Sembravano simpatici.", -"peering_inbox.raised_the_max_prefix_limit_for_7b4b":"Ha alzato il limite max-prefix per {who} a {ix}. Correttamente, stavolta.", -"peering_inbox.replied_to_a_peering_request_with":"Ha risposto a una richiesta di peering con un haiku sul BGP. Nessuna risposta per ora.", -"peering_inbox.session_with_who_is_back_up":"La sessione con {who} è di nuovo su.
Nuovo limite: {n} prefissi. Promettono di aggiornare PeeringDB.", -"peering_inbox.signed_you_up_for_a_webinar":"Ti ha iscritto a un webinar su “Il peering nell’era dell’IA”.", -"peering_inbox.that_was_a_route_leak_who":"Era un route leak.
{who} annunciava {n} prefissi: una full table. La prossima volta, tienila giù.", -"peering_inbox.the_session_stays_down_who_will":"La sessione resta giù.
{who} aggiornerà PeeringDB e chiederà di nuovo. Prima o poi.", -"peering_inbox.their_peeringdb_says_lim_last":{"one":"Il loro PeeringDB dice {lim}, aggiornato {n} anno fa.","other":"Il loro PeeringDB dice {lim}, aggiornato {n} anni fa."}, -"peering_inbox.tidied_up_a_session_it_decided":"Ha fatto ordine tra le sessioni che riteneva inutili: ha tolto il peering con {who} a {ix}.", -"peering_inbox.updated_your_peeringdb_record_your":"Ha aggiornato il tuo record su PeeringDB. Il numero del tuo NOC ora è una pizzeria.", -"peering_inbox.we_noticed_you_are_at_ix":"Abbiamo notato che siete a {ix}. Anche noi. Che ne dite?", -"peering_inbox.who_asked_a_mailing_list_whether":"{who} ha chiesto su una mailing list se qualcuno ha un contatto funzionante da {me}.
La loro richiesta di peering è rimasta nella tua casella per un mese.", -"peering_inbox.who_at_ix_was_sending_a":"{who} a {ix} stava mandando una full table, e il limite max-prefix era l’unica cosa che la fermava. Col limite alzato, i prefissi di {net} puntano alla loro cantina. Il traffico verso {net} via transito finisce in un buco nero per qualche giorno.", -"peering_inbox.wrote_a_thousand_word_apology_to":"Ha scritto mille parole di scuse a una rete con cui non hai mai fatto peering.", +"peering_desk.closed_desc":"Ogni richiesta di peering viene declinata, e niente route server. I clienti sentono dire che sei difficile da raggiungere, quindi ne chiamano meno.", +"peering_desk.n_more_exchanges":{"one":"{n} altro exchange","other":"altri {n} exchange"}, +"peering_desk.n_new_sessions_at_ix":{"one":"Ufficio peering: {n} nuova sessione a {ix} ({pol}).","other":"Ufficio peering: {n} nuove sessioni a {ix} ({pol})."}, +"peering_desk.n_new_sessions_at_ix_declined":{"one":"Ufficio peering: {n} nuova sessione a {ix}, {d} declinate ({pol}).","other":"Ufficio peering: {n} nuove sessioni a {ix}, {d} declinate ({pol})."}, +"peering_desk.n_requests_declined":{"one":"Ufficio peering: {n} richiesta declinata ({pol}).","other":"Ufficio peering: {n} richieste declinate ({pol})."}, +"peering_desk.open_desc":"Ogni rete che chiede ottiene una sessione, e i route server funzionano.", +"peering_desk.open_to_all":"Aperta a tutti", +"peering_desk.selective_desc":"Le reti piccole dell’exchange e i nuovi arrivati con PeeringDB aggiornato ottengono una sessione; le altre vengono declinate in silenzio. Niente route server: chiedi le reti che vuoi su ogni exchange.", "peering_policy.a_new_vp_wants_to_monetise":"Un nuovo VP vuole “monetizzare l’interconnessione” in questo mercato.", "peering_policy.already_reach_you_through_your":"Ti raggiungono già tramite il tuo provider di transit qui, e per loro va bene così.", "peering_policy.moved_everything_in_this_city_to":"In questa città hanno spostato tutto su PNI. Leggi la loro pagina PearingDB, tutte e 40 le pagine.", @@ -3309,7 +3242,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Prima stacca qualcosa.
Ci sono {used} porte in uso, e con un router in meno ne avresti solo {max}.", "rules.a_billion_dollars_every_unlock_your":"Un miliardo di dollari, tutto sbloccato, il tuo cavo sottomarino.", "rules.a_cut_now_and_then":"Un taglio ogni tanto.", -"rules.a_third_of_the_outages_no_ddos":"Un terzo dei guasti, niente DDoS. PNI e cantieri in pochi giorni. Niente posta, niente carenze, niente rotte esaurite, niente de-peering.", +"rules.a_third_of_the_outages_no_ddos_pnis":"Un terzo dei guasti, niente DDoS. PNI e cantieri in pochi giorni. Niente carenze, niente rotte esaurite, niente de-peering.", "rules.bgp_at_3_a_m":"BGP alle 3 di notte", "rules.change_freeze":"Change freeze", "rules.chaos_calm":"Calmo", @@ -3326,7 +3259,7 @@ "rules.on_call":"Reperibile", "rules.one_small_network_one_tricky_goal":"Una piccola rete, un obiettivo insidioso.", "rules.puzzle":"Rompicapo", -"rules.real_lead_times_real_outages_a":"Tempi di consegna veri, guasti veri, una casella di peering piena. Il gioco classico.", +"rules.real_lead_times_real_outages_a_real":"Tempi di consegna veri, guasti veri, un mercato vero. Il gioco classico.", "rules.rules_are_locked_for_this_network":"{rules}: le regole sono bloccate per questa rete.", "rules.the_real_thing_your_pager_has":"Il gioco vero. Il tuo cercapersone ha delle opinioni.", "rules.your_pager_never_sleeps":"Il tuo cercapersone non dorme mai.", @@ -3460,9 +3393,7 @@ "sites_peering_caches.bgp_session_established":"Sessione BGP stabilita.", "sites_peering_caches.cache_installed_in_city_net_shipped":"{cache} installata a {city}!
{net} te l’ha spedita gratis. Tu paghi {mo}/mese di corrente.", "sites_peering_caches.could_you_resend_the_loa_you":"“Può rimandarci la LOA?”
L’hai mandata quattro volte.", -"sites_peering_caches.hello_i_am_large_peering_model":"Ciao! Sono Large Peering Model. Ho letto la tua casella e ho già delle opinioni.", "sites_peering_caches.it_is_with_the_provisioning_team":"“È in mano al team di provisioning.”
Nessuno ha mai conosciuto il team di provisioning.", -"sites_peering_caches.large_peering_model_is_hired_your":"Large Peering Model è assunto.
La tua casella ora è un problema suo. {price} all’anno, fatturati ogni mese.", "sites_peering_caches.n_new_session_at_ix_small":{"one":"{n} nuova sessione a {ix}.
Reti piccole, ma fanno numero, e contano tutte per il club.","other":"{n} nuove sessioni a {ix}.
Reti piccole, ma fanno numero, e contano tutte per il club."}, "sites_peering_caches.net_accepted":"{net} ha accettato!", "sites_peering_caches.net_declined_the_pni_why":"{net} ha rifiutato il PNI.
{why}", @@ -3470,11 +3401,8 @@ "sites_peering_caches.net_does_not_do_port_pnis":"{net} non fa PNI da {port}.
Niente sotto i 100G. Torna con più traffico, o con un’ottica più grande.", "sites_peering_caches.net_says_not_yet_send_them":"{net} dice: non ancora.
Prima mandagli {min}+ Gbps.", "sites_peering_caches.pni_with_net_ordered_eta_a":"PNI con {net} ordinata.
{eta}. Un cross-connect in {dc}, appena qualcuno trova la LOA.", -"sites_peering_caches.raised_n_max_prefix_limits_all":"Alzati {n} limiti max-prefix.
Tutta crescita, nessun leak. Fortuna.", -"sites_peering_caches.raised_n_max_prefix_limits_one":{"one":"Alzati {n} limiti max-prefix.
Uno era un route leak. Ora è nel NOC.","other":"Alzati {n} limiti max-prefix.
{k} erano route leak. Ora sono nel NOC."}, "sites_peering_caches.second_lag_member_added_one_member":"Secondo membro LAG aggiunto.
Ora c’è un membro per edificio, così un edificio al buio si porta via solo metà porta.", "sites_peering_caches.second_site_live_in_city_b":"Secondo sito attivo a {city}.
{b} è collegato a {a} dal tuo anello metro. Sposta lì qualche uplink dalle schede Transit e Peering.", -"sites_peering_caches.the_ai_is_gone_it_left":"L’IA se n’è andata.
Ha lasciato un documento di passaggio di consegne di 40 pagine. Parla soprattutto di sé.", "sites_peering_caches.they_checked_your_pearingdb_page_and":"Hanno controllato la tua pagina PearingDB e i numeri del traffico gli sono piaciuti.", "sites_peering_caches.we_are_waiting_on_the_colo":"“Stiamo aspettando il colo per il cross-connect.”
Il colo dice che sta aspettando loro.", "sites_peering_caches.your_account_manager_found_the_order":"Il tuo account manager ha trovato l’ordine sotto una scrivania.
È un mese più vicino.", @@ -3496,6 +3424,7 @@ "slots.last_played_ago":"Ultima partita: {ago}", "slots.load_the_newest_version":"Carica la versione più recente", "slots.more_for_name":"Altro per {name}", +"slots.n_day_ago":{"one":"{n} giorno fa","other":"{n} giorni fa"}, "slots.n_h_ago":{"one":"{n} h fa","other":"{n} h fa"}, "slots.name_is_open_in_another_window":"{name} è aperta in un'altra finestra", "slots.name_is_waiting_in_your_other":"{name} ti aspetta nell'altra finestra.
Passa lì per continuare a giocare.", @@ -3519,7 +3448,6 @@ "slots.this_window_stopped_saving_so_it":"In un'altra finestra è stata salvata una versione più recente, quindi questa ha smesso di salvare invece di sovrascriverla.", "slots.two_windows_one_network":"Due finestre, una rete", "slots.your_networks":"Le tue reti", -"slots.your_networks_switch_or_start_another":"Le tue reti cambia o iniziane un'altra", "slots.your_other_networks_share_this_browser":"Le tue altre reti condividono lo spazio di questo browser. Esporta quelle che vuoi tenere, poi eliminale qui per fare posto.", "sold_out.a_hyperscaler_bought_every_wave_of":"Un hyperscaler ha comprato la settimana scorsa ogni onda di questa misura su questa tratta.", "sold_out.not_big_enough_yet_list":"Non sei ancora abbastanza grande: {list}", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index d665af3..fa6d14b 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -807,7 +807,6 @@ "common.aug":"ago", "common.auto":"Auto", "common.auto_enrolled":"inscrito automaticamente", -"common.average":"Na média", "common.avoid":"Evitar", "common.back":"Voltar", "common.back_to_the_map":"Voltar ao mapa", @@ -823,7 +822,6 @@ "common.bgp_hijack":"BGP hijack", "common.bgp_sessions":"Sessões BGP", "common.big_league":"Primeira divisão", -"common.black_hole":"Buraco negro", "common.blitz":"Blitz", "common.boot_time":"Tempo de boot", "common.boot_times":"Tempo de boot", @@ -831,7 +829,6 @@ "common.box_6ee3":"− box", "common.build_time":"Tempo de obra", "common.building":"em obras", -"common.bumped":"cobrado de novo", "common.bunker_two":"Bunker Dois", "common.busiest_links":"Links mais carregados", "common.business_customers":"Clientes empresariais", @@ -993,8 +990,6 @@ "common.import_a_save":"Importar um save", "common.in_progress":"em andamento", "common.in_use":"Em uso", -"common.inbox":"Caixa de entrada", -"common.inbox_zero":"Caixa zerada.", "common.incident":"Incidente", "common.incidents":"Incidentes", "common.incidents_survived":"Incidentes superados", @@ -1122,7 +1117,6 @@ "common.oops":"Ops", "common.open":"Abrir", "common.open_bank":"Abrir banco", -"common.open_inbox":"Abrir a caixa", "common.open_infra":"Abrir Infra", "common.open_lease":"Abrir aluguel", "common.open_noc":"Abrir NOC", @@ -1147,7 +1141,6 @@ "common.peered_ce2f":"Em peering ✓", "common.peering":"Peering", "common.peering_first":"Peering primeiro", -"common.peering_inbox":"Caixa de peering", "common.peering_policy":"Política de peering", "common.peering_ratio":"Taxa de peering", "common.peering_spat":"Briga de peering", @@ -1196,7 +1189,6 @@ "common.remove_port":"Remover porta", "common.remove_script":"Remover script", "common.request":"Pedir", -"common.responsive":"Responde rápido", "common.resume":"Continuar", "common.retention_offer":"Oferta de retenção", "common.revenue":"Receita", @@ -1302,7 +1294,6 @@ "common.to":"Para", "common.toaster_wrangler":"Domador de torradeiras", "common.today":"Hoje", -"common.today_4203":"hoje", "common.toggle_sound":"Ligar/desligar som", "common.too_far_for_this_cable":"longe demais para este cabo", "common.traceroute":"Traceroute", @@ -1364,7 +1355,6 @@ "common.your_network":"Sua rede", "common.your_pop":"Seu POP", "common.your_pops":"Seus POPs", -"common.your_reputation":"Sua reputação", "common.zombie_route":"Rota zumbi", "compute.attack_hauled_to_scrubbing_in_city":"Ataque levado ao scrubbing em {city}", "compute.courtesy_route_to_new_networks":"Rota de cortesia para novas redes", @@ -1611,8 +1601,6 @@ "failures.a_kilometre_of_copper_went_missing":"Um quilômetro de “cobre” sumiu da sua vala {a}–{b}. Era a sua fibra. O ferro-velho devolveu com um bilhete.", "failures.a_landslide_in_the_andes_buried":"Um deslizamento nos Andes soterrou sua fibra {a}–{b}.", "failures.a_llama_herd_trampled_the_fiber":"Um rebanho de lhamas pisoteou o marcador da fibra em {a}–{b}. Depois uma retroescavadeira achou a fibra.", -"failures.a_member_at_ix_leaked_the":"Um membro do {ix} vazou a tabela de roteamento inteira no route server. Limites de max-prefix estouraram em todo lugar. Seu peering lá caiu.", -"failures.a_member_at_ix_leaked_the_5563":"Um membro do {ix} vazou a tabela de roteamento inteira no route server. Limites de max-prefix estouraram em todo lugar. Seu peering lá, em {city}, caiu.", "failures.a_new_tech_in_a_tidied":"Um técnico novo em {a} “arrumou” a bagunça de cabos. Seu link {a}–{b} fazia parte da bagunça.", "failures.a_new_tech_in_city_used":"Um técnico novo em {city} usou Vegemite como pasta térmica. Ela conduz sabor, não calor, e seu roteador cozinhou.", "failures.a_optic_on_a_b_overheated":"Um {optic} em {a}–{b} superaqueceu e agora é um chaveiro caríssimo.", @@ -1679,7 +1667,6 @@ "failures.load_shedding_stage_n_in_city":"Rodízio de energia stage {n} em {city}, e você não tem gerador. Compre um: aqui não é opcional.", "failures.load_shedding_took_out_site_in":"O rodízio de energia derrubou {site} em {city}. {other} aguentou, então o POP roda com metade da capacidade. Tudo que está ligado só no site apagado está offline.", "failures.magpie_swooping_season_the_field":"Temporada dos rasantes das pegas: os técnicos em {a}–{b} não saem da van, e seu corte continua cortado.", -"failures.max_prefix_meltdown":"Pane de max-prefix", "failures.metro_ring_cut":"Anel metro cortado", "failures.microbursts_on_a_b_overflow_shallow":"Microbursts em {a}–{b} estouram os buffers rasos do router: 0,5% de perda no pico, e toda videochamada percebe.", "failures.microbursts_on_a_b_your_deep":"Microbursts em {a}–{b}.
Seus routers de buffer profundo absorveram tudo. Ninguém percebeu.", @@ -1794,11 +1781,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Seu POP · precisa de uma porta de fabric lá", "game_and_settings.delete_and_start_over":"Apagar e recomeçar", "game_and_settings.export_save_download_a_file":"Exportar save baixar um arquivo", -"game_and_settings.import_a_save_from_a_file":"Importar um save de um arquivo", "game_and_settings.import_failed_that_save_is_damaged":"Falha na importação.
Esse save está corrompido e não pôde ser carregado. Seu jogo atual não foi mexido.", "game_and_settings.name_and_everything_it_owns_will":"{name} e tudo o que ela possui serão apagados. Não dá para desfazer.", -"game_and_settings.scenarios_amp_weekly_challenge":"Cenários & desafio semanal", -"game_and_settings.share_your_network_image_card":"Compartilhar sua rede card de imagem", "game_and_settings.start_a_new_network":"Começar uma nova rede?", "game_and_settings.welcome_back_name_imported_and_saved":"Bem-vindo de volta, {name}.
Importado e salvo neste dispositivo.", "game_and_settings.your_game_saves_itself_every_few":"Seu jogo se salva sozinho a cada poucos segundos neste dispositivo.", @@ -1869,7 +1853,7 @@ "help.each_pop_s_router_model_caps":"O modelo de router de cada POP limita a porta mais rápida (100G, 400G, 800G, 1.6T) e quanto ele consegue encaminhar. Waves e portas maiores pedem routers melhores nas duas pontas. Modelos melhores desbloqueiam com seu nível de clientes. Com um router só, upgrade significa um dia fora do ar.", "help.event_networks_a_final_a_festival":"Redes de evento (uma final, um festival, uma keynote) precisam de uma rajada de capacidade numa cidade por alguns dias e pagam uma vez no fim, proporcional a quanto do público você atendeu; abaixo de 70% você paga multa. Redes SD-WAN ligam de 3 a 6 POPs seus em hub-and-spoke, então um spoke quebrado azeda o contrato inteiro. Quando você tiver sua própria dark fiber, as operadoras vão querer alugar canais livres como alien waves, e na fibra que você mesmo construiu, um par sobrando.", "help.events_chains_and_wholesale":"Eventos, redes e atacado", -"help.every_ix_port_brings_peering":"Cada porta de IX traz pedidos de peering e alertas de max-prefix, na aba Redes. Uma sessão que estoura o limite fica fora até você olhar: aumente o limite se for crescimento, deixe fora se for vazamento. Ignore seus e-mails e as redes seletivas ficam mais exigentes.", +"help.every_ix_port_brings_requests":"Cada porta de IX traz pedidos de peering, e a sua política de peering, na aba Redes, responde a eles: Aberta aceita todos, Seletiva aceita as redes com que vale a pena fazer peering e recusa o resto em silêncio, Fechada recusa todos. Uma vez por semana o log do NOC resume tudo.", "help.every_link_has_latency_high":"Todo link tem latência. Traders de alta frequência pagam uma fortuna por um circuito dentro do orçamento de latência deles; roteie-os por “Menor latência”. Clientes de backup em massa não ligam, então roteie-os pela “Panorâmica” nos seus links tranquilos para deixar livres os movimentados.", "help.home_broadband_users_they_mostly":"Usuários de banda larga residencial. Eles baixam principalmente de CDNs e te pagam por Gbps entregue. Atenda bem e eles se multiplicam.", "help.how_the_internet_works_here":"Como a internet funciona aqui", @@ -1883,7 +1867,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) é transit-free. Você faz peering com todos os gigantes do planeta e não paga ninguém para chegar à internet. Levou {days} dias e {n} incidentes.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG e a turma aparecem todo ano. Inscreva-se na aba Negócios por $8k. Nos 45 dias seguintes, redes seletivas presentes naquela região pedem só metade do tráfego de sempre antes de fazer peering com você. Às vezes você ainda ganha o sorteio.", "help.once_auto_te_is_installed_you":"Com o Auto-TE instalado, você pode programá-lo pela aba NOC. As regras incluem spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams e blackhole ddos. Verificar faz um dry run contra o tráfego real; Aplicar torna tudo real, erros incluídos.", -"help.one_game_four_doors_puzzles_are":"Um jogo, quatro portas, e as regras são escolhidas quando uma rede começa e ficam travadas depois. Os quebra-cabeças são pequenos nós para desatar, sem relógio. A sandbox dá um bilhão de dólares, tudo desbloqueado (incluindo o seu próprio cabo submarino) e o caos que você escolher, mas sem medalhas. O Normal vem de três jeitos: Congelamento de mudanças (poucas falhas, entregas em dias, sem caixa de entrada nem escassez), De plantão (o jogo clássico) e BGP às 3 da manhã (mais falhas e mais longas, mais DDoS). Os cenários são desafios feitos à mão com um objetivo e um prazo, e o desafio semanal dá a todos o mesmo mundo durante uma semana. Compartilhe o seu resultado com o cartão no menu.", +"help.one_game_four_doors_and_the":"Um jogo, quatro portas, e as regras são escolhidas quando uma rede começa e ficam travadas depois. Os quebra-cabeças são pequenos nós para desatar, sem relógio. A sandbox dá um bilhão de dólares, tudo desbloqueado (incluindo o seu próprio cabo submarino) e o caos que você escolher, mas sem medalhas. O Normal vem de três jeitos: Congelamento de mudanças (poucas falhas, entregas em dias, sem escassez), De plantão (o jogo clássico) e BGP às 3 da manhã (mais falhas e mais longas, mais DDoS). Os cenários são desafios feitos à mão com um objetivo e um prazo, e o desafio semanal dá a todos o mesmo mundo durante uma semana. Compartilhe o seu resultado com o cartão no menu.", "help.open_peers_with_anyone_selective":"Open faz peering com qualquer um. Selective quer ver tráfego antes. Restrictive (Tier 1s) só faz peering com gigantes, via PNI. Paid é exatamente isso. Redes seletivas grandes também têm seus humores: em algumas cidades recusam novos peers por alguns meses, ou só aceitam PNI, e de vez em quando derrubam uma sessão que você já tinha. Tente outra cidade ou um PNI, e peça de novo mais tarde.", "help.out_of_port_speed_bundle_up":"Sem velocidade de porta? Junte até 8 portas idênticas para o mesmo provedor de transit, IX ou PNI num LAG. Cada membro custa uma porta inteira; o hashing de fluxos nunca é perfeitamente uniforme, então o bundle carrega cerca de 95% da soma.", "help.pni_lead_times":"Prazos de PNI", @@ -2008,15 +1992,12 @@ "hud_and_panels.has_errors_not_running":"tem erros, não está rodando", "hud_and_panels.incidents_so_far":"Incidentes até agora", "hud_and_panels.install_auto_te_cost_mo_mo":"Instalar Auto-TE {cost} + {mo}/mês", -"hud_and_panels.large_peering_model_is_on_it":"Large Peering Model está cuidando disso.", "hud_and_panels.lv_n":"Nv {n}", "hud_and_panels.n_incident":{"one":"{n} incidente","other":"{n} incidentes"}, -"hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} mensagem esperando resposta.","other":"{n} mensagens esperando resposta."}, "hud_and_panels.n_more_networks":{"one":"+{n} rede a mais","other":"+{n} redes a mais"}, "hud_and_panels.n_networks_d_days_left":"{n} redes · faltam {d} dias", "hud_and_panels.n_new_notification":{"one":"{n} notificação nova","other":"{n} notificações novas"}, "hud_and_panels.n_rules_live":"{n} regras ativas", -"hud_and_panels.n_session_is_down_on_its":{"one":"{n} sessão está fora pelo limite de max-prefix.","other":"{n} sessões estão fora pelo limite de max-prefix."}, "hud_and_panels.n_small_networks":"{n} redes pequenas", "hud_and_panels.n_special_requirement":{"one":"{n} requisito especial","other":"{n} requisitos especiais"}, "hud_and_panels.n_unhappy_customer_price_mo_at":{"one":"{n} cliente insatisfeito, {price}/mês em risco","other":"{n} clientes insatisfeitos, {price}/mês em risco"}, @@ -2592,6 +2573,7 @@ "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.day_d":"Dia {d}", "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.", @@ -2630,8 +2612,6 @@ "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.", -"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.", @@ -2744,61 +2724,14 @@ "page.series_of_tubes_build_the_internet":"Series of Tubes: construa a internet, um tubo de cada vez", "page.world_map_of_your_network":"Mapa-múndi da sua rede", "page.x":"", -"peering_inbox.accept_all_requests":"Aceitar todos os pedidos", -"peering_inbox.an_ai_agent_that_answers_every":"Um agente de IA que responde por você a cada pedido de peering e alerta de max-prefix, todo dia. {price}/ano. Treinado em vinte anos de listas de e-mails sobre peering.", -"peering_inbox.answered_your_mail_a_accepted_d":"Respondeu seus e-mails: {a} aceitos, {d} recusados.", -"peering_inbox.asked_netchill_s_peering_team_to":"Pediu ao time de peering da NetChill “mais Netchill, por favor”.", -"peering_inbox.configured_lim_prefixes_received_got":"Configurado: {lim} prefixos. Recebidos: {got}.", -"peering_inbox.day_d":"Dia {d}", -"peering_inbox.dear_sir_or_madam_please_peer":"Prezado senhor ou senhora, por favor façam peering. Temos três prefixos e planos enormes.", -"peering_inbox.decline_all_requests":"Recusar todos os pedidos", -"peering_inbox.declined_who_at_ix_not_a":"Recusou {who} no {ix}: “não é estratégico”. Era.", -"peering_inbox.every_exchange_port_brings_mail":"Cada porta de IX traz e-mails. Responda aos pedidos de peering e olhe as sessões que estouraram o limite de max-prefix: é crescimento ou vazamento de rotas? E-mail sem resposta te dá uma reputação, e as redes seletivas ficam sabendo.", -"peering_inbox.everyone_who_asks_gets_a_session":"Quem pedir ganha uma sessão, e os route servers funcionam. Muitos peers minúsculos, e muitos alertas de max-prefix.", -"peering_inbox.fewer_requests_and_you_answer_them":"Menos pedidos, e você mesmo responde. Sem route servers: vá a cada exchange e peça as redes que quiser.", -"peering_inbox.fire_the_ai":"Demitir a IA", -"peering_inbox.good_call_it_was_a_route":"Boa: era um vazamento de rotas.
{who} achou um route map digitado errado. A sessão volta sozinha em alguns dias.", -"peering_inbox.greetings_we_are_a_fast_growing":"Saudações. Somos uma rede em rápido crescimento. Ano passado tínhamos um cliente; este ano temos dois.", -"peering_inbox.hello_please_find_attached_our":"Olá, segue em anexo nosso pedido de peering como documento Word, escaneado de uma impressão.", -"peering_inbox.hey_quick_one_can_you_peer":"E aí, rapidinho: dá pra fazer peering com a gente no {ix}? Temos um servidor de Minecraft muito importante.", -"peering_inbox.hi_we_would_like_to_peer":"Oi! Gostaríamos de fazer peering com vocês no {ix}. Nosso registro no PeeringDB está atualizado.", -"peering_inbox.hire_it_mo_mo":"Contratar {mo}/mês", -"peering_inbox.inbox_zero_enjoy_it_while_it":"Caixa zerada. Aproveite enquanto dura.", -"peering_inbox.keep_it_down":"Deixar fora", -"peering_inbox.kept_who_down_at_ix_for":"Deixou {who} fora no {ix} por “crescimento suspeito”. Eles tinham ganhado um cliente.", -"peering_inbox.kept_who_down_at_ix_it":"Deixou {who} fora no {ix}: era um vazamento de rotas. Acertou em cheio.", -"peering_inbox.large_peering_model":"Large Peering Model", -"peering_inbox.large_peering_model_is_answering":"Large Peering Model está respondendo seus e-mails", -"peering_inbox.max_prefix_limit_hit_who_at":"Limite de max-prefix estourado: {who} no {ix}.
A sessão fica fora até você dar uma olhada.", -"peering_inbox.max_prefix_limit_hit_who_at_5c56":"Limite de max-prefix estourado: {who} no {ix}", -"peering_inbox.mostly_ignores_email":"Ignora quase todos os e-mails", -"peering_inbox.n_day_ago":{"one":"há {n} dia","other":"há {n} dias"}, -"peering_inbox.n_unanswered":{"one":"{n} sem resposta","other":"{n} sem resposta"}, -"peering_inbox.no_mail_yet_buy_an_ix":"Nenhum e-mail ainda. Compre uma porta de IX que eles chegam.", -"peering_inbox.nobody_asks_and_no_route_servers":"Ninguém pede, e sem route servers. Os clientes ficam sabendo que você é difícil de alcançar, então menos deles ligam, e sua reputação afunda.", -"peering_inbox.open_to_all":"Aberta a todos", -"peering_inbox.opened_a_ticket_with_itself_to":"Abriu um chamado para si mesma para revisar as próprias decisões. Aprovou todas.", -"peering_inbox.peering_request_fifth_attempt_is":"Pedido de peering, quinta tentativa. Tem alguém aí?", -"peering_inbox.peeringdb_last_updated_n_year_ago":{"one":"PeeringDB atualizado há {n} ano","other":"PeeringDB atualizado há {n} anos"}, -"peering_inbox.peeringdb_updated_last_month":"PeeringDB atualizado no mês passado", -"peering_inbox.please_configure_sessions_with_us_at":"Por favor configurem as sessões com a gente no {ix}. Nós faremos as nossas semana que vem, ou na outra.", -"peering_inbox.price_year_it_never_sleeps_never":"{price}/ano. Nunca dorme, nunca reclama e erra com frequência.", -"peering_inbox.raise_all_max_prefix_limits":"Aumentar todos os limites de max-prefix", -"peering_inbox.raise_the_limit":"Aumentar o limite", -"peering_inbox.raised_the_max_prefix_limit_for":"Aumentou o limite de max-prefix de {who} no {ix} para {n}. Pareciam simpáticos.", -"peering_inbox.raised_the_max_prefix_limit_for_7b4b":"Aumentou o limite de max-prefix de {who} no {ix}. Corretamente, desta vez.", -"peering_inbox.replied_to_a_peering_request_with":"Respondeu a um pedido de peering com um haicai sobre BGP. Nenhuma resposta ainda.", -"peering_inbox.session_with_who_is_back_up":"A sessão com {who} voltou.
Novo limite: {n} prefixos. Eles prometem atualizar o PeeringDB.", -"peering_inbox.signed_you_up_for_a_webinar":"Inscreveu você num webinar sobre “Peering na era da IA”.", -"peering_inbox.that_was_a_route_leak_who":"Era um vazamento de rotas.
{who} anunciava {n} prefixos: uma tabela completa. Da próxima vez, deixe fora.", -"peering_inbox.the_session_stays_down_who_will":"A sessão continua fora.
{who} vai atualizar o PeeringDB e pedir de novo. Algum dia.", -"peering_inbox.their_peeringdb_says_lim_last":{"one":"O PeeringDB deles diz {lim}, atualizado há {n} ano.","other":"O PeeringDB deles diz {lim}, atualizado há {n} anos."}, -"peering_inbox.tidied_up_a_session_it_decided":"Fez uma faxina nas sessões que achou inúteis: desfez o peering com {who} no {ix}.", -"peering_inbox.updated_your_peeringdb_record_your":"Atualizou seu registro no PeeringDB. O telefone do seu NOC agora é de uma pizzaria.", -"peering_inbox.we_noticed_you_are_at_ix":"Vimos que vocês estão no {ix}. Nós também. Vamos?", -"peering_inbox.who_asked_a_mailing_list_whether":"{who} perguntou numa lista de e-mails se alguém tem um contato que funcione na {me}.
O pedido de peering deles ficou um mês na sua caixa de entrada.", -"peering_inbox.who_at_ix_was_sending_a":"{who} no {ix} estava mandando uma tabela completa, e o limite de max-prefix era a única coisa que segurava. Com o limite aumentado, os prefixos da {net} apontam para o porão deles. O tráfego para a {net} via trânsito vai para um buraco negro por alguns dias.", -"peering_inbox.wrote_a_thousand_word_apology_to":"Escreveu um pedido de desculpas de mil palavras para uma rede com quem você nunca fez peering.", +"peering_desk.closed_desc":"Todo pedido de peering é recusado, e sem route servers. Os clientes ficam sabendo que você é difícil de alcançar, então menos deles ligam.", +"peering_desk.n_more_exchanges":{"one":"mais {n} exchange","other":"mais {n} exchanges"}, +"peering_desk.n_new_sessions_at_ix":{"one":"Mesa de peering: {n} sessão nova em {ix} ({pol}).","other":"Mesa de peering: {n} sessões novas em {ix} ({pol})."}, +"peering_desk.n_new_sessions_at_ix_declined":{"one":"Mesa de peering: {n} sessão nova em {ix}, {d} recusados ({pol}).","other":"Mesa de peering: {n} sessões novas em {ix}, {d} recusados ({pol})."}, +"peering_desk.n_requests_declined":{"one":"Mesa de peering: {n} pedido recusado ({pol}).","other":"Mesa de peering: {n} pedidos recusados ({pol})."}, +"peering_desk.open_desc":"Toda rede que pede ganha uma sessão, e os route servers funcionam.", +"peering_desk.open_to_all":"Aberta a todos", +"peering_desk.selective_desc":"Redes pequenas do exchange e recém-chegadas com PeeringDB em dia ganham uma sessão; o resto é recusado em silêncio. Sem route servers: peça as redes que quiser em cada exchange.", "peering_policy.a_new_vp_wants_to_monetise":"Um novo VP quer “monetizar a interconexão” neste mercado.", "peering_policy.already_reach_you_through_your":"Já chegam até você pelo seu provedor de transit aqui e acham que está ótimo.", "peering_policy.moved_everything_in_this_city_to":"Passaram tudo nesta cidade para PNI. Leia a página deles no PearingDB, todas as 40 páginas.", @@ -3309,7 +3242,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Desconecte algo primeiro.
Há {used} portas em uso, e com um router a menos só teria {max}.", "rules.a_billion_dollars_every_unlock_your":"Um bilhão de dólares, tudo desbloqueado, o seu próprio cabo submarino.", "rules.a_cut_now_and_then":"Um corte de vez em quando.", -"rules.a_third_of_the_outages_no_ddos":"Um terço das falhas, sem DDoS. PNIs e obras em dias. Sem caixa de entrada, sem escassez, sem rotas esgotadas, sem de-peering.", +"rules.a_third_of_the_outages_no_ddos_pnis":"Um terço das falhas, sem DDoS. PNIs e obras em dias. Sem escassez, sem rotas esgotadas, sem de-peering.", "rules.bgp_at_3_a_m":"BGP às 3 da manhã", "rules.change_freeze":"Congelamento de mudanças", "rules.chaos_calm":"Calmo", @@ -3326,7 +3259,7 @@ "rules.on_call":"De plantão", "rules.one_small_network_one_tricky_goal":"Uma rede pequena, um objetivo traiçoeiro.", "rules.puzzle":"Quebra-cabeça", -"rules.real_lead_times_real_outages_a":"Prazos reais, falhas reais, uma caixa de peering cheia. O jogo clássico.", +"rules.real_lead_times_real_outages_a_real":"Prazos reais, falhas reais, um mercado real. O jogo clássico.", "rules.rules_are_locked_for_this_network":"{rules}: as regras estão travadas para esta rede.", "rules.the_real_thing_your_pager_has":"O jogo de verdade. O seu pager tem opiniões.", "rules.your_pager_never_sleeps":"O seu pager nunca dorme.", @@ -3460,9 +3393,7 @@ "sites_peering_caches.bgp_session_established":"Sessão BGP estabelecida.", "sites_peering_caches.cache_installed_in_city_net_shipped":"{cache} instalado em {city}!
{net} mandou de graça. Você paga {mo}/mês de energia.", "sites_peering_caches.could_you_resend_the_loa_you":"“Pode reenviar a LOA?”
Você já mandou quatro vezes.", -"sites_peering_caches.hello_i_am_large_peering_model":"Olá! Eu sou o Large Peering Model. Li sua caixa de entrada e já tenho opiniões.", "sites_peering_caches.it_is_with_the_provisioning_team":"“Está com o time de provisionamento.”
Ninguém nunca conheceu o time de provisionamento.", -"sites_peering_caches.large_peering_model_is_hired_your":"Large Peering Model contratado.
Sua caixa de entrada agora é problema dele. {price} por ano, cobrados por mês.", "sites_peering_caches.n_new_session_at_ix_small":{"one":"{n} nova sessão em {ix}.
Redes pequenas, mas somam, e todas contam para o clube.","other":"{n} novas sessões em {ix}.
Redes pequenas, mas somam, e todas contam para o clube."}, "sites_peering_caches.net_accepted":"{net} aceitou!", "sites_peering_caches.net_declined_the_pni_why":"{net} recusou o PNI.
{why}", @@ -3470,11 +3401,8 @@ "sites_peering_caches.net_does_not_do_port_pnis":"{net} não faz PNI de {port}.
Nada abaixo de 100G. Volte com mais tráfego, ou uma óptica maior.", "sites_peering_caches.net_says_not_yet_send_them":"{net} diz: ainda não.
Mande {min}+ Gbps pra eles primeiro.", "sites_peering_caches.pni_with_net_ordered_eta_a":"PNI com {net} encomendada.
{eta}. Um cross-connect em {dc}, assim que alguém achar a LOA.", -"sites_peering_caches.raised_n_max_prefix_limits_all":"{n} limites de max-prefix aumentados.
Tudo crescimento, nenhum vazamento. Sorte.", -"sites_peering_caches.raised_n_max_prefix_limits_one":{"one":"{n} limites de max-prefix aumentados.
Um deles era um vazamento de rotas. Está no NOC agora.","other":"{n} limites de max-prefix aumentados.
{k} deles eram vazamentos de rotas. Estão no NOC agora."}, "sites_peering_caches.second_lag_member_added_one_member":"Segundo membro do LAG adicionado.
Agora tem um membro em cada prédio, então um prédio apagado só derruba metade da porta.", "sites_peering_caches.second_site_live_in_city_b":"Segundo site ativo em {city}.
{b} está ligado a {a} pelo seu próprio anel metro. Mova alguns uplinks pra lá nas abas Transit e Peering.", -"sites_peering_caches.the_ai_is_gone_it_left":"A IA foi embora.
Deixou um documento de transição de 40 páginas. Ele fala principalmente dela mesma.", "sites_peering_caches.they_checked_your_pearingdb_page_and":"Eles olharam sua página no PearingDB e curtiram os números de tráfego.", "sites_peering_caches.we_are_waiting_on_the_colo":"“Estamos esperando o colo fazer o cross-connect.”
O colo diz que está esperando por eles.", "sites_peering_caches.your_account_manager_found_the_order":"Seu gerente de contas achou o pedido embaixo de uma mesa.
Está um mês mais perto.", @@ -3496,6 +3424,7 @@ "slots.last_played_ago":"Jogada pela última vez {ago}", "slots.load_the_newest_version":"Carregar a versão mais nova", "slots.more_for_name":"Mais para {name}", +"slots.n_day_ago":{"one":"há {n} dia","other":"há {n} dias"}, "slots.n_h_ago":{"one":"há {n} h","other":"há {n} h"}, "slots.name_is_open_in_another_window":"{name} está aberta em outra janela", "slots.name_is_waiting_in_your_other":"{name} está esperando na sua outra janela.
Vá para ela para continuar jogando.", @@ -3519,7 +3448,6 @@ "slots.this_window_stopped_saving_so_it":"Uma versão mais nova foi salva em outra janela, então esta parou de salvar em vez de sobrescrevê-la.", "slots.two_windows_one_network":"Duas janelas, uma rede", "slots.your_networks":"Suas redes", -"slots.your_networks_switch_or_start_another":"Suas redes trocar ou começar outra", "slots.your_other_networks_share_this_browser":"Suas outras redes dividem o armazenamento deste navegador. Exporte as que quiser manter e apague-as aqui para abrir espaço.", "sold_out.a_hyperscaler_bought_every_wave_of":"Um hyperscaler comprou semana passada todas as ondas desse tamanho nesta rota.", "sold_out.not_big_enough_yet_list":"Você ainda não é grande o bastante: {list}", diff --git a/src/game/40-progress/30-rules.js b/src/game/40-progress/30-rules.js index 656677e..12f7c92 100644 --- a/src/game/40-progress/30-rules.js +++ b/src/game/40-progress/30-rules.js @@ -3,15 +3,15 @@ these rules, not separate code: Normal comes as Change Freeze, On-call (the classic game) and BGP at 3 a.m.; Sandbox and Puzzles are presets too. Saves without rules load as On-call, so nothing changes for them. Scenarios and the weekly challenge run on On-call plus their own S.scn.rules (scnRule()). */ -const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder',mods:[]}; -const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],inbox:[true,false],money:['normal','infinite'],gates:['ladder','open']}; +const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder',mods:[]}; +const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],money:['normal','infinite'],gates:['ladder','open']}; // i: icon, n: name, d: the one-line joke, x: what is different, in small print. const PRESETS={ - freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos'),clock:true,chaos:'calm',lead:'quick',market:false,inbox:false,money:'normal',gates:'ladder'}, - oncall:{i:'📟',n:tr('rules.on_call'),d:tr('rules.the_real_thing_your_pager_has'),x:tr('rules.real_lead_times_real_outages_a'),clock:true,chaos:'normal',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder'}, - bgp:{i:'🔥',n:tr('rules.bgp_at_3_a_m'),d:tr('rules.everything_is_on_fire_and_it'),x:tr('rules.more_and_longer_outages_more_ddos'),clock:true,chaos:'spicy',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder'}, - sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,inbox:true,money:'infinite',gates:'open'}, - puzzle:{i:'🧩',n:tr('rules.puzzle'),d:tr('rules.one_small_network_one_tricky_goal'),x:tr('rules.no_clock_no_bills_nothing_breaks'),clock:false,chaos:'none',lead:'quick',market:false,inbox:false,money:'normal',gates:'open'}, + freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos_pnis'),clock:true,chaos:'calm',lead:'quick',market:false,money:'normal',gates:'ladder'}, + oncall:{i:'📟',n:tr('rules.on_call'),d:tr('rules.the_real_thing_your_pager_has'),x:tr('rules.real_lead_times_real_outages_a_real'),clock:true,chaos:'normal',lead:'real',market:true,money:'normal',gates:'ladder'}, + bgp:{i:'🔥',n:tr('rules.bgp_at_3_a_m'),d:tr('rules.everything_is_on_fire_and_it'),x:tr('rules.more_and_longer_outages_more_ddos'),clock:true,chaos:'spicy',lead:'real',market:true,money:'normal',gates:'ladder'}, + sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,money:'infinite',gates:'open'}, + puzzle:{i:'🧩',n:tr('rules.puzzle'),d:tr('rules.one_small_network_one_tricky_goal'),x:tr('rules.no_clock_no_bills_nothing_breaks'),clock:false,chaos:'none',lead:'quick',market:false,money:'normal',gates:'open'}, }; const NORMAL_PRESETS=['freeze','oncall','bgp']; // How often things break, against the classic game. Spicy outages also last half as long again. @@ -42,7 +42,7 @@ function stretchInc(i){if(rule('chaos')!=='spicy'||!i||!(i.until>S.day)||i.start else if(['crash','power','oops','cleaner','maint','shutdown'].includes(T))f(S.pops[r],'down'); else if(T==='ring')f(S.pops[r],'ringcut');else if(T==='ac')f(S.pops[r],'hot'); else if(T==='transit'||T==='prepend')f(S.transit.find(t=>t.id===r),'down'); - else if((T==='ixloop'||T==='maxpfx')&&E.ixdown)f(E.ixdown,r);else if(T==='fabric'&&E.fab)f(E.fab,r); + else if(T==='ixloop'&&E.ixdown)f(E.ixdown,r);else if(T==='fabric'&&E.fab)f(E.fab,r); else if(T==='lacp'){const [k,...x]=String(r).split(':'),id=x.join(':');f(k==='ix'?E.ixlacp&&E.ixlacp[id]:(k==='t'?S.transit:S.pni).find(o=>o.id===id)?.lacp,'until');} else if(T==='rpki'||T==='hijack')f(E.rpki,'until');else if(T==='leak'||T==='pmtud')f(E[T],'until');else if(T==='krroute'||T==='depeer')f(E,T); else if(T==='ddos')f(ddosAll(S,false).find(a=>a.id===i.atk),'until');} diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index a625c42..0bad8cd 100644 --- a/src/game/60-features/80-new-game.js +++ b/src/game/60-features/80-new-game.js @@ -1,6 +1,6 @@ function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, ltv:2,t1v:3,auV:1,ops:opsNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, - done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0}; + done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0}; } diff --git a/src/game/70-rules/20-exchanges.js b/src/game/70-rules/20-exchanges.js index 7a27f83..964a129 100644 --- a/src/game/70-rules/20-exchanges.js +++ b/src/game/70-rules/20-exchanges.js @@ -25,7 +25,7 @@ function ixCap(c){return ixLagF(c)*(S.myIx[c]?myFab(c).g*(myIxLive(c)?1:0):liveC function ixSessions(c){ const s=new Set(); if(S.ixp[c]===undefined)return s; for(const id of ixMembers(c)){const n=NET[id]; - if(S.peers[id+'@'+c]&&!snub(id,c)&&!(isRemote(c)&&noRemote(id))&&!mpDown(id,c))s.add(id); + if(S.peers[id+'@'+c]&&!snub(id,c)&&!(isRemote(c)&&noRemote(id)))s.add(id); else if(S.rs[c]&&n.pol==='open'&&ppol()==='open')s.add(id); else if(S.myIx[c]&&(n.pol==='open'||n.pol==='selective'))s.add(id);} return s; diff --git a/src/game/70-rules/40-peering-desk.js b/src/game/70-rules/40-peering-desk.js new file mode 100644 index 0000000..e8369bd --- /dev/null +++ b/src/game/70-rules/40-peering-desk.js @@ -0,0 +1,30 @@ +/* ---------- The peering desk ---------- + Every exchange port brings peering requests. Nobody answers them by hand any more: your peering policy does. + Open accepts everyone, Selective accepts the networks worth peering with and quietly declines the rest, Closed + declines them all. Once a week the NOC log gets one folded line about it. */ +const PPOL=['open','selective','closed'],ppol=()=>(S&&PPOL.includes(S.ppol))?S.ppol:'open'; +const PPOL_N={open:N_('peering_desk.open_to_all'),selective:N_('common.selective'),closed:N_('common.closed')}; +const PPOL_D={open:N_('peering_desk.open_desc'),selective:N_('peering_desk.selective_desc'),closed:N_('peering_desk.closed_desc')}; +// How often someone asks, against Open: a selective or closed network gets fewer requests. +const PDESK_ASK={open:1,selective:0.7,closed:0.5},PDESK_IX=12; +const pdeskNew=w=>({w,a:0,d:0,ix:[]}); +// Who is worth it: a real small network on the exchange, or a newcomer whose PeeringDB is up to date. +const pdeskWant=(p,net,fresh)=>p==='open'||(p==='selective'&&(!!net||fresh)); +function peeringDeskDay(d){const w=Math.floor(d/7);let D=S.pdesk; + // A new week: last week's tally becomes one line in the NOC log. + if(!D||D.w!==w){if(D&&D.w=Math.min(0.9,0.15*ixs.length)*PDESK_ASK[p])return; + const c=pick(ixs),real=ixMembers(c).filter(id=>{const n=NET[id];return !S.peers[id+'@'+c]&&!merged(id)&&n.type!=='t1'&&n.type!=='cdn'&&n.pol!=='paid'&&n.share<=0.006;}); + const net=real.length&&Math.random()<0.4?pick(real):null,fresh=Math.random()>=0.6; + if(!pdeskWant(p,net,fresh)){D.d++;return;} + if(net)S.peers[net+'@'+c]=true;D.a++;if(!D.ix.includes(c)&&D.ix.length4?3:4).map(ixName);if(x.ix.length>4)nm.push(trn('peering_desk.n_more_exchanges',x.ix.length-3)); + let ix;try{ix=new Intl.ListFormat(LANG,{type:'conjunction'}).format(nm);}catch(e){ix=nm.join(', ');} + return x.d?trn('peering_desk.n_new_sessions_at_ix_declined',x.a,{ix,d:x.d,pol}):trn('peering_desk.n_new_sessions_at_ix',x.a,{ix,pol});} +// The policy picker, in the Networks tab. +function pdeskCard(){const p=ppol(),r=S.pdeskRep; + return `
🤝 ${tr('common.peering_policy')}: ${tr(PPOL_N[p])}
${PPOL.map(x=>btn(tr(PPOL_N[x]),'peerPol',{p:x},p===x?'sm':'ghost sm')).join('')}
+

${tr(PPOL_D[p])}

${r&&r.w>=Math.floor(S.day/7)-1&&(r.a||r.d)?`

${esc(pdeskLine(r))}

`:''}
`;} diff --git a/src/game/70-rules/40-peering-inbox.js b/src/game/70-rules/40-peering-inbox.js deleted file mode 100644 index d679f32..0000000 --- a/src/game/70-rules/40-peering-inbox.js +++ /dev/null @@ -1,83 +0,0 @@ -/* ---------- The peering inbox ---------- - Every exchange port brings mail: peering requests from networks nobody has heard of, and sessions that drop - because someone's PeeringDB says 50 prefixes and they now send 400 (or a full table). Answer it, or hire an AI. */ -const PPOL_N={open:N_('peering_inbox.open_to_all'),selective:N_('common.selective'),closed:N_('common.closed')},PPOL_D={open:N_('peering_inbox.everyone_who_asks_gets_a_session'),selective:N_('peering_inbox.fewer_requests_and_you_answer_them'),closed:N_('peering_inbox.nobody_asks_and_no_route_servers')}; -const AI_MO=Math.round(20e6/12),INBOX_MAX=80,IBX_LEAKS=['nfx','ggl','fbk','amz','msf']; -const TINY=['Basement Broadband','Uncle Dave’s WISP','Fibre Fiesta','Raspberry Pi Transit','Vanity ASN Ltd','Moonshot Crypto Hosting','Minecraft Collective','Bob’s Bits','Homelab Heroes','Hackerspace Uplink','Tiny Tower Networks','Pigeon Post IP','Retro BBS Revival','Overkill Home Network','Two Guys and a Rack','Big Dreams Small Prefix','Mesh-y Business','Garden Shed Datacenter','Carrier-Grade NAT Fan Club','LIR in a Box','Yet Another VPN','Grandma’s Fibre Co-op','Seedbox Society','The /24 That Could']; -const REQ_SAY=[N_('peering_inbox.hi_we_would_like_to_peer'),N_('peering_inbox.dear_sir_or_madam_please_peer'),N_('peering_inbox.we_noticed_you_are_at_ix'),N_('peering_inbox.hello_please_find_attached_our'),N_('peering_inbox.peering_request_fifth_attempt_is'),N_('peering_inbox.hey_quick_one_can_you_peer'),N_('peering_inbox.greetings_we_are_a_fast_growing'),N_('peering_inbox.please_configure_sessions_with_us_at')]; -const IBX_AI=[N_('peering_inbox.replied_to_a_peering_request_with'),N_('peering_inbox.signed_you_up_for_a_webinar'),N_('peering_inbox.opened_a_ticket_with_itself_to'),N_('peering_inbox.wrote_a_thousand_word_apology_to'),N_('peering_inbox.updated_your_peeringdb_record_your'),N_('peering_inbox.asked_netchill_s_peering_team_to')]; -function ibx(){if(!S.inbox||typeof S.inbox!=='object')S.inbox={items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0};return S.inbox;} -// Reputation nudges selective networks by up to 10% either way: worth caring about, never a wall. -// Your peering policy. Open: everyone who asks gets a session and the route servers work. Selective: fewer requests, -// you answer them yourself, and no route servers, so you go and ask networks at each exchange. Closed: nobody asks, -// and customers hear that you are hard to reach. -const PPOL=['open','selective','closed'],ppol=()=>(S&&S.inbox&&PPOL.includes(S.inbox.pol))?S.inbox.pol:'open'; -const repMul=()=>1-clamp((S.inbox&&S.inbox.rep)||0,-10,5)*0.01; -const repName=r=>r>=1?tr('common.responsive'):r>=-2?tr('common.average'):r>=-6?tr('peering_inbox.mostly_ignores_email'):tr('common.black_hole'); -const ibxOpen=()=>S.inbox?S.inbox.items.length:0,ibxUrgent=()=>S.inbox?S.inbox.items.filter(x=>x.k==='mp').length:0; -const mpDown=(id,c)=>{const t=S.inbox&&S.inbox.down[id+'@'+c];return !!t&&t>S.day;}; -const ibxWho=x=>x.net?NET[x.net].name:x.nm,ibxAsn=x=>x.net?NET[x.net].asn:x.asn; -function ibxLog(m,a){const I=ibx();I.log.unshift({d:S.day,m,a:a||{}});I.log.length=Math.min(I.log.length,40);} -function inboxDay(d){if(!rule('inbox'))return;const I=ibx(),ixs=Object.keys(S.ixp); - // new peering requests: more exchange ports, more mail - if(ixs.length&&Math.random(){const n=NET[id];return !set.has(id)&&!merged(id)&&n.type!=='t1'&&n.type!=='cdn'&&n.pol!=='paid'&&n.share<=0.006&&!I.items.some(x=>x.net===id&&x.ix===c);}); - const it={id:++I.seq,k:'req',ix:c,day:d,stale:Math.random()<0.6,yrs:1+Math.floor(Math.random()*9),say:Math.floor(Math.random()*REQ_SAY.length)}; - if(real.length&&Math.random()<0.4)it.net=pick(real);else{it.nm=pick(TINY);it.asn=Math.random()<0.05?64512+Math.floor(Math.random()*1000):200000+Math.floor(Math.random()*200000);} - I.items.push(it);if(ppol()==='open')ibxAnswer(it.id,'accept',true);} - if(ppol()==='closed')I.rep=Math.max(-6,I.rep-0.05); - // max-prefix: someone grew past what their PeeringDB says, or leaked a full table - const ses=Object.keys(S.peers).filter(k=>{const n=NET[k.split('@')[0]];return n&&n.type!=='cdn'&&n.type!=='t1'&&!mpDown(...k.split('@'));}).map(k=>({key:k,net:k.split('@')[0],ix:k.split('@')[1]})) - .concat(Object.keys(I.tiny).map(a=>({key:'t'+a,nm:I.tiny[a].nm,asn:+a,ix:I.tiny[a].ix,stale:I.tiny[a].stale}))); - if(ses.length&&Math.random()y.k==='mp'&&y.key===x.key)){ - const lim=pick([10,20,50,100,200,500,1000]),leak=Math.random()<0.3,yrs=1+Math.floor(Math.random()*9); - I.items.push({id:++I.seq,k:'mp',key:x.key,net:x.net,nm:x.nm,asn:x.asn,ix:x.ix,day:d,lim,got:leak?940000+Math.floor(Math.random()*90000):Math.ceil(lim*(1.15+Math.random()*1.6)),leak,yrs}); - // A session that blows its limit is down for at most a few weeks: the other side eventually notices too. - if(x.net){I.down[x.key]=d+20+Math.floor(Math.random()*20);toast(tr('peering_inbox.max_prefix_limit_hit_who_at',{who:esc(ibxWho(x)),ix:esc(ixName(x.ix))}),'bad',[{l:tr('common.inbox'),act:'inbox',args:{}}]);}}} - // unanswered mail: requests go stale and people start asking around about you - for(const x of I.items){if(x.k==='mp')I.rep-=0.05;else if(d-x.day===14)x.bump=1;} - // A max-prefix alert nobody answers resolves itself in the end: the other side raises it, or gives up. - I.items=I.items.filter(x=>x.k!=='mp'||(x.net?(I.down[x.key]||0)>d:d-x.day<=30)); - const old=I.items.filter(x=>x.k==='req'&&d-x.day>30);if(old.length){I.rep-=0.25*old.length;I.items=I.items.filter(x=>!old.includes(x)); - if(old.some(x=>x.net))toast(tr('peering_inbox.who_asked_a_mailing_list_whether',{who:esc(ibxWho(old.find(x=>x.net))),me:esc(S.name)}),'bad',[{l:tr('common.inbox'),act:'inbox',args:{}}]);} - while(I.items.length>INBOX_MAX){const i=I.items.findIndex(x=>x.k==='req');if(i<0)break;I.items.splice(i,1);I.rep-=0.5;} - I.rep=clamp(I.rep,-10,5); - if(I.bot)inboxBot();} -// Answer one item. a: accept | decline | raise | keep. Returns false when the item is gone. -function ibxAnswer(id,a,bot){const I=ibx(),i=I.items.findIndex(x=>x.id===id);if(i<0)return false;const x=I.items[i];I.items.splice(i,1);const who=ibxWho(x),ix=ixName(x.ix); - if(x.k==='req'){if(a==='accept'){if(x.net){if(S.ixp[x.ix]!==undefined)S.peers[x.net+'@'+x.ix]=true;}else if(Object.keys(I.tiny).length<200)I.tiny[x.asn]={nm:x.nm,ix:x.ix,stale:!!x.stale};I.rep+=0.3;}else I.rep+=0.2;} - else if(a==='raise'){delete I.down[x.key];if(x.leak){const n=pick(IBX_LEAKS);S.ev.leak={net:n,until:S.day+4}; - addInc({type:'leak',ref:n,until:S.day+4,msg:tr('peering_inbox.who_at_ix_was_sending_a',{who,ix,net:NET[n].name}),cost:0}); - if(!bot)toast(tr('peering_inbox.that_was_a_route_leak_who',{who:esc(who),n:x.got.toLocaleString()}),'bad');I.rep-=1;} - else{I.rep+=0.3;if(!bot)toast(tr('peering_inbox.session_with_who_is_back_up',{who:esc(who),n:Math.ceil(x.got*1.5).toLocaleString()}),'good');}} - else{const back=S.day+(x.leak?3:10)+Math.floor(Math.random()*(x.leak?8:21));if(x.net)I.down[x.key]=back;I.rep+=x.leak?0.3:0.1; - if(!bot)toast(x.leak?tr('peering_inbox.good_call_it_was_a_route',{who:esc(who)}):tr('peering_inbox.the_session_stays_down_who_will',{who:esc(who)}),x.leak?'good':'');} - I.rep=clamp(I.rep,-10,5);return true;} -// The AI agent clears the inbox every day. It is fast, polite and wrong about a third of the time. -function inboxBot(){const I=ibx();let acc=0,dec=0; - for(const x of I.items.slice()){const oops=Math.random()<0.3; - if(x.k==='req'){const want=!x.stale||!!x.net;const a=(want!==oops)?'accept':'decline';ibxAnswer(x.id,a,true);a==='accept'?acc++:dec++;if(oops&&a==='decline'&&x.net)ibxLog(N_('peering_inbox.declined_who_at_ix_not_a'),{who:ibxWho(x),ix:ixName(x.ix)});} - else{const a=(x.leak!==oops)?'keep':'raise';ibxAnswer(x.id,a,true); - if(a==='raise'&&x.leak)ibxLog(N_('peering_inbox.raised_the_max_prefix_limit_for'),{who:ibxWho(x),ix:ixName(x.ix),n:Math.ceil(x.got*1.5).toLocaleString()}); - else if(a==='keep'&&!x.leak)ibxLog(N_('peering_inbox.kept_who_down_at_ix_for'),{who:ibxWho(x),ix:ixName(x.ix)}); - else ibxLog(a==='raise'?N_('peering_inbox.raised_the_max_prefix_limit_for_7b4b'):N_('peering_inbox.kept_who_down_at_ix_it'),{who:ibxWho(x),ix:ixName(x.ix)});}} - if(acc||dec)ibxLog(N_('peering_inbox.answered_your_mail_a_accepted_d'),{a:acc,d:dec}); - if(Math.random()<0.01){const ks=Object.keys(S.peers);if(ks.length){const k=pick(ks),[id,c]=k.split('@');delete S.peers[k];ibxLog(N_('peering_inbox.tidied_up_a_session_it_decided'),{who:NET[id].name,ix:ixName(c)});}} - if(Math.random()<0.08)ibxLog(pick(IBX_AI),{});} -function inboxModal(){const I=ibx(),items=I.items.slice().sort((a,b)=>(b.k==='mp')-(a.k==='mp')||b.day-a.day),reqs=items.filter(x=>x.k==='req').length,mps=items.length-reqs; - const age=x=>{const n=S.day-x.day;return n?trn('peering_inbox.n_day_ago',n):tr('common.today_4203');}; - const pdb=x=>x.stale?trn('peering_inbox.peeringdb_last_updated_n_year_ago',x.yrs):tr('peering_inbox.peeringdb_updated_last_month'); - const card=x=>x.k==='mp'?`
⚠️ ${tr('peering_inbox.max_prefix_limit_hit_who_at_5c56',{who:esc(ibxWho(x)),ix:esc(ixName(x.ix))})}
-
AS${ibxAsn(x)} · ${age(x)}

${tr('peering_inbox.configured_lim_prefixes_received_got',{lim:x.lim.toLocaleString(),got:x.got.toLocaleString()})} ${trn('peering_inbox.their_peeringdb_says_lim_last',x.yrs,{lim:x.lim.toLocaleString()})}

-
${btn(tr('peering_inbox.raise_the_limit'),'inboxAct',{id:x.id,a:'raise'},'sm')}${btn(tr('peering_inbox.keep_it_down'),'inboxAct',{id:x.id,a:'keep'},'ghost sm')}
` - :`
${esc(ibxWho(x))} AS${ibxAsn(x)}${x.bump?` ${tr('common.bumped')}`:''}
${esc(ixName(x.ix))} · ${age(x)} · ${pdb(x)}
-

“${esc(tr(REQ_SAY[x.say]||REQ_SAY[0],{ix:ixName(x.ix)}))}”

${btn(tr('common.accept'),'inboxAct',{id:x.id,a:'accept'},'sm')}${btn(tr('common.decline'),'inboxAct',{id:x.id,a:'decline'},'ghost sm')}
`; - openModal(`
${tr('common.peering_inbox')}

📬 ${trn('peering_inbox.n_unanswered',items.length)}

-

${tr('peering_inbox.every_exchange_port_brings_mail')}

-
${tr('common.your_reputation')}${repName(I.rep)}
-
${tr('common.peering_policy')}${tr(PPOL_N[ppol()])}
${PPOL.map(p=>btn(tr(PPOL_N[p]),'inboxPol',{p},ppol()===p?'sm':'ghost sm')).join('')}

${tr(PPOL_D[ppol()])}

-
${I.bot?`
🤖 ${tr('peering_inbox.large_peering_model_is_answering')}
${tr('peering_inbox.price_year_it_never_sleeps_never',{price:fmt$(20e6)})}
- ${I.log.length?`
${I.log.slice(0,8).map(e=>esc(tr('peering_inbox.day_d',{d:e.d})+': '+tr(e.m,e.a))).join('\n')}
`:''}
${btn(tr('peering_inbox.fire_the_ai'),'inboxBot',{on:0},'ghost sm')}
` - :`
🤖 ${tr('peering_inbox.large_peering_model')}
${tr('peering_inbox.an_ai_agent_that_answers_every',{price:fmt$(20e6)})}
${btn(tr('peering_inbox.hire_it_mo_mo',{mo:fmt$(AI_MO)}),'inboxBot',{on:1},'aibtn sm',S.cash`}
- ${reqs>1||mps>1?`
${reqs>1?btn(tr('peering_inbox.accept_all_requests'),'inboxAll',{a:'accept'},'sm')+btn(tr('peering_inbox.decline_all_requests'),'inboxAll',{a:'decline'},'ghost sm'):''}${mps>1?btn(tr('peering_inbox.raise_all_max_prefix_limits'),'inboxRaiseAll',{},'sm'):''}
`:''} - ${items.length?items.slice(0,40).map(card).join(''):`

${Object.keys(S.ixp).length?tr('peering_inbox.inbox_zero_enjoy_it_while_it'):tr('peering_inbox.no_mail_yet_buy_an_ix')}

`}`);} diff --git a/src/game/70-rules/70-sold-out.js b/src/game/70-rules/70-sold-out.js index eda5b0c..6ab07bc 100644 --- a/src/game/70-rules/70-sold-out.js +++ b/src/game/70-rules/70-sold-out.js @@ -16,7 +16,7 @@ function peerOk(id,via,city){ if(via==='ix'&&city&&isRemote(city)&&noRemote(id))return {ok:false,remote:true,why:REMOTE_WHY[hstr(id)%REMOTE_WHY.length]}; if(n.pol==='open')return {ok:true}; // In the Cogentle Spat, Goggle's peering desk wants eight times the usual traffic first, so cheap Cogentle-only transit really costs you Goggle (playtest). - if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*repMul()*(id==='ggl'&&scnRule('spat')?8:1));return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};} + if(n.pol==='selective'){const need=Math.round((via==='pni'?n.minPni:n.minIx)*confBoost(id)*(id==='ggl'&&scnRule('spat')?8:1));return dem>=need?{ok:true}:{ok:false,why:tr('sold_out.wants_need_gbps_of_traffic_from',{need,dem:dem.toFixed(1)})};} if(n.pol==='paid'&&paidFree(n))return via==='pni'?{ok:true,free:true}:{ok:false,why:tr('sold_out.peers_with_you_for_free_now')}; if(n.pol==='paid')return via==='pni'?{ok:true,fee:n.paidFee}:{ok:false,why:n.perG?tr('sold_out.sender_pays_a_paid_pni_only',{fee:fmt$(n.paidFee),g:fmt$(n.perG)}):tr('sold_out.paid_peering_only_over_a_pni')}; if(n.type!=='t1'){if(via!=='pni')return {ok:false,why:tr('sold_out.only_peers_over_pnis_and_only')};const need=Math.round(60*confBoost(id));return dem>=need||isTier2()?{ok:true}:{ok:false,why:tr('sold_out.wants_you_to_be_a_tier',{need,dem:dem.toFixed(1)})};} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index f2b08ba..eba967a 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -291,7 +291,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)+(S.ops&&S.ops.intern?INTERN_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.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*arpuOf(c);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 6ad5602..71cdda4 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -35,12 +35,10 @@ function sanitize(s){ {const H=s.hw&&typeof s.hw==='object'&&!Array.isArray(s.hw)?s.hw:{},o={};const sh=H.shock,lk=H.lock; if(sh&&typeof sh==='object'&&own(HW_SHOCK,sh.k))o.shock={k:sh.k,until:num(sh.until,0),mul:clamp(num(sh.mul,1),1,2)}; if(lk&&typeof lk==='object')o.lock={until:num(lk.until,0),mul:clamp(num(lk.mul,1),1,HW_CAP)};s.hw=o;} - {const I=s.inbox&&typeof s.inbox==='object'&&!Array.isArray(s.inbox)?s.inbox:{},o=v=>v&&typeof v==='object'&&!Array.isArray(v)?v:{},str=(v,n)=>String(v==null?'':v).slice(0,n); - const items=(Array.isArray(I.items)?I.items:[]).filter(x=>x&&typeof x==='object'&&(x.k==='req'||x.k==='mp')&&typeof x.ix==='string'&&isIx(x.ix)&&(x.net===undefined||isNet(x.net))&&(x.net!==undefined||typeof x.nm==='string')).slice(0,INBOX_MAX).map(x=>({id:int(x.id,0,1e9,0),k:x.k,ix:x.ix,net:x.net,nm:x.net?undefined:str(x.nm,40),asn:x.net?undefined:int(x.asn,1,4294967294,64512),day:num(x.day,0),stale:!!x.stale,yrs:int(x.yrs,1,30,1),say:int(x.say,0,REQ_SAY.length-1,0),bump:x.bump?1:undefined,key:x.k==='mp'?str(x.key,80):undefined,lim:x.k==='mp'?int(x.lim,1,1e7,100):undefined,got:x.k==='mp'?int(x.got,1,1e7,100):undefined,leak:x.k==='mp'?!!x.leak:undefined})); - const down={};for(const [k,v] of Object.entries(o(I.down)))if(typeof k==='string'&&k.length<80)down[k]=num(v,0); - const tiny={};for(const [k,v] of Object.entries(o(I.tiny)).slice(0,200))if(/^\d{1,10}$/.test(k)&&v&&typeof v==='object'&&isIx(v.ix))tiny[k]={nm:str(v.nm,40),ix:v.ix,stale:!!v.stale}; - const log=(Array.isArray(I.log)?I.log:[]).filter(e=>e&&typeof e==='object'&&typeof e.m==='string').slice(0,40).map(e=>{const a={};for(const [k,v] of Object.entries(o(e.a)).slice(0,6))a[str(k,12)]=typeof v==='number'?v:str(v,60);return {d:num(e.d,0),m:str(e.m,200),a};}); - s.inbox={items,down,tiny,rep:clamp(num(I.rep,0),-10,5),bot:!!I.bot,pol:PPOL.includes(I.pol)?I.pol:'open',log,seq:Math.max(int(I.seq,0,1e9,0),...items.map(x=>x.id))};} + // 2.0 replaced the peering inbox with the peering desk: keep the policy, drop the mail, max-prefix state and the AI. + {const I=s.inbox&&typeof s.inbox==='object'&&!Array.isArray(s.inbox)?s.inbox:{},pol=s.ppol!==undefined?s.ppol:I.pol;s.ppol=PPOL.includes(pol)?pol:'open';delete s.inbox; + const wk=(x,rep)=>{if(!x||typeof x!=='object'||Array.isArray(x))return null;const o={w:int(x.w,0,1e7,0),a:int(x.a,0,1e5,0),d:int(x.d,0,1e5,0),ix:[...new Set((Array.isArray(x.ix)?x.ix:[]).filter(isIx))].slice(0,PDESK_IX)};if(rep)o.p=PPOL.includes(x.p)?x.p:'open';return o;}; + s.pdesk=wk(s.pdesk);s.pdeskRep=wk(s.pdeskRep,1);} {const sp={};if(s.spares&&typeof s.spares==='object')for(const k in s.spares)if(own(OPT,k)){const v=Math.floor(+s.spares[k]);if(v>0)sp[k]=Math.min(999,v);}s.spares=sp;} s.caches=s.caches.filter(x=>x&&isCity(x.city)&&isNet(x.net)&&NET[x.net].cache).map(x=>(x.id=sid(x.id),x.site=x.site==='b'&&s.pops[x.city]&&s.pops[x.city].site2?'b':'a',x)); for(const c of Object.keys(s.ixp)){if(!isIx(c))delete s.ixp[c];else s.ixp[c]=tier(s.ixp[c]);} @@ -55,9 +53,9 @@ function sanitize(s){ for(const k of Object.keys(s.confReg))s.confReg[k]=s.confReg[k]==='sp'?'sp':!!s.confReg[k]; if(s.conf){const c=s.conf;if(typeof c!=='object'||!own(REG,c.reg))s.conf=null;else s.conf={until:num(c.until,0),reg:c.reg,name:String(c.name||'').slice(0,40),sp:!!c.sp};} s.capDeal=s.capDeal&&typeof s.capDeal==='object'&&own(CAP_ROUTES,s.capDeal.c)?{at:num(s.capDeal.at,0),c:s.capDeal.c}:null; - s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i)); + s.inc=s.inc.filter(i=>i&&typeof i.type==='string').map(i=>(i.type==='maxpfx'&&(i.type='ixloop'),i.id=sid(i.id),i.until=num(i.until,s.day),i.cost=num(i.cost,0),i.msg=String(i.msg||'').slice(0,400),i.fix=i.fix==null?undefined:String(i.fix).slice(0,60),i)); s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));for(const l of s.loans){if(l.model!==undefined&&!['balloon','storm','transit','astro'].includes(l.model))delete l.model;for(const k of ['apr0','cut','share'])if(l[k]!==undefined&&!isFinite(+l[k]))delete l[k];if(!Array.isArray(l.covs))l.covs=[];l.covs=l.covs.filter(c=>own(COVS,c));}s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank)); - s.usedNames=[...new Set(s.usedNames.filter(x=>typeof x==='string'))];s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'||e.o.a==='inbox'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null; + s.usedNames=[...new Set(s.usedNames.filter(x=>typeof x==='string'))];s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&e.o.a==='inbox'?{a:'tab',v:'nets'}:e&&e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null; return {id:typeof e.id==='string'&&e.id.length<=40?e.id:uid(),d:num(e.d,0),t:e.t.slice(0,600),h:typeof e.h==='string'?e.h.slice(0,200):'',k:LOG_KINDS.includes(e.k)?e.k:'',at:Number.isFinite(+e.at)?+e.at:0,o,n:int(e.n,1,9999,1)};}); // One scrubbing center became a list (#117): older saves carry theirs over. if(!Array.isArray(s.scrubs))s.scrubs=s.scrubAt&&isCity(s.scrubAt)?[{city:s.scrubAt,tier:s.scrubTier}]:[];delete s.scrubAt;delete s.scrubTier; diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index dd13d16..c43655e 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -20,7 +20,7 @@ function fireFailure(only){ let tot=opts.reduce((a,o)=>a+o[1],0),r=Math.random()*tot,type=opts[0][0]; for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}} if(only)type=only; - if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(Object.keys(S.ixp).length)f.push('maxpfx');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(lit.length)f.push('roadmff');type=pick(f);} + if(type==='funny'){const f=['oops','cleaner','harmless','harmless','harmless','ac'];if(live.length)f.push('fatwave','fatwave','mtu','label','loss','loss');if(lagsN().length)f.push('lacp','lacp');if(R.demand>1)f.push('pmtud');if(S.transit.length)f.push('prepend');if(S.day>30)f.push('rpki');if(lit.length)f.push('roadmff');type=pick(f);} const before=R.served; if(type==='harmless'){const m=pick(HARMLESS);S.stats.incidents++;S.stats.survived++;toast(`${m[0]}
${m[1]}`,'goal');sfx('alert');return;} if(type==='ring'){const cs=Object.keys(S.pops).filter(c=>S.pops[c].site2),c=pick(cs),pp=S.pops[c],dur=2+Math.floor(Math.random()*3);pp.ringcut=S.day+dur; @@ -67,9 +67,6 @@ function fireFailure(only){ pp.down=Math.max(pp.down||0,S.day+1); const msg=type==='cleaner'?tr('failures.the_cleaner_at_dc_unplugged_your',{dc:siteName(c,'a')}):pick([tr('failures.your_on_call_engineer_typed_clear',{city:C}),tr('failures.an_intern_pushed_an_acl_in',{city:C}),tr('failures.someone_ran_reload_on_the_city',{city:C}),tr('failures.a_config_template_rendered_router_id',{city:C}),tr('failures.someone_committed_a_config_in_city',{city:C}),tr('failures.someone_deployed_to_city_on_a',{city:C}),tr('failures.a_cosmic_ray_flipped_a_bit',{city:C}),tr('failures.an_automation_script_in_city_ran',{city:C})]); addInc({type,ref:c,until:pp.down,msg:msg+(type==='oops'&&(pp.routers||1)>=2?' '+tr('failures.automation_pushed_it_to_every_router'):''),cost:1500,fix:type==='oops'?tr('failures.roll_back_the_config'):tr('failures.hide_the_vacuum')}); - }else if(type==='maxpfx'){ - const c=pick(Object.keys(S.ixp));S.ev.ixdown=S.ev.ixdown||{};S.ev.ixdown[c]=Math.max(S.ev.ixdown[c]||0,S.day+1+Math.floor(Math.random()*2)); - addInc({type,ref:c,until:S.ev.ixdown[c],msg:ixNamesCity(c)?tr('failures.a_member_at_ix_leaked_the',{ix:ixName(c)}):tr('failures.a_member_at_ix_leaked_the_5563',{ix:ixName(c),city:CITY[ixCity(c)].name}),cost:0}); }else if(type==='prepend'){ const t=pick(S.transit);t.down=Math.max(t.down||0,S.day+2);addInc({type,ref:t.id,until:t.down,msg:tr('failures.net_fat_fingered_a_route_map',{net:NET[t.net].name,n:30+Math.floor(Math.random()*60),city:CITY[t.city].name}),cost:0}); }else if(type==='rpki'){ @@ -175,8 +172,8 @@ function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pop // Flood Season: 3 to 7 days apart as before, shrinking with age, level and gamers only when attacks are spicy. const floodGap=()=>!ddosSpicy()?3+Math.floor(Math.random()*5):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_('failures.a_botnet_of_40_000_smart'),N_('failures.every_unpatched_baby_monitor_in'),N_('failures.a_gaming_clan_that_lost_one'),N_('failures.a_fridge_that_achieved_sentience_and'),N_('failures.a_crypto_bro_shorting_your_stock'),N_('failures.a_teenager_with_a_stolen_credit'),N_('failures.a_rival_isp_s_stress_test'),N_('failures.ten_thousand_smart_light_bulbs'),N_('failures.a_printer_just_one_printer_nobody'),N_('failures.a_botnet_run_from_a_cloud'),N_('failures.somebody_who_did_not_like_your'),N_('failures.the_internet_connected_kettles_of_a')]; -function incTitle(t){return {ring:tr('failures.metro_ring_cut'),site:tr('common.site_outage'),cut:tr('common.fiber_cut'),crash:tr('common.router_crash'),power:tr('common.power_outage'),transit:tr('common.upstream_outage'),ixloop:tr('common.ix_meltdown'),leak:tr('common.route_leak'),ddos:tr('common.ddos_attack'),fabric:tr('common.fabric_outage'),depeer:tr('common.peering_spat'),fatwave:tr('failures.fat_fingered_wave'),label:tr('failures.patch_panel_mishap'),mtu:tr('common.mtu_mismatch'),krroute:tr('failures.rerouted_via_hong_kong'),ctrlplane:tr('failures.control_plane_meltdown'),lacp:tr('common.lacp_trouble'),loss:tr('common.packet_loss'),pmtud:tr('failures.pmtud_black_hole'),oops:tr('common.oops'),cleaner:tr('common.vacuum_incident'),maxpfx:tr('failures.max_prefix_meltdown'),prepend:tr('common.prepend_ageddon'),rpki:tr('common.rpki_invalid'),amp:tr('common.amplifier_failure'),roadmff:tr('failures.fat_fingered_roadm'),optic:tr('common.dead_optic'),maint:tr('common.maintenance_window_3a92'),ac:tr('common.cooling_failure'),hijack:tr('common.bgp_hijack'),shutdown:tr('common.government_shutdown'),redsea:tr('failures.geopolitical_cable_cut')}[t]||tr('common.incident');} -const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop','maxpfx'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic']; +function incTitle(t){return {ring:tr('failures.metro_ring_cut'),site:tr('common.site_outage'),cut:tr('common.fiber_cut'),crash:tr('common.router_crash'),power:tr('common.power_outage'),transit:tr('common.upstream_outage'),ixloop:tr('common.ix_meltdown'),leak:tr('common.route_leak'),ddos:tr('common.ddos_attack'),fabric:tr('common.fabric_outage'),depeer:tr('common.peering_spat'),fatwave:tr('failures.fat_fingered_wave'),label:tr('failures.patch_panel_mishap'),mtu:tr('common.mtu_mismatch'),krroute:tr('failures.rerouted_via_hong_kong'),ctrlplane:tr('failures.control_plane_meltdown'),lacp:tr('common.lacp_trouble'),loss:tr('common.packet_loss'),pmtud:tr('failures.pmtud_black_hole'),oops:tr('common.oops'),cleaner:tr('common.vacuum_incident'),prepend:tr('common.prepend_ageddon'),rpki:tr('common.rpki_invalid'),amp:tr('common.amplifier_failure'),roadmff:tr('failures.fat_fingered_roadm'),optic:tr('common.dead_optic'),maint:tr('common.maintenance_window_3a92'),ac:tr('common.cooling_failure'),hijack:tr('common.bgp_hijack'),shutdown:tr('common.government_shutdown'),redsea:tr('failures.geopolitical_cable_cut')}[t]||tr('common.incident');} +const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic']; function remainUntil(pred){let u=0;for(const x of S.inc)if(pred(x))u=Math.max(u,x.until);return u;} // Remove an incident, then restore each affected thing to whatever other incidents still hold it down. function clearInc(i){ diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 84e00f7..59ed88c 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -3,7 +3,7 @@ function dayTick(){ if(!S||S.lost||!rule('clock'))return; // no clock (puzzles): no days, no bills, nothing fires S.day++; const d=S.day; - dkTick(d);ixPriceWar(d);inboxDay(d);pniDay(d);mergerDay(d); + dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d); if(!S.phpDone&&d>45&&Math.random()<1/400)elephant(); if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved); {const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('day_tick.you_are_no_longer_tier_1',{why:t1Why()}),'bad');S.t1Now=t1;} diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 2efcb05..f11bd8f 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -43,7 +43,7 @@ const ACT={ if(o.a==='city'&&isCity(o.v)){ACT.focusCity({city:o.v});return;} if(o.a==='link'){if(S.links.some(l=>l.id===o.v)){ACT.selLink({id:o.v});return;}toast(tr('interface.that_link_is_gone_it_was'),'');return;} if(o.a==='cust'){if(S.biz.some(b=>b.id===o.v)){ACT.custGo({id:o.v});return;}toast(tr('interface.that_customer_is_gone_the_contract'),'');return;} - if(o.a==='bank'){ACT.bank({});return;}if(o.a==='inbox'){ACT.inbox({});return;}if(o.a==='tab'&&LOG_TABS.includes(o.v))ACT.leftTab({t:o.v});}, + if(o.a==='bank'){ACT.bank({});return;}if(o.a==='tab'&&LOG_TABS.includes(o.v))ACT.leftTab({t:o.v});}, logAll:()=>{UI.logAll=!UI.logAll;renderLeft();}, focusCity:({city})=>{selectCity(city);const C=CITY[city];cam.x=C.x;cam.y=C.y;cam.z=Math.max(cam.z,1.2);if(innerWidth<760)UI.leftOpen=false;renderLeft();}, selLink:({id})=>selectLink(id), diff --git a/src/game/90-actions/40-sites-peering-caches.js b/src/game/90-actions/40-sites-peering-caches.js index cf4da86..ddc3927 100644 --- a/src/game/90-actions/40-sites-peering-caches.js +++ b/src/game/90-actions/40-sites-peering-caches.js @@ -22,13 +22,7 @@ Object.assign(ACT,{ 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();}, - inbox:()=>{inboxModal();}, - inboxAct:({id,a})=>{if(!['accept','decline','raise','keep'].includes(a))return;ibxAnswer(+id,a);after();inboxModal();}, - inboxPol:({p})=>{if(!PPOL.includes(p))return;ibx().pol=p;after();inboxModal();}, - inboxRaiseAll:()=>{const I=ibx(),mp=I.items.filter(x=>x.k==='mp');if(!mp.length)return;const leaks=mp.filter(x=>x.leak).length;for(const x of mp)ibxAnswer(x.id,'raise',true); - toast(leaks?trn('sites_peering_caches.raised_n_max_prefix_limits_one',leaks,{n:mp.length,k:leaks}):tr('sites_peering_caches.raised_n_max_prefix_limits_all',{n:mp.length}),leaks?'bad':'good');after();inboxModal();}, - inboxAll:({a})=>{if(a!=='accept'&&a!=='decline')return;const I=ibx();for(const x of I.items.filter(x=>x.k==='req'))ibxAnswer(x.id,a,true);after();inboxModal();}, - inboxBot:({on})=>{const I=ibx();if(+on){if(I.bot||!spend(AI_MO))return;I.bot=true;ibxLog(N_('sites_peering_caches.hello_i_am_large_peering_model'),{});toast(tr('sites_peering_caches.large_peering_model_is_hired_your',{price:fmt$(20e6)}),'good');}else{I.bot=false;toast(tr('sites_peering_caches.the_ai_is_gone_it_left'));}after();inboxModal();}, + peerPol:({p})=>{if(!PPOL.includes(p))return;S.ppol=p;after();}, cancelPni:({id,ok})=>{if(!ok&&UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.pni=S.pni.filter(p=>p.id!==id);UI.confirm=null;after();}, cache:({city,net})=>{const n=NET[net];if(!n||!n.cache||!S.pops[city])return;if((R.demTo[net]||0)x.city===city&&x.net===net),nb=hv.filter(x=>x.site==='b').length;S.caches.push({id:uid(),city,net,site:S.pops[city].site2&&nb``; const h=(rule('clock')?``+ ``:'')+ - (()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length||(UI.left==='noc'&&UI.leftOpen?'':logUnread())||'',S.inc.length>0)+tab('nets','🌐',tr('common.networks'),ibxOpen()||'',ibxUrgent()>0); + (()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length||(UI.left==='noc'&&UI.leftOpen?'':logUnread())||'',S.inc.length>0)+tab('nets','🌐',tr('common.networks'),''); if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;} document.body.classList.toggle('sheet-open',!!(UI.sel||UI.leftOpen));} function haptic(ms){if(UI.muted)return;try{navigator.vibrate&&navigator.vibrate(ms||12);}catch(e){}} diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index c2be442..066905c 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -31,7 +31,7 @@ function renderLeft(){checkLayer(); renderTabbar(); if(!S||pzOn()){L.hidden=true;return;}L.hidden=false; const ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length; - const tabs=[['goals',`${tr('common.goals')}${ndone}/${GOALS.length}`],['deals',`${tr('common.deals')}${S.offers.length?`${S.offers.length}`:''}`],['noc',`NOC${S.inc.length?`${S.inc.length}`:''}`],['nets',`${tr('common.networks')}${ibxOpen()?`${ibxOpen()}`:''}`]]; + const tabs=[['goals',`${tr('common.goals')}${ndone}/${GOALS.length}`],['deals',`${tr('common.deals')}${S.offers.length?`${S.offers.length}`:''}`],['noc',`NOC${S.inc.length?`${S.inc.length}`:''}`],['nets',tr('common.networks')]]; $('leftTabs').innerHTML=tabs.map(([k,l])=>``).join('')+(innerWidth<760?``:''); let h=''; if(UI.left==='goals'){ @@ -72,7 +72,7 @@ function renderLeft(){checkLayer(); if(!S.inc.length&&!hot.length&&!hotR.length&&!slow.length)h+=`

${tr('hud_and_panels.all_systems_green_enjoy_it_while')}

`; h+=`
${tr('hud_and_panels.incidents_so_far')}${S.stats.incidents}
${tr('hud_and_panels.survived_with_no_impact')}${S.stats.survived}
`; }else{ - if(rule('inbox')&&(Object.keys(S.ixp).length||ibxOpen()||(S.inbox&&S.inbox.bot))){const n=ibxOpen(),u=ibxUrgent();h+=`
📬 ${tr('common.peering_inbox')} ${n?`${n}`:''}
${S.inbox&&S.inbox.bot?tr('hud_and_panels.large_peering_model_is_on_it'):u?trn('hud_and_panels.n_session_is_down_on_its',u):n?trn('hud_and_panels.n_message_waiting_for_an_answer',n):tr('common.inbox_zero')}
${btn(tr('common.open_inbox'),'inbox',{},'sm')}
`;} + if(Object.keys(S.ixp).length||ppol()!=='open')h+=pdeskCard(); h+=`

${tr('hud_and_panels.every_network_on_the_map_traffic')}

`; {const nc=conns().length;if(nc)h+=`
${btn(tr('hud_and_panels.all_connections_n',{n:nc}),'connOpen',{},'pink sm')}
`;} const where=netWhereIdx(),tl=NETS.filter(n=>n.tail),tlOn=tl.filter(n=>where(n.id).some(x=>x[2]==='ix')).length; diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js index 3398392..9eb55b0 100644 --- a/src/game/93-ui/55-utilities.js +++ b/src/game/93-ui/55-utilities.js @@ -23,7 +23,7 @@ function utilitiesModal(city,message){if(!S)return;const cities=Object.keys(S.po

${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')}`:''} + ${ppol()!=='open'?`

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

${btn(tr('common.peering_policy'),'leftTab',{t:'nets'},'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/game/93-ui/57-ops-panel.js b/src/game/93-ui/57-ops-panel.js index 711c913..e63fd93 100644 --- a/src/game/93-ui/57-ops-panel.js +++ b/src/game/93-ui/57-ops-panel.js @@ -23,8 +23,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()})}

+ ${O.log.length?`
${O.log.slice(0,6).map(e=>esc(tr('ops.day_d',{d:e.d})+': '+opsEntry(e))).join('\n')}
`:''}
${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. diff --git a/src/game/95-modals/20-notifications.js b/src/game/95-modals/20-notifications.js index 6062ebb..d0f530a 100644 --- a/src/game/95-modals/20-notifications.js +++ b/src/game/95-modals/20-notifications.js @@ -1,9 +1,9 @@ /* ---------- notifications: the NOC keeps the last ten minutes, readable and openable ---------- */ -const LOG_KEEP=60,LOG_MS=10*60*1000,LOG_KINDS=['','good','bad','goal'],LOG_OPEN=['city','link','cust','bank','tab','inbox'],LOG_TABS=['goals','deals','noc','nets']; +const LOG_KEEP=60,LOG_MS=10*60*1000,LOG_KINDS=['','good','bad','goal'],LOG_OPEN=['city','link','cust','bank','tab'],LOG_TABS=['goals','deals','noc','nets']; // What a notification is about, from the button it came with: the same place its own button would take you. function openOf(actions){for(const a of actions||[]){const g=a.args||{}; if(a.act==='focusCity'&&isCity(g.city))return {a:'city',v:g.city};if(a.act==='selLink'&&g.id)return {a:'link',v:String(g.id)}; - if(a.act==='custGo'&&g.id)return {a:'cust',v:String(g.id)};if(a.act==='bank')return {a:'bank'};if(a.act==='inbox')return {a:'inbox'};if(a.act==='leftTab'&&LOG_TABS.includes(g.t))return {a:'tab',v:g.t};}return null;} + if(a.act==='custGo'&&g.id)return {a:'cust',v:String(g.id)};if(a.act==='bank')return {a:'bank'};if(a.act==='leftTab'&&LOG_TABS.includes(g.t))return {a:'tab',v:g.t};}return null;} // Otherwise from the text: a link between two of your cities it names, or the first of your cities it names. function openFromText(t){const cs=Object.keys(S.pops).map(c=>[c,t.indexOf(CITY[c].name)]).filter(([,i])=>i>=0).sort((a,b)=>a[1]-b[1]).map(([c])=>c); if(cs.length>=2){const l=S.links.find(l=>(l.a===cs[0]&&l.b===cs[1])||(l.a===cs[1]&&l.b===cs[0]));if(l)return {a:'link',v:l.id};}return cs.length?{a:'city',v:cs[0]}:null;} diff --git a/src/game/95-modals/45-slots.js b/src/game/95-modals/45-slots.js index f83693d..0e060c0 100644 --- a/src/game/95-modals/45-slots.js +++ b/src/game/95-modals/45-slots.js @@ -1,6 +1,6 @@ /* "Your networks" on the title screen: drawn from the index alone, so it stays instant however big the saves are. */ function slotAgo(t){const m=Math.max(0,Math.round((Date.now()-t)/60000)); - return m<1?tr('slots.just_now'):m<60?trn('notifications.n_min_ago',m):m<1440?trn('slots.n_h_ago',Math.round(m/60)):trn('peering_inbox.n_day_ago',Math.round(m/1440));} + return m<1?tr('slots.just_now'):m<60?trn('notifications.n_min_ago',m):m<1440?trn('slots.n_h_ago',Math.round(m/60)):trn('slots.n_day_ago',Math.round(m/1440));} const slotIcon=e=>e.broken?'🩹':e.mode==='scenario'?'🏆':e.mode==='sandbox'?'🏖️':(PRESETS[e.preset]||PRESETS.oncall).i; // The network to continue: the most recent one that is not open in another window (or damaged). function slotTop(list){return slotByAt(list).find(e=>!e.broken&&!slotBusy(e.id))||null;} diff --git a/src/game/95-modals/60-help.js b/src/game/95-modals/60-help.js index 76899dc..4f77859 100644 --- a/src/game/95-modals/60-help.js +++ b/src/game/95-modals/60-help.js @@ -12,11 +12,11 @@ function showHelp(){
${tr('help.pni_lead_times')}
${tr('help.a_cross_connect_with_a_small')}
${tr('common.supply_chain')}
${tr('help.routers_optics_and_new_builds_get')}
${tr('common.backhaul_latency')}
${tr('help.users_feel_the_round_trip_to')}
-
${tr('common.peering_inbox')}
${tr('help.every_ix_port_brings_peering')}
+
${tr('common.peering_policy')}
${tr('help.every_ix_port_brings_requests')}
${tr('common.embedded_cache')}
${tr('help.a_cdn_s_server_in_your')}
DE-KICKS
${tr('help.the_group_behind_several_big')}
${tr('common.remote_peering')}
${tr('help.reach_an_ix_over_a_fabric')}
${tr('common.peering_policy')}
${tr('help.open_peers_with_anyone_selective')}
${tr('common.waves')}
${tr('help.your_fiber_links_are_leased_waves')}
${tr('common.95th_percentile')}
${tr('help.transit_bills_sample_your_usage')}
${tr('common.routers')}
${tr('help.each_pop_s_router_model_caps')}
${tr('common.dark_fiber')}
${tr('help.lease_an_iru_or_build_your')}
${tr('common.subsea_cables')}
${tr('help.subsea_waves_can_only_follow_cable')}
${tr('common.latency')}
${tr('help.every_link_has_latency_high')}
${tr('common.noc_dashboard')}
${tr('help.the_chart_button_at_the_top')}
${tr('common.asia')}
${tr('help.a_weird_underserved_market_transit')}
${tr('common.russia')}
${tr('help.moscow_needs_a_mandatory_government')}
${tr('help.events_chains_and_wholesale')}
${tr('help.event_networks_a_final_a_festival')}
${tr('common.bank')}
${tr('help.tap_your_cash_to_open_the')}
${tr('common.lags')}
${tr('help.out_of_port_speed_bundle_up')}
${tr('common.traffic_engineering')}
${tr('help.tap_a_link_to_see_which')}
${tr('common.china')}
${tr('help.mainland_china_needs_a_license_and')}
${tr('common.weird_requirements')}
${tr('help.some_customers_come_with_conditions')}
${tr('common.customer_levels')}
${tr('help.as_your_peak_traffic_and_footprint')}
${tr('help.l2vpn_ddos_protection')}
${tr('help.businesses_may_want_a_private')}
${tr('common.scrubbing_centers')}
${tr('help.build_one_in_as_many_pops')}
${tr('common.nni_fabrics')}
${tr('help.megapork_pocketfabric_and')}
-
${tr('common.conferences')}
${tr('help.nanog_ripe_denog_and_friends_come')}
${tr('common.modes')}
${tr('help.one_game_four_doors_puzzles_are')}
${tr('common.traceroute')}
${tr('help.tap_traceroute_on_any_of_your')}
${tr('common.badges')}
${tr('help.below_your_goals_sits_a_wall')}
${tr('common.the_giants')}
${tr('help.at_customer_level_3_and_4')}
RouteScript
${tr('help.once_auto_te_is_installed_you')}
Auto-TE
${tr('help.traffic_follows_the_shortest_path_by')}
${tr('common.metro_diversity')}
${tr('help.a_pop_is_one_building_until')}
${tr('common.wave_markets')}
${tr('help.what_a_wave_costs_depends_on')}
${tr('common.regional_quirks')}
${tr('help.in_the_gulf_saudi_pops_need')}
${tr('common.boot_times')}
${tr('help.some_routers_take_forever_to_boot')}
${tr('common.failures')}
${tr('help.things_break_all_the_time_fiber')}
+
${tr('common.conferences')}
${tr('help.nanog_ripe_denog_and_friends_come')}
${tr('common.modes')}
${tr('help.one_game_four_doors_and_the')}
${tr('common.traceroute')}
${tr('help.tap_traceroute_on_any_of_your')}
${tr('common.badges')}
${tr('help.below_your_goals_sits_a_wall')}
${tr('common.the_giants')}
${tr('help.at_customer_level_3_and_4')}
RouteScript
${tr('help.once_auto_te_is_installed_you')}
Auto-TE
${tr('help.traffic_follows_the_shortest_path_by')}
${tr('common.metro_diversity')}
${tr('help.a_pop_is_one_building_until')}
${tr('common.wave_markets')}
${tr('help.what_a_wave_costs_depends_on')}
${tr('common.regional_quirks')}
${tr('help.in_the_gulf_saudi_pops_need')}
${tr('common.boot_times')}
${tr('help.some_routers_take_forever_to_boot')}
${tr('common.failures')}
${tr('help.things_break_all_the_time_fiber')}
RouteScript
${tr('help.rules_for_your_auto_te_controller')}

${tr('help.want_to_know_how_it_really')}

${plugHtml(true)}${chatHtml()}${issueHtml()}
${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}
`); } diff --git a/src/i18n/en.js b/src/i18n/en.js index d273e23..223c014 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -808,7 +808,6 @@ "common.aug":"Aug", "common.auto":"Auto", "common.auto_enrolled":"auto-enrolled", -"common.average":"Average", "common.avoid":"Avoid", "common.back":"Back", "common.back_to_the_map":"Back to the map", @@ -824,7 +823,6 @@ "common.bgp_hijack":"BGP hijack", "common.bgp_sessions":"BGP sessions", "common.big_league":"Big league", -"common.black_hole":"Black hole", "common.blitz":"Blitz", "common.boot_time":"Boot time", "common.boot_times":"Boot times", @@ -832,7 +830,6 @@ "common.box_6ee3":"− box", "common.build_time":"Build time", "common.building":"building", -"common.bumped":"bumped", "common.bunker_two":"Bunker Two", "common.busiest_links":"Busiest links", "common.business_customers":"Business customers", @@ -994,8 +991,6 @@ "common.import_a_save":"Import a save", "common.in_progress":"in progress", "common.in_use":"In use", -"common.inbox":"Inbox", -"common.inbox_zero":"Inbox zero.", "common.incident":"Incident", "common.incidents":"Incidents", "common.incidents_survived":"Incidents survived", @@ -1123,7 +1118,6 @@ "common.oops":"Oops", "common.open":"Open", "common.open_bank":"Open bank", -"common.open_inbox":"Open inbox", "common.open_infra":"Open Infra", "common.open_lease":"Open lease", "common.open_noc":"Open NOC", @@ -1148,7 +1142,6 @@ "common.peered_ce2f":"Peered ✓", "common.peering":"Peering", "common.peering_first":"Peering First", -"common.peering_inbox":"Peering inbox", "common.peering_policy":"Peering policy", "common.peering_ratio":"Peering ratio", "common.peering_spat":"Peering spat", @@ -1197,7 +1190,6 @@ "common.remove_port":"Remove port", "common.remove_script":"Remove script", "common.request":"Request", -"common.responsive":"Responsive", "common.resume":"Resume", "common.retention_offer":"Retention offer", "common.revenue":"Revenue", @@ -1303,7 +1295,6 @@ "common.to":"To", "common.toaster_wrangler":"Toaster Wrangler", "common.today":"Today", -"common.today_4203":"today", "common.toggle_sound":"Toggle sound", "common.too_far_for_this_cable":"too far for this cable", "common.traceroute":"Traceroute", @@ -1365,7 +1356,6 @@ "common.your_network":"Your network", "common.your_pop":"Your POP", "common.your_pops":"Your POPs", -"common.your_reputation":"Your reputation", "common.zombie_route":"Zombie route", "compute.attack_hauled_to_scrubbing_in_city":"Attack hauled to scrubbing in {city}", "compute.courtesy_route_to_new_networks":"Courtesy route to new networks", @@ -1612,8 +1602,6 @@ "failures.a_kilometre_of_copper_went_missing":"A kilometre of “copper” went missing from your {a}–{b} trench. It was your fiber. The scrap yard sent it back with a note.", "failures.a_landslide_in_the_andes_buried":"A landslide in the Andes buried your {a}–{b} fiber.", "failures.a_llama_herd_trampled_the_fiber":"A llama herd trampled the fiber marker on {a}–{b}. Then a backhoe found the fiber.", -"failures.a_member_at_ix_leaked_the":"A member at {ix} leaked the full routing table into the route server. Max-prefix limits tripped everywhere. Your peering there is down.", -"failures.a_member_at_ix_leaked_the_5563":"A member at {ix} leaked the full routing table into the route server. Max-prefix limits tripped everywhere. Your peering there, in {city}, is down.", "failures.a_new_tech_in_a_tidied":"A new tech in {a} “tidied up” the cable mess. Your {a}–{b} link was part of the mess.", "failures.a_new_tech_in_city_used":"A new tech in {city} used Vegemite as thermal paste. It conducts flavour, not heat, and your router cooked.", "failures.a_optic_on_a_b_overheated":"A {optic} on {a}–{b} overheated and is now a very expensive keychain.", @@ -1680,7 +1668,6 @@ "failures.load_shedding_stage_n_in_city":"Load shedding stage {n} in {city}, and you have no generator. Buy one: here it is not optional.", "failures.load_shedding_took_out_site_in":"Load shedding took out {site} in {city}. {other} kept going, so the POP runs at half capacity. Anything plugged in only at the dark site is offline.", "failures.magpie_swooping_season_the_field":"Magpie swooping season: the field techs on {a}–{b} will not leave the van, and your cut stays cut.", -"failures.max_prefix_meltdown":"Max-prefix meltdown", "failures.metro_ring_cut":"Metro ring cut", "failures.microbursts_on_a_b_overflow_shallow":"Microbursts on {a}–{b} overflow shallow router buffers: 0.5% loss at peak, and every video call notices.", "failures.microbursts_on_a_b_your_deep":"Microbursts on {a}–{b}.
Your deep-buffer routers soaked them up. Nobody noticed.", @@ -1795,11 +1782,8 @@ "fiber_modals.your_pop_needs_a_fabric_port":"Your POP · needs a fabric port there", "game_and_settings.delete_and_start_over":"Delete and start over", "game_and_settings.export_save_download_a_file":"Export save download a file", -"game_and_settings.import_a_save_from_a_file":"Import a save from a file", "game_and_settings.import_failed_that_save_is_damaged":"Import failed.
That save is damaged and could not be loaded. Your current game is untouched.", "game_and_settings.name_and_everything_it_owns_will":"{name} and everything it owns will be deleted. This cannot be undone.", -"game_and_settings.scenarios_amp_weekly_challenge":"Scenarios & weekly challenge", -"game_and_settings.share_your_network_image_card":"Share your network image card", "game_and_settings.start_a_new_network":"Start a new network?", "game_and_settings.welcome_back_name_imported_and_saved":"Welcome back, {name}.
Imported and saved on this device.", "game_and_settings.your_game_saves_itself_every_few":"Your game saves itself every few seconds on this device.", @@ -1870,7 +1854,7 @@ "help.each_pop_s_router_model_caps":"Each POP's router model caps its fastest port (100G, 400G, 800G, 1.6T) and how much it can forward. Bigger waves and ports need better routers at both ends. Better models unlock with your customer level. With one router, upgrades mean a day of downtime.", "help.event_networks_a_final_a_festival":"Event networks (a final, a festival, a keynote) need a burst of capacity in one city for a few days and pay once at the end, prorated by how much of the crowd you served; below 70% you pay a penalty. SD-WAN chains connect 3–6 of your POPs hub-and-spoke, so one broken spoke upsets the whole contract. Once you run your own dark fiber, carriers want to rent spare channels as alien waves, and on fiber you built yourself, a spare pair.", "help.events_chains_and_wholesale":"Events, chains and wholesale", -"help.every_ix_port_brings_peering":"Every IX port brings peering requests and max-prefix alerts, in the Networks tab. A session that blows past its limit is down until you look: raise the limit for growth, keep it down for a leak. Ignore your mail and selective networks get pickier.", +"help.every_ix_port_brings_requests":"Every IX port brings peering requests, and your peering policy in the Networks tab answers them: Open accepts everyone, Selective accepts the networks worth peering with and quietly declines the rest, Closed declines them all. Once a week the NOC log sums it up.", "help.every_link_has_latency_high":"Every link has latency. High-frequency traders pay a fortune for a circuit within their latency budget; route them “Lowest latency”. Bulk backup customers do not care, so route them “Scenic” over your quiet links to keep busy ones free.", "help.home_broadband_users_they_mostly":"Home broadband users. They mostly download from CDNs and pay you per Gbps you deliver. Serve them well and they multiply.", "help.how_the_internet_works_here":"How the internet works here", @@ -1884,7 +1868,7 @@ "help.name_as_asn_is_transit_free":"{name} (AS{asn}) is transit-free. You peer with every giant on the planet and pay nobody to reach the internet. Took you {days} days and {n} incidents.", "help.nanog_ripe_denog_and_friends_come":"NANOG, RIPE, DENOG and friends come round every year. Register in the Deals tab for $8k. For 45 days after, selective networks with a presence in that region need only half the usual traffic before they peer with you. Sometimes you also win the raffle.", "help.once_auto_te_is_installed_you":"Once Auto-TE is installed, you can program it from the NOC tab. Rules include spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams and blackhole ddos. Check runs a dry run against live traffic; Deploy makes it real, mistakes included.", -"help.one_game_four_doors_puzzles_are":"One game, four doors, and the rules are picked when a network starts and locked after that. Puzzles are small knots to untie, with no clock. Sandbox gives you a billion dollars, every unlock (your own subsea cable included) and as much chaos as you pick, but no badges. Normal comes three ways: Change Freeze (few outages, deliveries in days, no inbox or shortages), On-call (the classic game) and BGP at 3 a.m. (more and longer outages, more DDoS). Scenarios are hand-built challenges with a goal and a deadline, and the weekly challenge gives everyone the same world for a week. Share your result with the card in the menu.", +"help.one_game_four_doors_and_the":"One game, four doors, and the rules are picked when a network starts and locked after that. Puzzles are small knots to untie, with no clock. Sandbox gives you a billion dollars, every unlock (your own subsea cable included) and as much chaos as you pick, but no badges. Normal comes three ways: Change Freeze (few outages, deliveries in days, no shortages), On-call (the classic game) and BGP at 3 a.m. (more and longer outages, more DDoS). Scenarios are hand-built challenges with a goal and a deadline, and the weekly challenge gives everyone the same world for a week. Share your result with the card in the menu.", "help.open_peers_with_anyone_selective":"Open peers with anyone. Selective wants to see traffic first. Restrictive (Tier 1s) only peers with giants, over PNIs. Paid means exactly that. Big selective networks also have moods: in some cities they refuse new peers for a few months, or only take PNIs, and now and then they tear down a session you already had. Try another city or a PNI, and ask again later.", "help.out_of_port_speed_bundle_up":"Out of port speed? Bundle up to 8 identical ports to the same transit provider, IX or PNI into a LAG. Each member costs a full port; flow hashing is never perfectly even, so a bundle carries about 95% of the sum.", "help.pni_lead_times":"PNI lead times", @@ -2009,15 +1993,12 @@ "hud_and_panels.has_errors_not_running":"has errors, not running", "hud_and_panels.incidents_so_far":"Incidents so far", "hud_and_panels.install_auto_te_cost_mo_mo":"Install Auto-TE {cost} + {mo}/mo", -"hud_and_panels.large_peering_model_is_on_it":"Large Peering Model is on it.", "hud_and_panels.lv_n":"Lv {n}", "hud_and_panels.n_incident":{"one":"{n} incident","other":"{n} incidents"}, -"hud_and_panels.n_message_waiting_for_an_answer":{"one":"{n} message waiting for an answer.","other":"{n} messages waiting for an answer."}, "hud_and_panels.n_more_networks":{"one":"+{n} more network","other":"+{n} more networks"}, "hud_and_panels.n_networks_d_days_left":"{n} networks · {d} days left", "hud_and_panels.n_new_notification":{"one":"{n} new notification","other":"{n} new notifications"}, "hud_and_panels.n_rules_live":"{n} rules live", -"hud_and_panels.n_session_is_down_on_its":{"one":"{n} session is down on its max-prefix limit.","other":"{n} sessions are down on their max-prefix limit."}, "hud_and_panels.n_small_networks":"{n} small networks", "hud_and_panels.n_special_requirement":{"one":"{n} special requirement","other":"{n} special requirements"}, "hud_and_panels.n_unhappy_customer_price_mo_at":{"one":"{n} unhappy customer, {price}/mo at risk","other":"{n} unhappy customers, {price}/mo at risk"}, @@ -2593,6 +2574,7 @@ "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.day_d":"Day {d}", "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.", @@ -2631,8 +2613,6 @@ "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.", -"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.", @@ -2745,61 +2725,14 @@ "page.series_of_tubes_build_the_internet":"Series of Tubes: build the internet, one tube at a time", "page.world_map_of_your_network":"World map of your network", "page.x":"", -"peering_inbox.accept_all_requests":"Accept all requests", -"peering_inbox.an_ai_agent_that_answers_every":"An AI agent that answers every peering request and max-prefix alert for you, every day. {price}/year. Trained on twenty years of peering mailing lists.", -"peering_inbox.answered_your_mail_a_accepted_d":"Answered your mail: {a} accepted, {d} declined.", -"peering_inbox.asked_netchill_s_peering_team_to":"Asked NetChill’s peering team to “please provide more Netchill”.", -"peering_inbox.configured_lim_prefixes_received_got":"Configured: {lim} prefixes. Received: {got}.", -"peering_inbox.day_d":"Day {d}", -"peering_inbox.dear_sir_or_madam_please_peer":"Dear Sir or Madam, please peer. We have three prefixes and very big plans.", -"peering_inbox.decline_all_requests":"Decline all requests", -"peering_inbox.declined_who_at_ix_not_a":"Declined {who} at {ix}: “not a strategic fit”. They were.", -"peering_inbox.every_exchange_port_brings_mail":"Every exchange port brings mail. Answer peering requests, and look at sessions that hit their max-prefix limit: is it growth, or a route leak? Unanswered mail gets you a reputation, and selective networks hear about it.", -"peering_inbox.everyone_who_asks_gets_a_session":"Everyone who asks gets a session, and the route servers work. Lots of tiny peers, and lots of max-prefix alerts.", -"peering_inbox.fewer_requests_and_you_answer_them":"Fewer requests, and you answer them yourself. No route servers: go to each exchange and request the networks you want.", -"peering_inbox.fire_the_ai":"Fire the AI", -"peering_inbox.good_call_it_was_a_route":"Good call: it was a route leak.
{who} found a fat-fingered route map. The session comes back on its own in a few days.", -"peering_inbox.greetings_we_are_a_fast_growing":"Greetings. We are a fast-growing network. Last year we had one customer; this year we have two.", -"peering_inbox.hello_please_find_attached_our":"Hello, please find attached our peering request as a Word document, scanned from a printout.", -"peering_inbox.hey_quick_one_can_you_peer":"Hey, quick one: can you peer with us at {ix}? We have a very important Minecraft server.", -"peering_inbox.hi_we_would_like_to_peer":"Hi! We would like to peer with you at {ix}. Our PeeringDB record is up to date.", -"peering_inbox.hire_it_mo_mo":"Hire it {mo}/mo", -"peering_inbox.inbox_zero_enjoy_it_while_it":"Inbox zero. Enjoy it while it lasts.", -"peering_inbox.keep_it_down":"Keep it down", -"peering_inbox.kept_who_down_at_ix_for":"Kept {who} down at {ix} for “suspicious growth”. They had grown by one customer.", -"peering_inbox.kept_who_down_at_ix_it":"Kept {who} down at {ix}: it was a route leak. Nailed it.", -"peering_inbox.large_peering_model":"Large Peering Model", -"peering_inbox.large_peering_model_is_answering":"Large Peering Model is answering your mail", -"peering_inbox.max_prefix_limit_hit_who_at":"Max-prefix limit hit: {who} at {ix}.
The session is down until you look at it.", -"peering_inbox.max_prefix_limit_hit_who_at_5c56":"Max-prefix limit hit: {who} at {ix}", -"peering_inbox.mostly_ignores_email":"Mostly ignores email", -"peering_inbox.n_day_ago":{"one":"{n} day ago","other":"{n} days ago"}, -"peering_inbox.n_unanswered":{"one":"{n} unanswered","other":"{n} unanswered"}, -"peering_inbox.no_mail_yet_buy_an_ix":"No mail yet. Buy an IX port and it will come.", -"peering_inbox.nobody_asks_and_no_route_servers":"Nobody asks, and no route servers. Customers hear that you are hard to reach, so fewer of them call, and your reputation sinks.", -"peering_inbox.open_to_all":"Open to all", -"peering_inbox.opened_a_ticket_with_itself_to":"Opened a ticket with itself to review its own decisions. It approved them.", -"peering_inbox.peering_request_fifth_attempt_is":"Peering request, fifth attempt. Is anyone there?", -"peering_inbox.peeringdb_last_updated_n_year_ago":{"one":"PeeringDB last updated {n} year ago","other":"PeeringDB last updated {n} years ago"}, -"peering_inbox.peeringdb_updated_last_month":"PeeringDB updated last month", -"peering_inbox.please_configure_sessions_with_us_at":"Please configure sessions with us at {ix}. We will do ours next week, or the week after.", -"peering_inbox.price_year_it_never_sleeps_never":"{price}/year. It never sleeps, never complains and is often wrong.", -"peering_inbox.raise_all_max_prefix_limits":"Raise all max-prefix limits", -"peering_inbox.raise_the_limit":"Raise the limit", -"peering_inbox.raised_the_max_prefix_limit_for":"Raised the max-prefix limit for {who} at {ix} to {n}. They seemed nice.", -"peering_inbox.raised_the_max_prefix_limit_for_7b4b":"Raised the max-prefix limit for {who} at {ix}. Correctly, this time.", -"peering_inbox.replied_to_a_peering_request_with":"Replied to a peering request with a haiku about BGP. No answer yet.", -"peering_inbox.session_with_who_is_back_up":"Session with {who} is back up.
New limit: {n} prefixes. They promise to update PeeringDB.", -"peering_inbox.signed_you_up_for_a_webinar":"Signed you up for a webinar on “Peering in the Age of AI”.", -"peering_inbox.that_was_a_route_leak_who":"That was a route leak.
{who} was announcing {n} prefixes: a full table. Next time, keep it down.", -"peering_inbox.the_session_stays_down_who_will":"The session stays down.
{who} will update PeeringDB and ask again. Eventually.", -"peering_inbox.their_peeringdb_says_lim_last":{"one":"Their PeeringDB says {lim}, last updated {n} year ago.","other":"Their PeeringDB says {lim}, last updated {n} years ago."}, -"peering_inbox.tidied_up_a_session_it_decided":"Tidied up a session it decided was unused: de-peered {who} at {ix}.", -"peering_inbox.updated_your_peeringdb_record_your":"Updated your PeeringDB record. Your NOC phone number is now a pizza place.", -"peering_inbox.we_noticed_you_are_at_ix":"We noticed you are at {ix}. So are we. Shall we?", -"peering_inbox.who_asked_a_mailing_list_whether":"{who} asked a mailing list whether anyone has a working contact at {me}.
Their peering request sat in your inbox for a month.", -"peering_inbox.who_at_ix_was_sending_a":"{who} at {ix} was sending a full table, and the max-prefix limit was the only thing stopping it. With the limit raised, {net}’s prefixes point at their basement. Traffic to {net} over transit is black-holed for a few days.", -"peering_inbox.wrote_a_thousand_word_apology_to":"Wrote a thousand-word apology to a network you never peered with.", +"peering_desk.closed_desc":"Every peering request is declined, and no route servers. Customers hear that you are hard to reach, so fewer of them call.", +"peering_desk.n_more_exchanges":{"one":"{n} more exchange","other":"{n} more exchanges"}, +"peering_desk.n_new_sessions_at_ix":{"one":"Peering desk: {n} new session at {ix} ({pol}).","other":"Peering desk: {n} new sessions at {ix} ({pol})."}, +"peering_desk.n_new_sessions_at_ix_declined":{"one":"Peering desk: {n} new session at {ix}, {d} declined ({pol}).","other":"Peering desk: {n} new sessions at {ix}, {d} declined ({pol})."}, +"peering_desk.n_requests_declined":{"one":"Peering desk: {n} request declined ({pol}).","other":"Peering desk: {n} requests declined ({pol})."}, +"peering_desk.open_desc":"Every network that asks gets a session, and the route servers work.", +"peering_desk.open_to_all":"Open to all", +"peering_desk.selective_desc":"Small networks on the exchange and newcomers with an up-to-date PeeringDB get a session; the rest are quietly declined. No route servers: ask the networks you want at each exchange.", "peering_policy.a_new_vp_wants_to_monetise":"A new VP wants to \"monetise interconnection\" in this market.", "peering_policy.already_reach_you_through_your":"Already reach you through your transit provider here and think that is fine.", "peering_policy.moved_everything_in_this_city_to":"Moved everything in this city to PNIs. Please read their PearingDB page, all 40 pages of it.", @@ -3310,7 +3243,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Unplug something first.
{used} ports are in use, and one router fewer only has {max}.", "rules.a_billion_dollars_every_unlock_your":"A billion dollars, every unlock, your own subsea cable.", "rules.a_cut_now_and_then":"A cut now and then.", -"rules.a_third_of_the_outages_no_ddos":"A third of the outages, no DDoS. PNIs and builds in days. No inbox, no shortages, no sold-out routes, no de-peering.", +"rules.a_third_of_the_outages_no_ddos_pnis":"A third of the outages, no DDoS. PNIs and builds in days. No shortages, no sold-out routes, no de-peering.", "rules.bgp_at_3_a_m":"BGP at 3 a.m.", "rules.change_freeze":"Change Freeze", "rules.chaos_calm":"Calm", @@ -3327,7 +3260,7 @@ "rules.on_call":"On-call", "rules.one_small_network_one_tricky_goal":"One small network, one tricky goal.", "rules.puzzle":"Puzzle", -"rules.real_lead_times_real_outages_a":"Real lead times, real outages, a full peering inbox. The classic game.", +"rules.real_lead_times_real_outages_a_real":"Real lead times, real outages, a real market. The classic game.", "rules.rules_are_locked_for_this_network":"{rules}: rules are locked for this network.", "rules.the_real_thing_your_pager_has":"The real thing. Your pager has opinions.", "rules.your_pager_never_sleeps":"Your pager never sleeps.", @@ -3461,9 +3394,7 @@ "sites_peering_caches.bgp_session_established":"BGP session established.", "sites_peering_caches.cache_installed_in_city_net_shipped":"{cache} installed in {city}!
{net} shipped it for free. You pay {mo}/mo power.", "sites_peering_caches.could_you_resend_the_loa_you":"“Could you resend the LOA?”
You have sent it four times.", -"sites_peering_caches.hello_i_am_large_peering_model":"Hello! I am Large Peering Model. I have read your inbox and I already have opinions.", "sites_peering_caches.it_is_with_the_provisioning_team":"“It is with the provisioning team.”
Nobody has ever met the provisioning team.", -"sites_peering_caches.large_peering_model_is_hired_your":"Large Peering Model is hired.
Your inbox is its problem now. {price} a year, billed monthly.", "sites_peering_caches.n_new_session_at_ix_small":{"one":"{n} new session at {ix}.
Small networks, but they add up, and they all count towards the club.","other":"{n} new sessions at {ix}.
Small networks, but they add up, and they all count towards the club."}, "sites_peering_caches.net_accepted":"{net} accepted!", "sites_peering_caches.net_declined_the_pni_why":"{net} declined the PNI.
{why}", @@ -3471,11 +3402,8 @@ "sites_peering_caches.net_does_not_do_port_pnis":"{net} does not do {port} PNIs.
Nothing smaller than 100G. Come back with more traffic, or a bigger optic.", "sites_peering_caches.net_says_not_yet_send_them":"{net} says not yet.
Send them {min}+ Gbps first.", "sites_peering_caches.pni_with_net_ordered_eta_a":"PNI with {net} ordered.
{eta}. A cross-connect in {dc}, once somebody finds the LOA.", -"sites_peering_caches.raised_n_max_prefix_limits_all":"Raised {n} max-prefix limits.
All growth, no leaks. Lucky.", -"sites_peering_caches.raised_n_max_prefix_limits_one":{"one":"Raised {n} max-prefix limits.
One of them was a route leak. It is in the NOC now.","other":"Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now."}, "sites_peering_caches.second_lag_member_added_one_member":"Second LAG member added.
One member in each building now, so a dark building only takes out half the port.", "sites_peering_caches.second_site_live_in_city_b":"Second site live in {city}.
{b} is joined to {a} by your own metro ring. Move some uplinks there from the Transit and Peering tabs.", -"sites_peering_caches.the_ai_is_gone_it_left":"The AI is gone.
It left a 40-page handover document. It is mostly about itself.", "sites_peering_caches.they_checked_your_pearingdb_page_and":"They checked your PearingDB page and liked the traffic numbers.", "sites_peering_caches.we_are_waiting_on_the_colo":"“We are waiting on the colo for the cross-connect.”
The colo says it is waiting on them.", "sites_peering_caches.your_account_manager_found_the_order":"Your account manager found the order under a desk.
It is a month closer.", @@ -3497,6 +3425,7 @@ "slots.last_played_ago":"Last played {ago}", "slots.load_the_newest_version":"Load the newest version", "slots.more_for_name":"More for {name}", +"slots.n_day_ago":{"one":"{n} day ago","other":"{n} days ago"}, "slots.n_h_ago":{"one":"{n} h ago","other":"{n} h ago"}, "slots.name_is_open_in_another_window":"{name} is open in another window", "slots.name_is_waiting_in_your_other":"{name} is waiting in your other window.
Switch to it to keep playing.", @@ -3520,7 +3449,6 @@ "slots.this_window_stopped_saving_so_it":"A newer version was saved in another window, so this one stopped saving instead of overwriting it.", "slots.two_windows_one_network":"Two windows, one network", "slots.your_networks":"Your networks", -"slots.your_networks_switch_or_start_another":"Your networks switch, or start another", "slots.your_other_networks_share_this_browser":"Your other networks share this browser's storage. Export the ones you want to keep, then delete them here to make room.", "sold_out.a_hyperscaler_bought_every_wave_of":"A hyperscaler bought every wave of that size on this route last week.", "sold_out.not_big_enough_yet_list":"Not big enough yet: {list}", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 5a27215..14a9d4f 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -48,7 +48,7 @@ select.pick:focus-visible{outline:3px solid #FF4F9A;outline-offset:2px} label.f+select.pick{width:100%} .thb{font:inherit;font-weight:900;background:none;border:0;padding:0;cursor:pointer;color:inherit} .ttop{margin:4px 0;padding:4px 8px;border-left:3px solid #FF8A3D;background:#FFF6EC;border-radius:6px} -.ibx{border:2px solid var(--line,#DDE3EE);border-radius:12px;padding:8px 10px;margin:8px 0;background:#fff}.ibx .nm{font-weight:800}.ibx.mp{border-color:#FF5A5F;background:#FFF1F1}.ibx.ai{border-color:#8E5CF7;background:#F7F2FF}.ibx .term{font-size:11.5px;white-space:pre-wrap;max-height:180px;overflow:auto}.ibx .cnt{display:inline-block;min-width:18px;padding:0 5px;border-radius:9px;background:var(--me);color:#fff;font-size:11px;text-align:center}.ibx .cnt.red{background:#FF5A5F} +.ibx{border:2px solid var(--line,#DDE3EE);border-radius:12px;padding:8px 10px;margin:8px 0;background:#fff}.ibx .nm{font-weight:800} .aibtn{background:linear-gradient(90deg,#8E5CF7,#E84FA8);color:#fff}.aisay{background:#F3ECFF;border:2px solid #8E5CF7;border-radius:10px;padding:8px 10px;color:var(--ink)} .tehelp h3{margin:14px 0 4px}.tehelp ul{margin:4px 0;padding-left:18px}.tehelp li{margin:4px 0;font-size:13.5px;line-height:1.4}.tehelp dt{margin-top:8px}.tehelp dd{margin:2px 0 0;font-size:13px;line-height:1.4;color:var(--ink2)}.tehelp code{font:600 12.5px ui-monospace,Menlo,Consolas,monospace;background:#1E2640;color:#E6F0FF;border-radius:6px;padding:1px 6px;word-break:break-word} .terec{display:flex;align-items:center;gap:10px;justify-content:space-between;border-top:2px dashed var(--line,#DDE3EE);padding:8px 0}.terec .btn{flex:none} diff --git a/tests/i18n.test.js b/tests/i18n.test.js index 08b4f74..ef9da0b 100644 --- a/tests/i18n.test.js +++ b/tests/i18n.test.js @@ -82,8 +82,8 @@ test('missing translations fall back to the English, with placeholders filled', assert.equal(ev("tr('test.no_such_label {n}',{n:3})"), 'test.no_such_label 3', 'an unknown label comes back as it is'); assert.equal(ev("trn('test.cats',1)"), '1 cat'); assert.equal(ev("trn('test.cats',2)"), '2 cats'); - assert.equal(ev("trn('peering_inbox.n_day_ago',1)"), '1 giorno fa'); - assert.equal(ev("trn('peering_inbox.n_day_ago',3)"), '3 giorni fa'); + assert.equal(ev("trn('slots.n_day_ago',1)"), '1 giorno fa'); + assert.equal(ev("trn('slots.n_day_ago',3)"), '3 giorni fa'); }); test('text that old saves stored in English is still translated', () => { From b6213344ce47febe74417584441b7cccb178e0ce Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 21:40:19 +0100 Subject: [PATCH 138/181] Test the menu's small GitHub and chat links --- tests/report-link.test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/report-link.test.js b/tests/report-link.test.js index 0facc87..d1931b5 100644 --- a/tests/report-link.test.js +++ b/tests/report-link.test.js @@ -20,10 +20,11 @@ test('bugs and ideas point to GitHub from the menu and How to play, and the chat } }); -test('the GitHub card fits a phone', () => { +test('the GitHub link fits a phone: a small link next to the chat link in the menu', () => { const { ev, errors } = load(); ev("ACT.start({});window.innerWidth=360;ACT.menu()"); assert.ok(ev('isPhone()')); - assert.ok(ev(`!!document.querySelector('#modal a.plug[href="${ISSUES}"] .go')`), 'same card layout as the chat card'); + assert.ok(ev(`!!document.querySelector('#modal .menu-plugs a.mplug[href="${ISSUES}"]')`), 'bug link in the menu'); + assert.ok(ev(`!!document.querySelector('#modal .menu-plugs a.mplug[href="'+SIGNAL+'"]')`), 'chat link beside it'); assert.deepEqual(errors, []); }); From 92536606ddbc0ba4b3f133b0ef72adbc5ae22812 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 21:41:28 +0100 Subject: [PATCH 139/181] Tests, CHANGELOG and docs for the peering desk --- .claude/skills/gameplay-rules/SKILL.md | 4 +- CHANGELOG.md | 3 +- docs/ARCHITECTURE.md | 2 +- docs/adr/0003-translations-by-label.md | 2 +- scripts/lib/compile-labels.js | 2 +- tests/eyeballs.test.js | 2 +- tests/game.test.js | 4 - tests/gameplay-rules.test.js | 11 +- tests/i18n.test.js | 4 +- tests/inbox.test.js | 252 ------------------------- tests/peering-desk.test.js | 117 ++++++++++++ tests/peering.test.js | 7 +- tests/pnis-and-sold-out.test.js | 127 +++++++++++++ tests/puzzles.test.js | 2 +- tests/rules.test.js | 5 +- tests/utilities.test.js | 2 +- 16 files changed, 266 insertions(+), 280 deletions(-) delete mode 100644 tests/inbox.test.js create mode 100644 tests/peering-desk.test.js create mode 100644 tests/pnis-and-sold-out.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index ecb01ed..770d3ce 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -43,8 +43,8 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | Id | Rule | Why | | --- | --- | --- | | M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. | -| M2 | Presets are ordered: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market, inbox; and a seeded year of incidents). | The names promise it. | -| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, the peering inbox, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock. A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | +| M2 | Presets are ordered: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). | The names promise it. | +| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock. A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | | M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. | | M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c98686..ebdfd49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. - Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. - Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. - Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price. @@ -19,7 +20,7 @@ All notable changes to this project are documented here. The project follows - A new weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands 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, 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). - 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. -- 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, sold-out routes and de-peering at exchanges. 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. +- 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 hardware shortages, sold-out routes and de-peering at exchanges. 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. - Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. - 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. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7af5613..3b2f4af 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -30,7 +30,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) | | `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` | | `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`) | -| `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 | +| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | | `80-simulation/` | Dijkstra, RouteScript, `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()` | | `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` | diff --git a/docs/adr/0003-translations-by-label.md b/docs/adr/0003-translations-by-label.md index 19a2c32..a75c209 100644 --- a/docs/adr/0003-translations-by-label.md +++ b/docs/adr/0003-translations-by-label.md @@ -35,7 +35,7 @@ fell back to English. Long sentences as keys made dictionary diffs hard to read - **`npm run i18n:check`** verifies that every label used in `src/` is defined in English, every English label is used, every translation keeps its English's placeholders, HTML tags and plural forms, and every dictionary is sorted. -- **Saves:** a few things in a save hold text to show later (the peering inbox log, sold-out reasons, +- **Saves:** a few things in a save hold text to show later (sold-out reasons, attack names). New saves hold labels. Saves from before labels (1.34 and older) hold the English text; `tr()` maps it back to its label the first time it sees one, so old saves still show the player's language. - **Translators** read `src/i18n/en.js` next to their file; both are sorted by the same labels, so the diff --git a/scripts/lib/compile-labels.js b/scripts/lib/compile-labels.js index 597adfd..a78cf4e 100644 --- a/scripts/lib/compile-labels.js +++ b/scripts/lib/compile-labels.js @@ -6,7 +6,7 @@ // static markup, in the inlined English and in every translation file, and the page ends up about the // size it was when the English text itself was the key. // -// Labels passed to N_() are kept whole: those are the ones the game stores (in saves, in the inbox log) +// Labels passed to N_() are kept whole: those are the ones the game stores (in saves) // and shows later, and an id would mean something else in the next release. const { CALL } = require('../legacy/labels'); const D = require('./dict'); diff --git a/tests/eyeballs.test.js b/tests/eyeballs.test.js index b5a4543..d2922d5 100644 --- a/tests/eyeballs.test.js +++ b/tests/eyeballs.test.js @@ -47,7 +47,7 @@ test('Coax gets Spectre-um’d a year in, and Final Frontear joins Very-Zone a y start(ev2); ev2("ACT.buildPop({city:'chi'});S.pni.push({id:'a',net:'cxc',city:'chi',tier:1,ready:0},{id:'b',net:'spc',city:'chi',tier:1,ready:0});S.day=400;dayTick()"); assert.equal(ev2("S.pni.filter(p=>p.city==='chi').map(p=>p.net).join()"), 'spc'); - // the inbox never brings requests from a brand that no longer exists, and saves keep the record + // saves keep the record of who merged ev("const o=JSON.parse(JSON.stringify(S));S=migrate(o)"); assert.equal(ev("merged('cxc')&&merged('ftr')"), true); ev("S.merged={cxc:'x',zzz:3};S=migrate(JSON.parse(JSON.stringify(S)))"); diff --git a/tests/game.test.js b/tests/game.test.js index 6f5d817..246a769 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -469,10 +469,6 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens const os = JSON.parse(ev("JSON.stringify(S.log.map(e=>e.o))")); assert.deepEqual(os, [null, { a: 'city', v: 'lon' }, { a: 'link', v: linkId }, { a: 'city', v: 'fra' }]); assert.equal(ev("S.log[0].h"), 'Raffle'); assert.equal(ev("S.log[0].t"), 'Raffle You won a T-shirt.'); - // the peering inbox's own button opens the peering inbox - ev("toast('Peering request
From a small network.','',[{l:'Inbox',act:'inbox',args:{}}])"); - assert.deepEqual(JSON.parse(ev('JSON.stringify(S.log[0].o)')), { a: 'inbox' }); - ev('ACT.logOpen({id:S.log[0].id})'); assert.equal(ev("$('modal').hidden"), false, 'the inbox opens');ev('closeModal();S.log.shift()'); // an incident points at what broke assert.deepEqual(JSON.parse(ev(`JSON.stringify(incOpen({ref:'${linkId}'}))`)), { a: 'link', v: linkId }); assert.deepEqual(JSON.parse(ev("JSON.stringify(incOpen({ref:S.links[0].trench||S.links[0].id}))")), { a: 'link', v: ev('S.links[0].id') }); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index ce95537..76cf1ba 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -215,8 +215,8 @@ test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at const P = J('PRESETS'), C = J('CHAOS'), lead = { quick: 0, real: 1 }; assert.ok(C[P.freeze.chaos].m <= C[P.oncall.chaos].m && C[P.oncall.chaos].m <= C[P.bgp.chaos].m, 'M2: chaos'); assert.ok(lead[P.freeze.lead] <= lead[P.oncall.lead] && lead[P.oncall.lead] <= lead[P.bgp.lead], 'M2: lead times'); - for (const k of ['market', 'inbox']) assert.ok(!P.freeze[k] || P.oncall[k], `M2: ${k}`); - assert.ok(P.bgp.market && P.bgp.inbox && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship'); + assert.ok(!P.freeze.market || P.oncall.market, 'M2: market'); + assert.ok(P.bgp.market && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship'); // seeded: the same network for a year under each preset const n = {}; for (const p of ['freeze', 'oncall', 'bgp']) { @@ -230,15 +230,14 @@ test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at test('M3: every subsystem that can annoy the player reads a rule', () => { // [function, what it must read] - const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['inboxDay', "rule('inbox')"], + const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], ['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"], ['snub', "rule('market')"]]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); - // and in play: no chaos, no market, no inbox means a quiet year + // and in play: no chaos and no market means a quiet year const g = load(); - g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false,inbox:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()"); + g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()"); assert.equal(g.ev('S.inc.length+(S.stats.incidents||0)'), 0, 'M3: nothing breaks without chaos'); - assert.equal(g.ev('S.inbox.items.length+S.inbox.seq'), 0, 'M3: no mail without the inbox'); assert.equal(g.ev("hwMul('rt')"), 1, 'M3: no hardware inflation without the market'); assert.equal(g.ev("CITIES.slice(0,40).some(c=>soldOut('fra',c.id,1))"), false, 'M3: no sold-out routes without the market'); assert.deepEqual(g.errors, []); diff --git a/tests/i18n.test.js b/tests/i18n.test.js index ef9da0b..29729c2 100644 --- a/tests/i18n.test.js +++ b/tests/i18n.test.js @@ -36,8 +36,8 @@ function tour(ev) { ['routers', "selectCity('fra');ACT.tab({t:'links'});ACT.models()"], ['vxc', "openVxcModal({from:'fra',to:'ams'});closeModal()"], ['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()']]) step(label, src); const failSrc = ev('fireFailure.toString()'); - for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) { - const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t; + for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) { + const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t; const patched = failSrc.replace(/^function fireFailure/, 'function') .replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${kind}'))return;opts.splice(0,opts.length,['${kind}',1]);let tot=opts.reduce`) .replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`); diff --git a/tests/inbox.test.js b/tests/inbox.test.js deleted file mode 100644 index 7acb7f3..0000000 --- a/tests/inbox.test.js +++ /dev/null @@ -1,252 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const { load } = require('./harness'); - -function setup(ev) { - ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()"); -} - -test('PNIs with the big networks take a month, now and then 6 to 12, and start at 100G; small ones take weeks', () => { - const { ev, errors } = load(); - setup(ev); - ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:0})"); - assert.equal(ev('S.pni.length'), 0, 'no 10G PNI with NetChill'); - assert.match(ev("document.getElementById('toasts').textContent"), /does not do 10G/); - // one order in seven gets lost in provisioning for months - ev("Math.random=()=>0.1;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})"); - const p = JSON.parse(ev('JSON.stringify(S.pni[0])')); - assert.ok(p.ready - ev('S.day') >= 180 && p.ready - ev('S.day') <= 365, `six to twelve months (${p.ready - ev('S.day')} days)`); - ev('compute()'); - assert.equal(ev('R.usePni[S.pni[0].id]||0'), 0, 'nothing flows before delivery'); - assert.equal(ev('R.cost.pni'), 0, 'and nothing is billed'); - ev('S.nextFail=S.nextEvent=1e9;S.pni[0].ready=S.day+1;dayTick();compute()'); - assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'delivered on the day'); - // an upgrade is an augment on order: the old port keeps working meanwhile - ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})"); - assert.equal(ev('S.pni[0].tier'), 1); - assert.equal(ev('S.pni[0].up.tier'), 2); - ev('ACT.lagP({id:S.pni[0].id,d:1})'); - assert.equal(ev('S.pni[0].up.n'), 1, 'one augment at a time'); - ev('S.day=S.pni[0].up.ready-1;dayTick()'); - assert.equal(ev('S.pni[0].tier'), 2); - assert.equal(ev('S.pni[0].up'), undefined); - // chasing it does nothing, mostly - ev("Math.random=()=>0.5;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:3});const r0=S.pni[0].up.ready;ACT.pniChase({id:S.pni[0].id});window.__r=[r0,S.pni[0].up.ready]"); - const [r0, r1] = JSON.parse(ev('JSON.stringify(__r)')); - assert.equal(r0, r1); - // most orders arrive in about a month - ev("Math.random=()=>0.5;S.pni=[];R.demTo.ggl=1e4;ACT.pni({city:'fra',net:'ggl',tier:1})"); - assert.equal(ev("S.pni.find(p=>p.net==='ggl').ready-S.day"), 30); - ev("S.pni=S.pni.filter(p=>p.net!=='ggl')"); - // a beer at a conference halves the wait - ev("Math.random=()=>0.99;S.conf={until:S.day+10,reg:'EU',name:'RIPE'}"); - assert.equal(ev("pniLead('ggl')"), 15, 'the usual month, halved'); - ev('Math.random=()=>0.1'); - assert.equal(ev("pniLead('ggl')"), Math.round((180 + Math.floor(0.1 * 186)) / 2), 'a slow one, halved'); - ev('Math.random=()=>0.99'); - ev('S.conf=null'); - // a small network: a few weeks - const small = ev("NETS.find(n=>n.pops.includes('fra')&&!pniBig(n.id)&&n.pol==='open'&&n.type!=='cdn').id"); - ev(`Math.random=()=>0.99;ACT.pni({city:'fra',net:'${small}',tier:0})`); - const lead = ev(`S.pni.find(p=>p.net==='${small}').ready-S.day`); - assert.ok(lead >= 14 && lead <= 42, `weeks, not months (${lead})`); - assert.deepEqual(errors, []); -}); - -test('Doitsche Telekomm sells 1G PNIs; nobody else does', () => { - const { ev, errors } = load(); - setup(ev); - ev("S.lvl=10;ACT.pni({city:'fra',net:'nfx',tier:-1})"); - assert.equal(ev('S.pni.length'), 0); - assert.equal(ev("peerOk('dtk','pni','fra').ok"), true); - ev("ACT.pni({city:'fra',net:'dtk',tier:-1})"); - assert.equal(ev('S.pni[0].g1'), true); - ev('S.pni[0].ready=S.day;compute()'); - assert.equal(ev('pniG(S.pni[0])'), 1); - assert.equal(ev("liveCap(pniG(S.pni[0]),'fra','a',1)"), 1); - assert.equal(ev('pniPN(S.pni[0])'), '1G'); - // and 1G grows into 10G - ev("ACT.pni({city:'fra',net:'dtk',tier:0})"); - assert.equal(ev('S.pni[0].up.tier'), 0); - ev('S.day=S.pni[0].up.ready-1;dayTick()'); - assert.equal(ev('S.pni[0].g1'), undefined); - assert.equal(ev('pniG(S.pni[0])'), 10); - ev("selectCity('fra');ACT.tab({t:'peer'})"); - assert.deepEqual(errors, []); -}); - -test('Microsnoft has no capacity on the US east coast, at any price', () => { - const { ev, errors } = load(); - setup(ev); - ev("for(const c of ['ash','nyc','hou'])ACT.buildPop({city:c});R.demTo.msf=1e5"); - for (const c of ['ash', 'nyc', 'bos', 'atn', 'mia']) { - assert.equal(ev(`peerOk('msf','pni','${c}').ok`), false, c); - assert.equal(ev(`peerOk('msf','ix','${c}').ok`), false, c); - } - assert.match(ev("peerOk('msf','pni','ash').why"), /capacity|sold out|coming online/i); - assert.equal(ev("peerOk('msf','pni','hou').ok"), true, 'Houston is fine'); - ev("ACT.pni({city:'ash',net:'msf',tier:1})"); - assert.equal(ev("S.pni.filter(p=>p.city==='ash').length"), 0); - assert.equal(ev("peerOk('ggl','pni','ash').ok"), ev("R.demTo.ggl>=Math.round(NET.ggl.minPni*repMul())"), 'other networks are not affected'); - assert.deepEqual(errors, []); -}); - -test('the peering inbox fills up, wants answers, and max-prefix alerts are growth or a leak', () => { - const { ev, errors } = load(); - setup(ev); - ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});S.inbox.pol='selective';compute()"); - ev('for(let i=0;i<60;i++)dayTick()'); - assert.ok(ev('S.inbox.items.length') >= 2, 'mail arrives with an exchange port'); - assert.ok(ev('S.inbox.rep') < 0, 'and ignoring it has a price'); - // accept a real network's request: a bilateral session - const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006&&!ixSessions('ams').has(id);})"); - assert.ok(net); - ev(`S.inbox.items=[{id:901,k:'req',ix:'ams',net:'${net}',day:S.day,stale:false,yrs:1,say:0},{id:902,k:'req',ix:'ams',nm:'Bob’s Bits',asn:212345,day:S.day,stale:true,yrs:7,say:3}];ACT.inbox()`); - assert.match(ev("document.getElementById('modalCard').textContent"), /Bob’s Bits/); - ev("ACT.inboxAct({id:901,a:'accept'});ACT.inboxAct({id:902,a:'accept'})"); - assert.equal(ev(`!!S.peers['${net}@ams']`), true); - assert.equal(ev('S.inbox.tiny[212345].nm'), 'Bob’s Bits'); - ev('compute()'); - assert.equal(ev(`ixSessions('ams').has('${net}')`), true); - // growth: raising the limit brings the session back - ev(`S.inbox.items.push({id:903,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:180,leak:false,yrs:4});S.inbox.down['${net}@ams']=1e9`); - assert.equal(ev(`ixSessions('ams').has('${net}')`), false, 'down on max-prefix'); - ev("ACT.inboxAct({id:903,a:'raise'})"); - assert.equal(ev(`ixSessions('ams').has('${net}')`), true); - // a leak: raising the limit is a route leak, keeping it down is right - ev(`S.inbox.items.push({id:904,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:987654,leak:true,yrs:4});S.inbox.down['${net}@ams']=1e9;ACT.inboxAct({id:904,a:'raise'})`); - assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'a route leak'); - assert.ok(ev("S.inc.some(i=>i.type==='leak')")); - ev(`S.inbox.items.push({id:905,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:987654,leak:true,yrs:4});S.inbox.down['${net}@ams']=1e9;ACT.inboxAct({id:905,a:'keep'})`); - const back = ev(`S.inbox.down['${net}@ams']`); - assert.ok(back > ev('S.day') && back < ev('S.day') + 12, 'back on its own in a few days'); - // unanswered requests expire, and the reputation makes selective networks pickier - ev("S.inbox.items=[{id:906,k:'req',ix:'ams',net:'" + net + "',day:S.day-31,stale:false,yrs:1,say:0}];S.inbox.rep=0;inboxDay(S.day)"); - assert.equal(ev('S.inbox.items.some(x=>x.id===906)'), false); - assert.ok(ev('S.inbox.rep') < 0); - ev('S.inbox.rep=-10'); - assert.ok(ev('repMul()') > 1.05 && ev('repMul()') <= 1.1, 'pickier, but never a wall'); - // an alert nobody answers clears itself once the other side notices - ev(`S.inbox.items=[{id:910,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:180,leak:false,yrs:4}];S.inbox.down['${net}@ams']=S.day+1;inboxDay(S.day+1)`); - assert.equal(ev('S.inbox.items.some(x=>x.id===910)'), false); - // bulk answers - ev("S.inbox.items=[{id:907,k:'req',ix:'ams',nm:'A',asn:1,day:S.day,say:0,yrs:1},{id:908,k:'req',ix:'ams',nm:'B',asn:2,day:S.day,say:0,yrs:1}];ACT.inboxAll({a:'decline'})"); - assert.equal(ev('S.inbox.items.length'), 0); - // the Networks tab says how much mail is waiting - ev("S.inbox.items=[{id:909,k:'req',ix:'ams',nm:'C',asn:3,day:S.day,say:1,yrs:1}];closeModal();UI.left='nets';UI.leftOpen=true;renderLeft()"); - assert.match(ev("document.getElementById('left').textContent"), /Peering inbox/); - assert.deepEqual(errors, []); -}); - -test('the AI agent answers everything, costs $20M a year and gets it wrong a lot', () => { - const { ev, errors } = load(); - setup(ev); - ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()"); - const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})"); - const cash = ev('S.cash'); - ev("ACT.inboxBot({on:1});compute()"); - assert.equal(ev('S.inbox.bot'), true); - assert.ok(cash - ev('S.cash') >= ev('AI_MO')); - assert.ok(ev('R.cost.extras') >= ev('AI_MO'), 'billed every month'); - assert.ok(Math.abs(ev('AI_MO*12') - 20e6) < 12); - // it always gets a leak wrong when the dice say so - ev(`S.peers['${net}@ams']=true;S.inbox.items=[{id:1,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3},{id:2,k:'req',ix:'ams',nm:'D',asn:4,day:S.day,say:0,yrs:1}];S.inbox.down['${net}@ams']=1e9`); - ev('Math.random=()=>0.1;inboxBot()'); - assert.equal(ev('S.inbox.items.length'), 0, 'inbox zero'); - assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'and a route leak'); - assert.ok(ev("S.inbox.log.some(e=>/They seemed nice/.test(tr(e.m,e.a)))"), 'the log keeps a label, read in the language of the player'); - ev('ACT.inbox()'); - assert.match(ev("document.getElementById('modalCard').textContent"), /They seemed nice/); - // and sometimes it gets it right - ev(`S.inbox.items=[{id:3,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3}];S.ev.leak=null;Math.random=()=>0.9;inboxBot()`); - assert.ok(!ev('S.ev.leak')); - ev('ACT.inboxBot({on:0});compute()'); - assert.equal(ev('S.inbox.bot'), false); - assert.ok(ev('R.cost.extras') < ev('AI_MO')); - assert.deepEqual(errors, []); -}); - -test('saves: the inbox and PNIs on order survive, and garbage is repaired', () => { - const { ev, errors } = load(); - setup(ev); - ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})"); - ev("S.inbox={items:[{id:1,k:'req',ix:'ams',nm:'Ok',asn:5,day:1,say:99},{k:'evil',ix:'ams'},{id:2,k:'mp',ix:'nowhere',key:'a'},'x'],down:{'a@b':'7'},tiny:{'12':{nm:'T',ix:'ams'},'no':{ix:'ams'}},rep:99,bot:'yes',log:[{d:1,m:'hi',a:{who:{x:1}}},5],seq:'z'}"); - ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o'); - assert.equal(ev('__o.inbox.items.length'), 1); - assert.equal(ev('__o.inbox.items[0].say'), ev('REQ_SAY.length-1')); - assert.equal(ev('__o.inbox.rep'), 5); - assert.equal(ev('__o.inbox.bot'), true); - assert.equal(ev("__o.inbox.down['a@b']"), 7); - assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(__o.inbox.tiny))')), ['12']); - assert.equal(ev('typeof __o.inbox.log[0].a.who'), 'string'); - assert.equal(ev('__o.inbox.seq'), 1); - assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX')); - assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true); - assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G'); - // an old save without an inbox loads with an empty one - ev('const p=JSON.parse(JSON.stringify(S));delete p.inbox;sanitize(p);window.__p=p'); - assert.equal(ev('__p.inbox.items.length'), 0); - assert.equal(ev('__p.inbox.bot'), false); - assert.deepEqual(errors, []); -}); - -test('now and then a route is sold out of a wave size, for a while, and asking again does not reroll it', () => { - const { ev, errors } = load(); - setup(ev); - ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3"); - assert.equal(ev("S.day=10;!!soldOut('fra','ams',3,null)||!!soldOut('fra','ams',1,null)"), false, 'never in the first 90 days'); - // find a day when 400G is sold out between Frankfurt and Amsterdam - const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null))return d;}return -1;})()"); - assert.ok(day > 0, 'it happens'); - ev(`S.day=${day}`); - const so = JSON.parse(ev("JSON.stringify(soldOut('fra','ams',2,null))")); - assert.ok(so.until > day && so.until - day <= 90); - assert.equal(ev(`S.day=${so.until - 1};!!soldOut('fra','ams',2,null)`), true, 'the same verdict for the whole window'); - ev(`S.day=${day}`); - const share = ev("(()=>{let n=0;for(let d=90;d<20090;d++){S.day=d;if(soldOut('ams','fra',5,null))n++;}return n/20000;})()"); - assert.ok(share > 0.02 && share < 0.2, `rare, a bit more for big waves (${share})`); - ev(`S.day=${day};UI.via=null;openLinkModal('fra','ams')`); - assert.match(ev("document.getElementById('modalCard').textContent"), /sold out for \d+ days/); - const n = ev('S.links.length'); - ev('ACT.buildLink({tier:2})'); - assert.equal(ev('S.links.length'), n, 'no 400G today'); - assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/); - assert.deepEqual(errors, []); -}); - -test('peering policy: open accepts everyone, selective is quieter but manual, closed scares customers; raise all limits at once', () => { - const { ev, errors } = load(); - setup(ev); - ev("S.nextFail=S.nextEvent=1e9;ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});ACT.rs({city:'ams'});compute()"); - assert.equal(ev("ppol()"), 'open', 'open by default, as before'); - const rsOpen = ev("ixSessions('ams').size"); - assert.ok(rsOpen > 0, 'the route server works'); - // open: requests are accepted as they come in - ev("Math.random=()=>0.01;inboxDay(S.day+1)"); - assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 0); - assert.ok(ev("Object.keys(S.inbox.tiny).length+Object.keys(S.peers).length") > 0, 'and they become sessions'); - // selective: the route server stops counting, you ask yourself, and requests wait for you - ev("ACT.inboxPol({p:'selective'});compute()"); - assert.ok(ev("ixSessions('ams').size") < rsOpen, 'no route server sessions'); - ev("selectCity('ams');ACT.tab({t:'peer'})"); - assert.match(ev("document.getElementById('panelBody').textContent"), /Off while your peering policy is Selective/); - ev("closeModal();S.inbox.items=[];inboxDay(S.day+1)"); - assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 1, 'it waits for an answer'); - // closed: no requests, a sinking reputation, fewer customers calling - ev("ACT.inboxPol({p:'closed'});S.inbox.items=[];S.inbox.rep=0;for(let i=0;i<10;i++)inboxDay(S.day+1)"); - assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 0); - assert.ok(ev('S.inbox.rep') < 0); - // raise all: every alert at once, leaks included - const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})"); - ev(`S.peers['${net}@ams']=true;S.inbox.items=[{id:71,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:80,leak:false,yrs:2},{id:72,k:'mp',key:'t9',nm:'X',asn:9,ix:'ams',day:S.day,lim:50,got:990000,leak:true,yrs:2}];S.inbox.down['${net}@ams']=1e9;ACT.inbox()`); - assert.match(ev("document.getElementById('modalCard').textContent"), /Raise all max-prefix limits/); - ev('ACT.inboxRaiseAll()'); - assert.equal(ev("S.inbox.items.length"), 0); - assert.equal(ev(`!!S.inbox.down['${net}@ams']`), false); - assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'one was a leak'); - assert.match(ev("document.getElementById('toasts').textContent"), /One of them was a route leak/); - // saves keep the policy - ev("const o=JSON.parse(JSON.stringify(S));o.inbox.pol='weird';sanitize(o);window.__o=o"); - assert.equal(ev('__o.inbox.pol'), 'open'); - assert.deepEqual(errors, []); -}); diff --git a/tests/peering-desk.test.js b/tests/peering-desk.test.js new file mode 100644 index 0000000..c5de75e --- /dev/null +++ b/tests/peering-desk.test.js @@ -0,0 +1,117 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()"); +} +// Math.random returns these, then 0.5: [ask?, which IX, a real network?, (which one), fresh PeeringDB?] +const seq = (ev, a) => ev(`(()=>{const q=${JSON.stringify(a)};Math.random=()=>q.length?q.shift():0.5;})()`); +const REAL = [0.01, 0.01, 0.01, 0.01, 0.01], STALE = [0.01, 0.01, 0.9, 0.1], FRESH = [0.01, 0.01, 0.9, 0.9]; + +test('peering requests are answered by policy: Open accepts all, Selective the worthwhile ones, Closed none', () => { + const { ev, errors } = load(); + setup(ev); + assert.equal(ev('ppol()'), 'open', 'open by default, as before'); + const day = () => ev('peeringDeskDay(S.day)'); + const peers = () => ev("Object.keys(S.peers).filter(k=>k.endsWith('@ams')).length"); + let n = peers(); + seq(ev, REAL); day(); + assert.equal(peers(), n + 1, 'Open: a real network on the exchange gets its session at once'); + assert.ok(ev("ixSessions('ams').size") > 0); + seq(ev, STALE); day(); + assert.deepEqual(JSON.parse(ev('JSON.stringify([S.pdesk.a,S.pdesk.d])')), [2, 0], 'Open even takes the stale newcomer'); + ev("ACT.peerPol({p:'selective'})"); + assert.equal(ev('ppol()'), 'selective'); + n = peers(); seq(ev, REAL); day(); + assert.equal(peers(), n + 1, 'Selective: a real small network is worth it'); + seq(ev, STALE); day(); + seq(ev, FRESH); day(); + assert.deepEqual(JSON.parse(ev('JSON.stringify([S.pdesk.a,S.pdesk.d])')), [4, 1], 'stale PeeringDB declined, up-to-date one accepted'); + ev("ACT.peerPol({p:'closed'})"); + n = peers(); seq(ev, REAL); day(); seq(ev, FRESH); day(); + assert.equal(peers(), n, 'Closed: nobody gets a session'); + assert.equal(ev('S.pdesk.d'), 3); + ev("ACT.peerPol({p:'nope'})"); + assert.equal(ev('ppol()'), 'closed', 'junk is ignored'); + assert.deepEqual(errors, []); +}); + +test('once a week the NOC log gets one folded peering desk line', () => { + const { ev, errors } = load(); + setup(ev); + ev("ACT.buyIx({city:'fra',tier:1,signed:true});ACT.peerPol({p:'selective'})"); + seq(ev, [0.99]); ev('S.day=Math.ceil(S.day/7)*7+7;S.pdesk=null;peeringDeskDay(S.day)'); + const w = ev('Math.floor(S.day/7)'); + for (let i = 0; i < 6; i++) { seq(ev, i % 3 === 2 ? STALE : [0.01, i % 2 ? 0.01 : 0.99, 0.9, 0.9]); ev(`peeringDeskDay(S.day+${i})`); } + assert.equal(ev('S.pdesk.w'), w); + const logs = ev('S.log.length'); + seq(ev, [0.99]); ev('peeringDeskDay(S.day+7)'); + assert.equal(ev('S.log.length'), logs + 1, 'one line for the week'); + const line = ev('S.log[0].t'); + assert.match(line, /^Peering desk: 4 new sessions at .+ and .+, 2 declined \(Selective\)\.$/); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.log[0].o)')), { a: 'tab', v: 'nets' }); + assert.equal(ev('S.pdesk.w'), w + 1); + // a quiet week says nothing + ev('peeringDeskDay(S.day+14)'); + assert.equal(ev('S.log.length'), logs + 1); + // the Networks tab has the policy picker, what it does, and last week's line; it fits a phone + ev("window.innerWidth=360;UI.left='nets';UI.leftOpen=true;S.pdeskRep.w=Math.floor(S.day/7)-1;renderLeft()"); + const left = ev("document.getElementById('left').textContent"); + assert.match(left, /Peering policy: Selective/); + assert.match(left, /newcomers with an up-to-date PeeringDB/); + assert.match(left, /Peering desk: 4 new sessions/); + assert.doesNotMatch(left, /inbox/i); + ev("document.querySelector('#left [data-act=peerPol][data-args*=closed]').click()"); + assert.equal(ev('ppol()'), 'closed'); + assert.match(ev("document.getElementById('left').textContent"), /Every peering request is declined/); + // more than four exchanges fold into "and N more" + ev("S.pdeskRep={w:0,a:9,d:0,p:'open',ix:['ams','fra','lon','par','nyc']}"); + assert.match(ev('pdeskLine(S.pdeskRep)'), /9 new sessions at .+, .+, .+ and 2 more exchanges \(Open to all\)/); + assert.match(ev("pdeskLine({a:0,d:1,p:'closed',ix:[]})"), /^Peering desk: 1 request declined \(Closed\)\.$/); + assert.deepEqual(errors, []); +}); + +test('old saves with inbox, max-prefix and Large Peering Model state load and play', () => { + const { ev, errors } = load(); + setup(ev); + const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})"); + ev(`S.peers['${net}@ams']=true;delete S.ppol;delete S.pdesk;delete S.pdeskRep; + S.inbox={items:[{id:1,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3},{id:2,k:'req',ix:'ams',nm:'D',asn:4,day:S.day,say:0,yrs:1}], + down:{'${net}@ams':S.day+30},tiny:{'4':{nm:'D',ix:'ams'}},rep:-8,bot:true,pol:'selective',log:[{d:1,m:'peering_inbox.fire_the_ai',a:{}}],seq:2}; + S.rules={...S.rules,inbox:true};S.ev.ixdown={ams:S.day+2}; + S.inc.push({id:'m1',type:'maxpfx',ref:'ams',until:S.day+2,msg:'A member leaked the table.',cost:0,start:S.day}); + S.log.unshift({id:'l1',t:'Peering request',h:'Peering request',k:'',o:{a:'inbox'},ts:Date.now()})`); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('S.inbox'), undefined, 'the inbox is gone'); + assert.equal(ev('ppol()'), 'selective', 'the policy is kept'); + assert.equal(ev("'inbox' in S.rules"), false); + assert.equal(ev("S.inc.find(i=>i.id==='m1').type"), 'ixloop', 'a max-prefix outage in flight becomes an ordinary IX outage'); + assert.equal(ev("S.inc.some(i=>i.type==='maxpfx')"), false); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.log.find(e=>e.id==='l1').o)")), { a: 'tab', v: 'nets' }); + assert.equal(ev(`ixSessions('ams').has('${net}')`), true, 'no session stays down on an old max-prefix limit'); + const extras = ev('R.cost.extras'); + assert.ok(extras < 20e6 / 12, 'the Large Peering Model no longer bills'); + ev("ACT.logOpen({id:'l1'})"); + assert.equal(ev('UI.left'), 'nets'); + ev('for(let i=0;i<40;i++)dayTick()'); + assert.ok(ev('S.inc.every(i=>i.type!=="maxpfx")')); + assert.ok(ev('S.pdesk&&S.pdesk.w>=0')); + // garbage in the new fields is repaired + ev("const o=JSON.parse(JSON.stringify(S));o.ppol='weird';o.pdesk={w:'x',a:-5,d:1e9,ix:['ams','ams','nowhere',3]};o.pdeskRep=[1];sanitize(o);window.__o=o"); + assert.equal(ev('__o.ppol'), 'open'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(__o.pdesk)')), { w: 0, a: 0, d: 1e5, ix: ['ams'] }); + assert.equal(ev('__o.pdeskRep'), null); + assert.deepEqual(errors, []); +}); + +test('max-prefix incidents can no longer fire', () => { + const { ev, errors } = load(); + setup(ev); + assert.equal(ev("fireFailure.toString().includes('maxpfx')"), false); + ev("S.day=100;const src=fireFailure.toString().replace(/^function fireFailure/,'function').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')"); + ev("__reseed(7);for(let i=0;i<200;i++){__ff();S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}"); + assert.equal(ev('!!window.__mp'), false); + assert.equal(ev("typeof inboxDay+typeof ibx+typeof ACT.inboxRaiseAll+typeof ACT.inboxBot"), 'undefinedundefinedundefinedundefined'); + assert.deepEqual(errors, []); +}); diff --git a/tests/peering.test.js b/tests/peering.test.js index 4e1d185..9377df9 100644 --- a/tests/peering.test.js +++ b/tests/peering.test.js @@ -200,15 +200,14 @@ test('a peer at a rival exchange can de-peer you without stopping the game', () assert.deepEqual(errors, []); }); -test('an IX meltdown at a rival exchange names the city, and a failing day tick does not stop the game', () => { +test('an IX meltdown at a rival exchange names it, and a failing day tick does not stop the game', () => { const { ev, errors } = load(); ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams~2',tier:1});S.day=100"); const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function') - .replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce") - .replace('type=pick(f);}', "type='maxpfx';}"); + .replace('let tot=opts.reduce', "opts.splice(0,opts.length,['ixloop',1]);let tot=opts.reduce"); ev('window.__ff=' + src); ev('__ff()'); - assert.match(ev("S.inc.find(i=>i.type==='maxpfx').msg"), /in Amsterdam, is down/); + assert.ok(ev("S.inc.find(i=>i.type==='ixloop').msg.includes(ixName('ams~2'))")); // a tick that throws is caught, reported once, and the loop keeps going ev("const dt0=dayTick;window.dayTick=()=>{throw new Error('boom')};UI.speed=1;acc=DAY_MS;last=0;frame(16);window.dayTick=dt0"); assert.equal(ev('UI.tickErr'), true); diff --git a/tests/pnis-and-sold-out.test.js b/tests/pnis-and-sold-out.test.js new file mode 100644 index 0000000..485482f --- /dev/null +++ b/tests/pnis-and-sold-out.test.js @@ -0,0 +1,127 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()"); +} + +test('PNIs with the big networks take a month, now and then 6 to 12, and start at 100G; small ones take weeks', () => { + const { ev, errors } = load(); + setup(ev); + ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:0})"); + assert.equal(ev('S.pni.length'), 0, 'no 10G PNI with NetChill'); + assert.match(ev("document.getElementById('toasts').textContent"), /does not do 10G/); + // one order in seven gets lost in provisioning for months + ev("Math.random=()=>0.1;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})"); + const p = JSON.parse(ev('JSON.stringify(S.pni[0])')); + assert.ok(p.ready - ev('S.day') >= 180 && p.ready - ev('S.day') <= 365, `six to twelve months (${p.ready - ev('S.day')} days)`); + ev('compute()'); + assert.equal(ev('R.usePni[S.pni[0].id]||0'), 0, 'nothing flows before delivery'); + assert.equal(ev('R.cost.pni'), 0, 'and nothing is billed'); + ev('S.nextFail=S.nextEvent=1e9;S.pni[0].ready=S.day+1;dayTick();compute()'); + assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'delivered on the day'); + // an upgrade is an augment on order: the old port keeps working meanwhile + ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})"); + assert.equal(ev('S.pni[0].tier'), 1); + assert.equal(ev('S.pni[0].up.tier'), 2); + ev('ACT.lagP({id:S.pni[0].id,d:1})'); + assert.equal(ev('S.pni[0].up.n'), 1, 'one augment at a time'); + ev('S.day=S.pni[0].up.ready-1;dayTick()'); + assert.equal(ev('S.pni[0].tier'), 2); + assert.equal(ev('S.pni[0].up'), undefined); + // chasing it does nothing, mostly + ev("Math.random=()=>0.5;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:3});const r0=S.pni[0].up.ready;ACT.pniChase({id:S.pni[0].id});window.__r=[r0,S.pni[0].up.ready]"); + const [r0, r1] = JSON.parse(ev('JSON.stringify(__r)')); + assert.equal(r0, r1); + // most orders arrive in about a month + ev("Math.random=()=>0.5;S.pni=[];R.demTo.ggl=1e4;ACT.pni({city:'fra',net:'ggl',tier:1})"); + assert.equal(ev("S.pni.find(p=>p.net==='ggl').ready-S.day"), 30); + ev("S.pni=S.pni.filter(p=>p.net!=='ggl')"); + // a beer at a conference halves the wait + ev("Math.random=()=>0.99;S.conf={until:S.day+10,reg:'EU',name:'RIPE'}"); + assert.equal(ev("pniLead('ggl')"), 15, 'the usual month, halved'); + ev('Math.random=()=>0.1'); + assert.equal(ev("pniLead('ggl')"), Math.round((180 + Math.floor(0.1 * 186)) / 2), 'a slow one, halved'); + ev('Math.random=()=>0.99'); + ev('S.conf=null'); + // a small network: a few weeks + const small = ev("NETS.find(n=>n.pops.includes('fra')&&!pniBig(n.id)&&n.pol==='open'&&n.type!=='cdn').id"); + ev(`Math.random=()=>0.99;ACT.pni({city:'fra',net:'${small}',tier:0})`); + const lead = ev(`S.pni.find(p=>p.net==='${small}').ready-S.day`); + assert.ok(lead >= 14 && lead <= 42, `weeks, not months (${lead})`); + assert.deepEqual(errors, []); +}); + +test('Doitsche Telekomm sells 1G PNIs; nobody else does', () => { + const { ev, errors } = load(); + setup(ev); + ev("S.lvl=10;ACT.pni({city:'fra',net:'nfx',tier:-1})"); + assert.equal(ev('S.pni.length'), 0); + assert.equal(ev("peerOk('dtk','pni','fra').ok"), true); + ev("ACT.pni({city:'fra',net:'dtk',tier:-1})"); + assert.equal(ev('S.pni[0].g1'), true); + ev('S.pni[0].ready=S.day;compute()'); + assert.equal(ev('pniG(S.pni[0])'), 1); + assert.equal(ev("liveCap(pniG(S.pni[0]),'fra','a',1)"), 1); + assert.equal(ev('pniPN(S.pni[0])'), '1G'); + // and 1G grows into 10G + ev("ACT.pni({city:'fra',net:'dtk',tier:0})"); + assert.equal(ev('S.pni[0].up.tier'), 0); + ev('S.day=S.pni[0].up.ready-1;dayTick()'); + assert.equal(ev('S.pni[0].g1'), undefined); + assert.equal(ev('pniG(S.pni[0])'), 10); + ev("selectCity('fra');ACT.tab({t:'peer'})"); + assert.deepEqual(errors, []); +}); + +test('Microsnoft has no capacity on the US east coast, at any price', () => { + const { ev, errors } = load(); + setup(ev); + ev("for(const c of ['ash','nyc','hou'])ACT.buildPop({city:c});R.demTo.msf=1e5"); + for (const c of ['ash', 'nyc', 'bos', 'atn', 'mia']) { + assert.equal(ev(`peerOk('msf','pni','${c}').ok`), false, c); + assert.equal(ev(`peerOk('msf','ix','${c}').ok`), false, c); + } + assert.match(ev("peerOk('msf','pni','ash').why"), /capacity|sold out|coming online/i); + assert.equal(ev("peerOk('msf','pni','hou').ok"), true, 'Houston is fine'); + ev("ACT.pni({city:'ash',net:'msf',tier:1})"); + assert.equal(ev("S.pni.filter(p=>p.city==='ash').length"), 0); + assert.equal(ev("peerOk('ggl','pni','ash').ok"), ev("R.demTo.ggl>=Math.round(NET.ggl.minPni)"), 'other networks are not affected'); + assert.deepEqual(errors, []); +}); + +test('saves: PNIs on order survive, and garbage is repaired', () => { + const { ev, errors } = load(); + setup(ev); + ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})"); + ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o'); + assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX')); + assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true); + assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G'); + assert.deepEqual(errors, []); +}); + +test('now and then a route is sold out of a wave size, for a while, and asking again does not reroll it', () => { + const { ev, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3"); + assert.equal(ev("S.day=10;!!soldOut('fra','ams',3,null)||!!soldOut('fra','ams',1,null)"), false, 'never in the first 90 days'); + // find a day when 400G is sold out between Frankfurt and Amsterdam + const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null))return d;}return -1;})()"); + assert.ok(day > 0, 'it happens'); + ev(`S.day=${day}`); + const so = JSON.parse(ev("JSON.stringify(soldOut('fra','ams',2,null))")); + assert.ok(so.until > day && so.until - day <= 90); + assert.equal(ev(`S.day=${so.until - 1};!!soldOut('fra','ams',2,null)`), true, 'the same verdict for the whole window'); + ev(`S.day=${day}`); + const share = ev("(()=>{let n=0;for(let d=90;d<20090;d++){S.day=d;if(soldOut('ams','fra',5,null))n++;}return n/20000;})()"); + assert.ok(share > 0.02 && share < 0.2, `rare, a bit more for big waves (${share})`); + ev(`S.day=${day};UI.via=null;openLinkModal('fra','ams')`); + assert.match(ev("document.getElementById('modalCard').textContent"), /sold out for \d+ days/); + const n = ev('S.links.length'); + ev('ACT.buildLink({tier:2})'); + assert.equal(ev('S.links.length'), n, 'no 400G today'); + assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/); + assert.deepEqual(errors, []); +}); diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 1ba9ef3..5dfddd8 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -488,7 +488,7 @@ test('main-game toasts and leftover buttons do nothing in a puzzle', () => { 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({})", + for (const a of ["opsOpen({})", "peerPol({p:'closed'})", "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); diff --git a/tests/rules.test.js b/tests/rules.test.js index 9d24992..413ad74 100644 --- a/tests/rules.test.js +++ b/tests/rules.test.js @@ -159,11 +159,10 @@ test('quick lead times: PNIs, dark fiber and own builds arrive in days (#151)', assert.deepEqual(errors, []); }); -test('Change Freeze: no peering inbox, no hardware market, no sold-out routes', () => { +test('Change Freeze: no hardware market, no sold-out routes', () => { const { ev, errors } = load(); start(ev, { mode: 'normal', preset: 'freeze' }); - ev("S.cash=1e9;ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<60;i++)inboxDay(S.day+i)"); - assert.equal(ev('S.inbox.items.length+S.inbox.seq'), 0, 'no mail'); + ev("S.cash=1e9;ACT.buyIx({city:'fra',tier:1,signed:true})"); ev('S.day=2000'); assert.equal(ev("hwMul('rt')"), 1, 'no inflation'); assert.equal(ev("hwCard()"), ''); diff --git a/tests/utilities.test.js b/tests/utilities.test.js index dae73a8..415925f 100644 --- a/tests/utilities.test.js +++ b/tests/utilities.test.js @@ -127,7 +127,7 @@ test('route-server batch leaves peering policy and player-owned exchanges alone' 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()"); + ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.peerPol({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'); From 101ced4482239b178a5dccbf061dbbd96f135fc3 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 22:12:43 +0100 Subject: [PATCH 140/181] Tests follow the peering desk: #134 uses an IX loop, Red Sea window, regenerated week 2026-W44 par --- site/scenarios/weekly/2026-W44.json | 2 +- tests/issues.test.js | 2 +- tests/scenarios-playtest.test.js | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/site/scenarios/weekly/2026-W44.json b/site/scenarios/weekly/2026-W44.json index 8424bfe..62a3d72 100644 --- a/site/scenarios/weekly/2026-W44.json +++ b/site/scenarios/weekly/2026-W44.json @@ -1 +1 @@ -{"v":1,"key":"2026-W44","theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":3,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":24,"big":1}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":195,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":1}} +{"v":1,"key":"2026-W44","theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":3,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":24,"big":1}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":169,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":1}} diff --git a/tests/issues.test.js b/tests/issues.test.js index e77f4fd..37b25dc 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -1311,7 +1311,7 @@ test('#134 an exchange named after its city does not repeat the city in messages const labs = JSON.parse(ev("JSON.stringify(lagsN().filter(o=>o.k==='ix').map(o=>o.lab))")); assert.ok(labs.includes('IX.brrr Campinas LAG'), labs.join(' | ')); assert.ok(labs.some(l => / LAG in Frankfurt$/.test(l)), labs.join(' | ')); - ev("S.inc=[];eval('('+fireFailure.toString().replace(\"if(type==='funny'){\",\"type='funny';if(type==='funny'){\").replace('type=pick(f);}',\"type='maxpfx';}\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()"); + ev("S.inc=[];eval('('+fireFailure.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()"); const msg = ev("S.inc.map(i=>i.msg).join(' ')"); assert.match(msg, /IX\.brrr Campinas/); assert.doesNotMatch(msg, /in Campinas/); diff --git a/tests/scenarios-playtest.test.js b/tests/scenarios-playtest.test.js index 663fb11..1e8afeb 100644 --- a/tests/scenarios-playtest.test.js +++ b/tests/scenarios-playtest.test.js @@ -18,7 +18,8 @@ const PLAY = { win: [120, 240], cheese: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['loans'], ['hire', ['routers', 'repair']]], by: null }, // The other way round the planet: Paris, New York, Los Angeles, Tokyo, Hong Kong, Singapore. redsea: { ref: [...home('mrs'), ['link', 'mrs', 'par', 1], ['bb', 'par'], ['ix', 'par'], ['link', 'par', 'nyc', 1, 'amitie'], ['tr', 'nyc', 1], ['ix', 'nyc'], ['link', 'nyc', 'lax', 1], ['ix', 'lax'], ['tr', 'lax', 1], ['link', 'lax', 'tok', 1, 'jup'], ['bb', 'tok'], ['tr', 'tok', 1], ['ix', 'tok'], ['link', 'tok', 'hkg', 1, 'apg'], ['bb', 'hkg'], ['tr', 'hkg', 1], ['ix', 'hkg'], ['link', 'hkg', 'sin', 1], ['bb', 'sin'], ['tr', 'sin', 1], ['ix', 'sin'], HIRE], - win: [100, 250], cheese: [...home('mrs'), ['loans'], ['link', 'mrs', 'sin', 1], ['bb', 'sin']], by: null }, + // 2.0.0: no more max-prefix outages to break the 30-day streak, so the reference can finish in under 100 days. + win: [80, 250], cheese: [...home('mrs'), ['loans'], ['link', 'mrs', 'sin', 1], ['bb', 'sin']], by: null }, spat: { ref: [...home('nyc'), HIRE], avoid: ['cog'], win: [50, 140], cheese: [...home('nyc'), ['hire', ['routers', 'repair']]], by: 160 }, carnaval: { ref: [...home('rio'), ['hire'], ['wait', 69], ['prep', 'rio', 400], ['wait', 76], ['prep', 'rio', 400], ['wait', 83], ['prep', 'rio', 400]], win: [95, 95], cheese: [...home('rio'), ['loans']], by: null }, darien: { ref: [...home('pan'), ['link', 'pan', 'bog', 1, 'pccs'], ['bb', 'bog'], ['ix', 'bog'], ['link', 'bog', 'lim', 1], ['bb', 'lim'], ['ix', 'lim'], ['link', 'lim', 'scl', 1], ['bb', 'scl'], ['ix', 'scl'], ['link', 'scl', 'sao', 1], ['bb', 'sao'], ['tr', 'sao', 1], ['ix', 'sao'], HIRE], From 644e6174d9483fdd777980de721db77acea7d5e2 Mon Sep 17 00:00:00 2001 From: tkjaer Date: Fri, 30 Oct 2026 08:01:42 +0100 Subject: [PATCH 141/181] Architect runs (prototype): one network, built brief by brief Three runs (Euro Run, Coast to Coast, Pacific Rim) on the puzzle machinery: briefs add sites, raise demand, make sites gold, ask for rings or latency caps, or close a city; earlier builds stay paid for, and the backhoe review cuts every trench and cable in turn. By tkjaer, from seriesoftubes-architect. --- src/game/60-features/92-puzzles.js | 14 +-- src/game/60-features/96-architect.js | 163 +++++++++++++++++++++++++++ src/game/90-actions/95-puzzles.js | 34 +++--- src/game/90-actions/96-architect.js | 8 ++ src/game/94-dashboard/80-hint.js | 2 +- src/game/95-modals/95-puzzles.js | 7 +- src/game/95-modals/96-architect.js | 82 ++++++++++++++ src/game/96-map/50-link-geometry.js | 4 +- src/game/96-map/60-draw.js | 6 +- src/game/96-map/70-world-layer.js | 6 +- src/game/96-map/85-puzzle-cities.js | 10 +- src/game/96-map/95-clicks.js | 2 +- src/i18n/en.js | 113 +++++++++++++++++++ src/styles/71-architect.css | 28 +++++ tests/architect.test.js | 149 ++++++++++++++++++++++++ 15 files changed, 588 insertions(+), 40 deletions(-) create mode 100644 src/game/60-features/96-architect.js create mode 100644 src/game/90-actions/96-architect.js create mode 100644 src/game/95-modals/96-architect.js create mode 100644 src/styles/71-architect.css create mode 100644 tests/architect.test.js diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index c840b9f..201d9bc 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -11,7 +11,7 @@ const pzOn=()=>!!(S&&S.mode==='puzzle'&&S.pz); const pzDef=id=>PZ.find(p=>p.id===id)||null; // goal: a city the traffic starts or ends in; via: a suggested stepping stone; avoid: off limits; off: any other city // (the whole world is open, it just is not part of the plan). -const pzKind=c=>!pzOn()?null:S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':pzCityOk(c)?'off':null; +const pzKind=c=>!pzOn()?null:S.ar?arKind(c):S.pz.cities.includes(c)?'goal':S.pz.via.includes(c)?'via':S.pz.avoid.includes(c)?'avoid':pzCityOk(c)?'off':null; 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); // Every city a puzzle's traffic touches, origins first. @@ -64,7 +64,7 @@ const pzFlowName=f=>f.t==='l2'?tr('puzzles.flow_circuit_a_b',{a:CITY[f.a].name,b function pzDemand(){const P=S.pz;S.transit=P.src.map((c,i)=>({id:'pzo'+i,city:c,net:PZ_NET,tier:PZ_ORIG,n:1,pz:1,pref:'normal',hist:[]})); S.biz=P.dem.map((f,i)=>f.t==='l2'?{id:pzFlowId(i),type:'l2vpn',name:pzFlowName(f),city:f.a,city2:f.b,bw:f.g,rate:0,route:'normal',reqs:[],day:0}:null).filter(Boolean);} const pzEye=c=>{const f=pzOn()&&S.pz.dem.find(x=>x.t==='eye'&&x.a===c);return f?f.g:0;}; -const pzNewPop=c=>{const g=pzEye(c);return {day:0,bb:g?{d:g}:null,boost:0,down:0,routers:1,gen:false};}; +const pzNewPop=c=>{const g=pzEye(c);return {day:0,bb:g?{d:g}:null,boost:0,down:0,routers:1,gen:false,br:S.ar?S.ar.bi:0};}; // What each flow gets from the last compute(): Gbps delivered, and a circuit's latency. // Eyeball traffic to networks behind the Great Firewall loses a fifth at the border, as in the main game; that is not // the player's doing, so a puzzle counts what crosses the border as delivered (pzGfw: the share that arrives). @@ -130,7 +130,7 @@ function pzBegin(def){if(!def)return; if(pzOn()){go();return;} const live=!!(S&&UI.started&&!S.lost);UI.pzFrom=live?'game':'title'; if(live)pzFlush();go();} -function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; +function pzLeave(){if(S&&S.ar)arStop(true);const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null; if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} // It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told. @@ -139,17 +139,17 @@ function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList. // The camera frames the puzzle's cities beside the puzzle card: left on wide screens, right on phones on their side, a bottom sheet on phones. function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0].x;let a=Infinity,b=-Infinity,c=Infinity,d=-Infinity; for(const C of cs){const x=x0+wrapDx(x0,C.x);a=Math.min(a,x);b=Math.max(b,x);c=Math.min(c,C.y);d=Math.max(d,C.y);} - const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); + const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:S.ar&&CW>760&&CH>500?410:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();} // ---------- building ---------- -function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();} +function pzSnap(){if(S.ar)arStop();const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route),k:S.ar?S.ar.sunk:0}));if(h.length>60)h.shift();} function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI.sel.id))||(UI.sel.type==='city'&&!pzKind(UI.sel.id))))UI.sel=null; - compute();renderAll();pzCheck();} + if(S.ar)arRouters();compute();renderAll();pzCheck();} // Stars count the moment they are earned. // Every solved state is recorded, so a cheaper build at the same stars counts too. // A new star below three is a cheer and a nudge, and play goes on; the results card opens at three stars, or when the // player says they are done (the card's Finish button). -function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}return e;} +function pzCheck(){if(arOn())return null;const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}return e;} // The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend. function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null}; if(e.starspzOn()&&!!S.ar; +const arRunDef=id=>AR_RUNS.find(r=>r.id===id)||null; +const arRun=()=>arRunDef(S.ar.id); +const arBrief=()=>arRun().briefs[S.ar.bi]; +const arLast=()=>S.ar.bi>=arRun().briefs.length-1; +// ---------- progress: best stars, spend and briefs cleared per run, under its own key ---------- +function arLoad(){let j=null;try{j=JSON.parse(localStorage.getItem(AR_KEY)||'{}');}catch(e){}const o={runs:{}}; + if(j&&j.runs&&typeof j.runs==='object')for(const k of Object.keys(j.runs)){const r=j.runs[k];if(!arRunDef(k)||!r||typeof r!=='object')continue; + o.runs[k]={st:int(r.st,0,3,0),br:int(r.br,0,99,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)};} + return o;} +function arStore(p){try{localStorage.setItem(AR_KEY,JSON.stringify(p));}catch(e){}} +function arRecord(st,br,sp){const p=arLoad(),r=p.runs[S.ar.id]||{st:0,br:0,sp:null}; + if(st>r.st||(st===r.st&&st>0&&(r.sp==null||sppzPopCost(c)+pzRouterCost(c); +const arLinkCost=l=>l.mo*PZ_YEAR; +const arSpend=()=>pzSpend()+S.ar.sunk; +// Removing what an earlier brief built gives nothing back. +const arAge=l=>l.ub==null?(l.br|0):l.ub; +function arSink(pops,links){const A=S.ar;for(const c of pops)if(S.pops[c]&&(S.pops[c].br|0)pzUnit(l)===u),r=arReach(S.ar.hq,nb);return S.pz.cities.filter(c=>S.pops[c]&&!r.has(c));} +// The fastest path between two sites, by the links' own latency. +function arLat(a,b){if(!S.pops[a]||!S.pops[b])return null;const d={[a]:0},done=new Set(); + for(;;){let u=null;for(const k in d)if(!done.has(k)&&(u===null||d[k]nb[c]&&nb[c].size>=2))return false;const st=cs[0],on=new Set([st]);let ok=false,n=0; + const dfs=(u,d)=>{for(const v of nb[u]){if(ok||++n>50000)return;if(v===st&&d>=3&&cs.every(c=>on.has(c))){ok=true;return;}if(on.has(v))continue;on.add(v);dfs(v,d+1);on.delete(v);}}; + dfs(st,1);return ok;} +// Tubes laid in this brief, against its plan. +const arTubes=()=>{const b=arBrief(),u=S.links.filter(l=>(l.br|0)===S.ar.bi).length;return {u,max:b.tubes==null?null:b.tubes,over:b.tubes==null?0:Math.max(0,u-b.tubes)};}; +// ---------- the brief's checklist ---------- +function arEval(){const A=S.ar,P=S.pz,nb=arAdj(),r=arReach(A.hq,nb); + const got=S.links.some(l=>l.cut)&&UI.arBaseGot?UI.arBaseGot:arGot(); + const sites=P.cities.map(c=>({c,pop:!!S.pops[c],ok:!!S.pops[c]&&r.has(c),gold:A.gold.includes(c),hq:c===A.hq,dem:c===A.hq?0:arDem(c),got:c===A.hq?0:got[c]||0}));for(const s of sites)s.full=s.hq||s.got>=s.dem*0.999-1e-6; + const conn=sites.every(s=>s.ok),lat=A.lat?{a:A.lat[0],b:A.lat[1],cap:A.lat[2],ms:arLat(A.lat[0],A.lat[1])}:null;if(lat)lat.ok=lat.ms!=null&&lat.ms<=lat.cap+1e-9; + const moveOut=P.avoid.filter(c=>S.pops[c]),spend=arSpend(),budget=arRun().budget,cheap=spend<=budget+1e-6,miss=sites.filter(s=>!s.ok).map(s=>CITY[s.c].name),rings=A.rings.map(cs=>({cs,ok:arRingOk(cs)})),tubes=arTubes(); + const why=!conn?tr('architect.not_connected_yet_list',{list:miss.join(', ')}):lat&&!lat.ok?tr('architect.too_slow_for_the_cap'):rings.some(r=>!r.ok)?tr('architect.not_a_ring_yet'):sites.some(s=>!s.full)?tr('architect.too_thin_list',{list:sites.filter(s=>!s.full).map(s=>`${CITY[s.c].name} ${arG(s.got)}/${arG(s.dem)}`).join(', ')}):moveOut.length?tr('architect.move_out_of_city',{city:moveOut.map(c=>CITY[c].name).join(', ')}):''; + return {sites,conn,lat,rings,tubes,moveOut,spend,budget,cheap,ready:!why,why,passed:A.passed===pzSig()};} +// ---------- the shape: the game names what you drew ---------- +const AR_SHAPES={braces:['🦺',N_('architect.shape_braces')],tube:['🧪',N_('architect.shape_tube')],line:['➖',N_('architect.shape_line')],star:['✳️',N_('architect.shape_star')],tree:['🌳',N_('architect.shape_tree')],ring:['💍',N_('architect.shape_ring')],lolli:['🍭',N_('architect.shape_lolli')],ladder:['🪜',N_('architect.shape_ladder')],mesh:['🕸️',N_('architect.shape_mesh')],full:['🧶',N_('architect.shape_full')],islands:['🏝️',N_('architect.shape_islands')],spaghetti:['🍝',N_('architect.shape_spaghetti')]}; +function arShape(){const ns=Object.keys(S.pops),n=ns.length;if(n<2||!S.links.length)return null;const nb=arAdj(),m=new Set(S.links.map(edgeKey)).size,deg=c=>nb[c].size,maxd=Math.max(...ns.map(deg)); + const dbl=[...new Set(S.links.map(edgeKey))].filter(e=>new Set(S.links.filter(l=>edgeKey(l)===e).map(pzUnit)).size>1).length; + let k;if(arReach(ns[0],nb).size=4?'star':maxd<=2?'line':'tree'; + else if(ns.every(c=>deg(c)===2))k='ring';else if(n>=4&&m===n*(n-1)/2)k='full'; + else{const core={};for(const c of ns)core[c]=new Set(nb[c]);let cut=true;while(cut){cut=false;for(const c in core)if(core[c].size<=1){for(const v of core[c])core[v]&&core[v].delete(c);delete core[c];cut=true;}} + const cs=Object.keys(core),cm=cs.reduce((a,c)=>a+core[c].size,0)/2,d2=cs.filter(c=>core[c].size===2).length; + k=cs.lengthcore[c].size===2)?'lolli':cs.length===n&&n>=6&&n%2===0&&cm===3*n/2-2&&d2===4&&cs.every(c=>core[c].size<=3)?'ladder':m>=n*1.8?'spaghetti':'mesh';} + return {k,i:AR_SHAPES[k][0],n:tr(AR_SHAPES[k][1])};} +// What later briefs do to a city, for the map: [{n: brief number, i: icon}], earliest first. +function arTags(c){const A=S.ar,out=[];arRun().briefs.forEach((b,j)=>{if(j<=A.bi)return;const i=(b.gold||[]).includes(c)?'🥇':(b.add||[]).includes(c)?'📍':(b.drop||[]).includes(c)?'🚫':b.dem&&b.dem[c]?'📈':(b.ring||[]).includes(c)?'💍':b.lat&&b.lat.slice(0,2).includes(c)?'⏱':'';if(i)out.push({n:j+1,i});});return out;} +// One line per brief for the plan on the card. +function arSum(b){const nm=c=>CITY[c].name,t=[],d=b.dem||{};if(b.add)t.push(b.add.map(c=>'+'+nm(c)+(d[c]?' '+arG(d[c]):'')).join(' '));for(const c in d)if(!(b.add||[]).includes(c))t.push('📈 '+nm(c)+' '+arG(d[c]));if(b.gold)t.push('🥇 '+b.gold.map(nm).join(', ')); + if(b.ring)t.push('💍 '+b.ring.map(nm).join('–'));if(b.lat)t.push(`⏱ ${nm(b.lat[0])}⇄${nm(b.lat[1])} < ${b.lat[2]} ms`);if(b.drop)t.push('🚫 '+b.drop.map(nm).join(', ')); + if(b.tubes!=null)t.push(trn('architect.n_tubes',b.tubes));return t.join(' · ');} +// ---------- starting, briefs and the end ---------- +const arDem=c=>S.ar.dem[c]||10; +// Short Gbps for chips and tags: 40G, 1.2T. +const arG=g=>g>=1000?+(g/1000).toFixed(1)+'T':Math.round(g)+'G'; +function arDemand(){const P=S.pz,A=S.ar;P.src=[A.hq];P.dem=P.cities.filter(c=>c!==A.hq).map(c=>({t:'eye',a:c,b:null,g:arDem(c),ms:0,be:false}));pzDemand(); + for(const c in S.pops)S.pops[c].bb=P.cities.includes(c)&&c!==A.hq?{d:arDem(c)}:null;} +// What each site gets right now, from the last compute(). +function arGot(){const g=pzGot(),o={};S.pz.dem.forEach((f,i)=>{o[f.a]=g[i].g;});return o;} +// Connected sites that do not get all of their traffic. +function arShort(dark){const got=arGot();return S.pz.cities.filter(c=>c!==S.ar.hq&&S.pops[c]&&!(dark||[]).includes(c)&&(got[c]||0)PZ_RG.slice().sort((a,b)=>pzRtCost(a,1)-pzRtCost(b,1)); +function arRouters(){for(const c in S.pops){const p=S.pops[c];p.routers=1;p.rgen=AR_RG().find(g=>!modelFits(c,g))??(p.rgen||0);}} +// The yearly router cost a tube of this size would add at a city (0 when its router already takes it). +function arRouterDelta(c,tier){const p=S.pops[c],cur=p?pzRtCost(p.rgen||0,1):0,need=Math.max(tier,...S.links.filter(l=>l.a===c||l.b===c).map(l=>l.tier)),g=AR_RG().find(i=>RG[i].maxLT>=need);return g==null?0:Math.max(0,pzRtCost(g,1)-cur);} +const arSnapStr=()=>JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},k:S.ar.sunk}); +function arBegin(run){if(!run)return;const b0=run.briefs[0]; + pzBegin({id:'ar_'+run.id,n:run.n,src:[run.hq],dem:b0.add.map(c=>({t:'eye',a:c,g:1})),via:run.via,budget:0}); + pzToastsClear();S.pz.n=run.n;S.te={on:true,day:0};S.ar={id:run.id,hq:run.hq,bi:-1,sunk:0,over:0,dem:{},rings:[],gold:[],lat:null,passed:null,start:null};UI.arAll=false;arStop(true); + S.pops[run.hq]=pzNewPop(run.hq);arApply(0);} +function arApply(i){const A=S.ar,P=S.pz,b=arRun().briefs[i];A.bi=i; + for(const c of b.drop||[]){P.cities=P.cities.filter(x=>x!==c);A.gold=A.gold.filter(x=>x!==c);if(!P.avoid.includes(c))P.avoid.push(c);if(A.lat&&A.lat.includes(c))A.lat=null;A.rings=A.rings.filter(r=>!r.includes(c));} + for(const c of b.add||[])if(!P.cities.includes(c))P.cities.push(c); + for(const c of b.gold||[])if(!A.gold.includes(c))A.gold.push(c); + if(b.ring)A.rings.push(b.ring.slice());Object.assign(A.dem,b.dem||{}); + if(b.lat)A.lat=b.lat.slice();A.passed=null; + P.via=[...new Set(arRun().briefs.slice(i+1).flatMap(x=>[...(x.add||[]),...(x.gold||[]),...(x.ring||[])]))].filter(c=>!P.cities.includes(c)&&!P.avoid.includes(c)); + arDemand();A.start=arSnapStr();UI.pzHist=[];UI.sel=null;UI.arFail=null; + compute();pzCam();renderAll(); + toast(`${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}
${esc(b.t)}${i===0&&arRun().briefs.length>1?'
'+tr('architect.numbers_on_the_map_show')+'':''}`,'goal');sfx('click');} +function arNext(){if(!arOn())return;const e=arEval();if(!e.passed)return;if(arLast()){arResults(true);return;}S.ar.over+=e.tubes.over;arApply(S.ar.bi+1);} +function arReset(){const o=JSON.parse(S.ar.start);S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};S.ar.sunk=o.k||0;arDemand();UI.sel=null;} +// Tubes over plan in the run so far, this brief included. +const arOver=()=>S.ar.over+arTubes().over; +function arStars(sp){return 1+(arOver()?0:1)+(sp<=arRun().budget+1e-6?1:0);} +function arShareText(st,sp){const sh=arShape();return tr('architect.share_line',{what:arRun().n,stars:pzStarStr(st),spend:fmt$(sp),shape:sh?sh.i+' '+sh.n:''});} +// ---------- ▶ the backhoe review ---------- +// Every trench and cable is cut in turn, routed by compute() so the traffic visibly moves; a gold site losing HQ stops +// the review with the cut still on the map, until the next edit. +function arStop(quiet){const sh=UI.arShow;if(sh&&sh.t)clearTimeout(sh.t);UI.arShow=null;if(!S||!S.links)return;let any=false;for(const l of S.links)if(l.cut){l.cut=0;any=true;} + if(UI.arFail){UI.arFail=null;any=true;}if(any&&!quiet)compute();} +function arShowStart(){if(!arOn()||UI.arShow)return;const e=arEval();if(!e.ready){toast(esc(e.why),'bad');sfx('err');return;} + arStop(true);UI.sel=null;closeModal();UI.arBaseGot=arGot();UI.arShow={units:[...new Set(S.links.map(pzUnit))],i:-1,t:0,dark:[],short:[]};arStep();} +// One cut, routed: who goes dark, which gold sites with it, and who is still connected but short of room. +function arCut(u){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1;compute();const dark=arDark(u);return {ls,dark,gold:dark.filter(c=>S.ar.gold.includes(c)),short:arShort(dark)};} +function arStep(){const sh=UI.arShow;if(!sh||!arOn())return;for(const l of S.links)l.cut=0;sh.i++; + if(sh.i>=sh.units.length){UI.arShow=null;compute();S.ar.passed=pzSig();renderAll();sfx('star');haptic(15); + toast(`✅ ${tr('architect.review_passed')}
${arLast()?tr('architect.last_brief_done'):tr('architect.next_brief_waiting')}`,'good');if(arLast())setTimeout(()=>{if(arOn()&&S.ar.passed===pzSig())arResults(true);},900);return;} + const u=sh.units[sh.i],{ls,dark,gold,short}=arCut(u),l0=ls[0],got=arGot();sh.dark=dark;sh.short=short;sh.u=u; + floater((CITY[l0.a].x+CITY[l0.a].x+wrapDx(CITY[l0.a].x,CITY[l0.b].x))/2,(CITY[l0.a].y+CITY[l0.b].y)/2-26,l0.sub?tr('architect.anchor'):tr('architect.backhoe'),'#FF8A3D'); + for(const c of dark)floater(CITY[c].x,CITY[c].y-34,gold.includes(c)?'💥 '+CITY[c].name:tr('architect.city_goes_dark',{city:CITY[c].name}),gold.includes(c)?'#FF4D5E':'#9AA3BE'); + for(const c of short)floater(CITY[c].x,CITY[c].y-34,tr('architect.city_short_g',{city:CITY[c].name,g:arG(arDem(c)-(got[c]||0))}),'#FF4D5E'); + const bad=gold.length||short.length;sfx(bad?'err':'click'); + if(bad){UI.arShow=null;UI.arFail={u,gold,dark,short};renderAll();haptic(30);return;} + renderAll();sh.t=setTimeout(arStep,dark.length?AR_STEP*1.6:AR_STEP);} +// Skip the show: check every cut at once, and stop at the first that breaks a gold site. +function arShowSkip(){const sh=UI.arShow;if(!sh)return;clearTimeout(sh.t);for(const l of S.links)l.cut=0; + for(let i=sh.i+1;i!S.pops[c]||portsUsed(c)+1<=portsMax(c)+1e-9; 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:()=>{if(pzWkLoading())return;pzBegin(pzWkDef());}, - pzFinish:()=>{if(!pzOn())return;const e=pzEval();if(e.stars)pzResults(e,e.stars);}, - pzRetry:()=>{if(!pzOn())return;pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, + pzFinish:()=>{if(!pzOn())return;if(S.ar){arResults(false);return;}const e=pzEval();if(e.stars)pzResults(e,e.stars);}, + pzRetry:()=>{if(!pzOn())return;if(S.ar){arBegin(arRun());return;}pzBegin(S.pz.id==='weekly'?pzWkDef():pzDef(S.pz.id));}, pzLeave:()=>{if(pzOn())pzLeave();}, pzPop:({city})=>{if(!pzOn()||S.pops[city]||!['goal','via','off'].includes(pzKind(city)))return;pzSnap();S.pops[city]=pzNewPop(city);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);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, + pzRmPop:({city})=>{if(!pzOn()||!S.pops[city]||(S.ar&&city===S.ar.hq))return;pzSnap();if(S.ar)arSink([city],S.links.filter(l=>l.a===city||l.b===city));delete S.pops[city];S.links=S.links.filter(l=>l.a!==city&&l.b!==city);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, pzLinkTo:({a,b})=>{if(!pzOn()||!S.pops[a]||a===b)return;pzLinkModal(a,b);}, pzVia:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzVia=v;pzLinkModal(p.a,p.b,true);}, pzDiv:({v})=>{const p=UI.pending;if(!pzOn()||!p)return;UI.pzDiv=!!+v;pzLinkModal(p.a,p.b,true);}, - pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!PZ_TIERS.includes(tier))return;const {a,b}=p,kb=pzKind(b);if(!S.pops[a]||!['goal','via','off'].includes(kb))return; + pzLink:({tier})=>{tier=+tier;const p=UI.pending;if(!pzOn()||!p||!(S.ar?AR_TIERS:PZ_TIERS).includes(tier))return;const {a,b}=p,kb=pzKind(b);if(!S.pops[a]||!['goal','via','off'].includes(kb))return; const r=pzRoutes(a,b).find(x=>x.via===UI.pzVia);if(!r||(S.pz.noSub&&r.sub))return; const why=pzWaveWhy(a,b,tier,r);if(why){toast(esc(why),'bad');sfx('err');return;} - if(!portGate(a,1)||(S.pops[b]&&!portGate(b,1)))return; + if(!S.ar&&(!portGate(a,1)||(S.pops[b]&&!portGate(b,1))))return; // Overland: the same trench as a link already on the pair (the one picked from, or the first), or a diverse route // of its own. Every trench but the first runs the long way round and costs 40% more. const lands=pzOn()&&!r.sub?S.links.filter(l=>edgeKey(l)===edgeKey({a,b})&&!l.cable):[],t0=lands.length?pzUnit(lands[0]):null; const same=UI.pzDiv===false&&lands.length?(lands.find(l=>pzUnit(l)===UI.pzTrench)||lands[0]):null,trench=same?pzUnit(same):null,div=!!t0&&trench!==t0; pzSnap();if(!S.pops[b])S.pops[b]=pzNewPop(b);const id=uid(),f=r.f*(div?DIVERSE:1); - S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:trench||id,cut:0,day:0}); - closeModal();sfx('build');haptic(12);floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');UI.sel=null;pzAfter();}, + S.links.push({id,a,b,kind:'wave',border:false,premium:false,tier,km:r.km,sub:r.sub,cable:r.cab,mo:pzMo(r,tier,div),mult:f,trench:r.cab?'cab:'+r.cab:trench||id,cut:0,day:0,br:S.ar?S.ar.bi:0}); + closeModal();sfx('build');haptic(12);floater((CITY[a].x+CITY[a].x+wrapDx(CITY[a].x,CITY[b].x))/2,(CITY[a].y+CITY[b].y)/2-20,S.ar?tr('architect.tube_laid'):tr('links.wave_lit',{wave:LT[tier].n}),'#FF4F9A');UI.sel=null;pzAfter();}, // Another link next to this one: the picker opens on the same pair, on the same route, in the same trench or a diverse one. pzAddPar:({id,div})=>{const l=pzOn()&&S.links.find(x=>x.id===id);if(!l)return;UI.pzVia=l.cable||'land';UI.pzDiv=!!+div;UI.pzTrench=l.cable?null:pzUnit(l); if(+div&&l.cable){const o=pzRoutes(l.a,l.b).find(x=>x.via!==l.cable&&!(S.pz.noSub&&x.sub));if(o)UI.pzVia=o.via;} pzLinkModal(l.a,l.b,true);}, - pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!PZ_TIERS.includes(tier)||l.tier===tier)return;const why=pzWaveWhy(l.a,l.b,tier,{km:l.km,sub:l.sub});if(why){toast(esc(why),'bad');sfx('err');return;} - pzSnap();l.tier=tier;l.mo=pzMo({km:l.km,sub:l.sub,f:l.mult||1},tier,false);sfx('build');pzAfter();}, - pzRmLink:({id})=>{if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();S.links=S.links.filter(l=>l.id!==id);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, + pzTier:({id,tier})=>{tier=+tier;const l=pzOn()&&S.links.find(x=>x.id===id);if(!l||!(S.ar?AR_TIERS:PZ_TIERS).includes(tier)||l.tier===tier)return;const why=pzWaveWhy(l.a,l.b,tier,{km:l.km,sub:l.sub});if(why){toast(esc(why),'bad');sfx('err');return;} + pzSnap();if(S.ar){if(arAge(l){if(!pzOn()||!S.links.some(l=>l.id===id))return;pzSnap();if(S.ar)arSink([],S.links.filter(l=>l.id===id));S.links=S.links.filter(l=>l.id!==id);prunePairMet();sfx('click');UI.sel=null;pzAfter();}, // Routers: one more of the same model, one fewer, or every router in the POP swapped for another model. - pzRtAdd:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;pzSnap();p.routers=(p.routers||1)+1;sfx('build');floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');pzAfter();}, - pzRtRm:({city})=>{const p=pzOn()&&S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;} + pzRtAdd:({city})=>{const p=pzOn()&&!S.ar&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;pzSnap();p.routers=(p.routers||1)+1;sfx('build');floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');pzAfter();}, + pzRtRm:({city})=>{const p=pzOn()&&!S.ar&&S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;} pzSnap();p.routers--;sfx('click');pzAfter();}, - pzRtModel:({city,g})=>{g=+g;const p=pzOn()&&S.pops[city];if(!p||!PZ_RG.includes(g)||g===(p.rgen||0))return;const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;} + pzRtModel:({city,g})=>{g=+g;const p=pzOn()&&!S.ar&&S.pops[city];if(!p||!PZ_RG.includes(g)||g===(p.rgen||0))return;const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;} pzSnap();p.rgen=g;sfx('build');floater(CITY[city].x,CITY[city].y-30,RG[g].n+'!','#FF4F9A');pzAfter();}, // A circuit follows the metrics (the IGP's shortest path) or takes the lowest-latency path, as customers can in the main game. pzRoute:({i,m})=>{const b=pzOn()&&S.biz.find(x=>x.id===pzFlowId(+i));if(!b||!['normal','fast'].includes(m)||b.route===m)return;pzSnap();b.route=m;sfx('click');pzAfter();}, - pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};(o.r||[]).forEach((m,i)=>{if(S.biz[i])S.biz[i].route=m;});sfx('click');pzAfter();}, - pzReset:()=>{if(!pzOn())return;pzSnap();S.pops={};S.links=[];S.pairMet={};for(const b of S.biz)b.route='normal';UI.sel=null;sfx('click');pzAfter();}, - pzShare:()=>{if(!pzOn())return;const t=pzShareText(pzEval()); + pzUndo:()=>{const h=UI.pzHist;if(!pzOn()||!h||!h.length)return;if(S.ar)arStop(true);const o=JSON.parse(h.pop());S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};if(S.ar){S.ar.sunk=o.k||0;arDemand();}(o.r||[]).forEach((m,i)=>{if(S.biz[i])S.biz[i].route=m;});sfx('click');pzAfter();}, + pzReset:()=>{if(!pzOn())return;pzSnap();if(S.ar){arReset();sfx('click');pzAfter();return;}S.pops={};S.links=[];S.pairMet={};for(const b of S.biz)b.route='normal';UI.sel=null;sfx('click');pzAfter();}, + pzShare:()=>{if(!pzOn())return;const t=S.ar?arShareText(arStars(arSpend()),arSpend()):pzShareText(pzEval()); 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');}, }); diff --git a/src/game/90-actions/96-architect.js b/src/game/90-actions/96-architect.js new file mode 100644 index 0000000..f74e15e --- /dev/null +++ b/src/game/90-actions/96-architect.js @@ -0,0 +1,8 @@ +// Architect runs (prototype). Named pz* like the puzzle actions, so a puzzle lets them through. +Object.assign(ACT,{ + pzArStart:({id})=>{const r=arRunDef(id);if(r)arBegin(r);}, + pzArGo:()=>{if(arOn())arShowStart();}, + pzArSkip:()=>{if(arOn())arShowSkip();}, + pzArNext:()=>{if(arOn())arNext();}, + pzArAll:()=>{if(!arOn())return;UI.arAll=!UI.arAll;if(!UI.arAll&&UI.sel&&UI.sel.type==='city'&&!arKind(UI.sel.id))UI.sel=null;sfx('click');renderAll();}, +}); diff --git a/src/game/94-dashboard/80-hint.js b/src/game/94-dashboard/80-hint.js index 037a7b3..387fb46 100644 --- a/src/game/94-dashboard/80-hint.js +++ b/src/game/94-dashboard/80-hint.js @@ -1,7 +1,7 @@ function renderHint(){ const hn=$('hint');if(!S||UI.hintOff||(S.tut!==undefined&&S.tut!==null)||(innerWidth<760&&(UI.sel||UI.leftOpen)&&!(UI.drag&&UI.drag.mode==='link'))){hn.hidden=true;return;} let t=''; - if(pzOn()){t=UI.drag&&UI.drag.mode==='link'?(UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city')):!Object.keys(S.pops).length?tr('puzzles.tap_a_goal_city_to_open'):!S.links.length?tr('puzzles.drag_from_a_pink_pop_to'):'';hn.textContent=t;hn.hidden=!t;return;} + if(pzOn()){t=UI.drag&&UI.drag.mode==='link'?(UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city')):!Object.keys(S.pops).length?tr('puzzles.tap_a_goal_city_to_open'):!S.links.length?(S.ar?tr('architect.drag_from_your_hq'):tr('puzzles.drag_from_a_pink_pop_to')):'';hn.textContent=t;hn.hidden=!t;return;} if(UI.drag&&UI.drag.mode==='link')t=UI.snap?tr('hint.release_to_plan_a_link'):tr('hint.drag_onto_another_city'); else if(!S.links.length&&S.done.tr)t=tr('hint.tip_drag_from_your_pink_router'); else if(!S.done.bb)t=tr('hint.tap_your_city_then_launch_broadband'); diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index e0311fd..3104a60 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -13,7 +13,7 @@ function pzFlowRow(x){const f=x.f,ok=x.full&&x.fast,u=f.g?Math.min(1,x.g/f.g):0; return `
${f.t==='l2'?'🔗':'👀'} ${esc(pzFlowName(f))}${f.be?` ${tr('puzzles.best_effort')}`:''}${fmtG(x.g)} / ${fmtG(f.g)}
${lat?`
${tr('puzzles.latency')}${lat}
`:''}${f.t==='l2'?pzRouteCtl(x.i):''}
`;} // A circuit's path: the metrics, or the lowest latency. function pzRouteCtl(i){const b=S.biz.find(x=>x.id===pzFlowId(i));if(!b)return '';return `
${['normal','fast'].map(m=>btn(RT[m],'pzRoute',{i,m},b.route===m?'pink sm':'ghost sm')).join('')}
`;} -function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false; +function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hidden=false;el.classList.toggle('ar',!!S.ar);if(S.ar){arRender(el);return;} 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):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')}
`; @@ -43,7 +43,7 @@ function pzPopSection(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1,G=RG[g],c

${tr('puzzles.router_model')}

`; h+=PZ_RG.map(i=>{const M=RG[i],why=i===g?'':modelFits(c,i);return `
${esc(M.n)}${i===g?` ${tr('puzzles.installed')}`:''}
${tr('puzzles.model_facts',{cap:fmtG(M.cap),ports:M.ports,wave:LT[M.maxLT].n})}
${why?`
${esc(why)}
`:''}
${i===g?'':btn(dl(pzRtCost(i,rt)-cur),'pzRtModel',{city:c,g:i},'ghost sm',!!why)}
`;}).join(''); return h;} -function pzPanel(sel){const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; +function pzPanel(sel){if(S.ar)return arPanel(sel);const head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c],C=CITY[c],P=S.pz;if(!k)return ''; const eb=k==='goal'?tr('puzzles.goal_city'):k==='via'?tr('puzzles.stepping_stone_optional'):k==='off'?tr('puzzles.not_in_the_plan'):tr('puzzles.off_limits'); let h=head(`${PZ_ICON[k]} ${eb}`,esc(C.name),p?`${tr('common.your_pop')}`:'')+'
'; @@ -79,7 +79,7 @@ function pzPanel(sel){const head=(eb,name,facts)=>`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} // The link picker: overland or one of the real cables between the two cities, and a size. Prices are for a year. -function pzLinkModal(a,b,keep){const kb=pzKind(b); +function pzLinkModal(a,b,keep){if(S.ar)return arLinkModal(a,b,keep);const kb=pzKind(b); if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.not_a_city_you_can_build_in'),'bad');sfx('err');return;} if(!keep){UI.pzVia=null;UI.pzDiv=true;UI.pzTrench=null;}UI.pending={a,b};const rs=pzRoutes(a,b),P=S.pz; const head=`
${kmBetween(a,b).toLocaleString()} km

${esc(CITY[a].name)} → ${esc(CITY[b].name)}

`; @@ -129,6 +129,7 @@ function pzMenu(){pzWkEnsure();const p=pzLoad(),tot=pzStarsTotal(p),max=PZ.lengt if(p.old&&!p.noted){h+=`
🖼️ ${tr('puzzles.puzzles_got_traffic_note',{n:p.old})}
`;p.noted=1;pzStore(p);} h+=`
${tr('puzzles.your_stars')}⭐ ${tot} / ${max}
${nxP?`
${tr('puzzles.next_pack_unlocks_at_n',{n:nxP.need,pack:esc(nxP.n)})}
`:''}${p.old?`
🖼️ ${tr('puzzles.framed_n_stars_from_the_old',{n:p.old})}
`:''}
`; if(pzOn())h+=`
${(UI.pzTop||0)>0&&(UI.pzTop||0)<3?btn(tr('puzzles.finish_here'),'pzFinish',{},'sm'):''}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'')}${btn(tr('puzzles.keep_building'),'closeModal',{},'ghost')}
`; + h+=arMenuRows(); 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})}

`; diff --git a/src/game/95-modals/96-architect.js b/src/game/95-modals/96-architect.js new file mode 100644 index 0000000..5f79ca5 --- /dev/null +++ b/src/game/95-modals/96-architect.js @@ -0,0 +1,82 @@ +/* ---------- architect runs (prototype): the card, the panels, the link picker, the results and the list rows ---------- */ +const arDarkNow=c=>!!((UI.arShow&&UI.arShow.dark.includes(c))||(UI.arFail&&UI.arFail.dark.includes(c))); +const arHide=c=>arOn()&&!arKind(c); +function arRender(el){const A=S.ar,run=arRun(),b=arBrief(),e=arEval(),sh=UI.arShow,f=UI.arFail,n=run.briefs.length,nm=c=>esc(CITY[c].name); + let h=`
🏗️ ${esc(run.n)}

${tr('architect.brief_n_of_m',{n:A.bi+1,m:n})}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; + h+=`
${run.briefs.map((x,i)=>``).join('')}
`; + h+=`

${esc(b.t)}

`; + h+=`
${e.sites.map(s=>`${s.hq?'🏠':s.gold?'🥇':s.ok?'✓':'○'} ${nm(s.c)}${s.hq?'':` ${s.ok&&!s.full?arG(s.got)+'/':''}${arG(s.dem)}`}`).join('')}
`; + if(A.gold.length)h+=`
🥇 ${tr('architect.gold_must_survive',{list:A.gold.map(nm).join(', ')})}
`; + for(const r of e.rings)h+=`
💍 ${tr('architect.ring_list',{list:r.cs.map(nm).join(' · ')})} ${r.ok?'✓':''}
`; + if(e.lat)h+=`
⏱ ${nm(e.lat.a)} ⇄ ${nm(e.lat.b)}: ${e.lat.ms==null?tr('common.no_path'):e.lat.ms.toFixed(1)+' ms'} / ${e.lat.cap} ms
`; + for(const c of S.pz.avoid)h+=`
🚫 ${tr('architect.closed_city',{city:nm(c)})}
`; + const T=e.tubes;if(T.max!=null)h+=`
${tr('architect.tubes_this_brief')}${'●'.repeat(Math.min(T.u,T.max))}${'○'.repeat(Math.max(0,T.max-T.u))}${T.over?` ${tr('architect.n_over_plan',{n:T.over})}`:''}
`; + h+=`
${tr('architect.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(e.budget)})}${e.cheap?'⭐':'☆'}
${A.sunk?`
${tr('architect.x_paid_for_and_gone',{x:fmt$(A.sunk)})}
`:''}
`; + if(sh)h+=`
🚜 ${tr('architect.cut_n_of_m',{n:sh.i+1,m:sh.units.length})}${sh.dark.length?`
${tr('architect.dark_list',{list:sh.dark.map(nm).join(', ')})}`:''}
`; + else if(f)h+=`
💥 ${f.gold.length?tr('architect.cut_on_x_cuts_off_y',{x:pzUnitName(f.u),y:f.gold.map(nm).join(', ')}):tr('architect.cut_on_x_no_room',{x:pzUnitName(f.u),y:f.short.map(nm).join(', ')})}
${tr('architect.fix_it_and_send_it_again')}
`; + else if(e.passed)h+=`
✅ ${tr('architect.review_passed')}
`; + else if(!e.ready)h+=`
${esc(e.why)}
`; + else h+=`
${A.gold.length?tr('architect.ready_send_the_backhoe'):tr('architect.ready_no_gold_yet')}
`; + const main=sh?btn('⏩ '+tr('architect.skip'),'pzArSkip',{},'big'):e.passed?btn(arLast()?tr('architect.finish_the_run')+' 🎉':tr('architect.next_brief')+' →','pzArNext',{},'pink big'):btn('▶ '+tr('architect.send_the_backhoe'),'pzArGo',{},'pink big',!e.ready); + h+=`
${main}${btn('↶ '+tr('puzzles.undo'),'pzUndo',{},'ghost sm',!!sh||!(UI.pzHist&&UI.pzHist.length))}${btn(tr('architect.reset_brief'),'pzReset',{},'ghost sm',!!sh)}${btn(UI.arAll?tr('architect.hide_other_cities'):tr('architect.show_all_cities'),'pzArAll',{},'ghost sm')}
`; + if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} +function arPanel(sel){const A=S.ar,head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; + const old=x=>(x.br|0)${tr('architect.built_in_an_earlier_brief')}

`:''; + if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c];if(!k)return ''; + const tg=arTags(c),eb=c===A.hq?'🏠 '+tr('architect.hq'):A.gold.includes(c)?'🥇 '+tr('architect.gold_site'):k==='goal'?'🎯 '+tr('architect.site'):k==='via'&&tg.length?'🔜 '+tr('architect.joins_in_brief_n',{n:tg[0].n}):k==='via'?'🪨 '+tr('puzzles.stepping_stone_optional'):k==='avoid'?'🚫 '+tr('architect.closed'):'📍 '+tr('puzzles.not_in_the_plan'); + let h=head(eb,esc(CITY[c].name),p?`${tr('common.your_pop')}${tr('puzzles.price_per_year',{price:fmt$(arPopCost(c))})}`:'')+'
'; + if(c===A.hq)h+=`

${tr('architect.hq_lead')}

`;else if(A.gold.includes(c))h+=`

${tr('architect.gold_lead')}

`; + if(tg.length)h+=`
${tr('architect.coming_up')}
${tg.map(t=>`
${t.n} ${esc(arSum(arRun().briefs[t.n-1]))}
`).join('')}
`; + if(k==='avoid'&&!p)return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

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

${tr('architect.or_drag_a_tube_here')}

`;} + if(k==='avoid')h+=`

${tr('architect.closed_lead')}

`; + {const G=RG[p.rgen||0],cap=nodeCap(c),ld=R.nodeLoad[c]||0;h+=`
${tr('architect.router_x',{x:esc(G.n)})}${pzRtCost(p.rgen||0,1)?tr('puzzles.price_per_year',{price:fmt$(pzRtCost(p.rgen||0,1))}):tr('puzzles.free')}
${tr('architect.router_follows')} · ${fmtG(ld)} / ${fmtG(cap)}
`;} + const ls=S.links.filter(l=>l.a===c||l.b===c); + h+=`

${tr('common.links')}

`; + if(!ls.length)h+=`

${tr('puzzles.drag_from_this_pop_onto_another')}

`; + for(const l of ls){const o=l.a===c?l.b:l.a;h+=`
→ ${esc(CITY[o].name)}
${pzTrench(l)} · ${linkLat(l).toFixed(1)} ms · ${tr('puzzles.price_per_year',{price:fmt$(arLinkCost(l))})}
${btn(tr('common.open'),'selLink',{id:l.id},'ghost sm')}
`;} + if(k!=='avoid'){const others=[...S.pz.cities,...S.pz.via].filter(x=>x!==c&&!S.pz.avoid.includes(x));if(others.length)h+=`

${tr('architect.lay_a_tube_to')}

${others.map(x=>btn(esc(CITY[x].name),'pzLinkTo',{a:c,b:x},S.pops[x]?'':'ghost')).join('')}
`;} + if(c!==A.hq)h+=old(p)+`
${btn(tr('puzzles.remove_this_pop'),'pzRmPop',{city:c},'red sm')}
`; + return h+'
';} + const l=S.links.find(x=>x.id===sel.id);if(!l)return ''; + let h=head(l.cable?esc(CAB[l.cable].name):tr('common.overland'),`${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)}`,`${l.km.toLocaleString()} km${linkLat(l).toFixed(1)} ms${tr('puzzles.price_per_year',{price:fmt$(arLinkCost(l))})}`)+'
'; + h+=`

${pzTrench(l)}${l.cable?' · '+esc(CAB[l.cable].blurb):''}

`; + {const u=capOf(l)?(R.load[l.id]||0)/capOf(l):0;h+=`
${tr('puzzles.this_link')}${pzLoadTxt(l)}
`;} + h+=`

${tr('architect.size')}

${AR_TIERS.map(i=>{const r={km:l.km,sub:l.sub,f:l.mult||1},why=subWaveWhy(i,l.km,l.sub);return btn(`${LT[i].n} ${why?esc(why):tr('puzzles.price_per_year',{price:fmt$(pzMo(r,i,false)*PZ_YEAR)})}`,'pzTier',{id:l.id,tier:i},l.tier===i?'pink':'ghost',!!why||l.tier===i);}).join('')}
${arAge(l)${tr('architect.changing_an_old_tube')}

`:''}`; + h+=`

${tr('puzzles.add_another_link_here')}

${btn(l.cable?tr('puzzles.another_wave_on_this_cable'):tr('puzzles.same_trench_cheaper'),'pzAddPar',{id:l.id,div:0},'sm')}${btn(l.cable?tr('puzzles.a_different_route'):tr('puzzles.a_diverse_route'),'pzAddPar',{id:l.id,div:1},'pink sm')}
`; + return h+old(l)+`
${btn(tr('puzzles.remove_this_link'),'pzRmLink',{id:l.id},'red sm')}
`;} +// The tube picker: overland or one of the real cables, a diverse trench when there is one already, and one price. +function arLinkModal(a,b,keep){const kb=pzKind(b); + if(!kb||kb==='avoid'||!pzKind(a)){toast(kb==='avoid'?tr('puzzles.not_this_one_find_a_way_around'):tr('puzzles.not_a_city_you_can_build_in'),'bad');sfx('err');return;} + if(!keep){UI.pzVia=null;UI.pzDiv=true;UI.pzTrench=null;}UI.pending={a,b};const rs=pzRoutes(a,b),cost1=x=>pzLinkCost(x,AR_TIER,false); + const head=`
${kmBetween(a,b).toLocaleString()} km

${esc(CITY[a].name)} → ${esc(CITY[b].name)}

`; + if(!rs.length){openModal(head+`

${tr('puzzles.no_cable_lands_in_both_try',{a:esc(CITY[a].name),b:esc(CITY[b].name)})}

`);return;} + const r=rs.find(x=>x.via===UI.pzVia)||rs.slice().sort((x,y)=>cost1(x)-cost1(y))[0];UI.pzVia=r.via; + const pl=pairLinks(a,b),land=!r.sub&&pl.some(l=>!l.cable),div=land&&UI.pzDiv!==false,pop=S.pops[b]?0:pzPopCost(b)+pzRtCost(0,1); + let h=head; + if(pl.length)h+=`

${tr('puzzles.already_here_list',{list:[...new Set(pl.map(pzTrench))].join(', ')})}

`; + h+=`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms · ${tr('architect.from_x',{x:fmt$(pzLinkCost(x,0,false))})}${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost')).join('')}
`; + if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}

`; + if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; + if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; + const T=arTubes();if(T.max!=null&&T.u>=T.max)h+=`

${tr('architect.this_tube_is_over_the_plan')}

`; + h+=`

${tr('architect.size')}

${AR_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),rt=arRouterDelta(a,i)+(S.pops[b]?arRouterDelta(b,i):arRouterDelta(b,i)),c=pzLinkCost(r,i,div); + return ``;}).join('')}
`; + openModal(h);} +// ---------- results ---------- +const arLine=st=>st>=3?tr('architect.line_3'):st===2?tr('architect.line_2'):tr('architect.line_1'); +function arResults(done){const A=S.ar,run=arRun(),sp=arSpend(),br=done?run.briefs.length:A.bi,st=done?arStars(sp):0,sh=arShape();arRecord(st,br,sp); + const nx=AR_RUNS[AR_RUNS.indexOf(run)+1]||null,stars=[0,1,2].map(i=>`⭐`).join(''); + openModal(`
${st>=3?pzConfetti():''}
🏗️ ${done?tr('architect.run_complete'):tr('architect.run_over')}

${esc(run.n)}

+
${stars}

${done?arLine(st):tr('architect.the_cfo_pulled_the_plug')}

+
${done?'⭐':'☆'} ${tr('architect.briefs_done')}${br} / ${run.briefs.length}
+
${arOver()?'☆':'⭐'} ${tr('architect.tubes_over_plan')}${arOver()}
+
${sp<=run.budget+1e-6?'⭐':'☆'} ${tr('architect.spent')}${fmt$(sp)} / ${fmt$(run.budget)}
+ ${sh?`
${tr('architect.your_shape')}${sh.i} ${esc(sh.n)}
`:''} +
${nx&&done?btn(tr('architect.next_run')+' →','pzArStart',{id:nx.id},'pink big'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big')}${btn(tr('architect.try_again'),'pzRetry',{},'')}${done?btn(tr('common.share_2cd9'),'pzShare',{},'ghost'):btn(tr('architect.keep_going'),'closeModal',{},'ghost')}
`); + for(let i=0;i{sfx('star');haptic(15);},i*450+150);if(st>=3)setTimeout(()=>sfx('fanfare'),3*450+250);} +// ---------- the list ---------- +function arMenuRows(){const p=arLoad();let h=`

🏗️ ${tr('architect.architect_runs')} ${tr('architect.new')}

${tr('architect.runs_lead')}

`; + for(const r of AR_RUNS){const x=p.runs[r.id]; + h+=`
${esc(r.n)} ${pzStarStr(x?x.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)}${' · '+tr('puzzles.budget_x',{x:fmt$(r.budget)})}${x&&x.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(x.sp)}):x&&x.br?' · '+tr('architect.best_n_briefs',{n:x.br}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},x&&x.st>=3?'ghost':'pink')}
`;} + return h;} diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index 422b708..2f6b4ea 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -30,10 +30,10 @@ function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.drag.from:(UI.sel&&UI.sel.type==='city'?UI.sel.id:null),cached=!!(WL.cv&&WL.key&&WL.cab); if(!selC&&z<1.7&&cached)return; ctx.font='800 10px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle'; - for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;const col=cableCol(C); + const ar=arOn();for(const cp of CABLE_PAIRS){const C=CAB[cp.cid],hot=!!selC&&(cp.a===selC||cp.b===selC);if(!hot&&cached&&z<1.7)continue;if(ar&&!hot&&!(arKind(cp.a)&&arKind(cp.b)))continue;const col=cableCol(C); for(const k of ks){const sp=cp.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]mx)mx=q[0];}if(mx<-20||mn>CW+20)continue; if(hot||!cached){ctx.globalAlpha=hot?0.95:0.4;ctx.strokeStyle=col;ctx.lineWidth=hot?3:1.6;ctx.lineJoin='round';ctx.setLineDash(C.age==='old'?[6,5]:[]);ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i=1.7){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);} + if(hot||(z>=1.7&&!ar)){const m=sp[Math.floor(sp.length/2)];ctx.globalAlpha=hot?1:0.75;ctx.lineWidth=3;ctx.strokeStyle='rgba(255,255,255,.85)';ctx.strokeText(C.name,m[0],m[1]-8);ctx.fillStyle=col;ctx.fillText(C.name,m[0],m[1]-8);} ctx.globalAlpha=1;}}} function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit; const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index f82dee0..897b7dc 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -50,7 +50,7 @@ function drawFrame(now){ const [mx2,my]=at(.5);const mxx=mx2; if(bld){if(far){ctx.fillStyle='#FF8A3D';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,4,0,7);ctx.fill();ctx.stroke();}else drawCone(mxx,my,now);} else if(cut&&!vx){if(far){ctx.fillStyle='#FF4D5E';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,5,0,7);ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',mxx,my+0.5);}else drawBackhoe(mxx,my,now,l.sub);} - else if(sel||pz||(z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} + else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} } } // drag preview @@ -69,7 +69,7 @@ function drawFrame(now){ // cities UI.feed=null;if(UI.sel&&UI.sel.type==='link'){const sl=S.links.find(x=>x.id===UI.sel.id);const rec=sl&&R.ef[edgeKey(sl)];if(rec){UI.feed=new Set(Object.keys(rec.eg).map(k=>R.egDesc[k].city));UI.dest=new Set(Object.keys(rec.dst));}} // Place labels: your POPs and the selected city first, then others; a label that would overlap moves above its city or hides. - const vis=[];for(const C of CITIES){if(C.off&&!cityOn(C.id))continue;for(const k of ks){const [sx,sy]=toS(C.x,C.y,k);if(sx<-60||sx>CW+60||sy<-60||sy>CH+60)continue;vis.push({C,sx,sy});}} + const vis=[];for(const C of CITIES){if(C.off&&!cityOn(C.id))continue;if(arHide(C.id))continue;for(const k of ks){const [sx,sy]=toS(C.x,C.y,k);if(sx<-60||sx>CW+60||sy<-60||sy>CH+60)continue;vis.push({C,sx,sy});}} const prio=v=>(UI.sel&&UI.sel.type==='city'&&UI.sel.id===v.C.id?0:S.pops[v.C.id]?1:2);vis.sort((a,b)=>prio(a)-prio(b)||b.C.P-a.C.P); const rects=[],labs=[],hit=(r)=>rects.some(q=>r.x=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; - if(pzOn())for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); + if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);if(S.ar)for(const v of vis)arDrawTags(v,sc);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); // floaters for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;} for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}} diff --git a/src/game/96-map/70-world-layer.js b/src/game/96-map/70-world-layer.js index cfe511a..ab36726 100644 --- a/src/game/96-map/70-world-layer.js +++ b/src/game/96-map/70-world-layer.js @@ -7,15 +7,15 @@ function wlCovers(z){if(WL.full)return true;const hw=CW/2/z,hh=CH/2/z,w=WL.cv.wi return cam.x-hw>=WL.ox&&cam.x+hw<=WL.ox+w&&cam.y-hh>=WL.oy&&cam.y+hh<=WL.oy+h;} function worldLayer(z){ const now=performance.now();if(z!==WL.lastZ){WL.lastZ=z;WL.zAt=now;} - const sc=z*DPR,key=sc.toFixed(4),have=!!(WL.cv&&WL.key); + const sc=z*DPR,key=sc.toFixed(4)+(arOn()?'a':''),have=!!(WL.cv&&WL.key); if(have&&WL.key===key&&wlCovers(z))return WL; if(have&&now-WL.zAt<250)return WL; // mid-gesture: scale the last image const full=W*sc+2<=MAXPX;let ox=0,oy=0,w=W,h=H; if(!full){const mx=Math.min(MAXPX/sc,CW/z*2),my=Math.min(MAXPX/sc,CH/z*2);w=mx;h=my;ox=cam.x-w/2;oy=cam.y-h/2;} const cv2=WL.cv||document.createElement('canvas');cv2.width=Math.ceil(w*sc)+2;cv2.height=Math.ceil(h*sc)+2; const c=cv2.getContext('2d',SOFT_CANVAS?{willReadFrequently:true}:undefined);if(!c)return null; - const kk=full?0:Math.floor(cam.x/W)*W;c.setTransform(1,0,0,1,0,0);c.clearRect(0,0,cv2.width,cv2.height);c.setTransform(sc,0,0,sc,-(ox-kk)*sc,-oy*sc);paintWorld(c,z,z<1.7); - Object.assign(WL,{cv:cv2,key,sc,ox,oy,full,cab:z<1.7});return WL; + const kk=full?0:Math.floor(cam.x/W)*W;c.setTransform(1,0,0,1,0,0);c.clearRect(0,0,cv2.width,cv2.height);c.setTransform(sc,0,0,sc,-(ox-kk)*sc,-oy*sc);paintWorld(c,z,z<1.7&&!arOn()); + Object.assign(WL,{cv:cv2,key,sc,ox,oy,full,cab:z<1.7&&!arOn()});return WL; } // Draw the world image for map copy k (full layers repeat per copy; a crop already holds what is visible). function drawWorldLayer(wl,k,z,k0){if(!wl.full&&k!==k0)return;const f=z*DPR/wl.sc,ox=(wl.full?k*W:wl.ox); diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js index 954a64a..621b5e7 100644 --- a/src/game/96-map/85-puzzle-cities.js +++ b/src/game/96-map/85-puzzle-cities.js @@ -1,16 +1,20 @@ /* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring and a badge for what they send or ask for, stepping stones with a dashed one, cities to avoid crossed out); every other city is on the map as usual, open to build in but not emphasised. */ -function pzBadge(c){const P=S.pz;return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';} +function pzBadge(c){const P=S.pz;if(S.ar)return c===S.ar.hq?'🏠':S.ar.gold.includes(c)?'🥇':'';return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';} function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); if(!k||k==='off'){drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);return;} const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc),p=S.pops[v.C.id]; ctx.save();ctx.lineWidth=3; if(k==='avoid'){ctx.strokeStyle='#FF4D5E';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.moveTo(v.sx-r*.7,y-r*.7);ctx.lineTo(v.sx+r*.7,y+r*.7);ctx.stroke();} - else{const a=animOn()?.55+.35*Math.sin(now/300):.8;ctx.strokeStyle=k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(k==='via')ctx.setLineDash([5,5]); + else{const a=animOn()?.55+.35*Math.sin(now/300):.8,gold=S.ar&&S.ar.gold.includes(v.C.id),dk=S.ar&&arDarkNow(v.C.id);ctx.strokeStyle=dk?`rgba(255,77,94,${a})`:gold?`rgba(224,160,0,${p?1:a})`:k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(gold||dk)ctx.lineWidth=5;if(k==='via')ctx.setLineDash([5,5]); ctx.fillStyle=k==='goal'&&!p?'rgba(255,210,63,.35)':'rgba(255,255,255,.25)';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.fill();ctx.stroke();ctx.setLineDash([]);} ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly); const b=k==='goal'&&!CM.far?pzBadge(v.C.id):'';if(b){ctx.font=`${Math.round(15*sc)}px sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(b,v.sx+r*.75,y-r*.75);}} // In a puzzle every line says what it is ("2×100G · 70%"), and a selected POP lights up every pair it has links on. -function pzLinkLab(grp,up,load,cap){return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');} +function pzLinkLab(grp,up,load,cap){if(S.ar)return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');} const pzLinkHot=grp=>!!(UI.sel&&UI.sel.type==='city'&&grp.some(x=>x.a===UI.sel.id||x.b===UI.sel.id)); +// Architect runs: what later briefs do here, as small numbered tags beside the city ("4🥇", "6🚫"). +function arDrawTags(v,sc){const tg=arTags(v.C.id).slice(0,2);if(!tg.length||!pzKind(v.C.id))return;const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc);const t=tg.map(x=>x.n+x.i).join(' '); + ctx.save();ctx.font=`900 ${Math.round((CM.far?10:12)*Math.max(0.9,Math.min(1.3,sc)))}px "Baloo 2", sans-serif`;const w=ctx.measureText(t).width+12,h=18,x=v.sx-r-w*0.35,yy=y-r-4; + ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(x,yy,w,h,9);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,x+w/2,yy+h/2+1);ctx.restore();} diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index 204c6f4..605eba6 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/i18n/en.js b/src/i18n/en.js index cf18cc8..78586e6 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -13,6 +13,119 @@ "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.", +"architect.anchor":"⚓ Anchor!", +"architect.architect_runs":"Architect runs", +"architect.backhoe":"🚜 Backhoe!", +"architect.best_n_briefs":"best: {n} briefs", +"architect.brief_n_of_m":"Brief {n} of {m}", +"architect.briefs_done":"Briefs done", +"architect.built_in_an_earlier_brief":"Built in an earlier brief: removing it gives nothing back.", +"architect.changing_an_old_tube":"This tube is from an earlier brief: a new size is a new lease, and the old one is paid for.", +"architect.city_goes_dark":"{city} goes dark", +"architect.city_short_g":"{city} short {g}", +"architect.closed":"Closed", +"architect.closed_city":"No POP in {city}", +"architect.closed_lead":"This city is closed now. Move out: remove the POP and find another way.", +"architect.coast_to_coast":"Coast to Coast", +"architect.coast_to_coast_joke":"From data center alley to Silicon Valley, one brief at a time.", +"architect.coming_up":"Coming up", +"architect.cut_n_of_m":"Cut {n} of {m}…", +"architect.cut_on_x_cuts_off_y":"A cut on {x} cuts off {y}.", +"architect.cut_on_x_no_room":"A cut on {x} leaves no room on the detour. Short: {y}.", +"architect.dark_list":"Dark for now: {list}. Not gold, so that's allowed.", +"architect.drag_from_your_hq":"Drag from your HQ to another city to lay a tube", +"architect.euro_1":"Your servers live in Amsterdam. First customer: Frankfurt. Connect it.", +"architect.euro_2b":"Paris and London want in.", +"architect.euro_3b":"Frankfurt and Paris sign banks. Both go gold.", +"architect.euro_5":"Zürich, another bank. Gold from day one.", +"architect.euro_6":"Your Frankfurt landlord sold the building. Move out. The bank moves to Düsseldorf, and it is still gold.", +"architect.euro_ring":"London, Paris and Amsterdam want a ring between them.", +"architect.euro_ring_grow":"Paris doubles to 100G. And London, Paris and Amsterdam want a ring between them.", +"architect.euro_run":"Euro Run", +"architect.euro_run_joke":"Six briefs, one landlord, one very nervous bank.", +"architect.finish_the_run":"Finish the run", +"architect.fix_it_and_send_it_again":"Fix it, then send the backhoe again.", +"architect.from_x":"from {x}", +"architect.gold_lead":"Gold: this site must stay connected to HQ whichever single trench or cable is cut, and the detour needs room for its traffic.", +"architect.gold_must_survive":"Must survive any single cut: {list}", +"architect.gold_site":"Gold site", +"architect.hide_other_cities":"Hide other cities", +"architect.hq":"HQ", +"architect.hq_lead":"Your servers live here. Every site needs a path to HQ.", +"architect.joins_in_brief_n":"Joins in brief {n}", +"architect.keep_going":"Keep building", +"architect.last_brief_done":"That was the last brief.", +"architect.lay_a_tube_to":"Lay a tube to", +"architect.lay_it_x":"Lay it · {x}", +"architect.line_1":"It works. Finance would like a word.", +"architect.line_2":"Solid design, a little gold plated. Finance can live with it.", +"architect.line_3":"At par or better. The backhoe went home bored.", +"architect.move_out_of_city":"Move out of {city} first.", +"architect.n_briefs":"{n} briefs", +"architect.n_over_plan":"{n} over plan", +"architect.n_tubes":{"one":"{n} tube","other":"{n} tubes"}, +"architect.new":"New", +"architect.next_brief":"Next brief", +"architect.next_brief_waiting":"The next brief is waiting.", +"architect.next_run":"Next run", +"architect.not_a_ring_yet":"Not a ring yet.", +"architect.not_connected_yet_list":"Not connected to HQ yet: {list}", +"architect.numbers_on_the_map_show":"Numbers on the map show what later briefs bring. You can build there early.", +"architect.or_drag_a_tube_here":"Or drag a tube here from one of your POPs.", +"architect.pac_1":"Your servers live in Tokyo. Hong Kong first.", +"architect.pac_2":"Singapore wants in.", +"architect.pac_3":"A stock exchange in Hong Kong. Hong Kong is gold.", +"architect.pac_4":"Singapore signs a bank. Gold too.", +"architect.pac_5":"Sydney. Far from everything: that is the point, and the problem.", +"architect.pacific_rim":"Pacific Rim", +"architect.pacific_rim_joke":"Oceans, anchors and very expensive glass.", +"architect.plus_router_x":"+ bigger router {x}", +"architect.ready_no_gold_yet":"Ready. No gold sites yet, so the backhoe can only make a mess.", +"architect.ready_send_the_backhoe":"Ready. Send the backhoe and see what survives.", +"architect.reset_brief":"Reset brief", +"architect.review_passed":"Review passed", +"architect.ring_list":"One ring through {list}", +"architect.router_follows":"Picked for your tubes", +"architect.router_x":"Router: {x}", +"architect.run_complete":"Run complete", +"architect.run_over":"Run over", +"architect.runs_lead":"One network, built brief by brief. Your build carries over, and a backhoe checks every design: cut any one tube, and everything still connected must get all its traffic.", +"architect.send_the_backhoe":"Send the backhoe", +"architect.shape_braces":"Belt and braces", +"architect.shape_full":"Full mesh", +"architect.shape_islands":"Islands", +"architect.shape_ladder":"Ladder", +"architect.shape_line":"Line", +"architect.shape_lolli":"Ring with spurs", +"architect.shape_mesh":"Mesh", +"architect.shape_ring":"Ring", +"architect.shape_spaghetti":"Spaghetti", +"architect.shape_star":"Star", +"architect.shape_tree":"Tree", +"architect.shape_tube":"One tube", +"architect.share_line":"Series of Tubes · {what} {stars} {spend} {shape} · seriesoftub.es", +"architect.show_all_cities":"Show all cities", +"architect.site":"Site", +"architect.size":"Size", +"architect.skip":"Skip", +"architect.spent":"Spent", +"architect.spent_x_of_y":"Spent {x} of {y}", +"architect.the_cfo_pulled_the_plug":"The CFO pulled the plug. Try a cheaper shape?", +"architect.this_tube_is_over_the_plan":"This brief's tubes are used up. You can still lay it, but it costs a star.", +"architect.too_slow_for_the_cap":"Too slow: find a faster path.", +"architect.too_thin_list":"Too thin: {list}", +"architect.try_again":"Try again", +"architect.tube_laid":"Tube laid!", +"architect.tubes_over_plan":"Tubes over plan", +"architect.tubes_this_brief":"Tubes this brief", +"architect.usa_1":"Your servers live in Ashburn. New York first.", +"architect.usa_2":"Chicago wants in.", +"architect.usa_3":"A bank in New York. New York is gold.", +"architect.usa_4":"Traders want New York ⇄ Chicago under 8 ms.", +"architect.usa_5":"Dallas and Silicon Valley want in.", +"architect.usa_6":"A cloud deal in Silicon Valley. It goes gold.", +"architect.x_paid_for_and_gone":"{x} of that paid for things you removed", +"architect.your_shape":"Your shape", "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/src/styles/71-architect.css b/src/styles/71-architect.css new file mode 100644 index 0000000..a531a7d --- /dev/null +++ b/src/styles/71-architect.css @@ -0,0 +1,28 @@ +/* Architect runs (prototype): the brief, its sites, the review line */ +.arsteps{display:flex;gap:4px;margin:4px 0 6px}.arsteps i{flex:1;height:7px;border:2px solid var(--ink);border-radius:99px;background:#fff} +.arsteps i.done{background:var(--ok)}.arsteps i.on{background:#FFD23F} +.arbrief{margin:2px 0 8px;font-size:14.5px;font-weight:800;line-height:1.35} +.arsites{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0 6px} +.arsite{font-weight:900;font-size:12px;border:2px solid var(--line);border-radius:999px;padding:1px 8px;background:#fff;color:var(--ink2)} +.arsite.ok{border-color:var(--ok);color:var(--ink)}.arsite.gold{border-color:#E0A000;background:#FFF3C4} +.arline{font-size:12.5px;font-weight:800;margin:3px 0;color:var(--ink2)}.arline.ok{color:var(--ink)}.arline.bad{color:var(--bad)} +.arshape{font-size:12.5px;font-weight:900;margin:4px 0} +.arrev{font-size:12.5px;font-weight:800;margin:6px 0;padding:5px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} +.arrev.on{border-color:#FF8A3D;background:#FFF0E3;color:var(--ink)}.arrev.ok{border-color:var(--ok);background:#DFFBEA;color:var(--ink)} +.arrev.bad{border-color:var(--bad);background:#FFE6E9;color:var(--ink)} +#pzBox .arbtns .b.big{flex:1 1 100%} +.artubes{display:flex;justify-content:space-between;align-items:center;font-size:12.5px;font-weight:800;margin:4px 0}.artubes b{font-size:15px;letter-spacing:2px;color:var(--me)} +.artubes em{font-style:normal;font-size:11.5px;letter-spacing:0;color:#B86A00}.artubes.over b{color:#B86A00} +.arplan{margin:6px 0;padding:5px 8px;border:2px dashed var(--line);border-radius:10px;font-size:12px;font-weight:700;color:var(--ink2)}.arplan b{display:inline-block;min-width:14px;color:var(--ink)} +/* Laptops and up: a bigger card, easier to read at a glance */ +@media (min-width:761px) and (min-height:501px){ + #pzBox.ar{width:390px;padding:14px 18px 16px} + #pzBox.ar h3{font-size:23px}#pzBox.ar .eyebrow{font-size:12px} + #pzBox.ar .arsteps i{height:9px} + #pzBox.ar .arbrief{font-size:17.5px;margin:4px 0 10px} + #pzBox.ar .arsite{font-size:14px;padding:2px 10px} + #pzBox.ar .arline,#pzBox.ar .arrev,#pzBox.ar .artubes,#pzBox.ar .pzbud .kv,#pzBox.ar .arplan{font-size:14px} + #pzBox.ar .artubes b{font-size:19px}#pzBox.ar .pzbud .bar{height:12px} + #pzBox.ar .arbtns .b.sm{font-size:13px;padding:5px 11px} +} +.arsite small{font-weight:800;opacity:.75}.arsite.thin{border-color:var(--bad);background:#FFE6E9;color:var(--ink)} diff --git a/tests/architect.test.js b/tests/architect.test.js new file mode 100644 index 0000000..445ec46 --- /dev/null +++ b/tests/architect.test.js @@ -0,0 +1,149 @@ +// Architect runs (prototype): one network built brief by brief, reviewed by a backhoe. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Reference builds, brief by brief: [a, b, route] lays a tube (a diverse trench when the pair has one), ['@rm', city] +// closes a POP. Each must pass every brief within budget and land at par. +const REF = { + euro: [[['ams', 'fra', 'land']], [['ams', 'par', 'land'], ['ams', 'lon', 'nshuttle']], [['par', 'fra', 'land']], + [['ams', 'zrh', 'land'], ['par', 'zrh', 'land']], [['lon', 'par', 'pasdc'], ['ams', 'lon', 'concerto']], [['@rm', 'fra'], ['ams', 'dus', 'land'], ['ams', 'dus', 'land']]], + usa: [[['ash', 'nyc', 'land']], [['ash', 'chi', 'land']], [['nyc', 'chi', 'land']], [], [['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], [['chi', 'sjc', 'land']]], + pacific: [[['tok', 'hkg', 'adc']], [['hkg', 'sin', 'land']], [['tok', 'hkg', 'apg']], [['hkg', 'sin', 'sjc2']], [['sin', 'syd', 'indigo']]], +}; +const lay = (ev, a, b, via, div = 1) => ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:${div}});ACT.pzLink({tier:AR_TIER});closeModal()`); +const review = (ev) => { ev('arShowStart();arShowSkip()'); return ev('S.ar.passed===pzSig()'); }; + +test('architect runs: every reference passes each brief, on plan and within budget', () => { + const { ev, errors } = load(); + assert.deepEqual(JSON.parse(ev('JSON.stringify(AR_RUNS.map(r=>r.id))')).sort(), Object.keys(REF).sort()); + for (const [id, plan] of Object.entries(REF)) { + ev(`ACT.pzArStart({id:'${id}'})`); + assert.equal(ev('arOn()&&!!S.pops[S.ar.hq]'), true, `${id}: starts with a POP at HQ`); + plan.forEach((steps, i) => { + for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s); + assert.equal(review(ev), true, `${id} brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`); + if (i < plan.length - 1) ev('ACT.pzArNext()'); + }); + assert.equal(ev('arOver()'), 0, `${id}: never over a brief's tubes`); + assert.equal(ev('arSpend()<=arRun().budget'), true, `${id}: within budget`); + assert.ok(ev('arSpend()>arRun().budget*0.95'), `${id}: the budget sits just above the reference`); + ev('ACT.pzArNext()'); + assert.equal(ev('JSON.parse(localStorage.getItem(AR_KEY)).runs[S.ar.id].st'), 3, `${id}: three stars stored`); + } + assert.deepEqual(errors, []); +}); + +test('architect runs: the backhoe finds a shared trench, edits clear the cut, old builds are paid for', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden'); + assert.deepEqual(JSON.parse(ev("JSON.stringify([arHide('dus'),arTags('dus'),arTags('fra').map(t=>t.n+t.i)])")), [false, [{ n: 6, i: '🥇' }], ['3🥇', '6🚫']], 'later briefs show on the map, numbered'); + ev('ACT.pzArAll()'); + assert.equal(ev("arHide('lis')"), false, 'and shown on request'); + ev('ACT.pzArAll()'); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'par', 'land'); lay(ev, 'ams', 'lon', 'nshuttle'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'fra', 'land', 0); // the same trench: looks redundant, is not + assert.equal(review(ev), false); + assert.deepEqual(JSON.parse(ev('JSON.stringify(UI.arFail.gold)')), ['fra']); + assert.ok(ev('S.links.some(l=>l.cut)'), 'the failing cut stays on the map'); + ev('ACT.pzUndo()'); + assert.equal(ev('!UI.arFail&&!S.links.some(l=>l.cut)'), true, 'an edit clears it'); + const sunk = ev('S.ar.sunk'); + ev("ACT.pzRmLink({id:S.links.find(l=>l.br===0).id})"); + assert.ok(ev('S.ar.sunk') > sunk, 'removing an earlier brief\'s tube refunds nothing'); + ev('ACT.pzReset()'); + assert.equal(ev('S.ar.sunk'), sunk, 'reset goes back to the start of the brief'); + // Two diverse trenches would make both gold, but the plan has one tube: the ring is the answer. + lay(ev, 'ams', 'fra', 'land'); lay(ev, 'ams', 'par', 'land'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(arTubes())')), { u: 2, max: 1, over: 1 }); + ev('ACT.pzReset()'); + lay(ev, 'par', 'fra', 'land'); + assert.equal(ev('arTubes().over'), 0); + assert.equal(review(ev), true); + assert.deepEqual(errors, []); +}); + +test('architect runs: a latency brief needs the fast path, and normal puzzles are untouched', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'usa'})"); + lay(ev, 'ash', 'nyc', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ash', 'chi', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ash', 'nyc', 'land'); assert.equal(review(ev), true, 'a diverse trench makes New York gold'); ev('ACT.pzArNext()'); + assert.equal(ev('arEval().lat.ok'), false, 'via Ashburn is too slow'); + lay(ev, 'nyc', 'chi', 'land'); + assert.equal(ev('arEval().lat.ok&&arEval().ready'), true); + ev("ACT.pzStart({id:'hello'})"); + assert.equal(ev('!S.ar&&pzKind("lon")==="goal"&&!arHide("par")'), true); + assert.deepEqual(errors, []); +}); + +test('architect runs: Play on the title screen\'s puzzle list starts a run', () => { + const { ev, errors } = load(); + ev('ACT.puzzleMenu()'); + assert.equal(ev('S'), null, 'no game loaded yet'); + ev("document.querySelector('#modal [data-act=pzArStart]').click()"); + assert.equal(ev('arOn()&&S.ar.id'), 'euro'); + assert.deepEqual(errors, []); +}); + +test('architect runs: a ring goal needs one cycle through its cities', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'par', 'land'); lay(ev, 'ams', 'lon', 'nshuttle'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'par', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); review(ev); ev('ACT.pzArNext()'); + assert.equal(ev("arRingOk(['ams','par','lon'])"), false, 'London hangs off Amsterdam: no ring'); + assert.match(ev('arEval().why'), /ring/i); + lay(ev, 'lon', 'par', 'pasdc'); + assert.equal(ev("arRingOk(['ams','par','lon'])&&arEval().ready"), true); + assert.ok(ev("arSum(arRun().briefs[5])").includes('Frankfurt'), 'the plan shows what is coming'); + assert.deepEqual(errors, []); +}); + +test('architect runs: the detour needs room, and a roomy but pricey build misses the budget star', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + const head = [[['ams', 'fra', 'land']], [['ams', 'par', 'land'], ['ams', 'lon', 'nshuttle']], [['par', 'fra', 'land']]]; + const run = (plan) => plan.forEach((steps, i) => { + for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s); + assert.equal(review(ev), true, `brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`); + ev('ACT.pzArNext()'); + }); + run(head); + // Zürich hung off Frankfurt: connected both ways, but a cut on Amsterdam-Frankfurt sends Frankfurt and Zürich through + // Paris, and that tube is too thin for all three. + lay(ev, 'fra', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); + assert.equal(review(ev), false); + assert.ok(JSON.parse(ev('JSON.stringify(UI.arFail.short)')).length > 0, 'someone still connected runs short'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(UI.arFail.gold)')), [], 'nobody gold is cut off'); + ev('ACT.pzReset()'); + lay(ev, 'ams', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); + assert.equal(review(ev), true, 'Zürich straight to HQ spreads the detours'); + ev('ACT.pzArNext()'); + // Paris doubles: a second Amsterdam-Paris trench gives room, at a price. + lay(ev, 'lon', 'par', 'pasdc'); lay(ev, 'ams', 'par', 'land'); + assert.equal(review(ev), true); ev('ACT.pzArNext()'); + ev("ACT.pzRmPop({city:'fra'})"); lay(ev, 'ams', 'dus', 'land'); lay(ev, 'dus', 'zrh', 'land'); + assert.equal(review(ev), true); + assert.equal(ev('arOver()'), 0); + assert.ok(ev('arSpend()') > ev('arRun().budget')); + assert.equal(ev('arStars(arSpend())'), 2, 'on plan, over budget: two stars'); + assert.deepEqual(errors, []); +}); + +test('architect runs: a bigger tube brings a bigger router, and changing an old tube is a new lease', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + assert.equal(ev("S.pops.ams.rgen||0"), 0, 'the free router takes 100G'); + const sunk = ev('S.ar.sunk'); + ev("ACT.pzTier({id:S.links[0].id,tier:2})"); + assert.ok(ev("RG[S.pops.ams.rgen].maxLT>=2&&RG[S.pops.fra.rgen].maxLT>=2"), '400G needs a bigger router at both ends'); + assert.ok(ev('S.ar.sunk') > sunk, 'the old 100G lease is paid for'); + ev('ACT.pzUndo()'); + assert.equal(ev("(S.pops.ams.rgen||0)===0&&S.ar.sunk===" + sunk), true, 'undo puts it all back'); + assert.deepEqual(errors, []); +}); From 1d3d8eb2ef98404b98799fa2d1b61f44d1dd5f70 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 08:06:14 +0100 Subject: [PATCH 142/181] Architect runs: translate into German, Spanish, French, Italian and Portuguese; drop two unused labels --- site/i18n/de.js | 111 ++++++++++++++++++++++++++++++++++++++++++++++++ site/i18n/es.js | 111 ++++++++++++++++++++++++++++++++++++++++++++++++ site/i18n/fr.js | 111 ++++++++++++++++++++++++++++++++++++++++++++++++ site/i18n/it.js | 111 ++++++++++++++++++++++++++++++++++++++++++++++++ site/i18n/pt.js | 111 ++++++++++++++++++++++++++++++++++++++++++++++++ src/i18n/en.js | 2 - 6 files changed, 555 insertions(+), 2 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index c255a30..4d99448 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -14,6 +14,117 @@ "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.", +"architect.anchor":"⚓ Anker!", +"architect.architect_runs":"Architekt-Runs", +"architect.backhoe":"🚜 Bagger!", +"architect.best_n_briefs":"Rekord: {n} Aufträge", +"architect.brief_n_of_m":"Auftrag {n} von {m}", +"architect.briefs_done":"Aufträge erledigt", +"architect.built_in_an_earlier_brief":"In einem früheren Auftrag gebaut: Abreißen bringt nichts zurück.", +"architect.changing_an_old_tube":"Diese Röhre stammt aus einem früheren Auftrag: Eine neue Größe ist ein neuer Mietvertrag, und der alte ist schon bezahlt.", +"architect.city_goes_dark":"In {city} gehen die Lichter aus", +"architect.city_short_g":"{city} fehlen {g}", +"architect.closed":"Geschlossen", +"architect.closed_city":"Kein POP in {city}", +"architect.closed_lead":"Diese Stadt ist jetzt dicht. Zieh aus: Entferne den POP und finde einen anderen Weg.", +"architect.coast_to_coast":"Coast to Coast", +"architect.coast_to_coast_joke":"Von der Data Center Alley bis ins Silicon Valley, ein Auftrag nach dem anderen.", +"architect.coming_up":"Demnächst", +"architect.cut_n_of_m":"Schnitt {n} von {m}…", +"architect.cut_on_x_cuts_off_y":"Ein Schnitt auf {x} schneidet {y} ab.", +"architect.cut_on_x_no_room":"Ein Schnitt auf {x} lässt auf dem Umweg keinen Platz. Es fehlt: {y}.", +"architect.dark_list":"Vorerst offline: {list}. Kein Gold, also ist das erlaubt.", +"architect.drag_from_your_hq":"Zieh von deinem HQ zu einer anderen Stadt, um eine Röhre zu legen", +"architect.euro_1":"Deine Server stehen in Amsterdam. Erster Kunde: Frankfurt. Schließ ihn an.", +"architect.euro_2b":"Paris und London wollen auch.", +"architect.euro_3b":"Frankfurt und Paris gewinnen Banken. Beide werden Gold.", +"architect.euro_5":"Zürich, noch eine Bank. Gold vom ersten Tag an.", +"architect.euro_6":"Dein Vermieter in Frankfurt hat das Gebäude verkauft. Zieh aus. Die Bank zieht nach Düsseldorf und bleibt Gold.", +"architect.euro_ring_grow":"Paris verdoppelt auf 100G. Und London, Paris und Amsterdam wollen einen Ring untereinander.", +"architect.euro_run":"Euro-Run", +"architect.euro_run_joke":"Sechs Aufträge, ein Vermieter, eine sehr nervöse Bank.", +"architect.finish_the_run":"Run beenden", +"architect.fix_it_and_send_it_again":"Reparier es und schick den Bagger noch mal los.", +"architect.from_x":"ab {x}", +"architect.gold_lead":"Gold: Dieser Standort muss mit dem HQ verbunden bleiben, egal welcher einzelne Graben oder welches Kabel gekappt wird, und der Umweg braucht Platz für seinen Traffic.", +"architect.gold_must_survive":"Muss jeden einzelnen Schnitt überleben: {list}", +"architect.gold_site":"Gold-Standort", +"architect.hide_other_cities":"Andere Städte ausblenden", +"architect.hq":"HQ", +"architect.hq_lead":"Hier stehen deine Server. Jeder Standort braucht einen Weg zum HQ.", +"architect.joins_in_brief_n":"Kommt in Auftrag {n} dazu", +"architect.keep_going":"Weiterbauen", +"architect.last_brief_done":"Das war der letzte Auftrag.", +"architect.lay_a_tube_to":"Röhre legen nach", +"architect.line_1":"Läuft. Die Buchhaltung hätte da noch Fragen.", +"architect.line_2":"Solides Design, ein bisschen vergoldet. Damit kann die Buchhaltung leben.", +"architect.line_3":"Im Plan oder besser. Der Bagger ist gelangweilt heimgefahren.", +"architect.move_out_of_city":"Zieh zuerst aus {city} aus.", +"architect.n_briefs":"{n} Aufträge", +"architect.n_over_plan":"{n} über Plan", +"architect.n_tubes":{"one":"{n} Röhre","other":"{n} Röhren"}, +"architect.new":"Neu", +"architect.next_brief":"Nächster Auftrag", +"architect.next_brief_waiting":"Der nächste Auftrag wartet.", +"architect.next_run":"Nächster Run", +"architect.not_a_ring_yet":"Noch kein Ring.", +"architect.not_connected_yet_list":"Noch nicht mit dem HQ verbunden: {list}", +"architect.numbers_on_the_map_show":"Die Zahlen auf der Karte zeigen, was spätere Aufträge bringen. Du darfst dort schon früher bauen.", +"architect.or_drag_a_tube_here":"Oder zieh eine Röhre von einem deiner POPs hierher.", +"architect.pac_1":"Deine Server stehen in Tokio. Zuerst Hongkong.", +"architect.pac_2":"Singapur will auch.", +"architect.pac_3":"Eine Börse in Hongkong. Hongkong ist Gold.", +"architect.pac_4":"Singapur gewinnt eine Bank. Auch Gold.", +"architect.pac_5":"Sydney. Weit weg von allem: Das ist der Witz, und das Problem.", +"architect.pacific_rim":"Pacific Rim", +"architect.pacific_rim_joke":"Ozeane, Anker und sehr teures Glas.", +"architect.plus_router_x":"+ größerer Router {x}", +"architect.ready_no_gold_yet":"Fertig. Noch keine Gold-Standorte, der Bagger kann also nur Chaos anrichten.", +"architect.ready_send_the_backhoe":"Fertig. Schick den Bagger los und schau, was überlebt.", +"architect.reset_brief":"Auftrag zurücksetzen", +"architect.review_passed":"Abnahme bestanden", +"architect.ring_list":"Ein Ring durch {list}", +"architect.router_follows":"Passend zu deinen Röhren gewählt", +"architect.router_x":"Router: {x}", +"architect.run_complete":"Run geschafft", +"architect.run_over":"Run vorbei", +"architect.runs_lead":"Ein Netz, Auftrag für Auftrag gebaut. Was du baust, bleibt stehen, und ein Bagger prüft jedes Design: Kapp eine beliebige Röhre, und alles, was noch verbunden ist, muss seinen ganzen Traffic bekommen.", +"architect.send_the_backhoe":"Bagger losschicken", +"architect.shape_braces":"Doppelt hält besser", +"architect.shape_full":"Full Mesh", +"architect.shape_islands":"Inseln", +"architect.shape_ladder":"Leiter", +"architect.shape_line":"Linie", +"architect.shape_lolli":"Ring mit Ausläufern", +"architect.shape_mesh":"Mesh", +"architect.shape_ring":"Ring", +"architect.shape_spaghetti":"Spaghetti", +"architect.shape_star":"Stern", +"architect.shape_tree":"Baum", +"architect.shape_tube":"Eine Röhre", +"architect.share_line":"Series of Tubes · {what} {stars} {spend} {shape} · seriesoftub.es", +"architect.show_all_cities":"Alle Städte zeigen", +"architect.site":"Standort", +"architect.size":"Größe", +"architect.skip":"Überspringen", +"architect.spent":"Ausgegeben", +"architect.spent_x_of_y":"{x} von {y} ausgegeben", +"architect.the_cfo_pulled_the_plug":"Der CFO hat den Stecker gezogen. Vielleicht eine günstigere Form?", +"architect.this_tube_is_over_the_plan":"Die Röhren für diesen Auftrag sind aufgebraucht. Du kannst sie trotzdem legen, aber es kostet einen Stern.", +"architect.too_slow_for_the_cap":"Zu langsam: Such einen schnelleren Weg.", +"architect.too_thin_list":"Zu dünn: {list}", +"architect.try_again":"Noch mal", +"architect.tube_laid":"Röhre liegt!", +"architect.tubes_over_plan":"Röhren über Plan", +"architect.tubes_this_brief":"Röhren in diesem Auftrag", +"architect.usa_1":"Deine Server stehen in Ashburn. Zuerst New York.", +"architect.usa_2":"Chicago will auch.", +"architect.usa_3":"Eine Bank in New York. New York ist Gold.", +"architect.usa_4":"Trader wollen New York ⇄ Chicago unter 8 ms.", +"architect.usa_5":"Dallas und das Silicon Valley wollen auch.", +"architect.usa_6":"Ein Cloud-Deal im Silicon Valley. Es wird Gold.", +"architect.x_paid_for_and_gone":"{x} davon für Dinge, die du wieder entfernt hast", +"architect.your_shape":"Deine Form", "badges.a_petabit_a_second":"Ein Petabit pro Sekunde", "badges.a_secret_badge":"Ein geheimes Abzeichen", "badges.attend_a_conference":"Besuche eine Konferenz.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 6a4af3e..d9c84b0 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -12,6 +12,117 @@ "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.", +"architect.anchor":"⚓ ¡Ancla!", +"architect.architect_runs":"Partidas de arquitecto", +"architect.backhoe":"🚜 ¡Retroexcavadora!", +"architect.best_n_briefs":"récord: {n} encargos", +"architect.brief_n_of_m":"Encargo {n} de {m}", +"architect.briefs_done":"Encargos hechos", +"architect.built_in_an_earlier_brief":"Construido en un encargo anterior: quitarlo no te devuelve nada.", +"architect.changing_an_old_tube":"Este tubo es de un encargo anterior: un tamaño nuevo es un contrato nuevo, y el viejo ya está pagado.", +"architect.city_goes_dark":"{city} se queda a oscuras", +"architect.city_short_g":"A {city} le faltan {g}", +"architect.closed":"Cerrado", +"architect.closed_city":"Sin POP en {city}", +"architect.closed_lead":"Esta ciudad ya está cerrada. Múdate: quita el POP y busca otro camino.", +"architect.coast_to_coast":"De costa a costa", +"architect.coast_to_coast_joke":"Del callejón de los data centers a Silicon Valley, encargo a encargo.", +"architect.coming_up":"Próximamente", +"architect.cut_n_of_m":"Corte {n} de {m}…", +"architect.cut_on_x_cuts_off_y":"Un corte en {x} deja aislado a {y}.", +"architect.cut_on_x_no_room":"Un corte en {x} no deja sitio en el desvío. Falta: {y}.", +"architect.dark_list":"A oscuras por ahora: {list}. No es oro, así que está permitido.", +"architect.drag_from_your_hq":"Arrastra desde tu sede a otra ciudad para tender un tubo", +"architect.euro_1":"Tus servidores viven en Ámsterdam. Primer cliente: Fráncfort. Conéctalo.", +"architect.euro_2b":"París y Londres se apuntan.", +"architect.euro_3b":"Fráncfort y París fichan bancos. Las dos pasan a oro.", +"architect.euro_5":"Zúrich, otro banco. Oro desde el primer día.", +"architect.euro_6":"Tu casero de Fráncfort vendió el edificio. Múdate. El banco se va a Düsseldorf, y sigue siendo oro.", +"architect.euro_ring_grow":"París se duplica a 100G. Y Londres, París y Ámsterdam quieren un anillo entre ellas.", +"architect.euro_run":"Ruta europea", +"architect.euro_run_joke":"Seis encargos, un casero y un banco muy nervioso.", +"architect.finish_the_run":"Terminar la partida", +"architect.fix_it_and_send_it_again":"Arréglalo y vuelve a mandar la retroexcavadora.", +"architect.from_x":"desde {x}", +"architect.gold_lead":"Oro: este sitio debe seguir conectado a la sede sea cual sea la zanja o el cable que se corte, y el desvío necesita sitio para su tráfico.", +"architect.gold_must_survive":"Debe sobrevivir a cualquier corte: {list}", +"architect.gold_site":"Sitio oro", +"architect.hide_other_cities":"Ocultar otras ciudades", +"architect.hq":"Sede", +"architect.hq_lead":"Aquí viven tus servidores. Cada sitio necesita un camino a la sede.", +"architect.joins_in_brief_n":"Llega en el encargo {n}", +"architect.keep_going":"Seguir construyendo", +"architect.last_brief_done":"Ese era el último encargo.", +"architect.lay_a_tube_to":"Tender un tubo a", +"architect.line_1":"Funciona. Finanzas quiere hablar contigo.", +"architect.line_2":"Diseño sólido, un poco bañado en oro. Finanzas puede vivir con ello.", +"architect.line_3":"En presupuesto o mejor. La retroexcavadora se fue a casa aburrida.", +"architect.move_out_of_city":"Primero sal de {city}.", +"architect.n_briefs":"{n} encargos", +"architect.n_over_plan":"{n} por encima del plan", +"architect.n_tubes":{"one":"{n} tubo","other":"{n} tubos"}, +"architect.new":"Nuevo", +"architect.next_brief":"Siguiente encargo", +"architect.next_brief_waiting":"El siguiente encargo te espera.", +"architect.next_run":"Siguiente partida", +"architect.not_a_ring_yet":"Todavía no es un anillo.", +"architect.not_connected_yet_list":"Aún sin conexión a la sede: {list}", +"architect.numbers_on_the_map_show":"Los números del mapa muestran lo que traen los próximos encargos. Puedes construir allí antes.", +"architect.or_drag_a_tube_here":"O arrastra un tubo hasta aquí desde uno de tus POP.", +"architect.pac_1":"Tus servidores viven en Tokio. Primero, Hong Kong.", +"architect.pac_2":"Singapur se apunta.", +"architect.pac_3":"Una bolsa en Hong Kong. Hong Kong es oro.", +"architect.pac_4":"Singapur ficha un banco. También es oro.", +"architect.pac_5":"Sídney. Lejos de todo: esa es la gracia, y el problema.", +"architect.pacific_rim":"Cinturón del Pacífico", +"architect.pacific_rim_joke":"Océanos, anclas y vidrio carísimo.", +"architect.plus_router_x":"+ router más grande {x}", +"architect.ready_no_gold_yet":"Listo. Aún no hay sitios oro, así que la retroexcavadora solo puede armar un lío.", +"architect.ready_send_the_backhoe":"Listo. Manda la retroexcavadora y mira qué sobrevive.", +"architect.reset_brief":"Reiniciar encargo", +"architect.review_passed":"Revisión superada", +"architect.ring_list":"Un anillo por {list}", +"architect.router_follows":"Elegido según tus tubos", +"architect.router_x":"Router: {x}", +"architect.run_complete":"Partida completada", +"architect.run_over":"Partida terminada", +"architect.runs_lead":"Una red, construida encargo a encargo. Lo que construyes se queda, y una retroexcavadora revisa cada diseño: corta cualquier tubo, y todo lo que siga conectado debe recibir todo su tráfico.", +"architect.send_the_backhoe":"Mandar la retroexcavadora", +"architect.shape_braces":"Cinturón y tirantes", +"architect.shape_full":"Malla completa", +"architect.shape_islands":"Islas", +"architect.shape_ladder":"Escalera", +"architect.shape_line":"Línea", +"architect.shape_lolli":"Anillo con ramales", +"architect.shape_mesh":"Malla", +"architect.shape_ring":"Anillo", +"architect.shape_spaghetti":"Espagueti", +"architect.shape_star":"Estrella", +"architect.shape_tree":"Árbol", +"architect.shape_tube":"Un solo tubo", +"architect.share_line":"Series of Tubes · {what} {stars} {spend} {shape} · seriesoftub.es", +"architect.show_all_cities":"Mostrar todas las ciudades", +"architect.site":"Sitio", +"architect.size":"Tamaño", +"architect.skip":"Saltar", +"architect.spent":"Gastado", +"architect.spent_x_of_y":"Gastado {x} de {y}", +"architect.the_cfo_pulled_the_plug":"El director financiero desenchufó el proyecto. ¿Probamos una forma más barata?", +"architect.this_tube_is_over_the_plan":"Ya gastaste los tubos de este encargo. Puedes tenderlo igual, pero cuesta una estrella.", +"architect.too_slow_for_the_cap":"Demasiado lento: busca un camino más rápido.", +"architect.too_thin_list":"Demasiado fino: {list}", +"architect.try_again":"Reintentar", +"architect.tube_laid":"¡Tubo tendido!", +"architect.tubes_over_plan":"Tubos por encima del plan", +"architect.tubes_this_brief":"Tubos de este encargo", +"architect.usa_1":"Tus servidores viven en Ashburn. Primero, Nueva York.", +"architect.usa_2":"Chicago se apunta.", +"architect.usa_3":"Un banco en Nueva York. Nueva York es oro.", +"architect.usa_4":"Los traders quieren Nueva York ⇄ Chicago en menos de 8 ms.", +"architect.usa_5":"Dallas y Silicon Valley se apuntan.", +"architect.usa_6":"Un acuerdo cloud en Silicon Valley. Pasa a oro.", +"architect.x_paid_for_and_gone":"{x} de eso pagó cosas que quitaste", +"architect.your_shape":"Tu forma", "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 b5e12d1..739a010 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -12,6 +12,117 @@ "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.", +"architect.anchor":"⚓ Ancre !", +"architect.architect_runs":"Parties d’architecte", +"architect.backhoe":"🚜 Pelleteuse !", +"architect.best_n_briefs":"record : {n} briefs", +"architect.brief_n_of_m":"Brief {n} sur {m}", +"architect.briefs_done":"Briefs terminés", +"architect.built_in_an_earlier_brief":"Construit lors d’un brief précédent : le retirer ne rapporte rien.", +"architect.changing_an_old_tube":"Ce tube vient d’un brief précédent : une nouvelle taille, c’est un nouveau bail, et l’ancien est déjà payé.", +"architect.city_goes_dark":"{city} s’éteint", +"architect.city_short_g":"Il manque {g} à {city}", +"architect.closed":"Fermé", +"architect.closed_city":"Pas de POP à {city}", +"architect.closed_lead":"Cette ville est fermée maintenant. Déménage : retire le POP et trouve un autre chemin.", +"architect.coast_to_coast":"D’une côte à l’autre", +"architect.coast_to_coast_joke":"De l’allée des data centers à la Silicon Valley, un brief à la fois.", +"architect.coming_up":"À venir", +"architect.cut_n_of_m":"Coupure {n} sur {m}…", +"architect.cut_on_x_cuts_off_y":"Une coupure sur {x} isole {y}.", +"architect.cut_on_x_no_room":"Une coupure sur {x} ne laisse pas de place sur le détour. Manque : {y}.", +"architect.dark_list":"Éteint pour l’instant : {list}. Pas en or, donc c’est permis.", +"architect.drag_from_your_hq":"Fais glisser depuis ton QG vers une autre ville pour poser un tube", +"architect.euro_1":"Tes serveurs vivent à Amsterdam. Premier client : Francfort. Connecte-le.", +"architect.euro_2b":"Paris et Londres veulent en être.", +"architect.euro_3b":"Francfort et Paris signent des banques. Les deux passent en or.", +"architect.euro_5":"Zurich, encore une banque. En or dès le premier jour.", +"architect.euro_6":"Ton proprio à Francfort a vendu l’immeuble. Déménage. La banque part à Düsseldorf, et reste en or.", +"architect.euro_ring_grow":"Paris double à 100G. Et Londres, Paris et Amsterdam veulent un anneau entre elles.", +"architect.euro_run":"Euro Run", +"architect.euro_run_joke":"Six briefs, un proprio, une banque très nerveuse.", +"architect.finish_the_run":"Terminer la partie", +"architect.fix_it_and_send_it_again":"Répare, puis renvoie la pelleteuse.", +"architect.from_x":"dès {x}", +"architect.gold_lead":"Or : ce site doit rester relié au QG quelle que soit la tranchée ou le câble coupé, et le détour doit avoir de la place pour son trafic.", +"architect.gold_must_survive":"Doit survivre à n’importe quelle coupure : {list}", +"architect.gold_site":"Site en or", +"architect.hide_other_cities":"Masquer les autres villes", +"architect.hq":"QG", +"architect.hq_lead":"Tes serveurs vivent ici. Chaque site a besoin d’un chemin vers le QG.", +"architect.joins_in_brief_n":"Arrive au brief {n}", +"architect.keep_going":"Continuer à construire", +"architect.last_brief_done":"C’était le dernier brief.", +"architect.lay_a_tube_to":"Poser un tube vers", +"architect.line_1":"Ça marche. La compta aimerait te dire un mot.", +"architect.line_2":"Design solide, un peu plaqué or. La compta peut vivre avec.", +"architect.line_3":"Dans le budget, voire mieux. La pelleteuse est rentrée chez elle en s’ennuyant.", +"architect.move_out_of_city":"Quitte d’abord {city}.", +"architect.n_briefs":"{n} briefs", +"architect.n_over_plan":"{n} au-delà du plan", +"architect.n_tubes":{"one":"{n} tube","other":"{n} tubes"}, +"architect.new":"Nouveau", +"architect.next_brief":"Brief suivant", +"architect.next_brief_waiting":"Le brief suivant t’attend.", +"architect.next_run":"Partie suivante", +"architect.not_a_ring_yet":"Pas encore un anneau.", +"architect.not_connected_yet_list":"Pas encore relié au QG : {list}", +"architect.numbers_on_the_map_show":"Les chiffres sur la carte montrent ce qu’apportent les briefs suivants. Tu peux y construire en avance.", +"architect.or_drag_a_tube_here":"Ou fais glisser un tube jusqu’ici depuis un de tes POP.", +"architect.pac_1":"Tes serveurs vivent à Tokyo. D’abord Hong Kong.", +"architect.pac_2":"Singapour veut en être.", +"architect.pac_3":"Une bourse à Hong Kong. Hong Kong est en or.", +"architect.pac_4":"Singapour signe une banque. En or aussi.", +"architect.pac_5":"Sydney. Loin de tout : c’est tout l’intérêt, et tout le problème.", +"architect.pacific_rim":"Ceinture du Pacifique", +"architect.pacific_rim_joke":"Des océans, des ancres et du verre hors de prix.", +"architect.plus_router_x":"+ routeur plus gros {x}", +"architect.ready_no_gold_yet":"Prêt. Pas encore de site en or, donc la pelleteuse ne peut que mettre le bazar.", +"architect.ready_send_the_backhoe":"Prêt. Envoie la pelleteuse et regarde ce qui survit.", +"architect.reset_brief":"Recommencer le brief", +"architect.review_passed":"Revue validée", +"architect.ring_list":"Un anneau par {list}", +"architect.router_follows":"Choisi selon tes tubes", +"architect.router_x":"Routeur : {x}", +"architect.run_complete":"Partie terminée", +"architect.run_over":"Partie perdue", +"architect.runs_lead":"Un réseau, construit brief après brief. Ce que tu construis reste, et une pelleteuse vérifie chaque design : coupe n’importe quel tube, et tout ce qui est encore relié doit recevoir tout son trafic.", +"architect.send_the_backhoe":"Envoyer la pelleteuse", +"architect.shape_braces":"Ceinture et bretelles", +"architect.shape_full":"Maillage complet", +"architect.shape_islands":"Îles", +"architect.shape_ladder":"Échelle", +"architect.shape_line":"Ligne", +"architect.shape_lolli":"Anneau avec antennes", +"architect.shape_mesh":"Maillage", +"architect.shape_ring":"Anneau", +"architect.shape_spaghetti":"Spaghettis", +"architect.shape_star":"Étoile", +"architect.shape_tree":"Arbre", +"architect.shape_tube":"Un seul tube", +"architect.share_line":"Series of Tubes · {what} {stars} {spend} {shape} · seriesoftub.es", +"architect.show_all_cities":"Afficher toutes les villes", +"architect.site":"Site", +"architect.size":"Taille", +"architect.skip":"Passer", +"architect.spent":"Dépensé", +"architect.spent_x_of_y":"Dépensé {x} sur {y}", +"architect.the_cfo_pulled_the_plug":"Le DAF a débranché la prise. Une forme moins chère, peut-être ?", +"architect.this_tube_is_over_the_plan":"Les tubes de ce brief sont épuisés. Tu peux quand même le poser, mais ça coûte une étoile.", +"architect.too_slow_for_the_cap":"Trop lent : trouve un chemin plus rapide.", +"architect.too_thin_list":"Trop fin : {list}", +"architect.try_again":"Réessayer", +"architect.tube_laid":"Tube posé !", +"architect.tubes_over_plan":"Tubes au-delà du plan", +"architect.tubes_this_brief":"Tubes de ce brief", +"architect.usa_1":"Tes serveurs vivent à Ashburn. D’abord New York.", +"architect.usa_2":"Chicago veut en être.", +"architect.usa_3":"Une banque à New York. New York est en or.", +"architect.usa_4":"Les traders veulent New York ⇄ Chicago en moins de 8 ms.", +"architect.usa_5":"Dallas et la Silicon Valley veulent en être.", +"architect.usa_6":"Un contrat cloud dans la Silicon Valley. Elle passe en or.", +"architect.x_paid_for_and_gone":"dont {x} pour des choses que tu as retirées", +"architect.your_shape":"Ta forme", "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 2afe831..f0e411f 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -12,6 +12,117 @@ "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.", +"architect.anchor":"⚓ Ancora!", +"architect.architect_runs":"Partite da architetto", +"architect.backhoe":"🚜 Ruspa!", +"architect.best_n_briefs":"record: {n} incarichi", +"architect.brief_n_of_m":"Incarico {n} di {m}", +"architect.briefs_done":"Incarichi completati", +"architect.built_in_an_earlier_brief":"Costruito in un incarico precedente: toglierlo non ti restituisce niente.", +"architect.changing_an_old_tube":"Questo tubo viene da un incarico precedente: una nuova taglia è un nuovo contratto, e quello vecchio è già pagato.", +"architect.city_goes_dark":"{city} resta al buio", +"architect.city_short_g":"A {city} mancano {g}", +"architect.closed":"Chiuso", +"architect.closed_city":"Nessun POP a {city}", +"architect.closed_lead":"Questa città ora è chiusa. Trasloca: togli il POP e trova un’altra strada.", +"architect.coast_to_coast":"Da costa a costa", +"architect.coast_to_coast_joke":"Dal vicolo dei data center alla Silicon Valley, un incarico alla volta.", +"architect.coming_up":"In arrivo", +"architect.cut_n_of_m":"Taglio {n} di {m}…", +"architect.cut_on_x_cuts_off_y":"Un taglio su {x} isola {y}.", +"architect.cut_on_x_no_room":"Un taglio su {x} non lascia spazio sulla deviazione. Manca: {y}.", +"architect.dark_list":"Al buio per ora: {list}. Non è oro, quindi si può.", +"architect.drag_from_your_hq":"Trascina dalla tua sede a un’altra città per posare un tubo", +"architect.euro_1":"I tuoi server vivono ad Amsterdam. Primo cliente: Francoforte. Collegalo.", +"architect.euro_2b":"Anche Parigi e Londra vogliono entrare.", +"architect.euro_3b":"Francoforte e Parigi firmano con delle banche. Diventano oro tutte e due.", +"architect.euro_5":"Zurigo, un’altra banca. Oro dal primo giorno.", +"architect.euro_6":"Il tuo padrone di casa a Francoforte ha venduto il palazzo. Trasloca. La banca si sposta a Düsseldorf, ed è ancora oro.", +"architect.euro_ring_grow":"Parigi raddoppia a 100G. E Londra, Parigi e Amsterdam vogliono un anello tra loro.", +"architect.euro_run":"Euro Run", +"architect.euro_run_joke":"Sei incarichi, un padrone di casa, una banca molto nervosa.", +"architect.finish_the_run":"Chiudi la partita", +"architect.fix_it_and_send_it_again":"Sistemalo, poi rimanda la ruspa.", +"architect.from_x":"da {x}", +"architect.gold_lead":"Oro: questo sito deve restare collegato alla sede qualunque scavo o cavo venga tagliato, e la deviazione deve avere spazio per il suo traffico.", +"architect.gold_must_survive":"Deve sopravvivere a qualsiasi taglio: {list}", +"architect.gold_site":"Sito oro", +"architect.hide_other_cities":"Nascondi le altre città", +"architect.hq":"Sede", +"architect.hq_lead":"Qui vivono i tuoi server. Ogni sito ha bisogno di una strada verso la sede.", +"architect.joins_in_brief_n":"Arriva nell’incarico {n}", +"architect.keep_going":"Continua a costruire", +"architect.last_brief_done":"Era l’ultimo incarico.", +"architect.lay_a_tube_to":"Posa un tubo verso", +"architect.line_1":"Funziona. L’amministrazione vorrebbe parlarti.", +"architect.line_2":"Progetto solido, un po’ placcato d’oro. L’amministrazione ci può convivere.", +"architect.line_3":"Nel budget o meglio. La ruspa è tornata a casa annoiata.", +"architect.move_out_of_city":"Prima lascia {city}.", +"architect.n_briefs":"{n} incarichi", +"architect.n_over_plan":"{n} oltre il piano", +"architect.n_tubes":{"one":"{n} tubo","other":"{n} tubi"}, +"architect.new":"Nuovo", +"architect.next_brief":"Prossimo incarico", +"architect.next_brief_waiting":"Il prossimo incarico ti aspetta.", +"architect.next_run":"Prossima partita", +"architect.not_a_ring_yet":"Non è ancora un anello.", +"architect.not_connected_yet_list":"Non ancora collegati alla sede: {list}", +"architect.numbers_on_the_map_show":"I numeri sulla mappa mostrano cosa portano i prossimi incarichi. Puoi costruirci già prima.", +"architect.or_drag_a_tube_here":"Oppure trascina qui un tubo da uno dei tuoi POP.", +"architect.pac_1":"I tuoi server vivono a Tokyo. Prima Hong Kong.", +"architect.pac_2":"Anche Singapore vuole entrare.", +"architect.pac_3":"Una borsa a Hong Kong. Hong Kong è oro.", +"architect.pac_4":"Singapore firma con una banca. Oro anche lei.", +"architect.pac_5":"Sydney. Lontana da tutto: è proprio questo il bello, e il problema.", +"architect.pacific_rim":"Anello del Pacifico", +"architect.pacific_rim_joke":"Oceani, ancore e vetro carissimo.", +"architect.plus_router_x":"+ router più grande {x}", +"architect.ready_no_gold_yet":"Pronto. Ancora nessun sito oro, quindi la ruspa può solo fare disastri.", +"architect.ready_send_the_backhoe":"Pronto. Manda la ruspa e guarda cosa sopravvive.", +"architect.reset_brief":"Ricomincia l’incarico", +"architect.review_passed":"Revisione superata", +"architect.ring_list":"Un anello attraverso {list}", +"architect.router_follows":"Scelto in base ai tuoi tubi", +"architect.router_x":"Router: {x}", +"architect.run_complete":"Partita completata", +"architect.run_over":"Partita finita", +"architect.runs_lead":"Una rete, costruita un incarico alla volta. Quello che costruisci resta, e una ruspa controlla ogni progetto: taglia un tubo qualsiasi, e tutto ciò che resta collegato deve ricevere tutto il suo traffico.", +"architect.send_the_backhoe":"Manda la ruspa", +"architect.shape_braces":"Cintura e bretelle", +"architect.shape_full":"Full mesh", +"architect.shape_islands":"Isole", +"architect.shape_ladder":"Scala", +"architect.shape_line":"Linea", +"architect.shape_lolli":"Anello con diramazioni", +"architect.shape_mesh":"Maglia", +"architect.shape_ring":"Anello", +"architect.shape_spaghetti":"Spaghetti", +"architect.shape_star":"Stella", +"architect.shape_tree":"Albero", +"architect.shape_tube":"Un tubo solo", +"architect.share_line":"Series of Tubes · {what} {stars} {spend} {shape} · seriesoftub.es", +"architect.show_all_cities":"Mostra tutte le città", +"architect.site":"Sito", +"architect.size":"Taglia", +"architect.skip":"Salta", +"architect.spent":"Speso", +"architect.spent_x_of_y":"Speso {x} di {y}", +"architect.the_cfo_pulled_the_plug":"Il CFO ha staccato la spina. Proviamo una forma più economica?", +"architect.this_tube_is_over_the_plan":"I tubi di questo incarico sono finiti. Puoi posarlo lo stesso, ma costa una stella.", +"architect.too_slow_for_the_cap":"Troppo lento: trova una strada più veloce.", +"architect.too_thin_list":"Troppo sottile: {list}", +"architect.try_again":"Riprova", +"architect.tube_laid":"Tubo posato!", +"architect.tubes_over_plan":"Tubi oltre il piano", +"architect.tubes_this_brief":"Tubi di questo incarico", +"architect.usa_1":"I tuoi server vivono ad Ashburn. Prima New York.", +"architect.usa_2":"Anche Chicago vuole entrare.", +"architect.usa_3":"Una banca a New York. New York è oro.", +"architect.usa_4":"I trader vogliono New York ⇄ Chicago sotto gli 8 ms.", +"architect.usa_5":"Anche Dallas e la Silicon Valley vogliono entrare.", +"architect.usa_6":"Un accordo cloud nella Silicon Valley. Diventa oro.", +"architect.x_paid_for_and_gone":"{x} di questi per cose che hai tolto", +"architect.your_shape":"La tua forma", "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 a5af6bb..790a2f8 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -12,6 +12,117 @@ "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.", +"architect.anchor":"⚓ Âncora!", +"architect.architect_runs":"Partidas de arquiteto", +"architect.backhoe":"🚜 Retroescavadeira!", +"architect.best_n_briefs":"recorde: {n} pedidos", +"architect.brief_n_of_m":"Pedido {n} de {m}", +"architect.briefs_done":"Pedidos concluídos", +"architect.built_in_an_earlier_brief":"Construído num pedido anterior: tirar não devolve nada.", +"architect.changing_an_old_tube":"Este tubo é de um pedido anterior: um tamanho novo é um contrato novo, e o antigo já está pago.", +"architect.city_goes_dark":"{city} fica no escuro", +"architect.city_short_g":"Faltam {g} em {city}", +"architect.closed":"Fechado", +"architect.closed_city":"Sem POP em {city}", +"architect.closed_lead":"Esta cidade fechou. Saia de lá: remova o POP e ache outro caminho.", +"architect.coast_to_coast":"De costa a costa", +"architect.coast_to_coast_joke":"Do beco dos data centers ao Vale do Silício, um pedido de cada vez.", +"architect.coming_up":"Vem aí", +"architect.cut_n_of_m":"Corte {n} de {m}…", +"architect.cut_on_x_cuts_off_y":"Um corte em {x} isola {y}.", +"architect.cut_on_x_no_room":"Um corte em {x} não deixa espaço no desvio. Falta: {y}.", +"architect.dark_list":"No escuro por enquanto: {list}. Não é ouro, então pode.", +"architect.drag_from_your_hq":"Arraste da sua sede até outra cidade para lançar um tubo", +"architect.euro_1":"Seus servidores moram em Amsterdã. Primeiro cliente: Frankfurt. Conecte.", +"architect.euro_2b":"Paris e Londres querem entrar.", +"architect.euro_3b":"Frankfurt e Paris fecham com bancos. As duas viram ouro.", +"architect.euro_5":"Zurique, mais um banco. Ouro desde o primeiro dia.", +"architect.euro_6":"Seu senhorio em Frankfurt vendeu o prédio. Saia de lá. O banco muda para Düsseldorf, e continua ouro.", +"architect.euro_ring_grow":"Paris dobra para 100G. E Londres, Paris e Amsterdã querem um anel entre elas.", +"architect.euro_run":"Euro Run", +"architect.euro_run_joke":"Seis pedidos, um senhorio, um banco muito nervoso.", +"architect.finish_the_run":"Encerrar a partida", +"architect.fix_it_and_send_it_again":"Conserte e mande a retroescavadeira de novo.", +"architect.from_x":"a partir de {x}", +"architect.gold_lead":"Ouro: este site precisa continuar ligado à sede, seja qual for a vala ou o cabo cortado, e o desvio precisa de espaço para o tráfego dele.", +"architect.gold_must_survive":"Precisa sobreviver a qualquer corte: {list}", +"architect.gold_site":"Site ouro", +"architect.hide_other_cities":"Esconder outras cidades", +"architect.hq":"Sede", +"architect.hq_lead":"Seus servidores moram aqui. Todo site precisa de um caminho até a sede.", +"architect.joins_in_brief_n":"Entra no pedido {n}", +"architect.keep_going":"Continuar construindo", +"architect.last_brief_done":"Esse foi o último pedido.", +"architect.lay_a_tube_to":"Lançar um tubo até", +"architect.line_1":"Funciona. O financeiro quer uma palavrinha.", +"architect.line_2":"Projeto sólido, meio banhado a ouro. O financeiro aguenta.", +"architect.line_3":"Dentro do orçamento ou melhor. A retroescavadeira voltou pra casa entediada.", +"architect.move_out_of_city":"Saia de {city} primeiro.", +"architect.n_briefs":"{n} pedidos", +"architect.n_over_plan":"{n} acima do plano", +"architect.n_tubes":{"one":"{n} tubo","other":"{n} tubos"}, +"architect.new":"Novo", +"architect.next_brief":"Próximo pedido", +"architect.next_brief_waiting":"O próximo pedido está esperando.", +"architect.next_run":"Próxima partida", +"architect.not_a_ring_yet":"Ainda não é um anel.", +"architect.not_connected_yet_list":"Ainda sem ligação com a sede: {list}", +"architect.numbers_on_the_map_show":"Os números no mapa mostram o que os próximos pedidos trazem. Dá para construir lá antes.", +"architect.or_drag_a_tube_here":"Ou arraste um tubo até aqui de um dos seus POPs.", +"architect.pac_1":"Seus servidores moram em Tóquio. Primeiro, Hong Kong.", +"architect.pac_2":"Singapura quer entrar.", +"architect.pac_3":"Uma bolsa de valores em Hong Kong. Hong Kong é ouro.", +"architect.pac_4":"Singapura fecha com um banco. Ouro também.", +"architect.pac_5":"Sydney. Longe de tudo: essa é a graça, e o problema.", +"architect.pacific_rim":"Círculo do Pacífico", +"architect.pacific_rim_joke":"Oceanos, âncoras e vidro caríssimo.", +"architect.plus_router_x":"+ router maior {x}", +"architect.ready_no_gold_yet":"Pronto. Ainda não há sites ouro, então a retroescavadeira só pode fazer bagunça.", +"architect.ready_send_the_backhoe":"Pronto. Mande a retroescavadeira e veja o que sobrevive.", +"architect.reset_brief":"Reiniciar pedido", +"architect.review_passed":"Revisão aprovada", +"architect.ring_list":"Um anel passando por {list}", +"architect.router_follows":"Escolhido pelos seus tubos", +"architect.router_x":"Router: {x}", +"architect.run_complete":"Partida concluída", +"architect.run_over":"Fim de partida", +"architect.runs_lead":"Uma rede, construída pedido a pedido. O que você constrói fica, e uma retroescavadeira testa cada projeto: corte qualquer tubo, e tudo que ainda estiver ligado precisa receber todo o seu tráfego.", +"architect.send_the_backhoe":"Mandar a retroescavadeira", +"architect.shape_braces":"Cinto e suspensório", +"architect.shape_full":"Malha completa", +"architect.shape_islands":"Ilhas", +"architect.shape_ladder":"Escada", +"architect.shape_line":"Linha", +"architect.shape_lolli":"Anel com ramais", +"architect.shape_mesh":"Malha", +"architect.shape_ring":"Anel", +"architect.shape_spaghetti":"Espaguete", +"architect.shape_star":"Estrela", +"architect.shape_tree":"Árvore", +"architect.shape_tube":"Um tubo só", +"architect.share_line":"Series of Tubes · {what} {stars} {spend} {shape} · seriesoftub.es", +"architect.show_all_cities":"Mostrar todas as cidades", +"architect.site":"Site", +"architect.size":"Tamanho", +"architect.skip":"Pular", +"architect.spent":"Gasto", +"architect.spent_x_of_y":"Gasto {x} de {y}", +"architect.the_cfo_pulled_the_plug":"O CFO puxou o plugue. Tenta um formato mais barato?", +"architect.this_tube_is_over_the_plan":"Os tubos deste pedido acabaram. Você ainda pode lançar, mas custa uma estrela.", +"architect.too_slow_for_the_cap":"Lento demais: ache um caminho mais rápido.", +"architect.too_thin_list":"Fino demais: {list}", +"architect.try_again":"Tentar de novo", +"architect.tube_laid":"Tubo lançado!", +"architect.tubes_over_plan":"Tubos acima do plano", +"architect.tubes_this_brief":"Tubos deste pedido", +"architect.usa_1":"Seus servidores moram em Ashburn. Primeiro, New York.", +"architect.usa_2":"Chicago quer entrar.", +"architect.usa_3":"Um banco em New York. New York é ouro.", +"architect.usa_4":"Os traders querem New York ⇄ Chicago abaixo de 8 ms.", +"architect.usa_5":"Dallas e o Vale do Silício querem entrar.", +"architect.usa_6":"Um contrato de cloud no Vale do Silício. Vira ouro.", +"architect.x_paid_for_and_gone":"{x} disso pagou coisas que você removeu", +"architect.your_shape":"Seu formato", "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/i18n/en.js b/src/i18n/en.js index ba303a6..7798646 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -39,7 +39,6 @@ "architect.euro_3b":"Frankfurt and Paris sign banks. Both go gold.", "architect.euro_5":"Zürich, another bank. Gold from day one.", "architect.euro_6":"Your Frankfurt landlord sold the building. Move out. The bank moves to Düsseldorf, and it is still gold.", -"architect.euro_ring":"London, Paris and Amsterdam want a ring between them.", "architect.euro_ring_grow":"Paris doubles to 100G. And London, Paris and Amsterdam want a ring between them.", "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Six briefs, one landlord, one very nervous bank.", @@ -56,7 +55,6 @@ "architect.keep_going":"Keep building", "architect.last_brief_done":"That was the last brief.", "architect.lay_a_tube_to":"Lay a tube to", -"architect.lay_it_x":"Lay it · {x}", "architect.line_1":"It works. Finance would like a word.", "architect.line_2":"Solid design, a little gold plated. Finance can live with it.", "architect.line_3":"At par or better. The backhoe went home bored.", From eeac6ebcf474ef12fef512436f3ea1e1c425df4a Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 08:08:48 +0100 Subject: [PATCH 143/181] CHANGELOG: Architect runs preview --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebdfd49..50f989c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Architect runs (preview), under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, gold sites must survive any single trench or cable cut with room on the detour, and a backhoe checks every design before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. + ## [2.0.0] — 2026-10-29 - The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. From ab05c80d687027aae3d8a548f3e07348b1344558 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 09:05:29 +0100 Subject: [PATCH 144/181] =?UTF-8?q?Architect=20runs:=20gold=20sites=20are?= =?UTF-8?q?=20now=20mission-critical=20(=F0=9F=9A=A8),=20in=20all=20six=20?= =?UTF-8?q?languages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- site/i18n/de.js | 22 +++++++++++----------- site/i18n/es.js | 22 +++++++++++----------- site/i18n/fr.js | 22 +++++++++++----------- site/i18n/it.js | 22 +++++++++++----------- site/i18n/pt.js | 22 +++++++++++----------- src/game/60-features/96-architect.js | 4 ++-- src/game/95-modals/96-architect.js | 6 +++--- src/i18n/en.js | 22 +++++++++++----------- src/styles/71-architect.css | 2 +- tests/architect.test.js | 2 +- 11 files changed, 74 insertions(+), 74 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50f989c..2b5af8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Architect runs (preview), under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, gold sites must survive any single trench or cable cut with room on the detour, and a backhoe checks every design before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. +- Architect runs (preview), under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, mission-critical sites must survive any single trench or cable cut with room on the detour, and a backhoe checks every design before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. ## [2.0.0] — 2026-10-29 diff --git a/site/i18n/de.js b/site/i18n/de.js index 4d99448..8ea780a 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -33,22 +33,22 @@ "architect.cut_n_of_m":"Schnitt {n} von {m}…", "architect.cut_on_x_cuts_off_y":"Ein Schnitt auf {x} schneidet {y} ab.", "architect.cut_on_x_no_room":"Ein Schnitt auf {x} lässt auf dem Umweg keinen Platz. Es fehlt: {y}.", -"architect.dark_list":"Vorerst offline: {list}. Kein Gold, also ist das erlaubt.", +"architect.dark_list":"Vorerst offline: {list}. Nicht geschäftskritisch, also ist das erlaubt.", "architect.drag_from_your_hq":"Zieh von deinem HQ zu einer anderen Stadt, um eine Röhre zu legen", "architect.euro_1":"Deine Server stehen in Amsterdam. Erster Kunde: Frankfurt. Schließ ihn an.", "architect.euro_2b":"Paris und London wollen auch.", -"architect.euro_3b":"Frankfurt und Paris gewinnen Banken. Beide werden Gold.", -"architect.euro_5":"Zürich, noch eine Bank. Gold vom ersten Tag an.", -"architect.euro_6":"Dein Vermieter in Frankfurt hat das Gebäude verkauft. Zieh aus. Die Bank zieht nach Düsseldorf und bleibt Gold.", +"architect.euro_3b":"Frankfurt und Paris gewinnen Banken. Beide sind jetzt geschäftskritisch.", +"architect.euro_5":"Zürich, noch eine Bank. Geschäftskritisch vom ersten Tag an.", +"architect.euro_6":"Dein Vermieter in Frankfurt hat das Gebäude verkauft. Raus da. Die Bank zieht nach Düsseldorf und bleibt geschäftskritisch.", "architect.euro_ring_grow":"Paris verdoppelt auf 100G. Und London, Paris und Amsterdam wollen einen Ring untereinander.", "architect.euro_run":"Euro-Run", "architect.euro_run_joke":"Sechs Aufträge, ein Vermieter, eine sehr nervöse Bank.", "architect.finish_the_run":"Run beenden", "architect.fix_it_and_send_it_again":"Reparier es und schick den Bagger noch mal los.", "architect.from_x":"ab {x}", -"architect.gold_lead":"Gold: Dieser Standort muss mit dem HQ verbunden bleiben, egal welcher einzelne Graben oder welches Kabel gekappt wird, und der Umweg braucht Platz für seinen Traffic.", +"architect.gold_lead":"Geschäftskritisch: Dieser Standort muss mit dem HQ verbunden bleiben, egal welcher einzelne Graben oder welches Kabel gekappt wird, und der Umweg braucht Platz für seinen Verkehr.", "architect.gold_must_survive":"Muss jeden einzelnen Schnitt überleben: {list}", -"architect.gold_site":"Gold-Standort", +"architect.gold_site":"Geschäftskritischer Standort", "architect.hide_other_cities":"Andere Städte ausblenden", "architect.hq":"HQ", "architect.hq_lead":"Hier stehen deine Server. Jeder Standort braucht einen Weg zum HQ.", @@ -73,13 +73,13 @@ "architect.or_drag_a_tube_here":"Oder zieh eine Röhre von einem deiner POPs hierher.", "architect.pac_1":"Deine Server stehen in Tokio. Zuerst Hongkong.", "architect.pac_2":"Singapur will auch.", -"architect.pac_3":"Eine Börse in Hongkong. Hongkong ist Gold.", -"architect.pac_4":"Singapur gewinnt eine Bank. Auch Gold.", +"architect.pac_3":"Eine Börse in Hongkong. Hongkong ist geschäftskritisch.", +"architect.pac_4":"Singapur gewinnt eine Bank. Ebenfalls geschäftskritisch.", "architect.pac_5":"Sydney. Weit weg von allem: Das ist der Witz, und das Problem.", "architect.pacific_rim":"Pacific Rim", "architect.pacific_rim_joke":"Ozeane, Anker und sehr teures Glas.", "architect.plus_router_x":"+ größerer Router {x}", -"architect.ready_no_gold_yet":"Fertig. Noch keine Gold-Standorte, der Bagger kann also nur Chaos anrichten.", +"architect.ready_no_gold_yet":"Bereit. Noch ist nichts geschäftskritisch, der Bagger kann also nur Chaos anrichten.", "architect.ready_send_the_backhoe":"Fertig. Schick den Bagger los und schau, was überlebt.", "architect.reset_brief":"Auftrag zurücksetzen", "architect.review_passed":"Abnahme bestanden", @@ -119,10 +119,10 @@ "architect.tubes_this_brief":"Röhren in diesem Auftrag", "architect.usa_1":"Deine Server stehen in Ashburn. Zuerst New York.", "architect.usa_2":"Chicago will auch.", -"architect.usa_3":"Eine Bank in New York. New York ist Gold.", +"architect.usa_3":"Eine Bank in New York. New York ist geschäftskritisch.", "architect.usa_4":"Trader wollen New York ⇄ Chicago unter 8 ms.", "architect.usa_5":"Dallas und das Silicon Valley wollen auch.", -"architect.usa_6":"Ein Cloud-Deal im Silicon Valley. Es wird Gold.", +"architect.usa_6":"Ein Cloud-Deal im Silicon Valley. Er ist geschäftskritisch.", "architect.x_paid_for_and_gone":"{x} davon für Dinge, die du wieder entfernt hast", "architect.your_shape":"Deine Form", "badges.a_petabit_a_second":"Ein Petabit pro Sekunde", diff --git a/site/i18n/es.js b/site/i18n/es.js index d9c84b0..704fce2 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -31,22 +31,22 @@ "architect.cut_n_of_m":"Corte {n} de {m}…", "architect.cut_on_x_cuts_off_y":"Un corte en {x} deja aislado a {y}.", "architect.cut_on_x_no_room":"Un corte en {x} no deja sitio en el desvío. Falta: {y}.", -"architect.dark_list":"A oscuras por ahora: {list}. No es oro, así que está permitido.", +"architect.dark_list":"A oscuras por ahora: {list}. No es crítico, así que está permitido.", "architect.drag_from_your_hq":"Arrastra desde tu sede a otra ciudad para tender un tubo", "architect.euro_1":"Tus servidores viven en Ámsterdam. Primer cliente: Fráncfort. Conéctalo.", "architect.euro_2b":"París y Londres se apuntan.", -"architect.euro_3b":"Fráncfort y París fichan bancos. Las dos pasan a oro.", -"architect.euro_5":"Zúrich, otro banco. Oro desde el primer día.", -"architect.euro_6":"Tu casero de Fráncfort vendió el edificio. Múdate. El banco se va a Düsseldorf, y sigue siendo oro.", +"architect.euro_3b":"Fráncfort y París fichan bancos. Las dos son ahora críticas.", +"architect.euro_5":"Zúrich, otro banco. Crítico desde el primer día.", +"architect.euro_6":"Tu casero de Fráncfort vendió el edificio. A mudarse. El banco se va a Düsseldorf y sigue siendo crítico.", "architect.euro_ring_grow":"París se duplica a 100G. Y Londres, París y Ámsterdam quieren un anillo entre ellas.", "architect.euro_run":"Ruta europea", "architect.euro_run_joke":"Seis encargos, un casero y un banco muy nervioso.", "architect.finish_the_run":"Terminar la partida", "architect.fix_it_and_send_it_again":"Arréglalo y vuelve a mandar la retroexcavadora.", "architect.from_x":"desde {x}", -"architect.gold_lead":"Oro: este sitio debe seguir conectado a la sede sea cual sea la zanja o el cable que se corte, y el desvío necesita sitio para su tráfico.", +"architect.gold_lead":"Crítico: este sitio debe seguir conectado a la sede corte quien corte una sola zanja o cable, y el desvío necesita sitio para su tráfico.", "architect.gold_must_survive":"Debe sobrevivir a cualquier corte: {list}", -"architect.gold_site":"Sitio oro", +"architect.gold_site":"Sitio crítico", "architect.hide_other_cities":"Ocultar otras ciudades", "architect.hq":"Sede", "architect.hq_lead":"Aquí viven tus servidores. Cada sitio necesita un camino a la sede.", @@ -71,13 +71,13 @@ "architect.or_drag_a_tube_here":"O arrastra un tubo hasta aquí desde uno de tus POP.", "architect.pac_1":"Tus servidores viven en Tokio. Primero, Hong Kong.", "architect.pac_2":"Singapur se apunta.", -"architect.pac_3":"Una bolsa en Hong Kong. Hong Kong es oro.", -"architect.pac_4":"Singapur ficha un banco. También es oro.", +"architect.pac_3":"Una bolsa en Hong Kong. Hong Kong es crítico.", +"architect.pac_4":"Singapur ficha un banco. También crítico.", "architect.pac_5":"Sídney. Lejos de todo: esa es la gracia, y el problema.", "architect.pacific_rim":"Cinturón del Pacífico", "architect.pacific_rim_joke":"Océanos, anclas y vidrio carísimo.", "architect.plus_router_x":"+ router más grande {x}", -"architect.ready_no_gold_yet":"Listo. Aún no hay sitios oro, así que la retroexcavadora solo puede armar un lío.", +"architect.ready_no_gold_yet":"Listo. Aún no hay nada crítico, así que la retroexcavadora solo puede armar lío.", "architect.ready_send_the_backhoe":"Listo. Manda la retroexcavadora y mira qué sobrevive.", "architect.reset_brief":"Reiniciar encargo", "architect.review_passed":"Revisión superada", @@ -117,10 +117,10 @@ "architect.tubes_this_brief":"Tubos de este encargo", "architect.usa_1":"Tus servidores viven en Ashburn. Primero, Nueva York.", "architect.usa_2":"Chicago se apunta.", -"architect.usa_3":"Un banco en Nueva York. Nueva York es oro.", +"architect.usa_3":"Un banco en Nueva York. Nueva York es crítico.", "architect.usa_4":"Los traders quieren Nueva York ⇄ Chicago en menos de 8 ms.", "architect.usa_5":"Dallas y Silicon Valley se apuntan.", -"architect.usa_6":"Un acuerdo cloud en Silicon Valley. Pasa a oro.", +"architect.usa_6":"Un trato de nube en Silicon Valley. Es crítico.", "architect.x_paid_for_and_gone":"{x} de eso pagó cosas que quitaste", "architect.your_shape":"Tu forma", "badges.a_petabit_a_second":"Un petabit por segundo", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 739a010..7c8cc5a 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -31,22 +31,22 @@ "architect.cut_n_of_m":"Coupure {n} sur {m}…", "architect.cut_on_x_cuts_off_y":"Une coupure sur {x} isole {y}.", "architect.cut_on_x_no_room":"Une coupure sur {x} ne laisse pas de place sur le détour. Manque : {y}.", -"architect.dark_list":"Éteint pour l’instant : {list}. Pas en or, donc c’est permis.", +"architect.dark_list":"Éteint pour l’instant : {list}. Pas critique, donc c’est permis.", "architect.drag_from_your_hq":"Fais glisser depuis ton QG vers une autre ville pour poser un tube", "architect.euro_1":"Tes serveurs vivent à Amsterdam. Premier client : Francfort. Connecte-le.", "architect.euro_2b":"Paris et Londres veulent en être.", -"architect.euro_3b":"Francfort et Paris signent des banques. Les deux passent en or.", -"architect.euro_5":"Zurich, encore une banque. En or dès le premier jour.", -"architect.euro_6":"Ton proprio à Francfort a vendu l’immeuble. Déménage. La banque part à Düsseldorf, et reste en or.", +"architect.euro_3b":"Francfort et Paris signent des banques. Les deux deviennent critiques.", +"architect.euro_5":"Zurich, encore une banque. Critique dès le premier jour.", +"architect.euro_6":"Ton propriétaire à Francfort a vendu l’immeuble. Déménage. La banque part à Düsseldorf, et elle reste critique.", "architect.euro_ring_grow":"Paris double à 100G. Et Londres, Paris et Amsterdam veulent un anneau entre elles.", "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Six briefs, un proprio, une banque très nerveuse.", "architect.finish_the_run":"Terminer la partie", "architect.fix_it_and_send_it_again":"Répare, puis renvoie la pelleteuse.", "architect.from_x":"dès {x}", -"architect.gold_lead":"Or : ce site doit rester relié au QG quelle que soit la tranchée ou le câble coupé, et le détour doit avoir de la place pour son trafic.", +"architect.gold_lead":"Critique : ce site doit rester relié au siège quelle que soit la tranchée ou le câble coupé, et le détour doit avoir de la place pour son trafic.", "architect.gold_must_survive":"Doit survivre à n’importe quelle coupure : {list}", -"architect.gold_site":"Site en or", +"architect.gold_site":"Site critique", "architect.hide_other_cities":"Masquer les autres villes", "architect.hq":"QG", "architect.hq_lead":"Tes serveurs vivent ici. Chaque site a besoin d’un chemin vers le QG.", @@ -71,13 +71,13 @@ "architect.or_drag_a_tube_here":"Ou fais glisser un tube jusqu’ici depuis un de tes POP.", "architect.pac_1":"Tes serveurs vivent à Tokyo. D’abord Hong Kong.", "architect.pac_2":"Singapour veut en être.", -"architect.pac_3":"Une bourse à Hong Kong. Hong Kong est en or.", -"architect.pac_4":"Singapour signe une banque. En or aussi.", +"architect.pac_3":"Une bourse à Hong Kong. Hong Kong est critique.", +"architect.pac_4":"Singapour signe une banque. Critique aussi.", "architect.pac_5":"Sydney. Loin de tout : c’est tout l’intérêt, et tout le problème.", "architect.pacific_rim":"Ceinture du Pacifique", "architect.pacific_rim_joke":"Des océans, des ancres et du verre hors de prix.", "architect.plus_router_x":"+ routeur plus gros {x}", -"architect.ready_no_gold_yet":"Prêt. Pas encore de site en or, donc la pelleteuse ne peut que mettre le bazar.", +"architect.ready_no_gold_yet":"Prêt. Rien n’est encore critique, donc la pelleteuse ne peut que faire des dégâts.", "architect.ready_send_the_backhoe":"Prêt. Envoie la pelleteuse et regarde ce qui survit.", "architect.reset_brief":"Recommencer le brief", "architect.review_passed":"Revue validée", @@ -117,10 +117,10 @@ "architect.tubes_this_brief":"Tubes de ce brief", "architect.usa_1":"Tes serveurs vivent à Ashburn. D’abord New York.", "architect.usa_2":"Chicago veut en être.", -"architect.usa_3":"Une banque à New York. New York est en or.", +"architect.usa_3":"Une banque à New York. New York est critique.", "architect.usa_4":"Les traders veulent New York ⇄ Chicago en moins de 8 ms.", "architect.usa_5":"Dallas et la Silicon Valley veulent en être.", -"architect.usa_6":"Un contrat cloud dans la Silicon Valley. Elle passe en or.", +"architect.usa_6":"Un contrat cloud dans la Silicon Valley. Il est critique.", "architect.x_paid_for_and_gone":"dont {x} pour des choses que tu as retirées", "architect.your_shape":"Ta forme", "badges.a_petabit_a_second":"Un pétabit par seconde", diff --git a/site/i18n/it.js b/site/i18n/it.js index f0e411f..c133a42 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -31,22 +31,22 @@ "architect.cut_n_of_m":"Taglio {n} di {m}…", "architect.cut_on_x_cuts_off_y":"Un taglio su {x} isola {y}.", "architect.cut_on_x_no_room":"Un taglio su {x} non lascia spazio sulla deviazione. Manca: {y}.", -"architect.dark_list":"Al buio per ora: {list}. Non è oro, quindi si può.", +"architect.dark_list":"Al buio per ora: {list}. Non è critico, quindi si può.", "architect.drag_from_your_hq":"Trascina dalla tua sede a un’altra città per posare un tubo", "architect.euro_1":"I tuoi server vivono ad Amsterdam. Primo cliente: Francoforte. Collegalo.", "architect.euro_2b":"Anche Parigi e Londra vogliono entrare.", -"architect.euro_3b":"Francoforte e Parigi firmano con delle banche. Diventano oro tutte e due.", -"architect.euro_5":"Zurigo, un’altra banca. Oro dal primo giorno.", -"architect.euro_6":"Il tuo padrone di casa a Francoforte ha venduto il palazzo. Trasloca. La banca si sposta a Düsseldorf, ed è ancora oro.", +"architect.euro_3b":"Francoforte e Parigi firmano con delle banche. Ora sono critiche tutte e due.", +"architect.euro_5":"Zurigo, un’altra banca. Critica dal primo giorno.", +"architect.euro_6":"Il tuo padrone di casa a Francoforte ha venduto l’edificio. Trasloca. La banca va a Düsseldorf ed è ancora critica.", "architect.euro_ring_grow":"Parigi raddoppia a 100G. E Londra, Parigi e Amsterdam vogliono un anello tra loro.", "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Sei incarichi, un padrone di casa, una banca molto nervosa.", "architect.finish_the_run":"Chiudi la partita", "architect.fix_it_and_send_it_again":"Sistemalo, poi rimanda la ruspa.", "architect.from_x":"da {x}", -"architect.gold_lead":"Oro: questo sito deve restare collegato alla sede qualunque scavo o cavo venga tagliato, e la deviazione deve avere spazio per il suo traffico.", +"architect.gold_lead":"Critico: questo sito deve restare collegato alla sede qualunque singolo scavo o cavo venga tagliato, e la deviazione deve avere spazio per il suo traffico.", "architect.gold_must_survive":"Deve sopravvivere a qualsiasi taglio: {list}", -"architect.gold_site":"Sito oro", +"architect.gold_site":"Sito critico", "architect.hide_other_cities":"Nascondi le altre città", "architect.hq":"Sede", "architect.hq_lead":"Qui vivono i tuoi server. Ogni sito ha bisogno di una strada verso la sede.", @@ -71,13 +71,13 @@ "architect.or_drag_a_tube_here":"Oppure trascina qui un tubo da uno dei tuoi POP.", "architect.pac_1":"I tuoi server vivono a Tokyo. Prima Hong Kong.", "architect.pac_2":"Anche Singapore vuole entrare.", -"architect.pac_3":"Una borsa a Hong Kong. Hong Kong è oro.", -"architect.pac_4":"Singapore firma con una banca. Oro anche lei.", +"architect.pac_3":"Una borsa a Hong Kong. Hong Kong è critica.", +"architect.pac_4":"Singapore firma con una banca. Critica anche lei.", "architect.pac_5":"Sydney. Lontana da tutto: è proprio questo il bello, e il problema.", "architect.pacific_rim":"Anello del Pacifico", "architect.pacific_rim_joke":"Oceani, ancore e vetro carissimo.", "architect.plus_router_x":"+ router più grande {x}", -"architect.ready_no_gold_yet":"Pronto. Ancora nessun sito oro, quindi la ruspa può solo fare disastri.", +"architect.ready_no_gold_yet":"Pronto. Ancora niente di critico, quindi la ruspa può solo fare disastri.", "architect.ready_send_the_backhoe":"Pronto. Manda la ruspa e guarda cosa sopravvive.", "architect.reset_brief":"Ricomincia l’incarico", "architect.review_passed":"Revisione superata", @@ -117,10 +117,10 @@ "architect.tubes_this_brief":"Tubi di questo incarico", "architect.usa_1":"I tuoi server vivono ad Ashburn. Prima New York.", "architect.usa_2":"Anche Chicago vuole entrare.", -"architect.usa_3":"Una banca a New York. New York è oro.", +"architect.usa_3":"Una banca a New York. New York è critica.", "architect.usa_4":"I trader vogliono New York ⇄ Chicago sotto gli 8 ms.", "architect.usa_5":"Anche Dallas e la Silicon Valley vogliono entrare.", -"architect.usa_6":"Un accordo cloud nella Silicon Valley. Diventa oro.", +"architect.usa_6":"Un accordo cloud nella Silicon Valley. È critico.", "architect.x_paid_for_and_gone":"{x} di questi per cose che hai tolto", "architect.your_shape":"La tua forma", "badges.a_petabit_a_second":"Un petabit al secondo", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 790a2f8..99f56dc 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -31,22 +31,22 @@ "architect.cut_n_of_m":"Corte {n} de {m}…", "architect.cut_on_x_cuts_off_y":"Um corte em {x} isola {y}.", "architect.cut_on_x_no_room":"Um corte em {x} não deixa espaço no desvio. Falta: {y}.", -"architect.dark_list":"No escuro por enquanto: {list}. Não é ouro, então pode.", +"architect.dark_list":"No escuro por enquanto: {list}. Não é crítico, então pode.", "architect.drag_from_your_hq":"Arraste da sua sede até outra cidade para lançar um tubo", "architect.euro_1":"Seus servidores moram em Amsterdã. Primeiro cliente: Frankfurt. Conecte.", "architect.euro_2b":"Paris e Londres querem entrar.", -"architect.euro_3b":"Frankfurt e Paris fecham com bancos. As duas viram ouro.", -"architect.euro_5":"Zurique, mais um banco. Ouro desde o primeiro dia.", -"architect.euro_6":"Seu senhorio em Frankfurt vendeu o prédio. Saia de lá. O banco muda para Düsseldorf, e continua ouro.", +"architect.euro_3b":"Frankfurt e Paris fecham com bancos. As duas agora são críticas.", +"architect.euro_5":"Zurique, mais um banco. Crítico desde o primeiro dia.", +"architect.euro_6":"O dono do prédio em Frankfurt vendeu o imóvel. Mude-se. O banco vai para Düsseldorf e continua crítico.", "architect.euro_ring_grow":"Paris dobra para 100G. E Londres, Paris e Amsterdã querem um anel entre elas.", "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Seis pedidos, um senhorio, um banco muito nervoso.", "architect.finish_the_run":"Encerrar a partida", "architect.fix_it_and_send_it_again":"Conserte e mande a retroescavadeira de novo.", "architect.from_x":"a partir de {x}", -"architect.gold_lead":"Ouro: este site precisa continuar ligado à sede, seja qual for a vala ou o cabo cortado, e o desvio precisa de espaço para o tráfego dele.", +"architect.gold_lead":"Crítico: este local precisa continuar ligado à sede qualquer que seja a vala ou o cabo cortado, e o desvio precisa de espaço para o tráfego dele.", "architect.gold_must_survive":"Precisa sobreviver a qualquer corte: {list}", -"architect.gold_site":"Site ouro", +"architect.gold_site":"Local crítico", "architect.hide_other_cities":"Esconder outras cidades", "architect.hq":"Sede", "architect.hq_lead":"Seus servidores moram aqui. Todo site precisa de um caminho até a sede.", @@ -71,13 +71,13 @@ "architect.or_drag_a_tube_here":"Ou arraste um tubo até aqui de um dos seus POPs.", "architect.pac_1":"Seus servidores moram em Tóquio. Primeiro, Hong Kong.", "architect.pac_2":"Singapura quer entrar.", -"architect.pac_3":"Uma bolsa de valores em Hong Kong. Hong Kong é ouro.", -"architect.pac_4":"Singapura fecha com um banco. Ouro também.", +"architect.pac_3":"Uma bolsa em Hong Kong. Hong Kong é crítico.", +"architect.pac_4":"Singapura fecha com um banco. Crítico também.", "architect.pac_5":"Sydney. Longe de tudo: essa é a graça, e o problema.", "architect.pacific_rim":"Círculo do Pacífico", "architect.pacific_rim_joke":"Oceanos, âncoras e vidro caríssimo.", "architect.plus_router_x":"+ router maior {x}", -"architect.ready_no_gold_yet":"Pronto. Ainda não há sites ouro, então a retroescavadeira só pode fazer bagunça.", +"architect.ready_no_gold_yet":"Pronto. Nada é crítico ainda, então a retroescavadeira só pode fazer bagunça.", "architect.ready_send_the_backhoe":"Pronto. Mande a retroescavadeira e veja o que sobrevive.", "architect.reset_brief":"Reiniciar pedido", "architect.review_passed":"Revisão aprovada", @@ -117,10 +117,10 @@ "architect.tubes_this_brief":"Tubos deste pedido", "architect.usa_1":"Seus servidores moram em Ashburn. Primeiro, New York.", "architect.usa_2":"Chicago quer entrar.", -"architect.usa_3":"Um banco em New York. New York é ouro.", +"architect.usa_3":"Um banco em New York. New York é crítico.", "architect.usa_4":"Os traders querem New York ⇄ Chicago abaixo de 8 ms.", "architect.usa_5":"Dallas e o Vale do Silício querem entrar.", -"architect.usa_6":"Um contrato de cloud no Vale do Silício. Vira ouro.", +"architect.usa_6":"Um contrato de nuvem no Vale do Silício. É crítico.", "architect.x_paid_for_and_gone":"{x} disso pagou coisas que você removeu", "architect.your_shape":"Seu formato", "badges.a_petabit_a_second":"Um petabit por segundo", diff --git a/src/game/60-features/96-architect.js b/src/game/60-features/96-architect.js index 3778a81..b191bff 100644 --- a/src/game/60-features/96-architect.js +++ b/src/game/60-features/96-architect.js @@ -95,9 +95,9 @@ function arShape(){const ns=Object.keys(S.pops),n=ns.length;if(n<2||!S.links.len k=cs.lengthcore[c].size===2)?'lolli':cs.length===n&&n>=6&&n%2===0&&cm===3*n/2-2&&d2===4&&cs.every(c=>core[c].size<=3)?'ladder':m>=n*1.8?'spaghetti':'mesh';} return {k,i:AR_SHAPES[k][0],n:tr(AR_SHAPES[k][1])};} // What later briefs do to a city, for the map: [{n: brief number, i: icon}], earliest first. -function arTags(c){const A=S.ar,out=[];arRun().briefs.forEach((b,j)=>{if(j<=A.bi)return;const i=(b.gold||[]).includes(c)?'🥇':(b.add||[]).includes(c)?'📍':(b.drop||[]).includes(c)?'🚫':b.dem&&b.dem[c]?'📈':(b.ring||[]).includes(c)?'💍':b.lat&&b.lat.slice(0,2).includes(c)?'⏱':'';if(i)out.push({n:j+1,i});});return out;} +function arTags(c){const A=S.ar,out=[];arRun().briefs.forEach((b,j)=>{if(j<=A.bi)return;const i=(b.gold||[]).includes(c)?'🚨':(b.add||[]).includes(c)?'📍':(b.drop||[]).includes(c)?'🚫':b.dem&&b.dem[c]?'📈':(b.ring||[]).includes(c)?'💍':b.lat&&b.lat.slice(0,2).includes(c)?'⏱':'';if(i)out.push({n:j+1,i});});return out;} // One line per brief for the plan on the card. -function arSum(b){const nm=c=>CITY[c].name,t=[],d=b.dem||{};if(b.add)t.push(b.add.map(c=>'+'+nm(c)+(d[c]?' '+arG(d[c]):'')).join(' '));for(const c in d)if(!(b.add||[]).includes(c))t.push('📈 '+nm(c)+' '+arG(d[c]));if(b.gold)t.push('🥇 '+b.gold.map(nm).join(', ')); +function arSum(b){const nm=c=>CITY[c].name,t=[],d=b.dem||{};if(b.add)t.push(b.add.map(c=>'+'+nm(c)+(d[c]?' '+arG(d[c]):'')).join(' '));for(const c in d)if(!(b.add||[]).includes(c))t.push('📈 '+nm(c)+' '+arG(d[c]));if(b.gold)t.push('🚨 '+b.gold.map(nm).join(', ')); if(b.ring)t.push('💍 '+b.ring.map(nm).join('–'));if(b.lat)t.push(`⏱ ${nm(b.lat[0])}⇄${nm(b.lat[1])} < ${b.lat[2]} ms`);if(b.drop)t.push('🚫 '+b.drop.map(nm).join(', ')); if(b.tubes!=null)t.push(trn('architect.n_tubes',b.tubes));return t.join(' · ');} // ---------- starting, briefs and the end ---------- diff --git a/src/game/95-modals/96-architect.js b/src/game/95-modals/96-architect.js index 5f79ca5..e11f017 100644 --- a/src/game/95-modals/96-architect.js +++ b/src/game/95-modals/96-architect.js @@ -5,8 +5,8 @@ function arRender(el){const A=S.ar,run=arRun(),b=arBrief(),e=arEval(),sh=UI.arSh let h=`
🏗️ ${esc(run.n)}

${tr('architect.brief_n_of_m',{n:A.bi+1,m:n})}

${btn('☰','puzzleMenu',{},'ghost sm')}
`; h+=`
${run.briefs.map((x,i)=>``).join('')}
`; h+=`

${esc(b.t)}

`; - h+=`
${e.sites.map(s=>`${s.hq?'🏠':s.gold?'🥇':s.ok?'✓':'○'} ${nm(s.c)}${s.hq?'':` ${s.ok&&!s.full?arG(s.got)+'/':''}${arG(s.dem)}`}`).join('')}
`; - if(A.gold.length)h+=`
🥇 ${tr('architect.gold_must_survive',{list:A.gold.map(nm).join(', ')})}
`; + h+=`
${e.sites.map(s=>`${s.hq?'🏠':s.gold?'🚨':s.ok?'✓':'○'} ${nm(s.c)}${s.hq?'':` ${s.ok&&!s.full?arG(s.got)+'/':''}${arG(s.dem)}`}`).join('')}
`; + if(A.gold.length)h+=`
🚨 ${tr('architect.gold_must_survive',{list:A.gold.map(nm).join(', ')})}
`; for(const r of e.rings)h+=`
💍 ${tr('architect.ring_list',{list:r.cs.map(nm).join(' · ')})} ${r.ok?'✓':''}
`; if(e.lat)h+=`
⏱ ${nm(e.lat.a)} ⇄ ${nm(e.lat.b)}: ${e.lat.ms==null?tr('common.no_path'):e.lat.ms.toFixed(1)+' ms'} / ${e.lat.cap} ms
`; for(const c of S.pz.avoid)h+=`
🚫 ${tr('architect.closed_city',{city:nm(c)})}
`; @@ -23,7 +23,7 @@ function arRender(el){const A=S.ar,run=arRun(),b=arBrief(),e=arEval(),sh=UI.arSh function arPanel(sel){const A=S.ar,head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; const old=x=>(x.br|0)${tr('architect.built_in_an_earlier_brief')}

`:''; if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c];if(!k)return ''; - const tg=arTags(c),eb=c===A.hq?'🏠 '+tr('architect.hq'):A.gold.includes(c)?'🥇 '+tr('architect.gold_site'):k==='goal'?'🎯 '+tr('architect.site'):k==='via'&&tg.length?'🔜 '+tr('architect.joins_in_brief_n',{n:tg[0].n}):k==='via'?'🪨 '+tr('puzzles.stepping_stone_optional'):k==='avoid'?'🚫 '+tr('architect.closed'):'📍 '+tr('puzzles.not_in_the_plan'); + const tg=arTags(c),eb=c===A.hq?'🏠 '+tr('architect.hq'):A.gold.includes(c)?'🚨 '+tr('architect.gold_site'):k==='goal'?'🎯 '+tr('architect.site'):k==='via'&&tg.length?'🔜 '+tr('architect.joins_in_brief_n',{n:tg[0].n}):k==='via'?'🪨 '+tr('puzzles.stepping_stone_optional'):k==='avoid'?'🚫 '+tr('architect.closed'):'📍 '+tr('puzzles.not_in_the_plan'); let h=head(eb,esc(CITY[c].name),p?`${tr('common.your_pop')}${tr('puzzles.price_per_year',{price:fmt$(arPopCost(c))})}`:'')+'
'; if(c===A.hq)h+=`

${tr('architect.hq_lead')}

`;else if(A.gold.includes(c))h+=`

${tr('architect.gold_lead')}

`; if(tg.length)h+=`
${tr('architect.coming_up')}
${tg.map(t=>`
${t.n} ${esc(arSum(arRun().briefs[t.n-1]))}
`).join('')}
`; diff --git a/src/i18n/en.js b/src/i18n/en.js index 7798646..5304ef1 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -32,22 +32,22 @@ "architect.cut_n_of_m":"Cut {n} of {m}…", "architect.cut_on_x_cuts_off_y":"A cut on {x} cuts off {y}.", "architect.cut_on_x_no_room":"A cut on {x} leaves no room on the detour. Short: {y}.", -"architect.dark_list":"Dark for now: {list}. Not gold, so that's allowed.", +"architect.dark_list":"Dark for now: {list}. Not mission-critical, so that's allowed.", "architect.drag_from_your_hq":"Drag from your HQ to another city to lay a tube", "architect.euro_1":"Your servers live in Amsterdam. First customer: Frankfurt. Connect it.", "architect.euro_2b":"Paris and London want in.", -"architect.euro_3b":"Frankfurt and Paris sign banks. Both go gold.", -"architect.euro_5":"Zürich, another bank. Gold from day one.", -"architect.euro_6":"Your Frankfurt landlord sold the building. Move out. The bank moves to Düsseldorf, and it is still gold.", +"architect.euro_3b":"Frankfurt and Paris sign banks. Both are now mission-critical.", +"architect.euro_5":"Zürich, another bank. Mission-critical from day one.", +"architect.euro_6":"Your Frankfurt landlord sold the building. Move out. The bank moves to Düsseldorf, and it is still mission-critical.", "architect.euro_ring_grow":"Paris doubles to 100G. And London, Paris and Amsterdam want a ring between them.", "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Six briefs, one landlord, one very nervous bank.", "architect.finish_the_run":"Finish the run", "architect.fix_it_and_send_it_again":"Fix it, then send the backhoe again.", "architect.from_x":"from {x}", -"architect.gold_lead":"Gold: this site must stay connected to HQ whichever single trench or cable is cut, and the detour needs room for its traffic.", +"architect.gold_lead":"Mission-critical: this site must stay connected to HQ whichever single trench or cable is cut, and the detour needs room for its traffic.", "architect.gold_must_survive":"Must survive any single cut: {list}", -"architect.gold_site":"Gold site", +"architect.gold_site":"Mission-critical site", "architect.hide_other_cities":"Hide other cities", "architect.hq":"HQ", "architect.hq_lead":"Your servers live here. Every site needs a path to HQ.", @@ -72,13 +72,13 @@ "architect.or_drag_a_tube_here":"Or drag a tube here from one of your POPs.", "architect.pac_1":"Your servers live in Tokyo. Hong Kong first.", "architect.pac_2":"Singapore wants in.", -"architect.pac_3":"A stock exchange in Hong Kong. Hong Kong is gold.", -"architect.pac_4":"Singapore signs a bank. Gold too.", +"architect.pac_3":"A stock exchange in Hong Kong. Hong Kong is mission-critical.", +"architect.pac_4":"Singapore signs a bank. Mission-critical too.", "architect.pac_5":"Sydney. Far from everything: that is the point, and the problem.", "architect.pacific_rim":"Pacific Rim", "architect.pacific_rim_joke":"Oceans, anchors and very expensive glass.", "architect.plus_router_x":"+ bigger router {x}", -"architect.ready_no_gold_yet":"Ready. No gold sites yet, so the backhoe can only make a mess.", +"architect.ready_no_gold_yet":"Ready. Nothing is mission-critical yet, so the backhoe can only make a mess.", "architect.ready_send_the_backhoe":"Ready. Send the backhoe and see what survives.", "architect.reset_brief":"Reset brief", "architect.review_passed":"Review passed", @@ -118,10 +118,10 @@ "architect.tubes_this_brief":"Tubes this brief", "architect.usa_1":"Your servers live in Ashburn. New York first.", "architect.usa_2":"Chicago wants in.", -"architect.usa_3":"A bank in New York. New York is gold.", +"architect.usa_3":"A bank in New York. New York is mission-critical.", "architect.usa_4":"Traders want New York ⇄ Chicago under 8 ms.", "architect.usa_5":"Dallas and Silicon Valley want in.", -"architect.usa_6":"A cloud deal in Silicon Valley. It goes gold.", +"architect.usa_6":"A cloud deal in Silicon Valley. It's mission-critical.", "architect.x_paid_for_and_gone":"{x} of that paid for things you removed", "architect.your_shape":"Your shape", "badges.a_petabit_a_second":"A Petabit a Second", diff --git a/src/styles/71-architect.css b/src/styles/71-architect.css index a531a7d..a31a7e3 100644 --- a/src/styles/71-architect.css +++ b/src/styles/71-architect.css @@ -4,7 +4,7 @@ .arbrief{margin:2px 0 8px;font-size:14.5px;font-weight:800;line-height:1.35} .arsites{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0 6px} .arsite{font-weight:900;font-size:12px;border:2px solid var(--line);border-radius:999px;padding:1px 8px;background:#fff;color:var(--ink2)} -.arsite.ok{border-color:var(--ok);color:var(--ink)}.arsite.gold{border-color:#E0A000;background:#FFF3C4} +.arsite.ok{border-color:var(--ok);color:var(--ink)}.arsite.gold{border-color:#E5484D;background:#FFE8E8} .arline{font-size:12.5px;font-weight:800;margin:3px 0;color:var(--ink2)}.arline.ok{color:var(--ink)}.arline.bad{color:var(--bad)} .arshape{font-size:12.5px;font-weight:900;margin:4px 0} .arrev{font-size:12.5px;font-weight:800;margin:6px 0;padding:5px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} diff --git a/tests/architect.test.js b/tests/architect.test.js index 445ec46..5041080 100644 --- a/tests/architect.test.js +++ b/tests/architect.test.js @@ -38,7 +38,7 @@ test('architect runs: the backhoe finds a shared trench, edits clear the cut, ol const { ev, errors } = load(); ev("ACT.pzArStart({id:'euro'})"); assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden'); - assert.deepEqual(JSON.parse(ev("JSON.stringify([arHide('dus'),arTags('dus'),arTags('fra').map(t=>t.n+t.i)])")), [false, [{ n: 6, i: '🥇' }], ['3🥇', '6🚫']], 'later briefs show on the map, numbered'); + assert.deepEqual(JSON.parse(ev("JSON.stringify([arHide('dus'),arTags('dus'),arTags('fra').map(t=>t.n+t.i)])")), [false, [{ n: 6, i: '🚨' }], ['3🚨', '6🚫']], 'later briefs show on the map, numbered'); ev('ACT.pzArAll()'); assert.equal(ev("arHide('lis')"), false, 'and shown on request'); ev('ACT.pzArAll()'); From b3351fb7d9adbf5388234ea5437245b5a9b91b26 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 09:25:20 +0100 Subject: [PATCH 145/181] Architect runs: a chaos monkey runs round the map snipping tubes The review is now an animated monkey that hops from cut to cut and sprays chaos where it snips, instead of the backhoe. --- CHANGELOG.md | 2 +- site/i18n/de.js | 16 ++++++------- site/i18n/es.js | 16 ++++++------- site/i18n/fr.js | 16 ++++++------- site/i18n/it.js | 16 ++++++------- site/i18n/pt.js | 16 ++++++------- src/game/60-features/96-architect.js | 14 +++++------ src/game/95-modals/96-architect.js | 2 +- src/game/96-map/60-draw.js | 1 + src/game/96-map/87-chaos-monkey.js | 35 ++++++++++++++++++++++++++++ src/game/99-loop.js | 2 +- src/i18n/en.js | 16 ++++++------- tests/architect.test.js | 4 ++-- 13 files changed, 96 insertions(+), 60 deletions(-) create mode 100644 src/game/96-map/87-chaos-monkey.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b5af8d..90442bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Architect runs (preview), under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, mission-critical sites must survive any single trench or cable cut with room on the detour, and a backhoe checks every design before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. +- Architect runs (preview), under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, mission-critical sites must survive any single trench or cable cut with room on the detour, and a chaos monkey runs round the map snipping tubes before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. ## [2.0.0] — 2026-10-29 diff --git a/site/i18n/de.js b/site/i18n/de.js index 8ea780a..0f13a5c 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -14,9 +14,9 @@ "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.", -"architect.anchor":"⚓ Anker!", +"architect.anchor":"🐒 Platsch!", "architect.architect_runs":"Architekt-Runs", -"architect.backhoe":"🚜 Bagger!", +"architect.backhoe":"🐒 Schnipp!", "architect.best_n_briefs":"Rekord: {n} Aufträge", "architect.brief_n_of_m":"Auftrag {n} von {m}", "architect.briefs_done":"Aufträge erledigt", @@ -44,7 +44,7 @@ "architect.euro_run":"Euro-Run", "architect.euro_run_joke":"Sechs Aufträge, ein Vermieter, eine sehr nervöse Bank.", "architect.finish_the_run":"Run beenden", -"architect.fix_it_and_send_it_again":"Reparier es und schick den Bagger noch mal los.", +"architect.fix_it_and_send_it_again":"Reparier es und lass den Chaos-Affen noch mal los.", "architect.from_x":"ab {x}", "architect.gold_lead":"Geschäftskritisch: Dieser Standort muss mit dem HQ verbunden bleiben, egal welcher einzelne Graben oder welches Kabel gekappt wird, und der Umweg braucht Platz für seinen Verkehr.", "architect.gold_must_survive":"Muss jeden einzelnen Schnitt überleben: {list}", @@ -58,7 +58,7 @@ "architect.lay_a_tube_to":"Röhre legen nach", "architect.line_1":"Läuft. Die Buchhaltung hätte da noch Fragen.", "architect.line_2":"Solides Design, ein bisschen vergoldet. Damit kann die Buchhaltung leben.", -"architect.line_3":"Im Plan oder besser. Der Bagger ist gelangweilt heimgefahren.", +"architect.line_3":"Auf Par oder besser. Der Chaos-Affe ist gelangweilt heimgegangen.", "architect.move_out_of_city":"Zieh zuerst aus {city} aus.", "architect.n_briefs":"{n} Aufträge", "architect.n_over_plan":"{n} über Plan", @@ -79,8 +79,8 @@ "architect.pacific_rim":"Pacific Rim", "architect.pacific_rim_joke":"Ozeane, Anker und sehr teures Glas.", "architect.plus_router_x":"+ größerer Router {x}", -"architect.ready_no_gold_yet":"Bereit. Noch ist nichts geschäftskritisch, der Bagger kann also nur Chaos anrichten.", -"architect.ready_send_the_backhoe":"Fertig. Schick den Bagger los und schau, was überlebt.", +"architect.ready_no_gold_yet":"Bereit. Noch ist nichts geschäftskritisch, der Chaos-Affe kann also nur Chaos anrichten.", +"architect.ready_send_the_backhoe":"Bereit. Lass den Chaos-Affen los und schau, was überlebt.", "architect.reset_brief":"Auftrag zurücksetzen", "architect.review_passed":"Abnahme bestanden", "architect.ring_list":"Ein Ring durch {list}", @@ -88,8 +88,8 @@ "architect.router_x":"Router: {x}", "architect.run_complete":"Run geschafft", "architect.run_over":"Run vorbei", -"architect.runs_lead":"Ein Netz, Auftrag für Auftrag gebaut. Was du baust, bleibt stehen, und ein Bagger prüft jedes Design: Kapp eine beliebige Röhre, und alles, was noch verbunden ist, muss seinen ganzen Traffic bekommen.", -"architect.send_the_backhoe":"Bagger losschicken", +"architect.runs_lead":"Ein Netz, Auftrag für Auftrag gebaut. Dein Ausbau bleibt bestehen, und ein Chaos-Affe testet jeden Entwurf: Er kappt eine Röhre nach der anderen, und alles, was noch verbunden ist, muss seinen ganzen Verkehr bekommen.", +"architect.send_the_backhoe":"Lass den Chaos-Affen los", "architect.shape_braces":"Doppelt hält besser", "architect.shape_full":"Full Mesh", "architect.shape_islands":"Inseln", diff --git a/site/i18n/es.js b/site/i18n/es.js index 704fce2..5c252e7 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -12,9 +12,9 @@ "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.", -"architect.anchor":"⚓ ¡Ancla!", +"architect.anchor":"🐒 ¡Chof!", "architect.architect_runs":"Partidas de arquitecto", -"architect.backhoe":"🚜 ¡Retroexcavadora!", +"architect.backhoe":"🐒 ¡Zas!", "architect.best_n_briefs":"récord: {n} encargos", "architect.brief_n_of_m":"Encargo {n} de {m}", "architect.briefs_done":"Encargos hechos", @@ -42,7 +42,7 @@ "architect.euro_run":"Ruta europea", "architect.euro_run_joke":"Seis encargos, un casero y un banco muy nervioso.", "architect.finish_the_run":"Terminar la partida", -"architect.fix_it_and_send_it_again":"Arréglalo y vuelve a mandar la retroexcavadora.", +"architect.fix_it_and_send_it_again":"Arréglalo y vuelve a soltar al mono del caos.", "architect.from_x":"desde {x}", "architect.gold_lead":"Crítico: este sitio debe seguir conectado a la sede corte quien corte una sola zanja o cable, y el desvío necesita sitio para su tráfico.", "architect.gold_must_survive":"Debe sobrevivir a cualquier corte: {list}", @@ -56,7 +56,7 @@ "architect.lay_a_tube_to":"Tender un tubo a", "architect.line_1":"Funciona. Finanzas quiere hablar contigo.", "architect.line_2":"Diseño sólido, un poco bañado en oro. Finanzas puede vivir con ello.", -"architect.line_3":"En presupuesto o mejor. La retroexcavadora se fue a casa aburrida.", +"architect.line_3":"En par o mejor. El mono del caos se fue a casa aburrido.", "architect.move_out_of_city":"Primero sal de {city}.", "architect.n_briefs":"{n} encargos", "architect.n_over_plan":"{n} por encima del plan", @@ -77,8 +77,8 @@ "architect.pacific_rim":"Cinturón del Pacífico", "architect.pacific_rim_joke":"Océanos, anclas y vidrio carísimo.", "architect.plus_router_x":"+ router más grande {x}", -"architect.ready_no_gold_yet":"Listo. Aún no hay nada crítico, así que la retroexcavadora solo puede armar lío.", -"architect.ready_send_the_backhoe":"Listo. Manda la retroexcavadora y mira qué sobrevive.", +"architect.ready_no_gold_yet":"Listo. Aún no hay nada crítico, así que el mono del caos solo puede armar lío.", +"architect.ready_send_the_backhoe":"Listo. Suelta al mono del caos y mira qué sobrevive.", "architect.reset_brief":"Reiniciar encargo", "architect.review_passed":"Revisión superada", "architect.ring_list":"Un anillo por {list}", @@ -86,8 +86,8 @@ "architect.router_x":"Router: {x}", "architect.run_complete":"Partida completada", "architect.run_over":"Partida terminada", -"architect.runs_lead":"Una red, construida encargo a encargo. Lo que construyes se queda, y una retroexcavadora revisa cada diseño: corta cualquier tubo, y todo lo que siga conectado debe recibir todo su tráfico.", -"architect.send_the_backhoe":"Mandar la retroexcavadora", +"architect.runs_lead":"Una red, construida encargo a encargo. Lo que construyes se queda, y un mono del caos prueba cada diseño: corta un tubo cada vez, y todo lo que siga conectado debe recibir todo su tráfico.", +"architect.send_the_backhoe":"Suelta al mono del caos", "architect.shape_braces":"Cinturón y tirantes", "architect.shape_full":"Malla completa", "architect.shape_islands":"Islas", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 7c8cc5a..3531dc6 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -12,9 +12,9 @@ "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.", -"architect.anchor":"⚓ Ancre !", +"architect.anchor":"🐒 Plouf !", "architect.architect_runs":"Parties d’architecte", -"architect.backhoe":"🚜 Pelleteuse !", +"architect.backhoe":"🐒 Clac !", "architect.best_n_briefs":"record : {n} briefs", "architect.brief_n_of_m":"Brief {n} sur {m}", "architect.briefs_done":"Briefs terminés", @@ -42,7 +42,7 @@ "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Six briefs, un proprio, une banque très nerveuse.", "architect.finish_the_run":"Terminer la partie", -"architect.fix_it_and_send_it_again":"Répare, puis renvoie la pelleteuse.", +"architect.fix_it_and_send_it_again":"Répare, puis relâche le singe du chaos.", "architect.from_x":"dès {x}", "architect.gold_lead":"Critique : ce site doit rester relié au siège quelle que soit la tranchée ou le câble coupé, et le détour doit avoir de la place pour son trafic.", "architect.gold_must_survive":"Doit survivre à n’importe quelle coupure : {list}", @@ -56,7 +56,7 @@ "architect.lay_a_tube_to":"Poser un tube vers", "architect.line_1":"Ça marche. La compta aimerait te dire un mot.", "architect.line_2":"Design solide, un peu plaqué or. La compta peut vivre avec.", -"architect.line_3":"Dans le budget, voire mieux. La pelleteuse est rentrée chez elle en s’ennuyant.", +"architect.line_3":"Au par ou mieux. Le singe du chaos est rentré s’ennuyer chez lui.", "architect.move_out_of_city":"Quitte d’abord {city}.", "architect.n_briefs":"{n} briefs", "architect.n_over_plan":"{n} au-delà du plan", @@ -77,8 +77,8 @@ "architect.pacific_rim":"Ceinture du Pacifique", "architect.pacific_rim_joke":"Des océans, des ancres et du verre hors de prix.", "architect.plus_router_x":"+ routeur plus gros {x}", -"architect.ready_no_gold_yet":"Prêt. Rien n’est encore critique, donc la pelleteuse ne peut que faire des dégâts.", -"architect.ready_send_the_backhoe":"Prêt. Envoie la pelleteuse et regarde ce qui survit.", +"architect.ready_no_gold_yet":"Prêt. Rien n’est encore critique, donc le singe du chaos ne peut que faire des dégâts.", +"architect.ready_send_the_backhoe":"Prêt. Lâche le singe du chaos et regarde ce qui tient.", "architect.reset_brief":"Recommencer le brief", "architect.review_passed":"Revue validée", "architect.ring_list":"Un anneau par {list}", @@ -86,8 +86,8 @@ "architect.router_x":"Routeur : {x}", "architect.run_complete":"Partie terminée", "architect.run_over":"Partie perdue", -"architect.runs_lead":"Un réseau, construit brief après brief. Ce que tu construis reste, et une pelleteuse vérifie chaque design : coupe n’importe quel tube, et tout ce qui est encore relié doit recevoir tout son trafic.", -"architect.send_the_backhoe":"Envoyer la pelleteuse", +"architect.runs_lead":"Un réseau, construit brief après brief. Ce que tu construis reste, et un singe du chaos teste chaque design : il coupe un tube à la fois, et tout ce qui reste connecté doit recevoir tout son trafic.", +"architect.send_the_backhoe":"Lâche le singe du chaos", "architect.shape_braces":"Ceinture et bretelles", "architect.shape_full":"Maillage complet", "architect.shape_islands":"Îles", diff --git a/site/i18n/it.js b/site/i18n/it.js index c133a42..4c92ff7 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -12,9 +12,9 @@ "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.", -"architect.anchor":"⚓ Ancora!", +"architect.anchor":"🐒 Splash!", "architect.architect_runs":"Partite da architetto", -"architect.backhoe":"🚜 Ruspa!", +"architect.backhoe":"🐒 Zac!", "architect.best_n_briefs":"record: {n} incarichi", "architect.brief_n_of_m":"Incarico {n} di {m}", "architect.briefs_done":"Incarichi completati", @@ -42,7 +42,7 @@ "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Sei incarichi, un padrone di casa, una banca molto nervosa.", "architect.finish_the_run":"Chiudi la partita", -"architect.fix_it_and_send_it_again":"Sistemalo, poi rimanda la ruspa.", +"architect.fix_it_and_send_it_again":"Sistema e libera di nuovo la scimmia del caos.", "architect.from_x":"da {x}", "architect.gold_lead":"Critico: questo sito deve restare collegato alla sede qualunque singolo scavo o cavo venga tagliato, e la deviazione deve avere spazio per il suo traffico.", "architect.gold_must_survive":"Deve sopravvivere a qualsiasi taglio: {list}", @@ -56,7 +56,7 @@ "architect.lay_a_tube_to":"Posa un tubo verso", "architect.line_1":"Funziona. L’amministrazione vorrebbe parlarti.", "architect.line_2":"Progetto solido, un po’ placcato d’oro. L’amministrazione ci può convivere.", -"architect.line_3":"Nel budget o meglio. La ruspa è tornata a casa annoiata.", +"architect.line_3":"In par o meglio. La scimmia del caos è tornata a casa annoiata.", "architect.move_out_of_city":"Prima lascia {city}.", "architect.n_briefs":"{n} incarichi", "architect.n_over_plan":"{n} oltre il piano", @@ -77,8 +77,8 @@ "architect.pacific_rim":"Anello del Pacifico", "architect.pacific_rim_joke":"Oceani, ancore e vetro carissimo.", "architect.plus_router_x":"+ router più grande {x}", -"architect.ready_no_gold_yet":"Pronto. Ancora niente di critico, quindi la ruspa può solo fare disastri.", -"architect.ready_send_the_backhoe":"Pronto. Manda la ruspa e guarda cosa sopravvive.", +"architect.ready_no_gold_yet":"Pronto. Ancora niente di critico, quindi la scimmia del caos può solo fare disastri.", +"architect.ready_send_the_backhoe":"Pronto. Libera la scimmia del caos e guarda cosa resiste.", "architect.reset_brief":"Ricomincia l’incarico", "architect.review_passed":"Revisione superata", "architect.ring_list":"Un anello attraverso {list}", @@ -86,8 +86,8 @@ "architect.router_x":"Router: {x}", "architect.run_complete":"Partita completata", "architect.run_over":"Partita finita", -"architect.runs_lead":"Una rete, costruita un incarico alla volta. Quello che costruisci resta, e una ruspa controlla ogni progetto: taglia un tubo qualsiasi, e tutto ciò che resta collegato deve ricevere tutto il suo traffico.", -"architect.send_the_backhoe":"Manda la ruspa", +"architect.runs_lead":"Una rete, costruita incarico dopo incarico. Quello che costruisci resta, e una scimmia del caos mette alla prova ogni progetto: taglia un tubo alla volta, e tutto ciò che resta collegato deve ricevere tutto il suo traffico.", +"architect.send_the_backhoe":"Libera la scimmia del caos", "architect.shape_braces":"Cintura e bretelle", "architect.shape_full":"Full mesh", "architect.shape_islands":"Isole", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 99f56dc..aea7dad 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -12,9 +12,9 @@ "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.", -"architect.anchor":"⚓ Âncora!", +"architect.anchor":"🐒 Tchibum!", "architect.architect_runs":"Partidas de arquiteto", -"architect.backhoe":"🚜 Retroescavadeira!", +"architect.backhoe":"🐒 Zás!", "architect.best_n_briefs":"recorde: {n} pedidos", "architect.brief_n_of_m":"Pedido {n} de {m}", "architect.briefs_done":"Pedidos concluídos", @@ -42,7 +42,7 @@ "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Seis pedidos, um senhorio, um banco muito nervoso.", "architect.finish_the_run":"Encerrar a partida", -"architect.fix_it_and_send_it_again":"Conserte e mande a retroescavadeira de novo.", +"architect.fix_it_and_send_it_again":"Conserte e solte o macaco do caos de novo.", "architect.from_x":"a partir de {x}", "architect.gold_lead":"Crítico: este local precisa continuar ligado à sede qualquer que seja a vala ou o cabo cortado, e o desvio precisa de espaço para o tráfego dele.", "architect.gold_must_survive":"Precisa sobreviver a qualquer corte: {list}", @@ -56,7 +56,7 @@ "architect.lay_a_tube_to":"Lançar um tubo até", "architect.line_1":"Funciona. O financeiro quer uma palavrinha.", "architect.line_2":"Projeto sólido, meio banhado a ouro. O financeiro aguenta.", -"architect.line_3":"Dentro do orçamento ou melhor. A retroescavadeira voltou pra casa entediada.", +"architect.line_3":"No par ou melhor. O macaco do caos foi para casa entediado.", "architect.move_out_of_city":"Saia de {city} primeiro.", "architect.n_briefs":"{n} pedidos", "architect.n_over_plan":"{n} acima do plano", @@ -77,8 +77,8 @@ "architect.pacific_rim":"Círculo do Pacífico", "architect.pacific_rim_joke":"Oceanos, âncoras e vidro caríssimo.", "architect.plus_router_x":"+ router maior {x}", -"architect.ready_no_gold_yet":"Pronto. Nada é crítico ainda, então a retroescavadeira só pode fazer bagunça.", -"architect.ready_send_the_backhoe":"Pronto. Mande a retroescavadeira e veja o que sobrevive.", +"architect.ready_no_gold_yet":"Pronto. Nada é crítico ainda, então o macaco do caos só pode fazer bagunça.", +"architect.ready_send_the_backhoe":"Pronto. Solte o macaco do caos e veja o que sobrevive.", "architect.reset_brief":"Reiniciar pedido", "architect.review_passed":"Revisão aprovada", "architect.ring_list":"Um anel passando por {list}", @@ -86,8 +86,8 @@ "architect.router_x":"Router: {x}", "architect.run_complete":"Partida concluída", "architect.run_over":"Fim de partida", -"architect.runs_lead":"Uma rede, construída pedido a pedido. O que você constrói fica, e uma retroescavadeira testa cada projeto: corte qualquer tubo, e tudo que ainda estiver ligado precisa receber todo o seu tráfego.", -"architect.send_the_backhoe":"Mandar a retroescavadeira", +"architect.runs_lead":"Uma rede, construída pedido a pedido. O que você constrói fica, e um macaco do caos testa cada projeto: ele corta um tubo de cada vez, e tudo o que continuar ligado precisa receber todo o seu tráfego.", +"architect.send_the_backhoe":"Solte o macaco do caos", "architect.shape_braces":"Cinto e suspensório", "architect.shape_full":"Malha completa", "architect.shape_islands":"Ilhas", diff --git a/src/game/60-features/96-architect.js b/src/game/60-features/96-architect.js index b191bff..b720cc0 100644 --- a/src/game/60-features/96-architect.js +++ b/src/game/60-features/96-architect.js @@ -1,14 +1,14 @@ /* ================= ARCHITECT RUNS (prototype) ================= One network, built brief by brief. A brief adds sites, makes some of them gold (a gold site must stay connected to HQ whichever single trench or cable is cut), sets a latency cap, or closes a city. The build carries over: what earlier - briefs built is paid for, so removing it gives nothing back. ▶ sends the backhoe: it cuts every trench and cable one + briefs built is paid for, so removing it gives nothing back. ▶ lets the chaos monkey loose: it cuts every trench and cable one at a time, and the brief is done when every gold site survives. Runs on the puzzle machinery (S.mode 'puzzle' with S.ar), so there is no clock, no bills, no incidents, and the main save is never touched. Capacity: every site pulls its traffic from HQ, and the review also checks that the detour has room: after any single cut, everything still connected gets all of its traffic. Tubes come in three sizes; routers follow by themselves (the cheapest model that takes the tubes), and traffic finds the detour by itself (Auto-TE): models, ports and metrics are someone else's job. */ -const AR_KEY='sot-architect',AR_TIER=1,AR_TIERS=[0,1,2],AR_STEP=650; +const AR_KEY='sot-architect',AR_TIER=1,AR_TIERS=[0,1,2],AR_STEP=1000; // A brief: add (new sites), gold (sites that must survive any single cut), ring (sites that must sit on one ring), drop // (close a city: no POP allowed there any more), dem {city: Gbps} (what a site pulls from HQ, 10G unless set; a later // brief can raise it), lat [a,b,ms] (the fastest path between two sites under ms), tubes (the @@ -136,23 +136,23 @@ function arReset(){const o=JSON.parse(S.ar.start);S.pops=o.p;S.links=o.l;S.pairM const arOver=()=>S.ar.over+arTubes().over; function arStars(sp){return 1+(arOver()?0:1)+(sp<=arRun().budget+1e-6?1:0);} function arShareText(st,sp){const sh=arShape();return tr('architect.share_line',{what:arRun().n,stars:pzStarStr(st),spend:fmt$(sp),shape:sh?sh.i+' '+sh.n:''});} -// ---------- ▶ the backhoe review ---------- +// ---------- ▶ the chaos monkey review ---------- // Every trench and cable is cut in turn, routed by compute() so the traffic visibly moves; a gold site losing HQ stops // the review with the cut still on the map, until the next edit. -function arStop(quiet){const sh=UI.arShow;if(sh&&sh.t)clearTimeout(sh.t);UI.arShow=null;if(!S||!S.links)return;let any=false;for(const l of S.links)if(l.cut){l.cut=0;any=true;} +function arStop(quiet){mkStop();const sh=UI.arShow;if(sh&&sh.t)clearTimeout(sh.t);UI.arShow=null;if(!S||!S.links)return;let any=false;for(const l of S.links)if(l.cut){l.cut=0;any=true;} if(UI.arFail){UI.arFail=null;any=true;}if(any&&!quiet)compute();} function arShowStart(){if(!arOn()||UI.arShow)return;const e=arEval();if(!e.ready){toast(esc(e.why),'bad');sfx('err');return;} - arStop(true);UI.sel=null;closeModal();UI.arBaseGot=arGot();UI.arShow={units:[...new Set(S.links.map(pzUnit))],i:-1,t:0,dark:[],short:[]};arStep();} + arStop(true);UI.sel=null;closeModal();UI.arBaseGot=arGot();UI.arShow={units:[...new Set(S.links.map(pzUnit))],i:-1,t:0,dark:[],short:[]};mkStart(S.ar.hq);arStep();} // One cut, routed: who goes dark, which gold sites with it, and who is still connected but short of room. function arCut(u){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1;compute();const dark=arDark(u);return {ls,dark,gold:dark.filter(c=>S.ar.gold.includes(c)),short:arShort(dark)};} function arStep(){const sh=UI.arShow;if(!sh||!arOn())return;for(const l of S.links)l.cut=0;sh.i++; if(sh.i>=sh.units.length){UI.arShow=null;compute();S.ar.passed=pzSig();renderAll();sfx('star');haptic(15); - toast(`✅ ${tr('architect.review_passed')}
${arLast()?tr('architect.last_brief_done'):tr('architect.next_brief_waiting')}`,'good');if(arLast())setTimeout(()=>{if(arOn()&&S.ar.passed===pzSig())arResults(true);},900);return;} + mkEnd(true);toast(`✅ ${tr('architect.review_passed')}
${arLast()?tr('architect.last_brief_done'):tr('architect.next_brief_waiting')}`,'good');if(arLast())setTimeout(()=>{if(arOn()&&S.ar.passed===pzSig())arResults(true);},900);return;} const u=sh.units[sh.i],{ls,dark,gold,short}=arCut(u),l0=ls[0],got=arGot();sh.dark=dark;sh.short=short;sh.u=u; floater((CITY[l0.a].x+CITY[l0.a].x+wrapDx(CITY[l0.a].x,CITY[l0.b].x))/2,(CITY[l0.a].y+CITY[l0.b].y)/2-26,l0.sub?tr('architect.anchor'):tr('architect.backhoe'),'#FF8A3D'); for(const c of dark)floater(CITY[c].x,CITY[c].y-34,gold.includes(c)?'💥 '+CITY[c].name:tr('architect.city_goes_dark',{city:CITY[c].name}),gold.includes(c)?'#FF4D5E':'#9AA3BE'); for(const c of short)floater(CITY[c].x,CITY[c].y-34,tr('architect.city_short_g',{city:CITY[c].name,g:arG(arDem(c)-(got[c]||0))}),'#FF4D5E'); - const bad=gold.length||short.length;sfx(bad?'err':'click'); + const bad=gold.length||short.length;mkRun(l0,dark.length?AR_STEP*1.6:AR_STEP,bad);sfx(bad?'err':'click'); if(bad){UI.arShow=null;UI.arFail={u,gold,dark,short};renderAll();haptic(30);return;} renderAll();sh.t=setTimeout(arStep,dark.length?AR_STEP*1.6:AR_STEP);} // Skip the show: check every cut at once, and stop at the first that breaks a gold site. diff --git a/src/game/95-modals/96-architect.js b/src/game/95-modals/96-architect.js index e11f017..fa37c81 100644 --- a/src/game/95-modals/96-architect.js +++ b/src/game/95-modals/96-architect.js @@ -12,7 +12,7 @@ function arRender(el){const A=S.ar,run=arRun(),b=arBrief(),e=arEval(),sh=UI.arSh for(const c of S.pz.avoid)h+=`
🚫 ${tr('architect.closed_city',{city:nm(c)})}
`; const T=e.tubes;if(T.max!=null)h+=`
${tr('architect.tubes_this_brief')}${'●'.repeat(Math.min(T.u,T.max))}${'○'.repeat(Math.max(0,T.max-T.u))}${T.over?` ${tr('architect.n_over_plan',{n:T.over})}`:''}
`; h+=`
${tr('architect.spent_x_of_y',{x:fmt$(e.spend),y:fmt$(e.budget)})}${e.cheap?'⭐':'☆'}
${A.sunk?`
${tr('architect.x_paid_for_and_gone',{x:fmt$(A.sunk)})}
`:''}
`; - if(sh)h+=`
🚜 ${tr('architect.cut_n_of_m',{n:sh.i+1,m:sh.units.length})}${sh.dark.length?`
${tr('architect.dark_list',{list:sh.dark.map(nm).join(', ')})}`:''}
`; + if(sh)h+=`
🐒 ${tr('architect.cut_n_of_m',{n:sh.i+1,m:sh.units.length})}${sh.dark.length?`
${tr('architect.dark_list',{list:sh.dark.map(nm).join(', ')})}`:''}
`; else if(f)h+=`
💥 ${f.gold.length?tr('architect.cut_on_x_cuts_off_y',{x:pzUnitName(f.u),y:f.gold.map(nm).join(', ')}):tr('architect.cut_on_x_no_room',{x:pzUnitName(f.u),y:f.short.map(nm).join(', ')})}
${tr('architect.fix_it_and_send_it_again')}
`; else if(e.passed)h+=`
✅ ${tr('architect.review_passed')}
`; else if(!e.ready)h+=`
${esc(e.why)}
`; diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 897b7dc..42f15db 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -86,6 +86,7 @@ function drawFrame(now){ CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);if(S.ar)for(const v of vis)arDrawTags(v,sc);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); + if(UI.mk)mkDraw(ks); // floaters for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;} for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}} diff --git a/src/game/96-map/87-chaos-monkey.js b/src/game/96-map/87-chaos-monkey.js new file mode 100644 index 0000000..b91d700 --- /dev/null +++ b/src/game/96-map/87-chaos-monkey.js @@ -0,0 +1,35 @@ +/* ---------- the chaos monkey: Architect's review, as a monkey running round the map ---------- + It hops from cut to cut, sprays chaos where it snips, and dances on the spot that breaks a mission-critical site. + Pure decoration on the animation clock: the review's result never depends on it, and with animations off the monkey + just sits at the cut. */ +const MK_RUN=0.62; // share of a review step the monkey spends running to the next cut +const MK_COLS=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF']; +// Where a link's middle is, in world coordinates (the shorter way round the date line). +const mkMid=l=>[(CITY[l.a].x+CITY[l.a].x+wrapDx(CITY[l.a].x,CITY[l.b].x))/2,(CITY[l.a].y+CITY[l.b].y)/2]; +function mkStart(c){const C=CITY[c];UI.mk={x:C.x,y:C.y,fx:C.x,fy:C.y,tx:C.x,ty:C.y,t0:animT,dur:1,face:1,mood:'run',spray:[],sprayAt:null,bad:false};} +// Off to the next cut: arrive, then spray. +function mkRun(l,dur,bad){const m=UI.mk;if(!m)return;const [x,y]=mkMid(l);m.fx=m.x;m.fy=m.y;m.tx=x;m.ty=y;m.t0=animT;m.dur=Math.max(1,dur*MK_RUN); + m.face=wrapDx(m.fx,x)<0?-1:1;m.mood='run';m.sprayAt=animT+m.dur;m.bad=!!bad;if(!animOn()){m.x=x;m.y=y;}} +function mkSpray(m){for(let i=0;i<(m.bad?26:16);i++){const a=Math.PI*2*i/(m.bad?26:16)+((i*37)%10)/10,v=0.05+((i*53)%10)/180; + m.spray.push({x:m.tx,y:m.ty,vx:Math.cos(a)*v,vy:Math.sin(a)*v-0.06,c:m.bad?(i%3?'#FF4D5E':'#FFD23F'):MK_COLS[i%MK_COLS.length],t:animT,s:i%4===0?(m.bad?'💥':'✂️'):null});}} +// The review is over: a cheer when everything held, a tantrum where it broke. +function mkEnd(ok){const m=UI.mk;if(!m)return;m.mood=ok?'cheer':'dance';m.t0=animT;} +function mkStop(){UI.mk=null;} +function mkDraw(ks){const m=UI.mk;if(!m)return; + const p=Math.min(1,(animT-m.t0)/m.dur),e=p<0.5?2*p*p:1-Math.pow(-2*p+2,2)/2; + if(m.mood==='run'){m.x=m.fx+wrapDx(m.fx,m.tx)*e;m.y=m.fy+(m.ty-m.fy)*e;} + if(m.sprayAt!=null&&animT>=m.sprayAt){m.sprayAt=null;if(animOn())mkSpray(m);m.mood=m.bad?'dance':'snip';m.t0=animT;} + const sz=Math.round(36*Math.max(0.85,Math.min(1.4,Math.sqrt(cam.z)))); + // Hops while running, bounces on the spot otherwise. + const hop=m.mood==='run'&&p<1?Math.abs(Math.sin((animT-m.t0)/70))*sz*0.45:m.mood==='dance'?Math.abs(Math.sin((animT-m.t0)/90))*sz*0.6:m.mood==='cheer'?Math.abs(Math.sin((animT-m.t0)/120))*sz*0.35:0; + ctx.save();ctx.textAlign='center';ctx.textBaseline='middle'; + for(let i=m.spray.length-1;i>=0;i--){const q=m.spray[i],a=(animT-q.t)/900;if(a>1){m.spray.splice(i,1);continue;} + const dt=animT-q.t,wx=q.x+q.vx*dt/cam.z,wy=q.y+(q.vy*dt+0.00012*dt*dt)/cam.z; + for(const k of ks){const [sx,sy]=toS(wx,wy,k);ctx.globalAlpha=1-a;if(q.s){ctx.font=`${Math.round(sz*0.7)}px sans-serif`;ctx.fillText(q.s,sx,sy);}else{ctx.fillStyle=q.c;ctx.beginPath();ctx.arc(sx,sy,Math.max(2,sz*0.13*(1-a*0.5)),0,Math.PI*2);ctx.fill();}}} + ctx.globalAlpha=1;ctx.font=`${sz}px sans-serif`; + for(const k of ks){const [sx,sy]=toS(m.x,m.y,k);ctx.save();ctx.translate(sx,sy-sz*0.7-hop); + const tilt=m.mood==='snip'?Math.sin((animT-m.t0)/60)*0.35:m.mood==='dance'?Math.sin((animT-m.t0)/80)*0.5:0;ctx.rotate(tilt);ctx.scale(m.face,1); + ctx.fillStyle='rgba(30,38,64,.18)';ctx.beginPath();ctx.ellipse(0,sz*0.62+hop,sz*0.38,sz*0.12,0,0,Math.PI*2);ctx.fill(); + // Emoji take the fill's alpha, so reset it after the shadow. + ctx.fillStyle='#000';ctx.fillText('🐒',0,0);if(m.mood==='cheer')ctx.fillText('🎉',sz*0.7,-sz*0.5);ctx.restore();} + ctx.restore();} diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 005bed4..381c1c0 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -23,7 +23,7 @@ function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c a second anyway, and every frame while the land picture is still catching up with a zoom. */ const FRAME=[]; function mapStill(t,now){const sl=UI.sel,dr=UI.drag; - const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length]; + const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length,UI.mk&&UI.mk.tx,UI.mk&&UI.mk.mood]; let same=v.length===FRAME.length;for(let i=0;iYour router can't take a {port} port.

Upgrade it in the Infra tab.", -"architect.anchor":"⚓ Anchor!", +"architect.anchor":"🐒 Splash!", "architect.architect_runs":"Architect runs", -"architect.backhoe":"🚜 Backhoe!", +"architect.backhoe":"🐒 Snip!", "architect.best_n_briefs":"best: {n} briefs", "architect.brief_n_of_m":"Brief {n} of {m}", "architect.briefs_done":"Briefs done", @@ -43,7 +43,7 @@ "architect.euro_run":"Euro Run", "architect.euro_run_joke":"Six briefs, one landlord, one very nervous bank.", "architect.finish_the_run":"Finish the run", -"architect.fix_it_and_send_it_again":"Fix it, then send the backhoe again.", +"architect.fix_it_and_send_it_again":"Fix it, then let the chaos monkey loose again.", "architect.from_x":"from {x}", "architect.gold_lead":"Mission-critical: this site must stay connected to HQ whichever single trench or cable is cut, and the detour needs room for its traffic.", "architect.gold_must_survive":"Must survive any single cut: {list}", @@ -57,7 +57,7 @@ "architect.lay_a_tube_to":"Lay a tube to", "architect.line_1":"It works. Finance would like a word.", "architect.line_2":"Solid design, a little gold plated. Finance can live with it.", -"architect.line_3":"At par or better. The backhoe went home bored.", +"architect.line_3":"At par or better. The chaos monkey went home bored.", "architect.move_out_of_city":"Move out of {city} first.", "architect.n_briefs":"{n} briefs", "architect.n_over_plan":"{n} over plan", @@ -78,8 +78,8 @@ "architect.pacific_rim":"Pacific Rim", "architect.pacific_rim_joke":"Oceans, anchors and very expensive glass.", "architect.plus_router_x":"+ bigger router {x}", -"architect.ready_no_gold_yet":"Ready. Nothing is mission-critical yet, so the backhoe can only make a mess.", -"architect.ready_send_the_backhoe":"Ready. Send the backhoe and see what survives.", +"architect.ready_no_gold_yet":"Ready. Nothing is mission-critical yet, so the chaos monkey can only make a mess.", +"architect.ready_send_the_backhoe":"Ready. Let the chaos monkey loose and see what survives.", "architect.reset_brief":"Reset brief", "architect.review_passed":"Review passed", "architect.ring_list":"One ring through {list}", @@ -87,8 +87,8 @@ "architect.router_x":"Router: {x}", "architect.run_complete":"Run complete", "architect.run_over":"Run over", -"architect.runs_lead":"One network, built brief by brief. Your build carries over, and a backhoe checks every design: cut any one tube, and everything still connected must get all its traffic.", -"architect.send_the_backhoe":"Send the backhoe", +"architect.runs_lead":"One network, built brief by brief. Your build carries over, and a chaos monkey tests every design: it cuts one tube at a time, and everything still connected must get all its traffic.", +"architect.send_the_backhoe":"Let the chaos monkey loose", "architect.shape_braces":"Belt and braces", "architect.shape_full":"Full mesh", "architect.shape_islands":"Islands", diff --git a/tests/architect.test.js b/tests/architect.test.js index 5041080..c17929f 100644 --- a/tests/architect.test.js +++ b/tests/architect.test.js @@ -1,4 +1,4 @@ -// Architect runs (prototype): one network built brief by brief, reviewed by a backhoe. +// Architect runs (prototype): one network built brief by brief, reviewed by a chaos monkey. const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); @@ -34,7 +34,7 @@ test('architect runs: every reference passes each brief, on plan and within budg assert.deepEqual(errors, []); }); -test('architect runs: the backhoe finds a shared trench, edits clear the cut, old builds are paid for', () => { +test('architect runs: the chaos monkey finds a shared trench, edits clear the cut, old builds are paid for', () => { const { ev, errors } = load(); ev("ACT.pzArStart({id:'euro'})"); assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden'); From 4701cefbfd796767870feb2b050820ffcf489c86 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 09:33:05 +0100 Subject: [PATCH 146/181] Architect runs: draw our own chaos monkey, in shades A hand-drawn monkey in the map's outline style replaces the emoji: sunglasses, a spray can, a swaying tail, and poses for running, snipping, dancing and cheering. --- src/game/96-map/87-chaos-monkey.js | 45 ++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/src/game/96-map/87-chaos-monkey.js b/src/game/96-map/87-chaos-monkey.js index b91d700..d9ccfde 100644 --- a/src/game/96-map/87-chaos-monkey.js +++ b/src/game/96-map/87-chaos-monkey.js @@ -27,9 +27,44 @@ function mkDraw(ks){const m=UI.mk;if(!m)return; const dt=animT-q.t,wx=q.x+q.vx*dt/cam.z,wy=q.y+(q.vy*dt+0.00012*dt*dt)/cam.z; for(const k of ks){const [sx,sy]=toS(wx,wy,k);ctx.globalAlpha=1-a;if(q.s){ctx.font=`${Math.round(sz*0.7)}px sans-serif`;ctx.fillText(q.s,sx,sy);}else{ctx.fillStyle=q.c;ctx.beginPath();ctx.arc(sx,sy,Math.max(2,sz*0.13*(1-a*0.5)),0,Math.PI*2);ctx.fill();}}} ctx.globalAlpha=1;ctx.font=`${sz}px sans-serif`; - for(const k of ks){const [sx,sy]=toS(m.x,m.y,k);ctx.save();ctx.translate(sx,sy-sz*0.7-hop); - const tilt=m.mood==='snip'?Math.sin((animT-m.t0)/60)*0.35:m.mood==='dance'?Math.sin((animT-m.t0)/80)*0.5:0;ctx.rotate(tilt);ctx.scale(m.face,1); - ctx.fillStyle='rgba(30,38,64,.18)';ctx.beginPath();ctx.ellipse(0,sz*0.62+hop,sz*0.38,sz*0.12,0,0,Math.PI*2);ctx.fill(); - // Emoji take the fill's alpha, so reset it after the shadow. - ctx.fillStyle='#000';ctx.fillText('🐒',0,0);if(m.mood==='cheer')ctx.fillText('🎉',sz*0.7,-sz*0.5);ctx.restore();} + for(const k of ks){const [sx,sy]=toS(m.x,m.y,k);ctx.save();ctx.translate(sx,sy+sz*0.15); + ctx.fillStyle='rgba(30,38,64,.18)';ctx.beginPath();ctx.ellipse(0,0,sz*0.38,sz*0.12,0,0,Math.PI*2);ctx.fill(); + ctx.translate(0,-hop);const tilt=m.mood==='snip'?Math.sin((animT-m.t0)/60)*0.25:m.mood==='dance'?Math.sin((animT-m.t0)/80)*0.35:0;ctx.rotate(tilt);ctx.scale(m.face,1); + mkSprite(sz*1.25,animT-m.t0,m.mood==='run'&&p>=1?'stand':m.mood); + if(m.mood==='cheer'){ctx.scale(m.face,1);ctx.fillStyle='#000';ctx.fillText('🎉',sz*0.75,-sz*1.1);}ctx.restore();} ctx.restore();} +// Our own monkey, drawn in the map's outline style, facing right with its feet at (0,0); s is its height. +// Shades on, spray can in hand: the arms and legs move with its mood. +function mkSprite(s,t,mood){const u=s/40,O='#1E2640',B='#A0673A',T='#F4CFA0',lw=Math.max(1.4,2*u),k=Math.sin(t/70); + ctx.lineJoin=ctx.lineCap='round';ctx.strokeStyle=O;ctx.lineWidth=lw; + const dot=(x,y,r,c)=>{ctx.fillStyle=c;ctx.beginPath();ctx.arc(x*u,y*u,r*u,0,Math.PI*2);ctx.fill();ctx.stroke();}; + const limb=(x1,y1,x2,y2,w)=>{ctx.beginPath();ctx.moveTo(x1*u,y1*u);ctx.lineTo(x2*u,y2*u);ctx.lineWidth=w*u+2*lw;ctx.strokeStyle=O;ctx.stroke();ctx.lineWidth=w*u;ctx.strokeStyle=B;ctx.stroke();ctx.lineWidth=lw;ctx.strokeStyle=O;}; + const run=mood==='run',up=mood==='cheer',wave=mood==='snip'||mood==='dance'; + // tail: a curl that sways + const sw=Math.sin(t/160)*3;ctx.beginPath();ctx.moveTo(-6*u,-9*u);ctx.bezierCurveTo(-19*u,-8*u,(-21+sw)*u,-26*u,(-13+sw)*u,-29*u);ctx.bezierCurveTo((-7+sw)*u,-31*u,(-6+sw)*u,-24*u,(-10+sw)*u,-24*u); + ctx.lineWidth=3*u+2*lw;ctx.stroke();ctx.lineWidth=3*u;ctx.strokeStyle=B;ctx.stroke();ctx.lineWidth=lw;ctx.strokeStyle=O; + // legs and feet + const g=run?5*k:mood==='dance'?3*k:0;limb(-3,-10,-4-g,-1.5,3.6);limb(4,-10,5+g,-1.5,3.6); + ctx.fillStyle=T;for(const x of [-4-g,5+g]){ctx.beginPath();ctx.ellipse((x+1)*u,-1*u,3*u,1.8*u,0,0,Math.PI*2);ctx.fill();ctx.stroke();} + // back arm, body, belly + const ba=up?[-10,-33]:wave?[-11,-25+2*k]:run?[-10,-14-3*k]:[-9,-13];limb(-4,-20,ba[0],ba[1],3.2);dot(ba[0],ba[1],2.2,T); + ctx.fillStyle=B;ctx.beginPath();ctx.ellipse(0,-15*u,9*u,10*u,0,0,Math.PI*2);ctx.fill();ctx.stroke(); + ctx.fillStyle=T;ctx.beginPath();ctx.ellipse(1.5*u,-14*u,5.5*u,7*u,0,0,Math.PI*2);ctx.fill(); + // head: ears, skull, face + dot(-6,-32,3.6,B);dot(10,-32,3.6,B);ctx.fillStyle=T;for(const x of [-6,10]){ctx.beginPath();ctx.arc(x*u,-32*u,1.9*u,0,Math.PI*2);ctx.fill();} + dot(2,-31,9,B);ctx.fillStyle=T;ctx.beginPath();ctx.arc(-1*u,-31.5*u,4*u,0,Math.PI*2);ctx.arc(5*u,-31.5*u,4*u,0,Math.PI*2);ctx.fill(); + ctx.beginPath();ctx.ellipse(2*u,-27.5*u,6.5*u,4.6*u,0,0,Math.PI*2);ctx.fill(); + // shades: two dark lenses on a bridge, with a glint + ctx.fillStyle=O;ctx.beginPath();ctx.ellipse(-1.2*u,-32.5*u,3.3*u,2.6*u,0,0,Math.PI*2);ctx.ellipse(5.4*u,-32.5*u,3.3*u,2.6*u,0,0,Math.PI*2);ctx.fill(); + ctx.beginPath();ctx.moveTo(1.5*u,-33.5*u);ctx.lineTo(2.7*u,-33.5*u);ctx.moveTo(-4.4*u,-33*u);ctx.lineTo(-7*u,-33.5*u);ctx.stroke(); + ctx.strokeStyle='#fff';ctx.lineWidth=Math.max(1,0.9*u);ctx.beginPath();ctx.moveTo(-2.6*u,-33.6*u);ctx.lineTo(-1.2*u,-34.3*u);ctx.moveTo(4*u,-33.6*u);ctx.lineTo(5.4*u,-34.3*u);ctx.stroke();ctx.strokeStyle=O;ctx.lineWidth=lw; + // mouth: a smirk, or a laugh when it breaks something + ctx.beginPath();if(mood==='dance'||up){ctx.fillStyle='#7A2633';ctx.ellipse(2.5*u,-26.5*u,2.6*u,2*u,0,0,Math.PI*2);ctx.fill();ctx.stroke();} + else{ctx.moveTo(-0.5*u,-27*u);ctx.quadraticCurveTo(3*u,-25*u,6*u,-28*u);ctx.stroke();} + // front arm with the spray can + const fa=up?[11,-34]:wave?[13,-27-2*k]:run?[11,-17+3*k]:[10,-14];limb(5,-20,fa[0],fa[1],3.2); + ctx.save();ctx.translate(fa[0]*u,fa[1]*u);ctx.rotate(wave?0.5:0); + ctx.fillStyle='#FF4F9A';ctx.beginPath();ctx.roundRect(-2.6*u,-8*u,5.2*u,9*u,1.2*u);ctx.fill();ctx.stroke(); + ctx.fillStyle='#FFD23F';ctx.fillRect(-2.6*u,-5*u,5.2*u,2*u);ctx.fillStyle='#C9D1E6';ctx.beginPath();ctx.roundRect(-1.6*u,-10.5*u,3.2*u,2.6*u,0.8*u);ctx.fill();ctx.stroke(); + if(wave){ctx.fillStyle='rgba(255,79,154,.45)';for(let i=0;i<4;i++){ctx.beginPath();ctx.arc((4+i*2.2)*u,(-11-i*1.4+Math.sin(t/40+i))*u,(0.9+i*0.4)*u,0,Math.PI*2);ctx.fill();}} + ctx.restore();dot(fa[0],fa[1],2.2,T);} From c8113d904390f00e95af5725dab919f821a9a0df Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 10:32:15 +0100 Subject: [PATCH 147/181] Map: stop redrawing every frame when no chaos monkey is on it --- src/game/99-loop.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 381c1c0..d06727a 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -23,7 +23,7 @@ function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c a second anyway, and every frame while the land picture is still catching up with a zoom. */ const FRAME=[]; function mapStill(t,now){const sl=UI.sel,dr=UI.drag; - const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length,UI.mk&&UI.mk.tx,UI.mk&&UI.mk.mood]; + const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length,UI.mk?UI.mk.tx:0,UI.mk?UI.mk.mood:0]; let same=v.length===FRAME.length;for(let i=0;i Date: Fri, 30 Oct 2026 10:54:25 +0100 Subject: [PATCH 148/181] Chaos monkey: a visitor that snips tubes in On-call and BGP at 3 a.m. Now and then a chaos monkey moves in for 120 to 240 days and snips a tube every couple of weeks, weak spots first, instead of the usual random outages. Outlast it without a customer noticing for a bonus and the Monkey-proof badge, or throw it a banana. Drawn on the map in shades; gameplay rule F4 with its test. --- .claude/skills/gameplay-rules/SKILL.md | 1 + CHANGELOG.md | 1 + site/i18n/de.js | 14 ++++ site/i18n/es.js | 14 ++++ site/i18n/fr.js | 14 ++++ site/i18n/it.js | 14 ++++ site/i18n/pt.js | 14 ++++ src/game/60-features/80-new-game.js | 2 +- src/game/80-simulation/50-sanitize.js | 4 + src/game/85-incidents/40-chaos-monkey.js | 52 +++++++++++++ src/game/88-days/10-day-tick.js | 4 +- src/game/88-days/20-badges.js | 1 + src/game/90-actions/60-links.js | 2 + src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/96-map/60-draw.js | 2 + src/game/96-map/87-chaos-monkey.js | 73 +++++++++++++++++ src/game/96-map/90-input.js | 1 + src/game/99-loop.js | 2 +- src/i18n/en.js | 14 ++++ tests/chaos-monkey.test.js | 99 ++++++++++++++++++++++++ tests/gameplay-rules.test.js | 21 +++++ 21 files changed, 347 insertions(+), 4 deletions(-) create mode 100644 src/game/85-incidents/40-chaos-monkey.js create mode 100644 src/game/96-map/87-chaos-monkey.js create mode 100644 tests/chaos-monkey.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 770d3ce..6e691fb 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -63,3 +63,4 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | F1 | A new network gets a gentle start: no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. | New players learn before they get punished. | | F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. | | F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. | +| F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. | diff --git a/CHANGELOG.md b/CHANGELOG.md index ebdfd49..2a605d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. - The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. - Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. - Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. diff --git a/site/i18n/de.js b/site/i18n/de.js index c255a30..a9aa838 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -68,8 +68,10 @@ "badges.lose_a_metro_ring_to_one":"Verliere einen Metro-Ring an einen einzigen Bagger.", "badges.lose_fiber_to_a_llama_herd":"Verliere Glasfaser an eine Lamaherde.", "badges.met_the_backhoe":"Den Bagger kennengelernt", +"badges.monkey_proof":"Affensicher", "badges.never_paid_list_price":"Nie den Listenpreis bezahlt", "badges.opt_out_of_3_auto_enrolled":"Kündige 3 automatisch gebuchte Zusatzleistungen.", +"badges.outlast_a_chaos_monkey_visit":"Überstehe einen Besuch des Chaos-Affen, ohne dass ein Kunde etwas merkt", "badges.over_the_mountains":"Über die Berge", "badges.paid_pnis_with_all_three_korean":"Bezahlte PNIs mit allen drei koreanischen Platzhirschen.", "badges.peer_at_an_ix_remotely":"Peere remote an einem IX.", @@ -453,6 +455,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/Monat · Lieferung innerhalb von {n} Tagen nach Unterschrift", "capacity_deals.what_price_mo_due_date":"{what} · {price}/Monat nach Lieferung · fällig am {date}", "capacity_deals.wholesale_waves":"Wholesale-Waves", +"chaos_monkey.arrived":"🐒 Ein Chaos-Affe ist in dein Netz gekommen!
Etwa {n} Tage lang kappt er absichtlich Leitungen, zuerst die ohne Ersatzweg. Übersteh es, ohne dass ein Kunde etwas merkt, und kassier einen Bonus.", +"chaos_monkey.banana":"🍌 Banane werfen {cost}", +"chaos_monkey.bribed":"🍌 Banane angenommen.
Der Chaos-Affe ist mit seinem Snack abgezogen. Dein Pager hat Pause.", +"chaos_monkey.card":"Kappt noch {n} Tage lang Leitungen. Bisher gekappt: {s}, von Kunden bemerkt: {hurt}.", +"chaos_monkey.loose":"Chaos-Affe los", +"chaos_monkey.rerouted":"🐒 Schnipp!
Der Chaos-Affe hat {a} ⇄ {b} gekappt, und der Verkehr ging einfach außen herum. Er wirkt enttäuscht.", +"chaos_monkey.snip_sprayed":"Der Chaos-Affe hat {a} ⇄ {b} mit etwas Klebrigem eingesprüht. Die Leitung ist down.", +"chaos_monkey.snip_to_see":"Der Chaos-Affe hat {a} ⇄ {b} gekappt, nur um zu sehen, was passiert.", +"chaos_monkey.snip_unplugged":"Der Chaos-Affe hat {a} ⇄ {b} ausgesteckt und grinst dich an.", +"chaos_monkey.survived":"🐒 Du hast den Chaos-Affen überstanden!
{n}-mal gekappt, und kein Kunde hat es gemerkt. Resilienz-Bonus: {cash}.", +"chaos_monkey.tap":"🐒 Er kappt absichtlich deine Leitungen, um zu beweisen, dass du es überstehst. Eine Banane würde ihn nach Hause schicken.", +"chaos_monkey.went_home":"🐒 Der Chaos-Affe ist nach Hause gegangen.
Gekappt: {n}. Von Kunden bemerkt: {hurt}. Wo es wehtat, hätte ein zweiter Weg dich gerettet.", "cities.270_million_people_on_17_000":"270 Millionen Menschen auf 17.000 Inseln. Mobile first und sehr hungrig nach Bandbreite.", "cities.a_capital_high_in_the_andes":"Eine Hauptstadt hoch in den Anden, knapp südlich des Äquators, die in US-Dollar zahlt. Vulkane an jedem Horizont.", "cities.a_capital_in_a_valley_under":"Eine Hauptstadt in einem Tal unter einem grünen Berg. Das nationale Stromnetz hatte schon ein paar berüchtigte schwarze Tage, also bring einen Generator mit.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 6a4af3e..d01b621 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -66,8 +66,10 @@ "badges.lose_a_metro_ring_to_one":"Pierde un anillo metropolitano por culpa de una sola retroexcavadora.", "badges.lose_fiber_to_a_llama_herd":"Pierde fibra por culpa de una manada de llamas.", "badges.met_the_backhoe":"Conoció a la retroexcavadora", +"badges.monkey_proof":"A prueba de monos", "badges.never_paid_list_price":"Nunca pagó precio de lista", "badges.opt_out_of_3_auto_enrolled":"Rechaza 3 complementos de alta automática.", +"badges.outlast_a_chaos_monkey_visit":"Aguanta una visita del mono del caos sin que ningún cliente lo note", "badges.over_the_mountains":"Sobre las montañas", "badges.paid_pnis_with_all_three_korean":"Paga PNIs a los tres operadores históricos coreanos.", "badges.peer_at_an_ix_remotely":"Haz peering en un IX de forma remota.", @@ -451,6 +453,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/mes · entregar en {n} días desde la firma", "capacity_deals.what_price_mo_due_date":"{what} · {price}/mes una vez entregado · vence el {date}", "capacity_deals.wholesale_waves":"Ondas al por mayor", +"chaos_monkey.arrived":"🐒 ¡Un mono del caos se ha colado en tu red!
Durante unos {n} días corta tubos a propósito, primero los que no tienen ruta de respaldo. Aguanta sin que ningún cliente lo note y te llevas un bonus.", +"chaos_monkey.banana":"🍌 Lanzar un plátano {cost}", +"chaos_monkey.bribed":"🍌 Plátano aceptado.
El mono del caos se fue con su merienda. Tu busca puede descansar.", +"chaos_monkey.card":"Cortando tubos {n} días más. Cortes hasta ahora: {s}, notados por clientes: {hurt}.", +"chaos_monkey.loose":"Mono del caos suelto", +"chaos_monkey.rerouted":"🐒 ¡Zas!
El mono del caos cortó {a} ⇄ {b} y el tráfico simplemente dio la vuelta. Parece decepcionado.", +"chaos_monkey.snip_sprayed":"El mono del caos roció {a} ⇄ {b} con algo pegajoso. Está caído.", +"chaos_monkey.snip_to_see":"El mono del caos cortó {a} ⇄ {b}, solo para ver qué pasaba.", +"chaos_monkey.snip_unplugged":"El mono del caos desenchufó {a} ⇄ {b} y te sonríe.", +"chaos_monkey.survived":"🐒 ¡Has aguantado al mono del caos!
{n} cortes y ningún cliente lo notó. Bonus de resiliencia: {cash}.", +"chaos_monkey.tap":"🐒 Corta tus tubos a propósito, para demostrar que puedes sobrevivir. Un plátano lo mandaría a casa.", +"chaos_monkey.went_home":"🐒 El mono del caos se fue a casa.
Cortes: {n}. Notados por clientes: {hurt}. Donde dolió, una segunda ruta te habría salvado.", "cities.270_million_people_on_17_000":"270 millones de personas en 17 000 islas. Móvil primero, y con muchísima hambre de ancho de banda.", "cities.a_capital_high_in_the_andes":"Una capital en lo alto de los Andes, justo al sur del ecuador, que paga en dólares estadounidenses. Volcanes en cada horizonte.", "cities.a_capital_in_a_valley_under":"Una capital en un valle bajo una montaña verde. La red eléctrica nacional ha tenido días malos famosos, así que trae un generador.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index b5e12d1..f2cfbad 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -66,8 +66,10 @@ "badges.lose_a_metro_ring_to_one":"Perds un anneau métropolitain à cause d’une seule pelleteuse.", "badges.lose_fiber_to_a_llama_herd":"Perds de la fibre à cause d’un troupeau de lamas.", "badges.met_the_backhoe":"Rencontre du troisième godet", +"badges.monkey_proof":"À l'épreuve des singes", "badges.never_paid_list_price":"Jamais au prix catalogue", "badges.opt_out_of_3_auto_enrolled":"Désactive 3 options souscrites d’office.", +"badges.outlast_a_chaos_monkey_visit":"Tiens bon face à une visite du singe du chaos sans qu'aucun client ne s'en aperçoive", "badges.over_the_mountains":"Par-delà les montagnes", "badges.paid_pnis_with_all_three_korean":"Des PNI payants avec les trois opérateurs historiques coréens.", "badges.peer_at_an_ix_remotely":"Fais du peering à distance sur un IX.", @@ -451,6 +453,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/mois · à livrer dans les {n} jours après la signature", "capacity_deals.what_price_mo_due_date":"{what} · {price}/mois une fois livré · échéance {date}", "capacity_deals.wholesale_waves":"Longueurs d'onde en gros", +"chaos_monkey.arrived":"🐒 Un singe du chaos s'est introduit dans ton réseau !
Pendant environ {n} jours, il coupe des tubes exprès, d'abord ceux sans chemin de secours. Tiens bon sans qu'aucun client ne s'en aperçoive et touche un bonus.", +"chaos_monkey.banana":"🍌 Lancer une banane {cost}", +"chaos_monkey.bribed":"🍌 Banane acceptée.
Le singe du chaos est reparti avec son goûter. Ton bipeur peut souffler.", +"chaos_monkey.card":"Coupe des tubes encore {n} jours. Coupures jusqu'ici : {s}, ressenties par les clients : {hurt}.", +"chaos_monkey.loose":"Singe du chaos en liberté", +"chaos_monkey.rerouted":"🐒 Clac !
Le singe du chaos a coupé {a} ⇄ {b}, et le trafic a simplement fait le tour. Il a l'air déçu.", +"chaos_monkey.snip_sprayed":"Le singe du chaos a aspergé {a} ⇄ {b} de quelque chose de collant. C'est en panne.", +"chaos_monkey.snip_to_see":"Le singe du chaos a coupé {a} ⇄ {b}, juste pour voir ce qui se passerait.", +"chaos_monkey.snip_unplugged":"Le singe du chaos a débranché {a} ⇄ {b} et te fait un grand sourire.", +"chaos_monkey.survived":"🐒 Tu as tenu face au singe du chaos !
{n} coupures et aucun client n'a rien vu. Bonus de résilience : {cash}.", +"chaos_monkey.tap":"🐒 Il coupe tes tubes exprès, pour prouver que tu peux y survivre. Une banane le renverrait chez lui.", +"chaos_monkey.went_home":"🐒 Le singe du chaos est rentré chez lui.
Coupures : {n}. Ressenties par les clients : {hurt}. Là où ça a fait mal, un deuxième chemin t'aurait sauvé.", "cities.270_million_people_on_17_000":"270 millions d’habitants sur 17 000 îles. Mobile first, et très gourmands en bande passante.", "cities.a_capital_high_in_the_andes":"Une capitale perchée dans les Andes, juste au sud de l’équateur, qui paie en dollars américains. Des volcans à chaque horizon.", "cities.a_capital_in_a_valley_under":"Une capitale dans une vallée au pied d’une montagne verte. Le réseau électrique national a connu quelques jours noirs célèbres : prévois un groupe électrogène.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 2afe831..bc48096 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -66,8 +66,10 @@ "badges.lose_a_metro_ring_to_one":"Perdi un anello metro per colpa di una sola ruspa.", "badges.lose_fiber_to_a_llama_herd":"Perdi la fibra per colpa di un branco di lama.", "badges.met_the_backhoe":"Incontro con la ruspa", +"badges.monkey_proof":"A prova di scimmia", "badges.never_paid_list_price":"Mai pagato il listino", "badges.opt_out_of_3_auto_enrolled":"Disattiva 3 add-on attivati d’ufficio.", +"badges.outlast_a_chaos_monkey_visit":"Resisti a una visita della scimmia del caos senza che nessun cliente se ne accorga", "badges.over_the_mountains":"Oltre le montagne", "badges.paid_pnis_with_all_three_korean":"PNI a pagamento con tutti e tre gli incumbent coreani.", "badges.peer_at_an_ix_remotely":"Fai peering da remoto su un IX.", @@ -451,6 +453,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/mese · da consegnare entro {n} giorni dalla firma", "capacity_deals.what_price_mo_due_date":"{what} · {price}/mese a consegna avvenuta · scadenza {date}", "capacity_deals.wholesale_waves":"Wave all'ingrosso", +"chaos_monkey.arrived":"🐒 Una scimmia del caos è entrata nella tua rete!
Per circa {n} giorni taglia tubi apposta, prima quelli senza un percorso di riserva. Resisti senza che nessun cliente se ne accorga e avrai un bonus.", +"chaos_monkey.banana":"🍌 Lancia una banana {cost}", +"chaos_monkey.bribed":"🍌 Banana accettata.
La scimmia del caos se n'è andata con la sua merenda. Il tuo cercapersone può riposare.", +"chaos_monkey.card":"Taglia tubi per altri {n} giorni. Tagli finora: {s}, notati dai clienti: {hurt}.", +"chaos_monkey.loose":"Scimmia del caos in libertà", +"chaos_monkey.rerouted":"🐒 Zac!
La scimmia del caos ha tagliato {a} ⇄ {b} e il traffico ha semplicemente girato intorno. Sembra delusa.", +"chaos_monkey.snip_sprayed":"La scimmia del caos ha spruzzato {a} ⇄ {b} con qualcosa di appiccicoso. È giù.", +"chaos_monkey.snip_to_see":"La scimmia del caos ha tagliato {a} ⇄ {b}, solo per vedere cosa succede.", +"chaos_monkey.snip_unplugged":"La scimmia del caos ha staccato {a} ⇄ {b} e ti sorride.", +"chaos_monkey.survived":"🐒 Hai resistito alla scimmia del caos!
{n} tagli e nessun cliente se n'è accorto. Bonus resilienza: {cash}.", +"chaos_monkey.tap":"🐒 Taglia i tuoi tubi apposta, per dimostrare che puoi sopravvivere. Una banana la rimanderebbe a casa.", +"chaos_monkey.went_home":"🐒 La scimmia del caos è tornata a casa.
Tagli: {n}. Notati dai clienti: {hurt}. Dove ha fatto male, un secondo percorso ti avrebbe salvato.", "cities.270_million_people_on_17_000":"270 milioni di persone su 17.000 isole. Mobile first, e affamatissime di banda.", "cities.a_capital_high_in_the_andes":"Una capitale in alto sulle Ande, appena a sud dell’equatore, che paga in dollari USA. Vulcani su ogni orizzonte.", "cities.a_capital_in_a_valley_under":"Una capitale in una valle sotto una montagna verde. La rete elettrica nazionale ha avuto qualche giornata nera famosa, quindi porta un generatore.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index a5af6bb..88db3e9 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -66,8 +66,10 @@ "badges.lose_a_metro_ring_to_one":"Perca um anel metro para uma única retroescavadeira.", "badges.lose_fiber_to_a_llama_herd":"Perca fibra para um rebanho de lhamas.", "badges.met_the_backhoe":"Conheceu a retroescavadeira", +"badges.monkey_proof":"À prova de macaco", "badges.never_paid_list_price":"Nunca paguei preço de tabela", "badges.opt_out_of_3_auto_enrolled":"Cancele 3 add-ons ativados sem você pedir.", +"badges.outlast_a_chaos_monkey_visit":"Aguente uma visita do macaco do caos sem nenhum cliente perceber", "badges.over_the_mountains":"Por cima das montanhas", "badges.paid_pnis_with_all_three_korean":"PNIs pagos com as três incumbentes coreanas.", "badges.peer_at_an_ix_remotely":"Faça peering remoto num IX.", @@ -451,6 +453,18 @@ "capacity_deals.what_price_mo_deliver_within_n":"{what} · {price}/mês · entregar em até {n} dias após assinar", "capacity_deals.what_price_mo_due_date":"{what} · {price}/mês após a entrega · prazo {date}", "capacity_deals.wholesale_waves":"Ondas no atacado", +"chaos_monkey.arrived":"🐒 Um macaco do caos entrou na sua rede!
Durante uns {n} dias, ele corta tubos de propósito, primeiro os que não têm rota de reserva. Aguente sem nenhum cliente perceber e ganhe um bônus.", +"chaos_monkey.banana":"🍌 Jogar uma banana {cost}", +"chaos_monkey.bribed":"🍌 Banana aceita.
O macaco do caos foi embora com o lanche. Seu pager pode descansar.", +"chaos_monkey.card":"Cortando tubos por mais {n} dias. Cortes até agora: {s}, sentidos pelos clientes: {hurt}.", +"chaos_monkey.loose":"Macaco do caos à solta", +"chaos_monkey.rerouted":"🐒 Zás!
O macaco do caos cortou {a} ⇄ {b} e o tráfego simplesmente deu a volta. Ele parece decepcionado.", +"chaos_monkey.snip_sprayed":"O macaco do caos borrifou {a} ⇄ {b} com algo grudento. Está fora do ar.", +"chaos_monkey.snip_to_see":"O macaco do caos cortou {a} ⇄ {b}, só para ver o que acontecia.", +"chaos_monkey.snip_unplugged":"O macaco do caos desligou {a} ⇄ {b} e está sorrindo para você.", +"chaos_monkey.survived":"🐒 Você aguentou o macaco do caos!
{n} cortes e nenhum cliente percebeu. Bônus de resiliência: {cash}.", +"chaos_monkey.tap":"🐒 Ele corta seus tubos de propósito, para provar que você aguenta. Uma banana o mandaria para casa.", +"chaos_monkey.went_home":"🐒 O macaco do caos foi para casa.
Cortes: {n}. Sentidos pelos clientes: {hurt}. Onde doeu, uma segunda rota teria salvado você.", "cities.270_million_people_on_17_000":"270 milhões de pessoas em 17.000 ilhas. Mobile first, e com muita fome de banda.", "cities.a_capital_high_in_the_andes":"Uma capital no alto dos Andes, logo ao sul do equador, que paga em dólar. Vulcões em todo horizonte.", "cities.a_capital_in_a_valley_under":"Uma capital num vale ao pé de uma montanha verde. A rede elétrica nacional já teve dias ruins famosos, então leve um gerador.", diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 0bad8cd..1d9d87b 100644 --- a/src/game/60-features/80-new-game.js +++ b/src/game/60-features/80-new-game.js @@ -1,6 +1,6 @@ function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, ltv:2,t1v:3,auV:1,ops:opsNew(),achP:{},seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{},pairMet:{}, - done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0}; + done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; } diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 71cdda4..13652cc 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -13,6 +13,10 @@ function sanitize(s){ s.priceMul=num(s.priceMul,1);s.nextFail=num(s.nextFail,s.day+45);s.nextEvent=num(s.nextEvent,s.day+40);s.lvl=int(s.lvl,1,LEVELS.length,1);s.neg=int(s.neg,0,1e7,0);s.loanStrikes=int(s.loanStrikes,0,1e3,0); for(const k of Object.keys(s.stats)){const v=s.stats[k];if(k==='by'||k==='f'){if(!v||typeof v!=='object')s.stats[k]={};else for(const j of Object.keys(v))v[j]=num(v[j],0);}else if(typeof v!=='boolean')s.stats[k]=num(v,0);} for(const k of ['survived','incidents','peak'])s.stats[k]=num(s.stats[k],0); + // The chaos monkey (2.0): saves without one get their first visit scheduled on the next day tick. + {const m=s.monkey&&typeof s.monkey==='object'&&!Array.isArray(s.monkey)?s.monkey:{},on=m.on?1:0,o={next:m.next==null?null:int(m.next,0,1e7,s.day+90),on}; + if(on){o.start=int(m.start,0,s.day,s.day);o.until=int(m.until,o.start,o.start+400,s.day+30);o.snip=int(m.snip,0,1e7,s.day+3);o.n=int(m.n,0,1e4,0);o.hurt=int(m.hurt,0,o.n,0);o.c=isCity(m.c)?m.c:isCity(s.home)?s.home:null;} + s.monkey=o;} for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object')p.bb.d=num(p.bb.d,0);else p.bb=null;} if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; opsSanitize(s); diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js new file mode 100644 index 0000000..09f93b2 --- /dev/null +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -0,0 +1,52 @@ +/* ---------- the chaos monkey: a visitor that breaks things on purpose ---------- + Like the real one (Netflix, 2011): something switches off random bits of production so you find out whether the + rest copes. Now and then, in On-call and BGP at 3 a.m. only, a monkey moves in for 120 to 240 days and snips a tube + every couple of weeks, preferring tubes with no other path round them. Its snips stand in for the usual random + failures while it is here, so the visit is a test, not a pile-on. Get through it without a customer noticing and + there is a bonus; a banana sends it home early. S.monkey: next (day of the next visit, null until the first tick), + on, start, until, snip (day of the next snip), n (snips), hurt (snips customers felt), c (city it last snipped by). */ +const MK_SNIPS=[N_('chaos_monkey.snip_unplugged'),N_('chaos_monkey.snip_sprayed'),N_('chaos_monkey.snip_to_see')]; +const mkSpicy=()=>rule('chaos')==='spicy'; +// Only the real game with real chaos: not Change Freeze (calm), Sandbox, puzzles or scenarios. +function mkElig(){return !!S&&S.mode!=='sandbox'&&S.mode!=='puzzle'&&!S.scn&&!S.lost&&['normal','spicy'].includes(rule('chaos'));} +const mkOn=()=>!!(S&&S.monkey&&S.monkey.on&&mkElig()); +const rint=(a,n)=>a+Math.floor(Math.random()*n); +// A quarter of a month's revenue to send it home; half a month's as the bonus for outlasting it. +const mkBananaCost=()=>Math.round(Math.min(1e6,Math.max(10000,(R.revMo||0)*0.25))/1000)*1000; +const mkBonus=()=>Math.round(Math.min(2e6,Math.max(20000,(R.revMo||0)*0.5))/1000)*1000; +// Is there another way between this tube's ends once its whole trench is gone? If not, it is a weak spot. +function mkWeak(l){const trc=l.trench||l.id,adj={}; + for(const x of S.links){if(x===l||(x.trench||x.id)===trc||linkDown(x))continue;(adj[x.a]||(adj[x.a]=[])).push(x.b);(adj[x.b]||(adj[x.b]=[])).push(x.a);} + const seen=new Set([l.a]),q=[l.a];while(q.length){const c=q.pop();if(c===l.b)return false;for(const n of adj[c]||[])if(!seen.has(n)){seen.add(n);q.push(n);}}return true;} +function mkTick(d){const M=S.monkey;if(!M)return; + if(!mkElig()){if(M.on)mkLeave('quiet');return;} + // The first visit is spread by the ASN, not the dice, so a game's other luck stays exactly as it was. + if(M.next==null)M.next=d+(mkSpicy()?180:270)+(S.asn||0)%120; + if(!M.on){if(dl.kind!=='vxc'&&!linkDown(l)).length<3){M.next=d+30;return;}mkArrive(d);return;} + if(d>=M.until){mkLeave();return;} + if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}} +function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121); + Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home}); + toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive'); + if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);} +function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));if(!live.length)return; + // Weak spots first: a sample keeps this cheap on big networks. + const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x])); + const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served; + hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));M.n++;M.c=l.a; + addInc({type:'cut',ref:trc,until:S.day+dur,msg:tr(pick(MK_SNIPS),{a:A,b:B}),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},''); + compute();const i=S.inc[S.inc.length-1],imp=Math.max(0,before-R.served);if(i)i.impact=imp; + const felt=before>1&&imp>=before*0.03;if(felt)M.hurt++;else S.stats.survived++; + toast(felt?`🐒 ${incTitle('cut')}
${esc(i?i.msg:'')}`:tr('chaos_monkey.rerouted',{a:A,b:B}),felt?'bad':'good',[],i?incOpen(i):null);sfx(felt?'err':'alert'); + if(typeof mkRun==='function'){if(!UI.mk&&CITY[M.c])mkStart(M.c);mkRun(l,1400,felt);}} +// why: 'banana' (bribed), 'quiet' (the rules or the game changed under it), or nothing (its time was up). +function mkLeave(why){const M=S.monkey,d=S.day,ok=!why&&M.n>0&&M.hurt===0;M.on=0;M.next=d+(mkSpicy()?rint(220,181):rint(360,361)); + // The usual failures were paused for the visit; give the NOC a breather before they start again. + S.nextFail=Math.max(S.nextFail,d+15); + if(why==='banana')toast(tr('chaos_monkey.bribed'),'good'); + else if(ok){const b=mkBonus();S.cash+=b;S.stats.mkSurv=(S.stats.mkSurv||0)+1;toast(tr('chaos_monkey.survived',{n:M.n,cash:fmt$(b)}),'goal');sfx('coin');track('monkey_survived');} + else if(!why)toast(tr('chaos_monkey.went_home',{n:M.n,hurt:M.hurt}),''); + if(typeof mkEnd==='function')mkEnd(ok,true);} +// The NOC tab's card while it is here. +function mkCard(){if(!mkOn())return '';const M=S.monkey,c=mkBananaCost(); + return `
🐒 ${tr('chaos_monkey.loose')}
${tr('chaos_monkey.card',{n:Math.max(1,M.until-S.day),s:M.n,hurt:M.hurt})}
${btn(tr('chaos_monkey.banana',{cost:fmt$(c)}),'mkBanana',{},'sm',S.cash
`;} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 59ed88c..ef8be3c 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -63,7 +63,9 @@ function dayTick(){ // failures & events // Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never. let dirty=false;const cm=chaosMul(); - if(cm&&d>=S.nextFail){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} + // A visiting chaos monkey does the breaking instead (its snips replace these while it is here). + mkTick(d); + if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} // Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year). if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 0492fe1..37f33a3 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -68,6 +68,7 @@ const BADGES=[ {id:'toaster',i:'🍞',t:tr('common.toaster_wrangler'),d:tr('badges.weather_a_ddos_with_your_defences'),r:'c',ok:()=>(st().ddosHeld||0)>=1}, {id:'cleanpipe',i:'🚿',t:tr('common.clean_pipes'),d:tr('badges.turn_on_a_transit_clean_pipe'),r:'r',ok:()=>S.transit.some(t=>t.clean)}, {id:'lamb',i:'🐐',t:tr('common.sacrificial_lamb'),d:tr('badges.run_a_sacrificial_pni_choke_point'),r:'r',ok:()=>S.pni.some(p=>p.sacrif)}, + {id:'monkey',i:'🐒',t:tr('badges.monkey_proof'),d:tr('badges.outlast_a_chaos_monkey_visit'),r:'e',ok:()=>(st().mkSurv||0)>=1}, {id:'flood',i:'🌊',t:tr('badges.held_the_flood'),d:tr('badges.weather_a_multi_terabit_ddos'),r:'e',ok:()=>(st().ddosMonster||0)>=1}, {id:'skynot',i:'🤖',t:tr('common.skynot_smiles'),d:tr('badges.land_a_hackback_3000tm_that_actually'),r:'e',secret:true,ok:()=>(st().hackWin||0)>=1}, {id:'zero',i:'🕳️',t:tr('badges.zero_peers_given'),d:tr('badges.reach_tier_2_with_every_single'),r:'l',secret:true,ok:()=>isTier2()&&!Object.keys(S.peers).length&&!S.pni.length}, diff --git a/src/game/90-actions/60-links.js b/src/game/90-actions/60-links.js index 7c046d0..a564a7e 100644 --- a/src/game/90-actions/60-links.js +++ b/src/game/90-actions/60-links.js @@ -4,6 +4,8 @@ Object.assign(ACT,{ decomToggle:({city})=>{if(!S.pops[city])return;UI.decom=UI.decom||new Set();if(UI.decom.has(city))UI.decom.delete(city);else UI.decom.add(city);decomModal();}, decomGo:()=>{const sel=[...(UI.decom||[])].filter(c=>S.pops[c]);if(!sel.length||sel.length>=Object.keys(S.pops).length)return;closeModal();UI.decom=null;UI.sel=null;decommission(sel);sfx('alert');after();}, rmLink:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}{const l=S.links.find(x=>x.id===id),back=cabBack(l);if(back>0){S.cash+=back;toast(tr('links.name_is_called_off_the_cable',{name:esc(l.cname||tr('common.your_cable')),price:fmt$(back)}),'good');}}S.links=S.links.filter(l=>l.id!==id);prunePairMet();UI.sel=null;UI.confirm=null;after();}, + // The chaos monkey takes a banana and goes home early (no bonus). + mkBanana:()=>{if(!mkOn())return;if(!spend(mkBananaCost()))return;S.stats.bananas=(S.stats.bananas||0)+1;mkLeave('banana');track('monkey_banana');after();}, fixInc:({id})=>{const i=S.inc.find(x=>x.id===id);if(!i||!(i.cost>0))return;if(i.slow&&i.rushed)return;if(!spend(i.cost))return; if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();}, myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();}, diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index f679918..85e538d 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -50,7 +50,7 @@ function renderLeft(){checkLayer(); }else if(UI.left==='noc'){ h+=`
${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${btn(tr('common.connections'),'connOpen',{},'')}${btn(tr('common.traceroute'),'trace',{},'')}
`; h+=`

${tr('hud_and_panels.your_network_operations_center_every')}

`; - h+=opsCard(); + h+=opsCard()+mkCard(); // Incidents come first, the ones you can fix with one click at the top (#63): no scrolling past hot ports to replace an optic. for(const i of S.inc.filter(i=>i.type!=='ddos').sort((a,b)=>(b.cost?1:0)-(a.cost?1:0)||(b.impact||0)-(a.impact||0))){h+=`
${incTitle(i.type)}
${esc(i.msg)}
${trn('hud_and_panels.auto_fix_in_n_day',i.until-S.day)}${i.impact?` · ${tr('hud_and_panels.g_lost',{g:fmtG(i.impact)})}`:''}
${i.cost?`
${btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash`:''}
`;} h+=logSection();UI.logSeen=Date.now(); diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index f82dee0..a0d1f0c 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -86,6 +86,8 @@ function drawFrame(now){ CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; if(pzOn())for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); + // the chaos monkey (woken here after a reload, wherever it last snipped) + if(UI.mk)mkDraw(ks);else if(mkOn()&&!pzOn()&&CITY[S.monkey.c])mkStart(S.monkey.c); // floaters for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;} for(const k of ks){const [sx,sy]=toS(f.x,f.y,k);ctx.globalAlpha=1-a*a;ctx.font='800 17px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.lineWidth=4;ctx.strokeStyle='#fff';ctx.strokeText(f.text,sx,sy-a*40);ctx.fillStyle=f.col;ctx.fillText(f.text,sx,sy-a*40);ctx.globalAlpha=1;}} diff --git a/src/game/96-map/87-chaos-monkey.js b/src/game/96-map/87-chaos-monkey.js new file mode 100644 index 0000000..7919764 --- /dev/null +++ b/src/game/96-map/87-chaos-monkey.js @@ -0,0 +1,73 @@ +/* ---------- the chaos monkey, on the map ---------- + It hops from cut to cut, sprays chaos where it snips, and dances where a snip really hurt. It visits normal games + (85-incidents/40-chaos-monkey.js) and reviews Architect runs. Pure decoration on the animation clock: nothing + depends on it, and with animations off the monkey just sits at the cut. */ +const MK_RUN=0.62; // share of a review step the monkey spends running to the next cut +const MK_COLS=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF']; +// Where a link's middle is, in world coordinates (the shorter way round the date line). +const mkMid=l=>[(CITY[l.a].x+CITY[l.a].x+wrapDx(CITY[l.a].x,CITY[l.b].x))/2,(CITY[l.a].y+CITY[l.b].y)/2]; +function mkStart(c){const C=CITY[c];UI.mk={x:C.x,y:C.y,fx:C.x,fy:C.y,tx:C.x,ty:C.y,t0:animT,dur:1,face:1,mood:'run',spray:[],sprayAt:null,bad:false};} +// Off to the next cut: arrive, then spray. +function mkRun(l,dur,bad){const m=UI.mk;if(!m)return;const [x,y]=mkMid(l);m.fx=m.x;m.fy=m.y;m.tx=x;m.ty=y;m.t0=animT;m.dur=Math.max(1,dur*MK_RUN); + m.face=wrapDx(m.fx,x)<0?-1:1;m.mood='run';m.sprayAt=animT+m.dur;m.bad=!!bad;if(!animOn()){m.x=x;m.y=y;}} +function mkSpray(m){for(let i=0;i<(m.bad?26:16);i++){const a=Math.PI*2*i/(m.bad?26:16)+((i*37)%10)/10,v=0.05+((i*53)%10)/180; + m.spray.push({x:m.tx,y:m.ty,vx:Math.cos(a)*v,vy:Math.sin(a)*v-0.06,c:m.bad?(i%3?'#FF4D5E':'#FFD23F'):MK_COLS[i%MK_COLS.length],t:animT,s:i%4===0?(m.bad?'💥':'✂️'):null});}} +// It is over: a cheer when everything held, a tantrum where it broke; with bye it then leaves the map. +function mkEnd(ok,bye){const m=UI.mk;if(!m)return;m.mood=ok?'cheer':'dance';m.t0=animT;m.bye=bye?animT:0;} +function mkStop(){UI.mk=null;} +function mkDraw(ks){const m=UI.mk;if(!m)return;if(m.bye&&animT-m.bye>2600){mkStop();return;} + if(m.mood==='snip'&&animT-m.t0>1500){m.mood='stand';m.t0=animT;} + const p=Math.min(1,(animT-m.t0)/m.dur),e=p<0.5?2*p*p:1-Math.pow(-2*p+2,2)/2; + if(m.mood==='run'){m.x=m.fx+wrapDx(m.fx,m.tx)*e;m.y=m.fy+(m.ty-m.fy)*e;} + if(m.sprayAt!=null&&animT>=m.sprayAt){m.sprayAt=null;if(animOn())mkSpray(m);m.mood=m.bad?'dance':'snip';m.t0=animT;} + const sz=Math.round(36*Math.max(0.85,Math.min(1.4,Math.sqrt(cam.z)))); + // Hops while running, bounces on the spot otherwise. + const hop=m.mood==='run'&&p<1?Math.abs(Math.sin((animT-m.t0)/70))*sz*0.45:m.mood==='dance'?Math.abs(Math.sin((animT-m.t0)/90))*sz*0.6:m.mood==='cheer'?Math.abs(Math.sin((animT-m.t0)/120))*sz*0.35:0; + ctx.save();ctx.textAlign='center';ctx.textBaseline='middle'; + for(let i=m.spray.length-1;i>=0;i--){const q=m.spray[i],a=(animT-q.t)/900;if(a>1){m.spray.splice(i,1);continue;} + const dt=animT-q.t,wx=q.x+q.vx*dt/cam.z,wy=q.y+(q.vy*dt+0.00012*dt*dt)/cam.z; + for(const k of ks){const [sx,sy]=toS(wx,wy,k);ctx.globalAlpha=1-a;if(q.s){ctx.font=`${Math.round(sz*0.7)}px sans-serif`;ctx.fillText(q.s,sx,sy);}else{ctx.fillStyle=q.c;ctx.beginPath();ctx.arc(sx,sy,Math.max(2,sz*0.13*(1-a*0.5)),0,Math.PI*2);ctx.fill();}}} + ctx.globalAlpha=1;ctx.font=`${sz}px sans-serif`; + for(const k of ks){const [sx,sy]=toS(m.x,m.y,k);m.sx=sx;m.sy=sy-sz*0.6;m.r=sz*0.8;ctx.save();ctx.translate(sx,sy+sz*0.15); + ctx.fillStyle='rgba(30,38,64,.18)';ctx.beginPath();ctx.ellipse(0,0,sz*0.38,sz*0.12,0,0,Math.PI*2);ctx.fill(); + ctx.translate(0,-hop);const tilt=m.mood==='snip'?Math.sin((animT-m.t0)/60)*0.25:m.mood==='dance'?Math.sin((animT-m.t0)/80)*0.35:0;ctx.rotate(tilt);ctx.scale(m.face,1); + mkSprite(sz*1.25,animT-m.t0,m.mood==='run'&&p>=1?'stand':m.mood); + if(m.mood==='cheer'){ctx.scale(m.face,1);ctx.fillStyle='#000';ctx.fillText('🎉',sz*0.75,-sz*1.1);}ctx.restore();} + ctx.restore();} +// Our own monkey, drawn in the map's outline style, facing right with its feet at (0,0); s is its height. +// Shades on, spray can in hand: the arms and legs move with its mood. +function mkSprite(s,t,mood){const u=s/40,O='#1E2640',B='#A0673A',T='#F4CFA0',lw=Math.max(1.4,2*u),k=Math.sin(t/70); + ctx.lineJoin=ctx.lineCap='round';ctx.strokeStyle=O;ctx.lineWidth=lw; + const dot=(x,y,r,c)=>{ctx.fillStyle=c;ctx.beginPath();ctx.arc(x*u,y*u,r*u,0,Math.PI*2);ctx.fill();ctx.stroke();}; + const limb=(x1,y1,x2,y2,w)=>{ctx.beginPath();ctx.moveTo(x1*u,y1*u);ctx.lineTo(x2*u,y2*u);ctx.lineWidth=w*u+2*lw;ctx.strokeStyle=O;ctx.stroke();ctx.lineWidth=w*u;ctx.strokeStyle=B;ctx.stroke();ctx.lineWidth=lw;ctx.strokeStyle=O;}; + const run=mood==='run',up=mood==='cheer',wave=mood==='snip'||mood==='dance'; + // tail: a curl that sways + const sw=Math.sin(t/160)*3;ctx.beginPath();ctx.moveTo(-6*u,-9*u);ctx.bezierCurveTo(-19*u,-8*u,(-21+sw)*u,-26*u,(-13+sw)*u,-29*u);ctx.bezierCurveTo((-7+sw)*u,-31*u,(-6+sw)*u,-24*u,(-10+sw)*u,-24*u); + ctx.lineWidth=3*u+2*lw;ctx.stroke();ctx.lineWidth=3*u;ctx.strokeStyle=B;ctx.stroke();ctx.lineWidth=lw;ctx.strokeStyle=O; + // legs and feet + const g=run?5*k:mood==='dance'?3*k:0;limb(-3,-10,-4-g,-1.5,3.6);limb(4,-10,5+g,-1.5,3.6); + ctx.fillStyle=T;for(const x of [-4-g,5+g]){ctx.beginPath();ctx.ellipse((x+1)*u,-1*u,3*u,1.8*u,0,0,Math.PI*2);ctx.fill();ctx.stroke();} + // back arm, body, belly + const ba=up?[-10,-33]:wave?[-11,-25+2*k]:run?[-10,-14-3*k]:[-9,-13];limb(-4,-20,ba[0],ba[1],3.2);dot(ba[0],ba[1],2.2,T); + ctx.fillStyle=B;ctx.beginPath();ctx.ellipse(0,-15*u,9*u,10*u,0,0,Math.PI*2);ctx.fill();ctx.stroke(); + ctx.fillStyle=T;ctx.beginPath();ctx.ellipse(1.5*u,-14*u,5.5*u,7*u,0,0,Math.PI*2);ctx.fill(); + // head: ears, skull, face + dot(-6,-32,3.6,B);dot(10,-32,3.6,B);ctx.fillStyle=T;for(const x of [-6,10]){ctx.beginPath();ctx.arc(x*u,-32*u,1.9*u,0,Math.PI*2);ctx.fill();} + dot(2,-31,9,B);ctx.fillStyle=T;ctx.beginPath();ctx.arc(-1*u,-31.5*u,4*u,0,Math.PI*2);ctx.arc(5*u,-31.5*u,4*u,0,Math.PI*2);ctx.fill(); + ctx.beginPath();ctx.ellipse(2*u,-27.5*u,6.5*u,4.6*u,0,0,Math.PI*2);ctx.fill(); + // shades: two dark lenses on a bridge, with a glint + ctx.fillStyle=O;ctx.beginPath();ctx.ellipse(-1.2*u,-32.5*u,3.3*u,2.6*u,0,0,Math.PI*2);ctx.ellipse(5.4*u,-32.5*u,3.3*u,2.6*u,0,0,Math.PI*2);ctx.fill(); + ctx.beginPath();ctx.moveTo(1.5*u,-33.5*u);ctx.lineTo(2.7*u,-33.5*u);ctx.moveTo(-4.4*u,-33*u);ctx.lineTo(-7*u,-33.5*u);ctx.stroke(); + ctx.strokeStyle='#fff';ctx.lineWidth=Math.max(1,0.9*u);ctx.beginPath();ctx.moveTo(-2.6*u,-33.6*u);ctx.lineTo(-1.2*u,-34.3*u);ctx.moveTo(4*u,-33.6*u);ctx.lineTo(5.4*u,-34.3*u);ctx.stroke();ctx.strokeStyle=O;ctx.lineWidth=lw; + // mouth: a smirk, or a laugh when it breaks something + ctx.beginPath();if(mood==='dance'||up){ctx.fillStyle='#7A2633';ctx.ellipse(2.5*u,-26.5*u,2.6*u,2*u,0,0,Math.PI*2);ctx.fill();ctx.stroke();} + else{ctx.moveTo(-0.5*u,-27*u);ctx.quadraticCurveTo(3*u,-25*u,6*u,-28*u);ctx.stroke();} + // front arm with the spray can + const fa=up?[11,-34]:wave?[13,-27-2*k]:run?[11,-17+3*k]:[10,-14];limb(5,-20,fa[0],fa[1],3.2); + ctx.save();ctx.translate(fa[0]*u,fa[1]*u);ctx.rotate(wave?0.5:0); + ctx.fillStyle='#FF4F9A';ctx.beginPath();ctx.roundRect(-2.6*u,-8*u,5.2*u,9*u,1.2*u);ctx.fill();ctx.stroke(); + ctx.fillStyle='#FFD23F';ctx.fillRect(-2.6*u,-5*u,5.2*u,2*u);ctx.fillStyle='#C9D1E6';ctx.beginPath();ctx.roundRect(-1.6*u,-10.5*u,3.2*u,2.6*u,0.8*u);ctx.fill();ctx.stroke(); + if(wave){ctx.fillStyle='rgba(255,79,154,.45)';for(let i=0;i<4;i++){ctx.beginPath();ctx.arc((4+i*2.2)*u,(-11-i*1.4+Math.sin(t/40+i))*u,(0.9+i*0.4)*u,0,Math.PI*2);ctx.fill();}} + ctx.restore();dot(fa[0],fa[1],2.2,T);} +// Did a tap land on the monkey? (Where it was last drawn.) +const mkHit=(x,y)=>!!(UI.mk&&UI.mk.sx!=null&&Math.hypot(x-UI.mk.sx,y-UI.mk.sy)🐒 A chaos monkey got into your network!

For about {n} days it snips tubes on purpose, the ones without a backup path first. Ride it out with no customer noticing for a bonus.", +"chaos_monkey.banana":"🍌 Throw a banana {cost}", +"chaos_monkey.bribed":"🍌 Banana accepted.
The chaos monkey wandered off with its snack. Your pager can rest.", +"chaos_monkey.card":"Snipping tubes for {n} more days. Snips so far: {s}, felt by customers: {hurt}.", +"chaos_monkey.loose":"Chaos monkey on the loose", +"chaos_monkey.rerouted":"🐒 Snip!
The chaos monkey cut {a} ⇄ {b}, and traffic simply went round. It looks disappointed.", +"chaos_monkey.snip_sprayed":"The chaos monkey sprayed {a} ⇄ {b} with something sticky. It is down.", +"chaos_monkey.snip_to_see":"The chaos monkey cut {a} ⇄ {b}, just to see what would happen.", +"chaos_monkey.snip_unplugged":"The chaos monkey unplugged {a} ⇄ {b} and is grinning at you.", +"chaos_monkey.survived":"🐒 You outlasted the chaos monkey!
{n} snips and no customer noticed. Resilience bonus: {cash}.", +"chaos_monkey.tap":"🐒 It snips your tubes on purpose, to prove you can survive it. A banana would send it home.", +"chaos_monkey.went_home":"🐒 The chaos monkey went home.
Snips: {n}. Felt by customers: {hurt}. Where it hurt, a second path would have saved you.", "cities.270_million_people_on_17_000":"270 million people on 17,000 islands. Mobile first, and very hungry for bandwidth.", "cities.a_capital_high_in_the_andes":"A capital high in the Andes, just south of the equator, that pays in US dollars. Volcanoes on every horizon.", "cities.a_capital_in_a_valley_under":"A capital in a valley under a green mountain. The national grid has had some famous bad days, so bring a generator.", diff --git a/tests/chaos-monkey.test.js b/tests/chaos-monkey.test.js new file mode 100644 index 0000000..4089064 --- /dev/null +++ b/tests/chaos-monkey.test.js @@ -0,0 +1,99 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// A small network on a fixed seed: Frankfurt, Amsterdam, London and Paris in a ring, with a spur out to Zurich. +function net(preset) { + const { ev, errors, dom } = load(); + ev(`beginGame('Monkey Testers','fra',${JSON.stringify({ mode: 'normal', preset })});if(UI.pendGame)ACT.pitchSkip()`); + ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par','zrh'])ACT.buildPop({city:c})"); + ev("ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1})"); + ev("for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['fra','zrh']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()"); + ev('for(let i=0;i<60;i++)dayTick();S.inc=[];for(const l of S.links)l.cut=0;compute()'); + return { ev, errors, dom }; +} +const link = (ev, a, b) => `S.links.find(l=>(l.a==='${a}'&&l.b==='${b}')||(l.a==='${b}'&&l.b==='${a}'))`; + +test('the chaos monkey visits On-call and BGP at 3 a.m., never Change Freeze or Sandbox', () => { + for (const [preset, ok] of [['oncall', true], ['bgp', true], ['freeze', false]]) { + const { ev, errors } = net(preset); + assert.equal(ev('mkElig()'), ok, preset); + ev('S.monkey.next=S.day;dayTick()'); + assert.equal(ev('!!S.monkey.on'), ok, preset); + assert.deepEqual(errors, []); + } + const { ev } = net('oncall'); + ev("S.mode='sandbox'"); + assert.equal(ev('mkElig()'), false); + ev("S.mode='normal';S.monkey.next=S.day;dayTick();S.scn={rules:{}}"); + assert.equal(ev('mkOn()'), false, 'never in a scenario'); +}); + +test('a visit lasts 120 to 240 days, snips every couple of weeks and pauses the usual failures', () => { + const { ev, errors } = net('oncall'); + ev('S.monkey.next=S.day;dayTick()'); + const len = ev('S.monkey.until-S.monkey.start'); + assert.ok(len >= 120 && len <= 240, `visit of ${len} days`); + ev('S.nextFail=S.day'); + const nf = ev('S.nextFail'); + ev('for(let i=0;i<60;i++)dayTick()'); + assert.ok(ev('S.monkey.n') >= 2, 'it snipped'); + assert.equal(ev('S.nextFail'), nf, 'no ordinary failure fired while it was here'); + assert.ok(ev("S.inc.some(i=>i.type==='cut')||S.stats.survived>0")); + // It leaves on time, and the ordinary failures wait a little before they start again. + ev('for(let i=0;i<200&&S.monkey.on;i++)dayTick()'); + assert.equal(ev('S.monkey.on'), 0); + assert.ok(ev('S.monkey.next>S.day+200')); + assert.ok(ev('S.nextFail>=S.day')); + assert.deepEqual(errors, []); +}); + +test('weak spots are tubes with no other way round', () => { + const { ev } = net('oncall'); + assert.equal(ev(`mkWeak(${link(ev, 'fra', 'zrh')})`), true); + assert.equal(ev(`mkWeak(${link(ev, 'fra', 'ams')})`), false); +}); + +test('outlasting it unnoticed pays a bonus and earns the badge; going home hurt pays nothing', () => { + const { ev, errors } = net('oncall'); + ev('S.monkey.next=S.day;dayTick();S.monkey.n=4;S.monkey.hurt=0;S.monkey.until=S.day+1'); + const cash = ev('S.cash'), bonus = ev('mkBonus()'); + ev('dayTick();checkBadges()'); + assert.equal(ev('S.monkey.on'), 0); + assert.equal(ev('S.stats.mkSurv'), 1); + assert.ok(ev('S.cash') >= cash + bonus - 1e6, 'bonus paid'); + assert.ok(ev("S.ach.monkey!==undefined")); + ev('S.monkey.next=S.day;dayTick();S.monkey.n=4;S.monkey.hurt=2;S.monkey.until=S.day+1;dayTick()'); + assert.equal(ev('S.stats.mkSurv'), 1, 'no bonus when customers felt it'); + assert.deepEqual(errors, []); +}); + +test('a banana sends it home early, for a price', () => { + const { ev, errors, dom } = net('bgp'); + ev("S.monkey.next=S.day;dayTick();UI.left='noc';renderLeft()"); + assert.ok(dom.window.document.querySelector('[data-act=mkBanana]'), 'the NOC card offers a banana'); + const cash = ev('S.cash'), cost = ev('mkBananaCost()'); + ev('ACT.mkBanana({})'); + assert.equal(ev('S.monkey.on'), 0); + assert.equal(ev('S.cash'), cash - cost); + assert.equal(ev('S.stats.mkSurv||0'), 0); + ev('S.cash=0;S.monkey.next=S.day;dayTick();ACT.mkBanana({})'); + assert.equal(ev('S.monkey.on'), 1, 'no banana without the cash'); + assert.deepEqual(errors, []); +}); + +test('saves keep the monkey; old and broken saves are repaired', () => { + const { ev, errors } = net('oncall'); + ev('S.monkey.next=S.day;dayTick();const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))'); + assert.equal(ev('S.monkey.on'), 1); + assert.ok(ev('S.monkey.until>S.day')); + ev("const o=JSON.parse(JSON.stringify(packSave(S)));delete o.monkey;S=migrate(o)"); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.monkey)')), { next: null, on: 0 }); + ev("const o=JSON.parse(JSON.stringify(packSave(S)));o.monkey={on:1,until:'soon',n:-3,hurt:99,c:''};S=migrate(o)"); + assert.equal(ev('S.monkey.n'), 0); + assert.equal(ev('S.monkey.hurt'), 0); + assert.equal(ev('S.monkey.c'), ev('S.home')); + assert.ok(ev('S.monkey.until>=S.monkey.start')); + ev('for(let i=0;i<5;i++)dayTick()'); + assert.deepEqual(errors, []); +}); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 76cf1ba..fb1603c 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -361,6 +361,27 @@ test('F3: a specialist path only brings customers you can already serve', () => assert.deepEqual(g.errors, []); }); +test('F4: the chaos monkey only visits On-call and BGP at 3 a.m., late, for 120 to 240 days, instead of the ordinary failures', () => { + for (const preset of ['freeze', 'oncall', 'bgp']) { + const g = load(); + g.ev(`beginGame('Monkey','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip()`); + g.ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()"); + g.ev('for(let i=0;i<2;i++)dayTick()'); + if (preset === 'freeze') { assert.equal(g.ev('mkElig()'), false, 'F4: never in Change Freeze'); continue; } + assert.ok(g.ev('S.monkey.next') >= 180, 'F4: not before day 180'); + g.ev('S.monkey.next=S.day;dayTick();S.nextFail=S.day'); + const len = g.ev('S.monkey.until-S.monkey.start'); + assert.ok(len >= 120 && len <= 240, `F4: a visit of ${len} days`); + g.ev('for(let i=0;i<40;i++)dayTick()'); + assert.ok(g.ev('S.nextFail') <= g.ev('S.day'), 'F4: no ordinary failure fired during the visit'); + assert.ok(g.ev("S.inc.filter(i=>i.type==='cut').every(i=>i.until-i.start<=(rule('chaos')==='spicy'?11:7))"), 'F4: snips heal within a week (spicy stretches by half)'); + assert.deepEqual(g.errors, []); + } + const g = load(); + g.ev("beginGame('Monkey','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.mode='sandbox'"); + assert.equal(g.ev('mkElig()'), false, 'F4: never in Sandbox'); +}); + test('no page errors while checking the rules', () => { assert.deepEqual(errors, []); }); From 170914b05ee57dd4bf273fe3e08aa1f051b3f201 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 11:18:54 +0100 Subject: [PATCH 149/181] Architect runs: later briefs stay a surprise No numbered tags beside cities, no "coming up" plan on a city card and no hint to build there early: you design for today's brief and find out what comes next. --- site/i18n/de.js | 4 ---- site/i18n/es.js | 4 ---- site/i18n/fr.js | 4 ---- site/i18n/it.js | 4 ---- site/i18n/pt.js | 4 ---- src/game/60-features/96-architect.js | 7 +------ src/game/95-modals/96-architect.js | 3 +-- src/game/96-map/60-draw.js | 2 +- src/game/96-map/85-puzzle-cities.js | 4 ---- src/i18n/en.js | 4 ---- src/styles/71-architect.css | 3 +-- tests/architect.test.js | 7 +++++-- 12 files changed, 9 insertions(+), 41 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 0f13a5c..5a95062 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -29,7 +29,6 @@ "architect.closed_lead":"Diese Stadt ist jetzt dicht. Zieh aus: Entferne den POP und finde einen anderen Weg.", "architect.coast_to_coast":"Coast to Coast", "architect.coast_to_coast_joke":"Von der Data Center Alley bis ins Silicon Valley, ein Auftrag nach dem anderen.", -"architect.coming_up":"Demnächst", "architect.cut_n_of_m":"Schnitt {n} von {m}…", "architect.cut_on_x_cuts_off_y":"Ein Schnitt auf {x} schneidet {y} ab.", "architect.cut_on_x_no_room":"Ein Schnitt auf {x} lässt auf dem Umweg keinen Platz. Es fehlt: {y}.", @@ -52,7 +51,6 @@ "architect.hide_other_cities":"Andere Städte ausblenden", "architect.hq":"HQ", "architect.hq_lead":"Hier stehen deine Server. Jeder Standort braucht einen Weg zum HQ.", -"architect.joins_in_brief_n":"Kommt in Auftrag {n} dazu", "architect.keep_going":"Weiterbauen", "architect.last_brief_done":"Das war der letzte Auftrag.", "architect.lay_a_tube_to":"Röhre legen nach", @@ -62,14 +60,12 @@ "architect.move_out_of_city":"Zieh zuerst aus {city} aus.", "architect.n_briefs":"{n} Aufträge", "architect.n_over_plan":"{n} über Plan", -"architect.n_tubes":{"one":"{n} Röhre","other":"{n} Röhren"}, "architect.new":"Neu", "architect.next_brief":"Nächster Auftrag", "architect.next_brief_waiting":"Der nächste Auftrag wartet.", "architect.next_run":"Nächster Run", "architect.not_a_ring_yet":"Noch kein Ring.", "architect.not_connected_yet_list":"Noch nicht mit dem HQ verbunden: {list}", -"architect.numbers_on_the_map_show":"Die Zahlen auf der Karte zeigen, was spätere Aufträge bringen. Du darfst dort schon früher bauen.", "architect.or_drag_a_tube_here":"Oder zieh eine Röhre von einem deiner POPs hierher.", "architect.pac_1":"Deine Server stehen in Tokio. Zuerst Hongkong.", "architect.pac_2":"Singapur will auch.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 5c252e7..481f2a2 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -27,7 +27,6 @@ "architect.closed_lead":"Esta ciudad ya está cerrada. Múdate: quita el POP y busca otro camino.", "architect.coast_to_coast":"De costa a costa", "architect.coast_to_coast_joke":"Del callejón de los data centers a Silicon Valley, encargo a encargo.", -"architect.coming_up":"Próximamente", "architect.cut_n_of_m":"Corte {n} de {m}…", "architect.cut_on_x_cuts_off_y":"Un corte en {x} deja aislado a {y}.", "architect.cut_on_x_no_room":"Un corte en {x} no deja sitio en el desvío. Falta: {y}.", @@ -50,7 +49,6 @@ "architect.hide_other_cities":"Ocultar otras ciudades", "architect.hq":"Sede", "architect.hq_lead":"Aquí viven tus servidores. Cada sitio necesita un camino a la sede.", -"architect.joins_in_brief_n":"Llega en el encargo {n}", "architect.keep_going":"Seguir construyendo", "architect.last_brief_done":"Ese era el último encargo.", "architect.lay_a_tube_to":"Tender un tubo a", @@ -60,14 +58,12 @@ "architect.move_out_of_city":"Primero sal de {city}.", "architect.n_briefs":"{n} encargos", "architect.n_over_plan":"{n} por encima del plan", -"architect.n_tubes":{"one":"{n} tubo","other":"{n} tubos"}, "architect.new":"Nuevo", "architect.next_brief":"Siguiente encargo", "architect.next_brief_waiting":"El siguiente encargo te espera.", "architect.next_run":"Siguiente partida", "architect.not_a_ring_yet":"Todavía no es un anillo.", "architect.not_connected_yet_list":"Aún sin conexión a la sede: {list}", -"architect.numbers_on_the_map_show":"Los números del mapa muestran lo que traen los próximos encargos. Puedes construir allí antes.", "architect.or_drag_a_tube_here":"O arrastra un tubo hasta aquí desde uno de tus POP.", "architect.pac_1":"Tus servidores viven en Tokio. Primero, Hong Kong.", "architect.pac_2":"Singapur se apunta.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 3531dc6..b84ff22 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -27,7 +27,6 @@ "architect.closed_lead":"Cette ville est fermée maintenant. Déménage : retire le POP et trouve un autre chemin.", "architect.coast_to_coast":"D’une côte à l’autre", "architect.coast_to_coast_joke":"De l’allée des data centers à la Silicon Valley, un brief à la fois.", -"architect.coming_up":"À venir", "architect.cut_n_of_m":"Coupure {n} sur {m}…", "architect.cut_on_x_cuts_off_y":"Une coupure sur {x} isole {y}.", "architect.cut_on_x_no_room":"Une coupure sur {x} ne laisse pas de place sur le détour. Manque : {y}.", @@ -50,7 +49,6 @@ "architect.hide_other_cities":"Masquer les autres villes", "architect.hq":"QG", "architect.hq_lead":"Tes serveurs vivent ici. Chaque site a besoin d’un chemin vers le QG.", -"architect.joins_in_brief_n":"Arrive au brief {n}", "architect.keep_going":"Continuer à construire", "architect.last_brief_done":"C’était le dernier brief.", "architect.lay_a_tube_to":"Poser un tube vers", @@ -60,14 +58,12 @@ "architect.move_out_of_city":"Quitte d’abord {city}.", "architect.n_briefs":"{n} briefs", "architect.n_over_plan":"{n} au-delà du plan", -"architect.n_tubes":{"one":"{n} tube","other":"{n} tubes"}, "architect.new":"Nouveau", "architect.next_brief":"Brief suivant", "architect.next_brief_waiting":"Le brief suivant t’attend.", "architect.next_run":"Partie suivante", "architect.not_a_ring_yet":"Pas encore un anneau.", "architect.not_connected_yet_list":"Pas encore relié au QG : {list}", -"architect.numbers_on_the_map_show":"Les chiffres sur la carte montrent ce qu’apportent les briefs suivants. Tu peux y construire en avance.", "architect.or_drag_a_tube_here":"Ou fais glisser un tube jusqu’ici depuis un de tes POP.", "architect.pac_1":"Tes serveurs vivent à Tokyo. D’abord Hong Kong.", "architect.pac_2":"Singapour veut en être.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 4c92ff7..de9a748 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -27,7 +27,6 @@ "architect.closed_lead":"Questa città ora è chiusa. Trasloca: togli il POP e trova un’altra strada.", "architect.coast_to_coast":"Da costa a costa", "architect.coast_to_coast_joke":"Dal vicolo dei data center alla Silicon Valley, un incarico alla volta.", -"architect.coming_up":"In arrivo", "architect.cut_n_of_m":"Taglio {n} di {m}…", "architect.cut_on_x_cuts_off_y":"Un taglio su {x} isola {y}.", "architect.cut_on_x_no_room":"Un taglio su {x} non lascia spazio sulla deviazione. Manca: {y}.", @@ -50,7 +49,6 @@ "architect.hide_other_cities":"Nascondi le altre città", "architect.hq":"Sede", "architect.hq_lead":"Qui vivono i tuoi server. Ogni sito ha bisogno di una strada verso la sede.", -"architect.joins_in_brief_n":"Arriva nell’incarico {n}", "architect.keep_going":"Continua a costruire", "architect.last_brief_done":"Era l’ultimo incarico.", "architect.lay_a_tube_to":"Posa un tubo verso", @@ -60,14 +58,12 @@ "architect.move_out_of_city":"Prima lascia {city}.", "architect.n_briefs":"{n} incarichi", "architect.n_over_plan":"{n} oltre il piano", -"architect.n_tubes":{"one":"{n} tubo","other":"{n} tubi"}, "architect.new":"Nuovo", "architect.next_brief":"Prossimo incarico", "architect.next_brief_waiting":"Il prossimo incarico ti aspetta.", "architect.next_run":"Prossima partita", "architect.not_a_ring_yet":"Non è ancora un anello.", "architect.not_connected_yet_list":"Non ancora collegati alla sede: {list}", -"architect.numbers_on_the_map_show":"I numeri sulla mappa mostrano cosa portano i prossimi incarichi. Puoi costruirci già prima.", "architect.or_drag_a_tube_here":"Oppure trascina qui un tubo da uno dei tuoi POP.", "architect.pac_1":"I tuoi server vivono a Tokyo. Prima Hong Kong.", "architect.pac_2":"Anche Singapore vuole entrare.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index aea7dad..df7ae8f 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -27,7 +27,6 @@ "architect.closed_lead":"Esta cidade fechou. Saia de lá: remova o POP e ache outro caminho.", "architect.coast_to_coast":"De costa a costa", "architect.coast_to_coast_joke":"Do beco dos data centers ao Vale do Silício, um pedido de cada vez.", -"architect.coming_up":"Vem aí", "architect.cut_n_of_m":"Corte {n} de {m}…", "architect.cut_on_x_cuts_off_y":"Um corte em {x} isola {y}.", "architect.cut_on_x_no_room":"Um corte em {x} não deixa espaço no desvio. Falta: {y}.", @@ -50,7 +49,6 @@ "architect.hide_other_cities":"Esconder outras cidades", "architect.hq":"Sede", "architect.hq_lead":"Seus servidores moram aqui. Todo site precisa de um caminho até a sede.", -"architect.joins_in_brief_n":"Entra no pedido {n}", "architect.keep_going":"Continuar construindo", "architect.last_brief_done":"Esse foi o último pedido.", "architect.lay_a_tube_to":"Lançar um tubo até", @@ -60,14 +58,12 @@ "architect.move_out_of_city":"Saia de {city} primeiro.", "architect.n_briefs":"{n} pedidos", "architect.n_over_plan":"{n} acima do plano", -"architect.n_tubes":{"one":"{n} tubo","other":"{n} tubos"}, "architect.new":"Novo", "architect.next_brief":"Próximo pedido", "architect.next_brief_waiting":"O próximo pedido está esperando.", "architect.next_run":"Próxima partida", "architect.not_a_ring_yet":"Ainda não é um anel.", "architect.not_connected_yet_list":"Ainda sem ligação com a sede: {list}", -"architect.numbers_on_the_map_show":"Os números no mapa mostram o que os próximos pedidos trazem. Dá para construir lá antes.", "architect.or_drag_a_tube_here":"Ou arraste um tubo até aqui de um dos seus POPs.", "architect.pac_1":"Seus servidores moram em Tóquio. Primeiro, Hong Kong.", "architect.pac_2":"Singapura quer entrar.", diff --git a/src/game/60-features/96-architect.js b/src/game/60-features/96-architect.js index b720cc0..1fb2f5a 100644 --- a/src/game/60-features/96-architect.js +++ b/src/game/60-features/96-architect.js @@ -95,11 +95,6 @@ function arShape(){const ns=Object.keys(S.pops),n=ns.length;if(n<2||!S.links.len k=cs.lengthcore[c].size===2)?'lolli':cs.length===n&&n>=6&&n%2===0&&cm===3*n/2-2&&d2===4&&cs.every(c=>core[c].size<=3)?'ladder':m>=n*1.8?'spaghetti':'mesh';} return {k,i:AR_SHAPES[k][0],n:tr(AR_SHAPES[k][1])};} // What later briefs do to a city, for the map: [{n: brief number, i: icon}], earliest first. -function arTags(c){const A=S.ar,out=[];arRun().briefs.forEach((b,j)=>{if(j<=A.bi)return;const i=(b.gold||[]).includes(c)?'🚨':(b.add||[]).includes(c)?'📍':(b.drop||[]).includes(c)?'🚫':b.dem&&b.dem[c]?'📈':(b.ring||[]).includes(c)?'💍':b.lat&&b.lat.slice(0,2).includes(c)?'⏱':'';if(i)out.push({n:j+1,i});});return out;} -// One line per brief for the plan on the card. -function arSum(b){const nm=c=>CITY[c].name,t=[],d=b.dem||{};if(b.add)t.push(b.add.map(c=>'+'+nm(c)+(d[c]?' '+arG(d[c]):'')).join(' '));for(const c in d)if(!(b.add||[]).includes(c))t.push('📈 '+nm(c)+' '+arG(d[c]));if(b.gold)t.push('🚨 '+b.gold.map(nm).join(', ')); - if(b.ring)t.push('💍 '+b.ring.map(nm).join('–'));if(b.lat)t.push(`⏱ ${nm(b.lat[0])}⇄${nm(b.lat[1])} < ${b.lat[2]} ms`);if(b.drop)t.push('🚫 '+b.drop.map(nm).join(', ')); - if(b.tubes!=null)t.push(trn('architect.n_tubes',b.tubes));return t.join(' · ');} // ---------- starting, briefs and the end ---------- const arDem=c=>S.ar.dem[c]||10; // Short Gbps for chips and tags: 40G, 1.2T. @@ -129,7 +124,7 @@ function arApply(i){const A=S.ar,P=S.pz,b=arRun().briefs[i];A.bi=i; P.via=[...new Set(arRun().briefs.slice(i+1).flatMap(x=>[...(x.add||[]),...(x.gold||[]),...(x.ring||[])]))].filter(c=>!P.cities.includes(c)&&!P.avoid.includes(c)); arDemand();A.start=arSnapStr();UI.pzHist=[];UI.sel=null;UI.arFail=null; compute();pzCam();renderAll(); - toast(`${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}
${esc(b.t)}${i===0&&arRun().briefs.length>1?'
'+tr('architect.numbers_on_the_map_show')+'':''}`,'goal');sfx('click');} + toast(`${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}
${esc(b.t)}`,'goal');sfx('click');} function arNext(){if(!arOn())return;const e=arEval();if(!e.passed)return;if(arLast()){arResults(true);return;}S.ar.over+=e.tubes.over;arApply(S.ar.bi+1);} function arReset(){const o=JSON.parse(S.ar.start);S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};S.ar.sunk=o.k||0;arDemand();UI.sel=null;} // Tubes over plan in the run so far, this brief included. diff --git a/src/game/95-modals/96-architect.js b/src/game/95-modals/96-architect.js index fa37c81..a150a98 100644 --- a/src/game/95-modals/96-architect.js +++ b/src/game/95-modals/96-architect.js @@ -23,10 +23,9 @@ function arRender(el){const A=S.ar,run=arRun(),b=arBrief(),e=arEval(),sh=UI.arSh function arPanel(sel){const A=S.ar,head=(eb,name,facts)=>`
${eb}

${name}

${facts?`
${facts}
`:''}
`; const old=x=>(x.br|0)${tr('architect.built_in_an_earlier_brief')}

`:''; if(sel.type==='city'){const c=sel.id,k=pzKind(c),p=S.pops[c];if(!k)return ''; - const tg=arTags(c),eb=c===A.hq?'🏠 '+tr('architect.hq'):A.gold.includes(c)?'🚨 '+tr('architect.gold_site'):k==='goal'?'🎯 '+tr('architect.site'):k==='via'&&tg.length?'🔜 '+tr('architect.joins_in_brief_n',{n:tg[0].n}):k==='via'?'🪨 '+tr('puzzles.stepping_stone_optional'):k==='avoid'?'🚫 '+tr('architect.closed'):'📍 '+tr('puzzles.not_in_the_plan'); + const eb=c===A.hq?'🏠 '+tr('architect.hq'):A.gold.includes(c)?'🚨 '+tr('architect.gold_site'):k==='goal'?'🎯 '+tr('architect.site'):k==='via'?'🪨 '+tr('puzzles.stepping_stone_optional'):k==='avoid'?'🚫 '+tr('architect.closed'):'📍 '+tr('puzzles.not_in_the_plan'); let h=head(eb,esc(CITY[c].name),p?`${tr('common.your_pop')}${tr('puzzles.price_per_year',{price:fmt$(arPopCost(c))})}`:'')+'
'; if(c===A.hq)h+=`

${tr('architect.hq_lead')}

`;else if(A.gold.includes(c))h+=`

${tr('architect.gold_lead')}

`; - if(tg.length)h+=`
${tr('architect.coming_up')}
${tg.map(t=>`
${t.n} ${esc(arSum(arRun().briefs[t.n-1]))}
`).join('')}
`; if(k==='avoid'&&!p)return h+`

${tr('puzzles.not_this_one_find_a_way_around')}

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

${tr('architect.or_drag_a_tube_here')}

`;} if(k==='avoid')h+=`

${tr('architect.closed_lead')}

`; diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 42f15db..4874205 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -85,7 +85,7 @@ function drawFrame(now){ // Which cities show an offer bubble (a big one?) or an incident marker, worked out once for all of them. CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; - if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);if(S.ar)for(const v of vis)arDrawTags(v,sc);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); + if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); if(UI.mk)mkDraw(ks); // floaters for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;} diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js index 621b5e7..19041d1 100644 --- a/src/game/96-map/85-puzzle-cities.js +++ b/src/game/96-map/85-puzzle-cities.js @@ -14,7 +14,3 @@ function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); // In a puzzle every line says what it is ("2×100G · 70%"), and a selected POP lights up every pair it has links on. function pzLinkLab(grp,up,load,cap){if(S.ar)return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');} const pzLinkHot=grp=>!!(UI.sel&&UI.sel.type==='city'&&grp.some(x=>x.a===UI.sel.id||x.b===UI.sel.id)); -// Architect runs: what later briefs do here, as small numbered tags beside the city ("4🥇", "6🚫"). -function arDrawTags(v,sc){const tg=arTags(v.C.id).slice(0,2);if(!tg.length||!pzKind(v.C.id))return;const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc);const t=tg.map(x=>x.n+x.i).join(' '); - ctx.save();ctx.font=`900 ${Math.round((CM.far?10:12)*Math.max(0.9,Math.min(1.3,sc)))}px "Baloo 2", sans-serif`;const w=ctx.measureText(t).width+12,h=18,x=v.sx-r-w*0.35,yy=y-r-4; - ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(x,yy,w,h,9);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,x+w/2,yy+h/2+1);ctx.restore();} diff --git a/src/i18n/en.js b/src/i18n/en.js index d334d8c..f33be0d 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -28,7 +28,6 @@ "architect.closed_lead":"This city is closed now. Move out: remove the POP and find another way.", "architect.coast_to_coast":"Coast to Coast", "architect.coast_to_coast_joke":"From data center alley to Silicon Valley, one brief at a time.", -"architect.coming_up":"Coming up", "architect.cut_n_of_m":"Cut {n} of {m}…", "architect.cut_on_x_cuts_off_y":"A cut on {x} cuts off {y}.", "architect.cut_on_x_no_room":"A cut on {x} leaves no room on the detour. Short: {y}.", @@ -51,7 +50,6 @@ "architect.hide_other_cities":"Hide other cities", "architect.hq":"HQ", "architect.hq_lead":"Your servers live here. Every site needs a path to HQ.", -"architect.joins_in_brief_n":"Joins in brief {n}", "architect.keep_going":"Keep building", "architect.last_brief_done":"That was the last brief.", "architect.lay_a_tube_to":"Lay a tube to", @@ -61,14 +59,12 @@ "architect.move_out_of_city":"Move out of {city} first.", "architect.n_briefs":"{n} briefs", "architect.n_over_plan":"{n} over plan", -"architect.n_tubes":{"one":"{n} tube","other":"{n} tubes"}, "architect.new":"New", "architect.next_brief":"Next brief", "architect.next_brief_waiting":"The next brief is waiting.", "architect.next_run":"Next run", "architect.not_a_ring_yet":"Not a ring yet.", "architect.not_connected_yet_list":"Not connected to HQ yet: {list}", -"architect.numbers_on_the_map_show":"Numbers on the map show what later briefs bring. You can build there early.", "architect.or_drag_a_tube_here":"Or drag a tube here from one of your POPs.", "architect.pac_1":"Your servers live in Tokyo. Hong Kong first.", "architect.pac_2":"Singapore wants in.", diff --git a/src/styles/71-architect.css b/src/styles/71-architect.css index a31a7e3..e4f6d62 100644 --- a/src/styles/71-architect.css +++ b/src/styles/71-architect.css @@ -13,7 +13,6 @@ #pzBox .arbtns .b.big{flex:1 1 100%} .artubes{display:flex;justify-content:space-between;align-items:center;font-size:12.5px;font-weight:800;margin:4px 0}.artubes b{font-size:15px;letter-spacing:2px;color:var(--me)} .artubes em{font-style:normal;font-size:11.5px;letter-spacing:0;color:#B86A00}.artubes.over b{color:#B86A00} -.arplan{margin:6px 0;padding:5px 8px;border:2px dashed var(--line);border-radius:10px;font-size:12px;font-weight:700;color:var(--ink2)}.arplan b{display:inline-block;min-width:14px;color:var(--ink)} /* Laptops and up: a bigger card, easier to read at a glance */ @media (min-width:761px) and (min-height:501px){ #pzBox.ar{width:390px;padding:14px 18px 16px} @@ -21,7 +20,7 @@ #pzBox.ar .arsteps i{height:9px} #pzBox.ar .arbrief{font-size:17.5px;margin:4px 0 10px} #pzBox.ar .arsite{font-size:14px;padding:2px 10px} - #pzBox.ar .arline,#pzBox.ar .arrev,#pzBox.ar .artubes,#pzBox.ar .pzbud .kv,#pzBox.ar .arplan{font-size:14px} + #pzBox.ar .arline,#pzBox.ar .arrev,#pzBox.ar .artubes,#pzBox.ar .pzbud .kv{font-size:14px} #pzBox.ar .artubes b{font-size:19px}#pzBox.ar .pzbud .bar{height:12px} #pzBox.ar .arbtns .b.sm{font-size:13px;padding:5px 11px} } diff --git a/tests/architect.test.js b/tests/architect.test.js index c17929f..d54d1ac 100644 --- a/tests/architect.test.js +++ b/tests/architect.test.js @@ -38,7 +38,11 @@ test('architect runs: the chaos monkey finds a shared trench, edits clear the cu const { ev, errors } = load(); ev("ACT.pzArStart({id:'euro'})"); assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden'); - assert.deepEqual(JSON.parse(ev("JSON.stringify([arHide('dus'),arTags('dus'),arTags('fra').map(t=>t.n+t.i)])")), [false, [{ n: 6, i: '🚨' }], ['3🚨', '6🚫']], 'later briefs show on the map, numbered'); + assert.equal(ev("arHide('dus')"), false); + // Later briefs stay a surprise: nothing on the map or a city card says where the run goes next. + assert.equal(ev("typeof arTags"), 'undefined'); + ev("UI.sel={type:'city',id:'fra'};renderPanel()"); + assert.doesNotMatch(ev("document.getElementById('panelBody')?.textContent||''"), /brief \d|Coming up/i); ev('ACT.pzArAll()'); assert.equal(ev("arHide('lis')"), false, 'and shown on request'); ev('ACT.pzArAll()'); @@ -99,7 +103,6 @@ test('architect runs: a ring goal needs one cycle through its cities', () => { assert.match(ev('arEval().why'), /ring/i); lay(ev, 'lon', 'par', 'pasdc'); assert.equal(ev("arRingOk(['ams','par','lon'])&&arEval().ready"), true); - assert.ok(ev("arSum(arRun().briefs[5])").includes('Frankfurt'), 'the plan shows what is coming'); assert.deepEqual(errors, []); }); From b04e1e22c1d77d33d75086a18984843fb3380dc2 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 11:36:51 +0100 Subject: [PATCH 150/181] Architect runs: the chaos monkey leaves when you move on to the next brief --- src/game/60-features/96-architect.js | 2 +- tests/architect.test.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/game/60-features/96-architect.js b/src/game/60-features/96-architect.js index 1fb2f5a..61e2bc1 100644 --- a/src/game/60-features/96-architect.js +++ b/src/game/60-features/96-architect.js @@ -125,7 +125,7 @@ function arApply(i){const A=S.ar,P=S.pz,b=arRun().briefs[i];A.bi=i; arDemand();A.start=arSnapStr();UI.pzHist=[];UI.sel=null;UI.arFail=null; compute();pzCam();renderAll(); toast(`${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}
${esc(b.t)}`,'goal');sfx('click');} -function arNext(){if(!arOn())return;const e=arEval();if(!e.passed)return;if(arLast()){arResults(true);return;}S.ar.over+=e.tubes.over;arApply(S.ar.bi+1);} +function arNext(){if(!arOn())return;const e=arEval();if(!e.passed)return;mkStop();if(arLast()){arResults(true);return;}S.ar.over+=e.tubes.over;arApply(S.ar.bi+1);} function arReset(){const o=JSON.parse(S.ar.start);S.pops=o.p;S.links=o.l;S.pairMet=o.m||{};S.ar.sunk=o.k||0;arDemand();UI.sel=null;} // Tubes over plan in the run so far, this brief included. const arOver=()=>S.ar.over+arTubes().over; diff --git a/tests/architect.test.js b/tests/architect.test.js index d54d1ac..8439242 100644 --- a/tests/architect.test.js +++ b/tests/architect.test.js @@ -23,7 +23,7 @@ test('architect runs: every reference passes each brief, on plan and within budg plan.forEach((steps, i) => { for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s); assert.equal(review(ev), true, `${id} brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`); - if (i < plan.length - 1) ev('ACT.pzArNext()'); + if (i < plan.length - 1) { ev('ACT.pzArNext()'); assert.equal(ev('UI.mk'), null, `${id}: the monkey leaves with the next brief`); } }); assert.equal(ev('arOver()'), 0, `${id}: never over a brief's tubes`); assert.equal(ev('arSpend()<=arRun().budget'), true, `${id}: within budget`); From 87364af55d3b31f1dd3ca1529b09494d0dd3d7e9 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 11:42:34 +0100 Subject: [PATCH 151/181] Architect runs: a skipped review that passes still ends with the monkey's cheer --- src/game/96-map/87-chaos-monkey.js | 3 ++- tests/architect.test.js | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/game/96-map/87-chaos-monkey.js b/src/game/96-map/87-chaos-monkey.js index d9ccfde..8deeec2 100644 --- a/src/game/96-map/87-chaos-monkey.js +++ b/src/game/96-map/87-chaos-monkey.js @@ -13,7 +13,8 @@ function mkRun(l,dur,bad){const m=UI.mk;if(!m)return;const [x,y]=mkMid(l);m.fx=m function mkSpray(m){for(let i=0;i<(m.bad?26:16);i++){const a=Math.PI*2*i/(m.bad?26:16)+((i*37)%10)/10,v=0.05+((i*53)%10)/180; m.spray.push({x:m.tx,y:m.ty,vx:Math.cos(a)*v,vy:Math.sin(a)*v-0.06,c:m.bad?(i%3?'#FF4D5E':'#FFD23F'):MK_COLS[i%MK_COLS.length],t:animT,s:i%4===0?(m.bad?'💥':'✂️'):null});}} // The review is over: a cheer when everything held, a tantrum where it broke. -function mkEnd(ok){const m=UI.mk;if(!m)return;m.mood=ok?'cheer':'dance';m.t0=animT;} +function mkEnd(ok){const m=UI.mk;if(!m)return;// a pending spray (the review was skipped mid-run) would override the cheer + m.sprayAt=null;m.mood=ok?'cheer':'dance';m.t0=animT;} function mkStop(){UI.mk=null;} function mkDraw(ks){const m=UI.mk;if(!m)return; const p=Math.min(1,(animT-m.t0)/m.dur),e=p<0.5?2*p*p:1-Math.pow(-2*p+2,2)/2; diff --git a/tests/architect.test.js b/tests/architect.test.js index 8439242..322bcbc 100644 --- a/tests/architect.test.js +++ b/tests/architect.test.js @@ -23,6 +23,7 @@ test('architect runs: every reference passes each brief, on plan and within budg plan.forEach((steps, i) => { for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s); assert.equal(review(ev), true, `${id} brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`); + assert.deepEqual(JSON.parse(ev('JSON.stringify([UI.mk.mood,UI.mk.sprayAt])')), ['cheer', null], `${id}: a skipped review that passes still ends in a cheer`); if (i < plan.length - 1) { ev('ACT.pzArNext()'); assert.equal(ev('UI.mk'), null, `${id}: the monkey leaves with the next brief`); } }); assert.equal(ev('arOver()'), 0, `${id}: never over a brief's tubes`); From cbb7ca8772f3728ceec6eeb753aaf12c177a8ce1 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 11:44:22 +0100 Subject: [PATCH 152/181] Badges: Met the Backhoe becomes Met the Chaos Monkey Earned on the monkey's first visit instead of any fiber cut; the badge keeps its id, so ones already earned carry over. Monkey-proof gets a shield. The monkey's cheer also cancels a spray still pending from its last hop. --- CHANGELOG.md | 2 +- site/i18n/de.js | 4 ++-- site/i18n/es.js | 4 ++-- site/i18n/fr.js | 4 ++-- site/i18n/it.js | 4 ++-- site/i18n/pt.js | 4 ++-- src/game/85-incidents/40-chaos-monkey.js | 1 + src/game/88-days/20-badges.js | 5 +++-- src/game/96-map/87-chaos-monkey.js | 3 ++- src/i18n/en.js | 4 ++-- tests/chaos-monkey.test.js | 10 ++++++++++ tests/issues.test.js | 2 +- 12 files changed, 30 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a605d6..1a3466c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 -- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. +- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. - The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. - Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. - Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. diff --git a/site/i18n/de.js b/site/i18n/de.js index a9aa838..1e5b775 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -37,6 +37,7 @@ "badges.fire_the_hackback_3000tm_and_flatten":"Feuere den HackBack 3000™ ab und plätte einen Unschuldigen.", "badges.friend_of_giants":"Freund der Riesen", "badges.get_a_subsea_cable_bitten_by":"Lass ein Seekabel von einem Hai anknabbern.", +"badges.get_a_visit_from_the_chaos_monkey":"Bekomme Besuch vom Chaos-Affen.", "badges.get_bitten_by_sharks_3_times":"Werde in einem Spiel dreimal von Haien gebissen.", "badges.get_de_peered_by_a_big":"Werde von einem großen Netz de-peert.", "badges.go_transit_free":"Werde transitfrei.", @@ -44,7 +45,6 @@ "badges.got_total_this_game_ever_ever":"{got}/{total} in diesem Spiel · {ever} insgesamt", "badges.haggle_a_de_kicks_quote_down":"Handle ein DE-KICKS-Angebot herunter.", "badges.have_a_cable_cut_by_a":"Lass ein Kabel von einem schleifenden Anker kappen.", -"badges.have_a_fiber_cut":"Erlebe einen Faserbruch.", "badges.have_a_second_site_in_3":"Habe in 3 Städten einen zweiten Standort.", "badges.have_auto_te_move_100_gbps":"Lass Auto-TE auf einen Schlag 100 Gbps auf Ausweichpfade verschieben.", "badges.have_pops_in_50_cities":"Habe POPs in 50 Städten.", @@ -67,7 +67,7 @@ "badges.live_through_the_day_half_the":"Überlebe den Tag, an dem das halbe Internet ausfiel.", "badges.lose_a_metro_ring_to_one":"Verliere einen Metro-Ring an einen einzigen Bagger.", "badges.lose_fiber_to_a_llama_herd":"Verliere Glasfaser an eine Lamaherde.", -"badges.met_the_backhoe":"Den Bagger kennengelernt", +"badges.met_the_chaos_monkey":"Den Chaos-Affen kennengelernt", "badges.monkey_proof":"Affensicher", "badges.never_paid_list_price":"Nie den Listenpreis bezahlt", "badges.opt_out_of_3_auto_enrolled":"Kündige 3 automatisch gebuchte Zusatzleistungen.", diff --git a/site/i18n/es.js b/site/i18n/es.js index d01b621..de095d6 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -35,6 +35,7 @@ "badges.fire_the_hackback_3000tm_and_flatten":"Dispara el HackBack 3000™ y arrasa a un inocente.", "badges.friend_of_giants":"Amigo de gigantes", "badges.get_a_subsea_cable_bitten_by":"Haz que un tiburón muerda un cable submarino.", +"badges.get_a_visit_from_the_chaos_monkey":"Recibe la visita del mono del caos.", "badges.get_bitten_by_sharks_3_times":"Que te muerdan los tiburones 3 veces en una partida.", "badges.get_de_peered_by_a_big":"Que una red grande te quite el peering.", "badges.go_transit_free":"Sé libre de tránsito.", @@ -42,7 +43,6 @@ "badges.got_total_this_game_ever_ever":"{got}/{total} en esta partida · {ever} en total", "badges.haggle_a_de_kicks_quote_down":"Regatea a la baja una oferta de DE-KICKS.", "badges.have_a_cable_cut_by_a":"Que un ancla arrastrada corte un cable.", -"badges.have_a_fiber_cut":"Sufre un corte de fibra.", "badges.have_a_second_site_in_3":"Ten una segunda sede en 3 áreas metropolitanas.", "badges.have_auto_te_move_100_gbps":"Haz que Auto-TE mueva 100 Gbps a rutas alternativas de golpe.", "badges.have_pops_in_50_cities":"Ten POPs en 50 ciudades.", @@ -65,7 +65,7 @@ "badges.live_through_the_day_half_the":"Sobrevive al día en que se cayó medio internet.", "badges.lose_a_metro_ring_to_one":"Pierde un anillo metropolitano por culpa de una sola retroexcavadora.", "badges.lose_fiber_to_a_llama_herd":"Pierde fibra por culpa de una manada de llamas.", -"badges.met_the_backhoe":"Conoció a la retroexcavadora", +"badges.met_the_chaos_monkey":"Conoció al mono del caos", "badges.monkey_proof":"A prueba de monos", "badges.never_paid_list_price":"Nunca pagó precio de lista", "badges.opt_out_of_3_auto_enrolled":"Rechaza 3 complementos de alta automática.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index f2cfbad..19870ef 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -35,6 +35,7 @@ "badges.fire_the_hackback_3000tm_and_flatten":"Lance le HackBack 3000™ et écrase un innocent.", "badges.friend_of_giants":"Ami des géants", "badges.get_a_subsea_cable_bitten_by":"Fais mordre un câble sous-marin par un requin.", +"badges.get_a_visit_from_the_chaos_monkey":"Reçois la visite du singe du chaos.", "badges.get_bitten_by_sharks_3_times":"Fais-toi mordre par des requins 3 fois dans une même partie.", "badges.get_de_peered_by_a_big":"Fais-toi couper le peering par un gros réseau.", "badges.go_transit_free":"Deviens transit-free.", @@ -42,7 +43,6 @@ "badges.got_total_this_game_ever_ever":"{got}/{total} dans cette partie · {ever} au total", "badges.haggle_a_de_kicks_quote_down":"Fais baisser un devis DE-KICKS en négociant.", "badges.have_a_cable_cut_by_a":"Fais couper un câble par une ancre qui traîne.", -"badges.have_a_fiber_cut":"Subis une coupure de fibre.", "badges.have_a_second_site_in_3":"Aie un second site dans 3 métropoles.", "badges.have_auto_te_move_100_gbps":"Fais déplacer 100 Gbps d’un coup sur des chemins alternatifs par l’Auto-TE.", "badges.have_pops_in_50_cities":"Aie des POP dans 50 villes.", @@ -65,7 +65,7 @@ "badges.live_through_the_day_half_the":"Survis au jour où la moitié d’internet est tombée.", "badges.lose_a_metro_ring_to_one":"Perds un anneau métropolitain à cause d’une seule pelleteuse.", "badges.lose_fiber_to_a_llama_herd":"Perds de la fibre à cause d’un troupeau de lamas.", -"badges.met_the_backhoe":"Rencontre du troisième godet", +"badges.met_the_chaos_monkey":"Rencontre avec le singe du chaos", "badges.monkey_proof":"À l'épreuve des singes", "badges.never_paid_list_price":"Jamais au prix catalogue", "badges.opt_out_of_3_auto_enrolled":"Désactive 3 options souscrites d’office.", diff --git a/site/i18n/it.js b/site/i18n/it.js index bc48096..b0565fd 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -35,6 +35,7 @@ "badges.fire_the_hackback_3000tm_and_flatten":"Spara con l’HackBack 3000™ e travolgi un innocente.", "badges.friend_of_giants":"Amico dei giganti", "badges.get_a_subsea_cable_bitten_by":"Fatti mordere un cavo sottomarino da uno squalo.", +"badges.get_a_visit_from_the_chaos_monkey":"Ricevi la visita della scimmia del caos.", "badges.get_bitten_by_sharks_3_times":"Fatti mordere dagli squali 3 volte in una partita.", "badges.get_de_peered_by_a_big":"Fatti togliere il peering da una grande rete.", "badges.go_transit_free":"Diventa transit-free.", @@ -42,7 +43,6 @@ "badges.got_total_this_game_ever_ever":"{got}/{total} in questa partita · {ever} in totale", "badges.haggle_a_de_kicks_quote_down":"Tira giù un preventivo DE-KICKS trattando.", "badges.have_a_cable_cut_by_a":"Fatti tagliare un cavo da un’ancora trascinata.", -"badges.have_a_fiber_cut":"Subisci un taglio di fibra.", "badges.have_a_second_site_in_3":"Apri un secondo sito in 3 città.", "badges.have_auto_te_move_100_gbps":"Fai spostare all’Auto-TE 100 Gbps su percorsi alternativi in un colpo solo.", "badges.have_pops_in_50_cities":"Apri POP in 50 città.", @@ -65,7 +65,7 @@ "badges.live_through_the_day_half_the":"Sopravvivi al giorno in cui è caduta mezza internet.", "badges.lose_a_metro_ring_to_one":"Perdi un anello metro per colpa di una sola ruspa.", "badges.lose_fiber_to_a_llama_herd":"Perdi la fibra per colpa di un branco di lama.", -"badges.met_the_backhoe":"Incontro con la ruspa", +"badges.met_the_chaos_monkey":"Incontro con la scimmia del caos", "badges.monkey_proof":"A prova di scimmia", "badges.never_paid_list_price":"Mai pagato il listino", "badges.opt_out_of_3_auto_enrolled":"Disattiva 3 add-on attivati d’ufficio.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 88db3e9..69b353d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -35,6 +35,7 @@ "badges.fire_the_hackback_3000tm_and_flatten":"Dispare o HackBack 3000™ e derrube um inocente.", "badges.friend_of_giants":"Amigo dos gigantes", "badges.get_a_subsea_cable_bitten_by":"Tenha um cabo submarino mordido por um tubarão.", +"badges.get_a_visit_from_the_chaos_monkey":"Receba a visita do macaco do caos.", "badges.get_bitten_by_sharks_3_times":"Seja mordido por tubarões 3 vezes numa partida.", "badges.get_de_peered_by_a_big":"Leve um corte de peering de uma rede grande.", "badges.go_transit_free":"Fique transit-free.", @@ -42,7 +43,6 @@ "badges.got_total_this_game_ever_ever":"{got}/{total} nesta partida · {ever} no total", "badges.haggle_a_de_kicks_quote_down":"Pechinche um orçamento da DE-KICKS.", "badges.have_a_cable_cut_by_a":"Tenha um cabo cortado por uma âncora arrastada.", -"badges.have_a_fiber_cut":"Sofra um corte de fibra.", "badges.have_a_second_site_in_3":"Tenha um segundo site em 3 cidades.", "badges.have_auto_te_move_100_gbps":"Faça o Auto-TE mover 100 Gbps para caminhos alternativos de uma vez.", "badges.have_pops_in_50_cities":"Tenha POPs em 50 cidades.", @@ -65,7 +65,7 @@ "badges.live_through_the_day_half_the":"Sobreviva ao dia em que metade da internet caiu.", "badges.lose_a_metro_ring_to_one":"Perca um anel metro para uma única retroescavadeira.", "badges.lose_fiber_to_a_llama_herd":"Perca fibra para um rebanho de lhamas.", -"badges.met_the_backhoe":"Conheceu a retroescavadeira", +"badges.met_the_chaos_monkey":"Conheceu o macaco do caos", "badges.monkey_proof":"À prova de macaco", "badges.never_paid_list_price":"Nunca paguei preço de tabela", "badges.opt_out_of_3_auto_enrolled":"Cancele 3 add-ons ativados sem você pedir.", diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js index 09f93b2..6798c37 100644 --- a/src/game/85-incidents/40-chaos-monkey.js +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -26,6 +26,7 @@ function mkTick(d){const M=S.monkey;if(!M)return; if(d>=M.until){mkLeave();return;} if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}} function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121); + S.stats.mkMet=(S.stats.mkMet||0)+1; Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home}); toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive'); if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);} diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 37f33a3..d309736 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -4,7 +4,8 @@ const RARITY={c:{n:tr('common.common'),col:'#16A866'},r:{n:tr('common.rare'),col const st=()=>S.stats||{}; const BADGES=[ {id:'hello',i:'👋',t:tr('common.hello_neighbour'),d:tr('badges.bring_up_your_first_peering_session'),r:'c',ok:()=>R.sessions>=1}, - {id:'backhoe',i:'🚜',t:tr('badges.met_the_backhoe'),d:tr('badges.have_a_fiber_cut'),r:'c',ok:()=>(st().by||{}).cut>=1}, + // Keeps its old id so badges already earned (in saves and the hall of fame) carry over. + {id:'backhoe',i:'🐒',t:tr('badges.met_the_chaos_monkey'),d:tr('badges.get_a_visit_from_the_chaos_monkey'),r:'c',ok:()=>(st().mkMet||0)>=1}, {id:'debt',i:'🏦',t:tr('badges.in_debt_we_trust'),d:tr('badges.take_out_a_loan'),r:'c',ok:()=>(st().loans||0)>=1||(S.loans||[]).length>0}, {id:'twins',i:'👯',t:tr('common.twins'),d:tr('badges.run_two_routers_in_one_pop'),r:'c',ok:()=>Object.values(S.pops).some(p=>(p.routers||1)>=2)}, {id:'shark',i:'🦈',t:tr('common.shark_week'),d:tr('badges.get_a_subsea_cable_bitten_by'),r:'r',ok:()=>(st().sharks||0)>=1}, @@ -68,7 +69,7 @@ const BADGES=[ {id:'toaster',i:'🍞',t:tr('common.toaster_wrangler'),d:tr('badges.weather_a_ddos_with_your_defences'),r:'c',ok:()=>(st().ddosHeld||0)>=1}, {id:'cleanpipe',i:'🚿',t:tr('common.clean_pipes'),d:tr('badges.turn_on_a_transit_clean_pipe'),r:'r',ok:()=>S.transit.some(t=>t.clean)}, {id:'lamb',i:'🐐',t:tr('common.sacrificial_lamb'),d:tr('badges.run_a_sacrificial_pni_choke_point'),r:'r',ok:()=>S.pni.some(p=>p.sacrif)}, - {id:'monkey',i:'🐒',t:tr('badges.monkey_proof'),d:tr('badges.outlast_a_chaos_monkey_visit'),r:'e',ok:()=>(st().mkSurv||0)>=1}, + {id:'monkey',i:'🛡️',t:tr('badges.monkey_proof'),d:tr('badges.outlast_a_chaos_monkey_visit'),r:'e',ok:()=>(st().mkSurv||0)>=1}, {id:'flood',i:'🌊',t:tr('badges.held_the_flood'),d:tr('badges.weather_a_multi_terabit_ddos'),r:'e',ok:()=>(st().ddosMonster||0)>=1}, {id:'skynot',i:'🤖',t:tr('common.skynot_smiles'),d:tr('badges.land_a_hackback_3000tm_that_actually'),r:'e',secret:true,ok:()=>(st().hackWin||0)>=1}, {id:'zero',i:'🕳️',t:tr('badges.zero_peers_given'),d:tr('badges.reach_tier_2_with_every_single'),r:'l',secret:true,ok:()=>isTier2()&&!Object.keys(S.peers).length&&!S.pni.length}, diff --git a/src/game/96-map/87-chaos-monkey.js b/src/game/96-map/87-chaos-monkey.js index 7919764..373f18d 100644 --- a/src/game/96-map/87-chaos-monkey.js +++ b/src/game/96-map/87-chaos-monkey.js @@ -13,7 +13,8 @@ function mkRun(l,dur,bad){const m=UI.mk;if(!m)return;const [x,y]=mkMid(l);m.fx=m function mkSpray(m){for(let i=0;i<(m.bad?26:16);i++){const a=Math.PI*2*i/(m.bad?26:16)+((i*37)%10)/10,v=0.05+((i*53)%10)/180; m.spray.push({x:m.tx,y:m.ty,vx:Math.cos(a)*v,vy:Math.sin(a)*v-0.06,c:m.bad?(i%3?'#FF4D5E':'#FFD23F'):MK_COLS[i%MK_COLS.length],t:animT,s:i%4===0?(m.bad?'💥':'✂️'):null});}} // It is over: a cheer when everything held, a tantrum where it broke; with bye it then leaves the map. -function mkEnd(ok,bye){const m=UI.mk;if(!m)return;m.mood=ok?'cheer':'dance';m.t0=animT;m.bye=bye?animT:0;} +function mkEnd(ok,bye){const m=UI.mk;if(!m)return;// a pending spray (the review was skipped mid-run) would override the cheer + m.sprayAt=null;m.mood=ok?'cheer':'dance';m.t0=animT;m.bye=bye?animT:0;} function mkStop(){UI.mk=null;} function mkDraw(ks){const m=UI.mk;if(!m)return;if(m.bye&&animT-m.bye>2600){mkStop();return;} if(m.mood==='snip'&&animT-m.t0>1500){m.mood='stand';m.t0=animT;} diff --git a/src/i18n/en.js b/src/i18n/en.js index bdf3fa2..15850a5 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -36,6 +36,7 @@ "badges.fire_the_hackback_3000tm_and_flatten":"Fire the HackBack 3000™ and flatten an innocent.", "badges.friend_of_giants":"Friend of Giants", "badges.get_a_subsea_cable_bitten_by":"Get a subsea cable bitten by a shark.", +"badges.get_a_visit_from_the_chaos_monkey":"Get a visit from the chaos monkey.", "badges.get_bitten_by_sharks_3_times":"Get bitten by sharks 3 times in one game.", "badges.get_de_peered_by_a_big":"Get de-peered by a big network.", "badges.go_transit_free":"Go transit-free.", @@ -43,7 +44,6 @@ "badges.got_total_this_game_ever_ever":"{got}/{total} this game · {ever} ever", "badges.haggle_a_de_kicks_quote_down":"Haggle a DE-KICKS quote down.", "badges.have_a_cable_cut_by_a":"Have a cable cut by a dragged anchor.", -"badges.have_a_fiber_cut":"Have a fiber cut.", "badges.have_a_second_site_in_3":"Have a second site in 3 metros.", "badges.have_auto_te_move_100_gbps":"Have Auto-TE move 100 Gbps onto alternate paths at once.", "badges.have_pops_in_50_cities":"Have POPs in 50 cities.", @@ -66,7 +66,7 @@ "badges.live_through_the_day_half_the":"Live through the day half the internet went down.", "badges.lose_a_metro_ring_to_one":"Lose a metro ring to one backhoe.", "badges.lose_fiber_to_a_llama_herd":"Lose fiber to a llama herd.", -"badges.met_the_backhoe":"Met the Backhoe", +"badges.met_the_chaos_monkey":"Met the Chaos Monkey", "badges.monkey_proof":"Monkey-proof", "badges.never_paid_list_price":"Never Paid List Price", "badges.opt_out_of_3_auto_enrolled":"Opt out of 3 auto-enrolled add-ons.", diff --git a/tests/chaos-monkey.test.js b/tests/chaos-monkey.test.js index 4089064..4e75a9e 100644 --- a/tests/chaos-monkey.test.js +++ b/tests/chaos-monkey.test.js @@ -97,3 +97,13 @@ test('saves keep the monkey; old and broken saves are repaired', () => { ev('for(let i=0;i<5;i++)dayTick()'); assert.deepEqual(errors, []); }); + +test('"Met the Chaos Monkey" comes from a visit, not from an ordinary fiber cut', () => { + const { ev, errors } = net('oncall'); + ev("fireFailure('cut');checkBadges()"); + assert.equal(ev('S.ach.backhoe===undefined'), true, 'a cut alone is not the monkey'); + ev('S.monkey.next=S.day;dayTick();checkBadges()'); + assert.notEqual(ev('S.ach.backhoe'), undefined); + assert.equal(ev("BADGES.find(b=>b.id==='backhoe').t"), 'Met the Chaos Monkey'); + assert.deepEqual(errors, []); +}); diff --git a/tests/issues.test.js b/tests/issues.test.js index 37b25dc..3ccb226 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -154,7 +154,7 @@ test('rare badges hook into incidents and deals', () => { const { ev, errors } = load(); base(ev); ev("addInc({type:'cut',ref:'x',until:S.day+1,msg:'A crocodile took a bite. A ship dragged its anchor.'});checkGoals()"); - assert.ok(ev("S.ach.croc!==undefined&&S.ach.anchor!==undefined&&S.ach.backhoe!==undefined")); + assert.ok(ev("S.ach.croc!==undefined&&S.ach.anchor!==undefined&&S.ach.backhoe===undefined"), "a cut alone earns no Met the Chaos Monkey"); ev("S.stats.survived=100;checkGoals()"); assert.ok(ev("S.ach.unbreak!==undefined")); assert.equal(ev("BADGES.length>=46&&new Set(BADGES.map(b=>b.id)).size===BADGES.length"), true); From 5216a66db3269748cc0550b73cf0a1866873d94e Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 11:47:22 +0100 Subject: [PATCH 153/181] Architect runs: a tube goes red when the monkey snips it, and heals as it runs off Each review step is now a run (the last cut is whole again) and a snip on arrival, so the red follows the monkey. --- src/game/60-features/96-architect.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/game/60-features/96-architect.js b/src/game/60-features/96-architect.js index 61e2bc1..a6b22a5 100644 --- a/src/game/60-features/96-architect.js +++ b/src/game/60-features/96-architect.js @@ -8,7 +8,7 @@ cut, everything still connected gets all of its traffic. Tubes come in three sizes; routers follow by themselves (the cheapest model that takes the tubes), and traffic finds the detour by itself (Auto-TE): models, ports and metrics are someone else's job. */ -const AR_KEY='sot-architect',AR_TIER=1,AR_TIERS=[0,1,2],AR_STEP=1000; +const AR_KEY='sot-architect',AR_TIER=1,AR_TIERS=[0,1,2],AR_RUN=550,AR_HOLD=650; // ms: the monkey's run to a tube, then how long the cut shows // A brief: add (new sites), gold (sites that must survive any single cut), ring (sites that must sit on one ring), drop // (close a city: no POP allowed there any more), dem {city: Gbps} (what a site pulls from HQ, 10G unless set; a later // brief can raise it), lat [a,b,ms] (the fastest path between two sites under ms), tubes (the @@ -140,19 +140,24 @@ function arShowStart(){if(!arOn()||UI.arShow)return;const e=arEval();if(!e.ready arStop(true);UI.sel=null;closeModal();UI.arBaseGot=arGot();UI.arShow={units:[...new Set(S.links.map(pzUnit))],i:-1,t:0,dark:[],short:[]};mkStart(S.ar.hq);arStep();} // One cut, routed: who goes dark, which gold sites with it, and who is still connected but short of room. function arCut(u){const ls=S.links.filter(l=>pzUnit(l)===u);for(const l of ls)l.cut=1;compute();const dark=arDark(u);return {ls,dark,gold:dark.filter(c=>S.ar.gold.includes(c)),short:arShort(dark)};} -function arStep(){const sh=UI.arShow;if(!sh||!arOn())return;for(const l of S.links)l.cut=0;sh.i++; +// The monkey sets off: the tube it last snipped is whole again, the next one stays whole until it gets there. +function arStep(now){const sh=UI.arShow;if(!sh||!arOn())return;for(const l of S.links)l.cut=0;sh.i++;sh.hit=false; if(sh.i>=sh.units.length){UI.arShow=null;compute();S.ar.passed=pzSig();renderAll();sfx('star');haptic(15); mkEnd(true);toast(`✅ ${tr('architect.review_passed')}
${arLast()?tr('architect.last_brief_done'):tr('architect.next_brief_waiting')}`,'good');if(arLast())setTimeout(()=>{if(arOn()&&S.ar.passed===pzSig())arResults(true);},900);return;} - const u=sh.units[sh.i],{ls,dark,gold,short}=arCut(u),l0=ls[0],got=arGot();sh.dark=dark;sh.short=short;sh.u=u; + const u=sh.units[sh.i];compute();renderAll();mkRun(S.links.find(l=>pzUnit(l)===u),AR_RUN/MK_RUN); + if(now)arHit();else sh.t=setTimeout(arHit,AR_RUN);} +// It has arrived and snips: who goes dark, and does a mission-critical site go with it? +function arHit(){const sh=UI.arShow;if(!sh||!arOn())return;sh.hit=true; + const u=sh.units[sh.i],{ls,dark,gold,short}=arCut(u),l0=ls[0];sh.dark=dark;sh.short=short;sh.u=u; floater((CITY[l0.a].x+CITY[l0.a].x+wrapDx(CITY[l0.a].x,CITY[l0.b].x))/2,(CITY[l0.a].y+CITY[l0.b].y)/2-26,l0.sub?tr('architect.anchor'):tr('architect.backhoe'),'#FF8A3D'); for(const c of dark)floater(CITY[c].x,CITY[c].y-34,gold.includes(c)?'💥 '+CITY[c].name:tr('architect.city_goes_dark',{city:CITY[c].name}),gold.includes(c)?'#FF4D5E':'#9AA3BE'); - for(const c of short)floater(CITY[c].x,CITY[c].y-34,tr('architect.city_short_g',{city:CITY[c].name,g:arG(arDem(c)-(got[c]||0))}),'#FF4D5E'); - const bad=gold.length||short.length;mkRun(l0,dark.length?AR_STEP*1.6:AR_STEP,bad);sfx(bad?'err':'click'); + for(const c of short)floater(CITY[c].x,CITY[c].y-34,tr('architect.city_short_g',{city:CITY[c].name,g:arG(arDem(c)-(arGot()[c]||0))}),'#FF4D5E'); + const bad=gold.length||short.length;if(UI.mk)UI.mk.bad=!!bad;sfx(bad?'err':'click'); if(bad){UI.arShow=null;UI.arFail={u,gold,dark,short};renderAll();haptic(30);return;} - renderAll();sh.t=setTimeout(arStep,dark.length?AR_STEP*1.6:AR_STEP);} + renderAll();sh.t=setTimeout(arStep,dark.length?AR_HOLD*1.7:AR_HOLD);} // Skip the show: check every cut at once, and stop at the first that breaks a gold site. function arShowSkip(){const sh=UI.arShow;if(!sh)return;clearTimeout(sh.t);for(const l of S.links)l.cut=0; - for(let i=sh.i+1;i Date: Fri, 30 Oct 2026 11:52:54 +0100 Subject: [PATCH 154/181] Architect runs: show whether tubes share a trench or take separate paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tubes in one trench are drawn as strands of one bundle with an orange '2× one trench' pill; separate paths bow well apart with a green '2 paths' pill. Cut tubes no longer show the backhoe: the monkey does the snipping. --- 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/96-map/50-link-geometry.js | 7 +++++-- src/game/96-map/60-draw.js | 10 ++++++++-- src/i18n/en.js | 2 ++ tests/architect.test.js | 12 ++++++++++++ 9 files changed, 37 insertions(+), 4 deletions(-) diff --git a/site/i18n/de.js b/site/i18n/de.js index 5a95062..f4418f0 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -59,7 +59,9 @@ "architect.line_3":"Auf Par oder besser. Der Chaos-Affe ist gelangweilt heimgegangen.", "architect.move_out_of_city":"Zieh zuerst aus {city} aus.", "architect.n_briefs":"{n} Aufträge", +"architect.n_in_one_trench":"{n}× ein Graben", "architect.n_over_plan":"{n} über Plan", +"architect.n_paths":"{n} Wege", "architect.new":"Neu", "architect.next_brief":"Nächster Auftrag", "architect.next_brief_waiting":"Der nächste Auftrag wartet.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 481f2a2..5868996 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -57,7 +57,9 @@ "architect.line_3":"En par o mejor. El mono del caos se fue a casa aburrido.", "architect.move_out_of_city":"Primero sal de {city}.", "architect.n_briefs":"{n} encargos", +"architect.n_in_one_trench":"{n}× una zanja", "architect.n_over_plan":"{n} por encima del plan", +"architect.n_paths":"{n} rutas", "architect.new":"Nuevo", "architect.next_brief":"Siguiente encargo", "architect.next_brief_waiting":"El siguiente encargo te espera.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index b84ff22..16b29fd 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -57,7 +57,9 @@ "architect.line_3":"Au par ou mieux. Le singe du chaos est rentré s’ennuyer chez lui.", "architect.move_out_of_city":"Quitte d’abord {city}.", "architect.n_briefs":"{n} briefs", +"architect.n_in_one_trench":"{n}× une tranchée", "architect.n_over_plan":"{n} au-delà du plan", +"architect.n_paths":"{n} chemins", "architect.new":"Nouveau", "architect.next_brief":"Brief suivant", "architect.next_brief_waiting":"Le brief suivant t’attend.", diff --git a/site/i18n/it.js b/site/i18n/it.js index de9a748..221be11 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -57,7 +57,9 @@ "architect.line_3":"In par o meglio. La scimmia del caos è tornata a casa annoiata.", "architect.move_out_of_city":"Prima lascia {city}.", "architect.n_briefs":"{n} incarichi", +"architect.n_in_one_trench":"{n}× una trincea", "architect.n_over_plan":"{n} oltre il piano", +"architect.n_paths":"{n} percorsi", "architect.new":"Nuovo", "architect.next_brief":"Prossimo incarico", "architect.next_brief_waiting":"Il prossimo incarico ti aspetta.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index df7ae8f..61b222b 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -57,7 +57,9 @@ "architect.line_3":"No par ou melhor. O macaco do caos foi para casa entediado.", "architect.move_out_of_city":"Saia de {city} primeiro.", "architect.n_briefs":"{n} pedidos", +"architect.n_in_one_trench":"{n}× uma vala", "architect.n_over_plan":"{n} acima do plano", +"architect.n_paths":"{n} rotas", "architect.new":"Novo", "architect.next_brief":"Próximo pedido", "architect.next_brief_waiting":"O próximo pedido está esperando.", diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index 2f6b4ea..adb0642 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -37,7 +37,8 @@ function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.dra ctx.globalAlpha=1;}}} function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit; const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} - const base=Math.max(4,Math.min(len*0.1,90)),step=Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?0.2:1)+Math.ceil(i/2)*step); + // Architect runs bow diverse paths well apart, so two routes never read as one. + const wide=S&&S.ar&&pzOn(),base=Math.max(4,Math.min(len*0.1,90)),step=wide?Math.min(30,len*.14):Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?(wide?0.9:0.2):1)+Math.ceil(i/2)*step); const mx=(A.x+bx)/2,my=(A.y+by)/2; const sg=Math.sign(off0)||1,mag=Math.abs(off0); // Bend around cities in the way, but gently: short links need less room, no curve bows out more than about a @@ -56,4 +57,6 @@ function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:l const g={ax:A.x,ay:A.y,bx,by,cx:best[0],cy:best[1],len};GEO.set(key,g);return g;} const qpt=(g,t)=>[(1-t)*(1-t)*g.ax+2*(1-t)*t*g.cx+t*t*g.bx,(1-t)*(1-t)*g.ay+2*(1-t)*t*g.cy+t*t*g.by]; const utilCol=u=>u<=0.001?'#AFC0D6':u<0.65?'#22C47A':u<0.9?'#FFAA1F':'#FF4D5E'; - +// How many separate paths (trenches or cables) join this tube's two cities. +const arPaths=l=>new Set(pairLinks(l.a,l.b).map(gKey)).size; +const AR_PILLS=[]; // filled while the links are drawn, painted after the cities diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 4874205..649f933 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -25,10 +25,11 @@ function drawFrame(now){ // cable systems drawCables(ks); // links + AR_PILLS.length=0; const far=lodFar(),PI=pairIdx(),LG=linkGroups(),GM=LG.map(g=>linkGeom(g[0],PI.get(edgeKey(g[0])))),busy=linesOnScreen(GM,ks)>MAP_BUSY; for(let gi=0;gi1,up=many?grp.filter(x=>!linkDown(x)):null; const gm=GM[gi],cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc',idle=!cut&&!bld&&load<1e-3&&(many?up.length>0&&up.every(x=>x.standby):!!l.standby); - const pz=pzOn(),sel=(UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id))||(pz&&pzLinkHot(grp));let lab=null; + const pz=pzOn(),arPz=pz&&!!S.ar,sel=(UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id))||(pz&&pzLinkHot(grp));let lab=null; const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1),np=gm.pts.length; if(SX.length0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]); + // Architect runs: tubes sharing one trench are drawn as strands of one bundle (one snip takes them all). + if(arPz&&many&&!far){ctx.strokeStyle='#1E2640';ctx.lineWidth=1.3;for(let j=1;jpolyAtXY(SX,SY,gm.cum,t); @@ -49,7 +52,8 @@ function drawFrame(now){ const rr2=far?1.6:Math.max(2.2,w*.42),base=now/1000*spd/Math.max(len,40);ctx.beginPath();for(let i=0;i1)){const k=arPaths(l);if(many||lineIdx(l,PI.get(edgeKey(l)))===0){AR_PILLS.push([mxx,my,many?tr('architect.n_in_one_trench',{n:grp.length}):'✓ '+tr('architect.n_paths',{n:k}),many]);}} else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} } } @@ -86,6 +90,8 @@ function drawFrame(now){ CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; if(pzOn()){for(const v of vis.slice().reverse())pzDrawCity(v,sc,now);}else for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly); + // Architect runs: what the tubes between two cities are (one trench, or separate paths), above the cities. + for(const [x,y,t,one] of AR_PILLS){ctx.font='800 11px "Baloo 2", sans-serif';const tw=ctx.measureText(t).width+12;ctx.fillStyle=one?'#FFE3C2':'#DDF7E7';ctx.strokeStyle=one?'#FF8A3D':'#16A866';ctx.lineWidth=2;rr(x-tw/2,y-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,x,y+1);} if(UI.mk)mkDraw(ks); // floaters for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;} diff --git a/src/i18n/en.js b/src/i18n/en.js index f33be0d..14f163c 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -58,7 +58,9 @@ "architect.line_3":"At par or better. The chaos monkey went home bored.", "architect.move_out_of_city":"Move out of {city} first.", "architect.n_briefs":"{n} briefs", +"architect.n_in_one_trench":"{n}× one trench", "architect.n_over_plan":"{n} over plan", +"architect.n_paths":"{n} paths", "architect.new":"New", "architect.next_brief":"Next brief", "architect.next_brief_waiting":"The next brief is waiting.", diff --git a/tests/architect.test.js b/tests/architect.test.js index 322bcbc..a245070 100644 --- a/tests/architect.test.js +++ b/tests/architect.test.js @@ -151,3 +151,15 @@ test('architect runs: a bigger tube brings a bigger router, and changing an old assert.equal(ev("(S.pops.ams.rgen||0)===0&&S.ar.sunk===" + sunk), true, 'undo puts it all back'); assert.deepEqual(errors, []); }); + +test('architect runs: the map tells two tubes in one trench from two separate paths', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'});ACT.pzArAll();S.cash=1e9"); + lay(ev, 'ams', 'fra', 'land', 1); lay(ev, 'ams', 'fra', 'land', 0); + lay(ev, 'ams', 'par', 'land', 1); lay(ev, 'ams', 'par', 'land', 1); + assert.equal(ev("arPaths(S.links.find(l=>l.b==='fra'||l.a==='fra'))"), 1, 'same trench: one path'); + assert.equal(ev("arPaths(S.links.find(l=>l.b==='par'||l.a==='par'))"), 2, 'diverse: two paths'); + ev("cam.x=CITY.ams.x;cam.y=CITY.ams.y;cam.z=2.4;drawFrame(performance.now())"); + assert.deepEqual(JSON.parse(ev("JSON.stringify(AR_PILLS.map(p=>p[2]).sort())")), ['2× one trench', '✓ 2 paths']); + assert.deepEqual(errors, []); +}); From 9fc38fa4f4e9842edb7f1512c102a618d9f16b3d Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 12:24:53 +0100 Subject: [PATCH 155/181] Puzzles: the chaos monkey acts out the N-1 star in every puzzle When a build earns a new star the monkey snips each trench and cable in turn on the map, and cities that lose traffic say how much; then the stars show. It can be let loose again or skipped. Puzzle texts talk about the chaos monkey instead of a backhoe. --- CHANGELOG.md | 1 + site/i18n/de.js | 14 +++++--- site/i18n/es.js | 14 +++++--- site/i18n/fr.js | 14 +++++--- site/i18n/it.js | 14 +++++--- site/i18n/pt.js | 14 +++++--- src/game/60-features/92-puzzles.js | 10 +++--- src/game/60-features/97-puzzle-monkey.js | 23 +++++++++++++ src/game/90-actions/95-puzzles.js | 3 ++ src/game/95-modals/95-puzzles.js | 5 +-- src/i18n/en.js | 14 +++++--- tests/puzzle-monkey.test.js | 42 ++++++++++++++++++++++++ tests/puzzles.test.js | 6 ++-- 13 files changed, 134 insertions(+), 40 deletions(-) create mode 100644 src/game/60-features/97-puzzle-monkey.js create mode 100644 tests/puzzle-monkey.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a3466c..a099b36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. - A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. - The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. - Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. diff --git a/site/i18n/de.js b/site/i18n/de.js index 1e5b775..0e537da 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2884,8 +2884,8 @@ "progress.under_attack_now":"Gerade unter Beschuss", "progress.your_score_peak_traffic":"Dein Ergebnis: Spitzen-Traffic", "progress.your_traffic_to_and_from_asia":"Dein Traffic von und nach Asien", -"puzzles.a_backhoe_walks_into_your_network":"Kommt ein Bagger in dein Netz. Nichts passiert.", "puzzles.a_bigger_boat":"Wir brauchen ein größeres Boot", +"puzzles.a_chaos_monkey_walks_into_your_network":"Kommt ein Chaos-Affe in dein Netz. Nichts passiert.", "puzzles.a_cut_on_where_drops_g":"Ein Schnitt bei {where} kostet {g}", "puzzles.a_different_route":"Eine andere Route", "puzzles.a_diverse_route":"Eine diverse Route (+40%)", @@ -2909,11 +2909,12 @@ "puzzles.carry_list":"Zu transportieren: {list}.", "puzzles.carrying":"Transportiert", "puzzles.carrying_on_this_pair":"Transportiert (alle {n} Links dieses Paars)", +"puzzles.city_loses_g":"{city} −{g}", "puzzles.content_lives_in_list":"Die Inhalte liegen in {list}: Privatkunden ziehen vom nächsten.", "puzzles.copied_paste_it_anywhere":"Kopiert! Füg es irgendwo ein:
{t}", "puzzles.de_kicks_sales_has_your_number":"Der DE-KICKS-Vertrieb hat deine Nummer. Verbinde Deutschland ohne Frankfurt.", "puzzles.delivered":"Geliefert", -"puzzles.diverse_route_40_survives_a_backhoe":"Getrennte Trasse (+40 %, übersteht einen Bagger)", +"puzzles.diverse_route_40_survives_the_monkey":"Getrennte Trasse (+40 %, übersteht den Chaos-Affen)", "puzzles.down_under_up_and_running":"Down Under, up and running", "puzzles.drag_from_a_pink_pop_to":"Zieh von einem pinken POP zu einer anderen Stadt, um eine Wave zu mieten", "puzzles.drag_from_this_pop_onto_another":"Zieh von diesem POP auf eine andere Puzzle-Stadt oder wähl eine hier.", @@ -2940,15 +2941,17 @@ "puzzles.hub_cap":"Radkappe", "puzzles.includes_a_new_pop_in_city":"Mit neuem POP in {city} ({price} für ein Jahr).", "puzzles.installed":"verbaut", -"puzzles.it_works_finance_and_the_backhoe":"Läuft! Die Buchhaltung und der Bagger hätten da noch Fragen.", +"puzzles.it_works_finance_and_the_monkey":"Läuft! Die Buchhaltung und der Chaos-Affe hätten da noch Fragen.", "puzzles.keep_building":"Weiterbauen", "puzzles.kiwi_fruit_salad":"Kiwi-Obstsalat", "puzzles.latency":"Latenz", "puzzles.latency_caps":"Latenzgrenzen", "puzzles.lease_a_wave_to":"Wave mieten nach", +"puzzles.let_the_chaos_monkey_loose":"🐒 Lass den Chaos-Affen los", "puzzles.loading_this_week_s_puzzle":"Lade das Puzzle dieser Woche…", "puzzles.london_wants_half_a_terabit_your":"London will ein halbes Terabit, und deine Router sind von eBuy.", "puzzles.model_facts":"{cap} · {ports} Ports · Waves bis {wave}", +"puzzles.monkey_snip":"🐒 Schnipp!", "puzzles.more_puzzles":"Mehr Puzzles", "puzzles.n_1_club":"N-1-Club", "puzzles.n_1_deliver_everything_first":"N-1: erst alles liefern", @@ -2978,7 +2981,7 @@ "puzzles.not_through_frankfurt":"Nicht über Frankfurt", "puzzles.off_limits":"Tabu", "puzzles.on_the_house":"Aufs Haus", -"puzzles.one_backhoe_away_from_a_very":"Ein Bagger trennt dich von einer sehr langen Nacht. Ein zweiter Weg gibt ⭐⭐⭐.", +"puzzles.one_monkey_away_from_a_very":"Ein Chaos-Affe trennt dich von einer sehr langen Nacht. Ein zweiter Weg gibt ⭐⭐⭐.", "puzzles.one_ring_through_every_pop":"Ein Ring durch jeden POP", "puzzles.one_very_big_island_and_a":"Eine sehr große Insel und sehr viel sehr leere Glasfaser.", "puzzles.open_a_pop_cost":"POP eröffnen · {cost}", @@ -3008,12 +3011,13 @@ "puzzles.same_cable_same_anchor":"Dasselbe Kabel wie ein Link, den du schon hast: Ein Anker erwischt beide.", "puzzles.same_puzzle_for_everyone_this_week":"Diese Woche für alle dasselbe Puzzle", "puzzles.same_trench_cheaper":"Gleicher Graben (günstiger)", -"puzzles.same_trench_cheaper_one_backhoe_cuts":"Gleicher Graben (billiger, ein Bagger kappt beide)", +"puzzles.same_trench_cheaper_one_snip_cuts":"Gleicher Graben (billiger, ein Schnipp kappt beide)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo nach Miami, bevor der Caipirinha warm wird.", "puzzles.sea_to_shining_sea":"Von Küste zu Küste", "puzzles.share_line":"Series of Tubes Puzzle {what} {stars} {spend} · seriesoftub.es", "puzzles.six_cities_a_few_gigs_each":"Sechs Städte, je ein paar Gigabit, und ein Router mit acht Ports. Erst zählen, dann graben.", "puzzles.size":"Größe", +"puzzles.skip_the_monkey":"Überspringen", "puzzles.small_networks_real_traffic":"Kleine Netze, echter Traffic", "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 de095d6..1eb5df5 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2882,8 +2882,8 @@ "progress.under_attack_now":"Bajo ataque ahora", "progress.your_score_peak_traffic":"Tu puntuación: tráfico pico", "progress.your_traffic_to_and_from_asia":"Tu tráfico desde y hacia Asia", -"puzzles.a_backhoe_walks_into_your_network":"Una retroexcavadora entra en tu red. No pasa nada.", "puzzles.a_bigger_boat":"Necesitaremos un barco más grande", +"puzzles.a_chaos_monkey_walks_into_your_network":"Un mono del caos entra en tu red. No pasa nada.", "puzzles.a_cut_on_where_drops_g":"Un corte en {where} tira {g}", "puzzles.a_different_route":"Otra ruta", "puzzles.a_diverse_route":"Una ruta diversa (+40%)", @@ -2907,11 +2907,12 @@ "puzzles.carry_list":"A transportar: {list}.", "puzzles.carrying":"Transporta", "puzzles.carrying_on_this_pair":"Transporta (los {n} enlaces de este par)", +"puzzles.city_loses_g":"{city} −{g}", "puzzles.content_lives_in_list":"El contenido vive en {list}: los usuarios tiran del más cercano.", "puzzles.copied_paste_it_anywhere":"¡Copiado! Pégalo donde quieras:
{t}", "puzzles.de_kicks_sales_has_your_number":"Ventas de DE-KICKS tiene tu número. Conecta Alemania sin pasar por Fráncfort.", "puzzles.delivered":"Entregado", -"puzzles.diverse_route_40_survives_a_backhoe":"Ruta diversa (+40 %, sobrevive a una retroexcavadora)", +"puzzles.diverse_route_40_survives_the_monkey":"Ruta diversa (+40 %, sobrevive al mono del caos)", "puzzles.down_under_up_and_running":"Down Under, en marcha", "puzzles.drag_from_a_pink_pop_to":"Arrastra desde un POP rosa a otra ciudad para alquilar una onda", "puzzles.drag_from_this_pop_onto_another":"Arrastra desde este POP a otra ciudad del puzle, o elige una aquí.", @@ -2938,15 +2939,17 @@ "puzzles.hub_cap":"Tapacubos", "puzzles.includes_a_new_pop_in_city":"Incluye un POP nuevo en {city} ({price} por un año).", "puzzles.installed":"instalado", -"puzzles.it_works_finance_and_the_backhoe":"¡Funciona! Finanzas y la retroexcavadora quieren hablar contigo.", +"puzzles.it_works_finance_and_the_monkey":"¡Funciona! Finanzas y el mono del caos quieren hablar contigo.", "puzzles.keep_building":"Seguir construyendo", "puzzles.kiwi_fruit_salad":"Macedonia de kiwi", "puzzles.latency":"Latencia", "puzzles.latency_caps":"límites de latencia", "puzzles.lease_a_wave_to":"Alquilar una onda hasta", +"puzzles.let_the_chaos_monkey_loose":"🐒 Suelta al mono del caos", "puzzles.loading_this_week_s_puzzle":"Cargando el puzle de esta semana…", "puzzles.london_wants_half_a_terabit_your":"Londres quiere medio terabit, y tus routers salieron de eBuy.", "puzzles.model_facts":"{cap} · {ports} puertos · waves hasta {wave}", +"puzzles.monkey_snip":"🐒 ¡Zas!", "puzzles.more_puzzles":"Más puzles", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_deliver_everything_first":"N-1: primero entrégalo todo", @@ -2976,7 +2979,7 @@ "puzzles.not_through_frankfurt":"Sin pasar por Fráncfort", "puzzles.off_limits":"Prohibida", "puzzles.on_the_house":"Invita la casa", -"puzzles.one_backhoe_away_from_a_very":"A una retroexcavadora de una noche muy larga. Añade un segundo camino para ⭐⭐⭐.", +"puzzles.one_monkey_away_from_a_very":"A un mono del caos de una noche muy larga. Añade una segunda ruta para ⭐⭐⭐.", "puzzles.one_ring_through_every_pop":"Un anillo por todos los POP", "puzzles.one_very_big_island_and_a":"Una isla enorme y muchísima fibra vacía.", "puzzles.open_a_pop_cost":"Abrir un POP · {cost}", @@ -3006,12 +3009,13 @@ "puzzles.same_cable_same_anchor":"Mismo cable que un enlace que ya tienes: un ancla se lleva los dos.", "puzzles.same_puzzle_for_everyone_this_week":"El mismo puzle para todos esta semana", "puzzles.same_trench_cheaper":"Misma zanja (más barato)", -"puzzles.same_trench_cheaper_one_backhoe_cuts":"Misma zanja (más barata, una retroexcavadora corta las dos)", +"puzzles.same_trench_cheaper_one_snip_cuts":"Misma zanja (más barata, un corte se lleva las dos)", "puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes de que se caliente la caipiriña.", "puzzles.sea_to_shining_sea":"De costa a costa", "puzzles.share_line":"Series of Tubes puzle {what} {stars} {spend} · seriesoftub.es", "puzzles.six_cities_a_few_gigs_each":"Seis ciudades, pocos gigas cada una, y un router con ocho puertos. Cuenta antes de cavar.", "puzzles.size":"Tamaño", +"puzzles.skip_the_monkey":"Saltar", "puzzles.small_networks_real_traffic":"Redes pequeñas, tráfico de verdad", "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 19870ef..dda0146 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2882,8 +2882,8 @@ "progress.under_attack_now":"Sous attaque", "progress.your_score_peak_traffic":"Ton score : pic de trafic", "progress.your_traffic_to_and_from_asia":"Ton trafic vers et depuis l’Asie", -"puzzles.a_backhoe_walks_into_your_network":"C’est une pelleteuse qui entre dans ton réseau. Il ne se passe rien.", "puzzles.a_bigger_boat":"Il nous faut un plus gros bateau", +"puzzles.a_chaos_monkey_walks_into_your_network":"C’est un singe du chaos qui entre dans ton réseau. Il ne se passe rien.", "puzzles.a_cut_on_where_drops_g":"Une coupure sur {where} fait tomber {g}", "puzzles.a_different_route":"Une autre route", "puzzles.a_diverse_route":"Une route diverse (+40 %)", @@ -2907,11 +2907,12 @@ "puzzles.carry_list":"À transporter : {list}.", "puzzles.carrying":"Transporte", "puzzles.carrying_on_this_pair":"Transporte (les {n} liens de cette paire)", +"puzzles.city_loses_g":"{city} −{g}", "puzzles.content_lives_in_list":"Le contenu vit à {list} : les internautes tirent du plus proche.", "puzzles.copied_paste_it_anywhere":"Copié ! Colle-le où tu veux :
{t}", "puzzles.de_kicks_sales_has_your_number":"Les commerciaux de DE-KICKS ont ton numéro. Relie l’Allemagne sans passer par Francfort.", "puzzles.delivered":"Livré", -"puzzles.diverse_route_40_survives_a_backhoe":"Route diverse (+40 %, survit à une pelleteuse)", +"puzzles.diverse_route_40_survives_the_monkey":"Route diverse (+40 %, survit au singe du chaos)", "puzzles.down_under_up_and_running":"Down Under, ça tourne", "puzzles.drag_from_a_pink_pop_to":"Glisse depuis un POP rose vers une autre ville pour louer une longueur d’onde", "puzzles.drag_from_this_pop_onto_another":"Glisse depuis ce POP vers une autre ville du puzzle, ou choisis-en une ici.", @@ -2938,15 +2939,17 @@ "puzzles.hub_cap":"Enjoliveur", "puzzles.includes_a_new_pop_in_city":"Inclut un nouveau POP à {city} ({price} pour un an).", "puzzles.installed":"installé", -"puzzles.it_works_finance_and_the_backhoe":"Ça marche ! La compta et la pelleteuse aimeraient te dire un mot.", +"puzzles.it_works_finance_and_the_monkey":"Ça marche ! La compta et le singe du chaos aimeraient te dire un mot.", "puzzles.keep_building":"Continuer à construire", "puzzles.kiwi_fruit_salad":"Salade de kiwis", "puzzles.latency":"Latence", "puzzles.latency_caps":"plafonds de latence", "puzzles.lease_a_wave_to":"Louer une longueur d’onde vers", +"puzzles.let_the_chaos_monkey_loose":"🐒 Lâche le singe du chaos", "puzzles.loading_this_week_s_puzzle":"Chargement du puzzle de la semaine…", "puzzles.london_wants_half_a_terabit_your":"Londres veut un demi-térabit, et tes routeurs viennent d'eBuy.", "puzzles.model_facts":"{cap} · {ports} ports · waves jusqu'à {wave}", +"puzzles.monkey_snip":"🐒 Clac !", "puzzles.more_puzzles":"Plus de puzzles", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_deliver_everything_first":"N-1 : livre tout d'abord", @@ -2976,7 +2979,7 @@ "puzzles.not_through_frankfurt":"Pas par Francfort", "puzzles.off_limits":"Interdite", "puzzles.on_the_house":"Offert par la maison", -"puzzles.one_backhoe_away_from_a_very":"À une pelleteuse d’une très longue nuit. Ajoute un deuxième chemin pour ⭐⭐⭐.", +"puzzles.one_monkey_away_from_a_very":"À un singe du chaos d’une très longue nuit. Ajoute un deuxième chemin pour ⭐⭐⭐.", "puzzles.one_ring_through_every_pop":"Un anneau qui passe par chaque POP", "puzzles.one_very_big_island_and_a":"Une très grande île, et beaucoup de fibre très vide.", "puzzles.open_a_pop_cost":"Ouvrir un POP · {cost}", @@ -3006,12 +3009,13 @@ "puzzles.same_cable_same_anchor":"Même câble qu'un lien que tu as : une ancre emporte les deux.", "puzzles.same_puzzle_for_everyone_this_week":"Le même puzzle pour tout le monde cette semaine", "puzzles.same_trench_cheaper":"Même tranchée (moins cher)", -"puzzles.same_trench_cheaper_one_backhoe_cuts":"Même tranchée (moins cher, une pelleteuse coupe les deux)", +"puzzles.same_trench_cheaper_one_snip_cuts":"Même tranchée (moins cher, une coupure tranche les deux)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo–Miami avant que la caïpirinha ne tiédisse.", "puzzles.sea_to_shining_sea":"D’une côte à l’autre", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", "puzzles.six_cities_a_few_gigs_each":"Six villes, quelques gigas chacune, et un routeur à huit ports. Compte avant de creuser.", "puzzles.size":"Taille", +"puzzles.skip_the_monkey":"Passer", "puzzles.small_networks_real_traffic":"Petits réseaux, vrai trafic", "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 b0565fd..0b4eb9c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2882,8 +2882,8 @@ "progress.under_attack_now":"Sotto attacco ora", "progress.your_score_peak_traffic":"Il tuo punteggio: picco di traffico", "progress.your_traffic_to_and_from_asia":"Il tuo traffico da e per l’Asia", -"puzzles.a_backhoe_walks_into_your_network":"Una ruspa entra nella tua rete. Non succede niente.", "puzzles.a_bigger_boat":"Ci serve una barca più grande", +"puzzles.a_chaos_monkey_walks_into_your_network":"Una scimmia del caos entra nella tua rete. Non succede niente.", "puzzles.a_cut_on_where_drops_g":"Un taglio su {where} perde {g}", "puzzles.a_different_route":"Un altro percorso", "puzzles.a_diverse_route":"Un percorso diverso (+40%)", @@ -2907,11 +2907,12 @@ "puzzles.carry_list":"Da trasportare: {list}.", "puzzles.carrying":"Trasporta", "puzzles.carrying_on_this_pair":"Trasporta (tutti i {n} link di questa coppia)", +"puzzles.city_loses_g":"{city} −{g}", "puzzles.content_lives_in_list":"I contenuti vivono a {list}: gli utenti pescano dal più vicino.", "puzzles.copied_paste_it_anywhere":"Copiato! Incollalo dove vuoi:
{t}", "puzzles.de_kicks_sales_has_your_number":"Il commerciale di DE-KICKS ha il tuo numero. Collega la Germania senza passare da Francoforte.", "puzzles.delivered":"Consegnato", -"puzzles.diverse_route_40_survives_a_backhoe":"Percorso diverso (+40%, sopravvive a una ruspa)", +"puzzles.diverse_route_40_survives_the_monkey":"Percorso diverso (+40%, resiste alla scimmia del caos)", "puzzles.down_under_up_and_running":"Down Under, operativi", "puzzles.drag_from_a_pink_pop_to":"Trascina da un POP rosa a un’altra città per noleggiare una wave", "puzzles.drag_from_this_pop_onto_another":"Trascina da questo POP su un’altra città del puzzle, o scegline una qui.", @@ -2938,15 +2939,17 @@ "puzzles.hub_cap":"Coprimozzo", "puzzles.includes_a_new_pop_in_city":"Include un nuovo POP a {city} ({price} per un anno).", "puzzles.installed":"installato", -"puzzles.it_works_finance_and_the_backhoe":"Funziona! L’amministrazione e la ruspa vorrebbero parlarti.", +"puzzles.it_works_finance_and_the_monkey":"Funziona! L’amministrazione e la scimmia del caos vorrebbero parlarti.", "puzzles.keep_building":"Continua a costruire", "puzzles.kiwi_fruit_salad":"Macedonia di kiwi", "puzzles.latency":"Latenza", "puzzles.latency_caps":"limiti di latenza", "puzzles.lease_a_wave_to":"Noleggia una wave verso", +"puzzles.let_the_chaos_monkey_loose":"🐒 Libera la scimmia del caos", "puzzles.loading_this_week_s_puzzle":"Carico il puzzle della settimana…", "puzzles.london_wants_half_a_terabit_your":"Londra vuole mezzo terabit, e i tuoi router vengono da eBuy.", "puzzles.model_facts":"{cap} · {ports} porte · wave fino a {wave}", +"puzzles.monkey_snip":"🐒 Zac!", "puzzles.more_puzzles":"Altri puzzle", "puzzles.n_1_club":"Club N-1", "puzzles.n_1_deliver_everything_first":"N-1: prima consegna tutto", @@ -2976,7 +2979,7 @@ "puzzles.not_through_frankfurt":"Non da Francoforte", "puzzles.off_limits":"Vietata", "puzzles.on_the_house":"Offre la casa", -"puzzles.one_backhoe_away_from_a_very":"A una ruspa da una nottata lunghissima. Aggiungi un secondo percorso per ⭐⭐⭐.", +"puzzles.one_monkey_away_from_a_very":"A una scimmia del caos da una notte lunghissima. Aggiungi un secondo percorso per ⭐⭐⭐.", "puzzles.one_ring_through_every_pop":"Un anello che passa per ogni POP", "puzzles.one_very_big_island_and_a":"Un’isola enorme e tantissima fibra vuota.", "puzzles.open_a_pop_cost":"Apri un POP · {cost}", @@ -3006,12 +3009,13 @@ "puzzles.same_cable_same_anchor":"Stesso cavo di un link che hai già: un'ancora li prende tutti e due.", "puzzles.same_puzzle_for_everyone_this_week":"Lo stesso puzzle per tutti questa settimana", "puzzles.same_trench_cheaper":"Stessa trincea (costa meno)", -"puzzles.same_trench_cheaper_one_backhoe_cuts":"Stesso scavo (più economico, una ruspa li taglia tutti e due)", +"puzzles.same_trench_cheaper_one_snip_cuts":"Stessa trincea (più economica, un taglio le prende entrambe)", "puzzles.sao_paulo_to_miami_before_the":"Da São Paulo a Miami prima che la caipirinha si scaldi.", "puzzles.sea_to_shining_sea":"Da costa a costa", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", "puzzles.six_cities_a_few_gigs_each":"Sei città, pochi giga ciascuna, e un router con otto porte. Conta prima di scavare.", "puzzles.size":"Taglia", +"puzzles.skip_the_monkey":"Salta", "puzzles.small_networks_real_traffic":"Reti piccole, traffico vero", "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 69b353d..94a0f4d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2882,8 +2882,8 @@ "progress.under_attack_now":"Sob ataque agora", "progress.your_score_peak_traffic":"Sua pontuação: pico de tráfego", "progress.your_traffic_to_and_from_asia":"Seu tráfego de e para a Ásia", -"puzzles.a_backhoe_walks_into_your_network":"Uma retroescavadeira entra na sua rede. Nada acontece.", "puzzles.a_bigger_boat":"Vamos precisar de um barco maior", +"puzzles.a_chaos_monkey_walks_into_your_network":"Um macaco do caos entra na sua rede. Nada acontece.", "puzzles.a_cut_on_where_drops_g":"Um corte em {where} derruba {g}", "puzzles.a_different_route":"Outra rota", "puzzles.a_diverse_route":"Uma rota diversa (+40%)", @@ -2907,11 +2907,12 @@ "puzzles.carry_list":"Transporte: {list}.", "puzzles.carrying":"Transportando", "puzzles.carrying_on_this_pair":"Transportando (todos os {n} links deste par)", +"puzzles.city_loses_g":"{city} −{g}", "puzzles.content_lives_in_list":"O conteúdo mora em {list}: os usuários puxam do mais próximo.", "puzzles.copied_paste_it_anywhere":"Copiado! Cole onde quiser:
{t}", "puzzles.de_kicks_sales_has_your_number":"O comercial da DE-KICKS tem seu número. Conecte a Alemanha sem passar por Frankfurt.", "puzzles.delivered":"Entregue", -"puzzles.diverse_route_40_survives_a_backhoe":"Rota diversa (+40%, sobrevive a uma retroescavadeira)", +"puzzles.diverse_route_40_survives_the_monkey":"Rota diversa (+40%, aguenta o macaco do caos)", "puzzles.down_under_up_and_running":"Down Under, no ar", "puzzles.drag_from_a_pink_pop_to":"Arraste de um POP rosa até outra cidade para alugar uma wave", "puzzles.drag_from_this_pop_onto_another":"Arraste deste POP até outra cidade do puzzle, ou escolha uma aqui.", @@ -2938,15 +2939,17 @@ "puzzles.hub_cap":"Calota", "puzzles.includes_a_new_pop_in_city":"Inclui um POP novo em {city} ({price} por um ano).", "puzzles.installed":"instalado", -"puzzles.it_works_finance_and_the_backhoe":"Funciona! O financeiro e a retroescavadeira querem uma palavrinha.", +"puzzles.it_works_finance_and_the_monkey":"Funciona! O financeiro e o macaco do caos querem dar uma palavrinha.", "puzzles.keep_building":"Continuar construindo", "puzzles.kiwi_fruit_salad":"Salada de kiwi", "puzzles.latency":"Latência", "puzzles.latency_caps":"limites de latência", "puzzles.lease_a_wave_to":"Alugar uma wave até", +"puzzles.let_the_chaos_monkey_loose":"🐒 Solte o macaco do caos", "puzzles.loading_this_week_s_puzzle":"Carregando o puzzle da semana…", "puzzles.london_wants_half_a_terabit_your":"Londres quer meio terabit, e seus routers vieram do eBuy.", "puzzles.model_facts":"{cap} · {ports} portas · waves até {wave}", +"puzzles.monkey_snip":"🐒 Zás!", "puzzles.more_puzzles":"Mais puzzles", "puzzles.n_1_club":"Clube N-1", "puzzles.n_1_deliver_everything_first":"N-1: entregue tudo primeiro", @@ -2976,7 +2979,7 @@ "puzzles.not_through_frankfurt":"Sem passar por Frankfurt", "puzzles.off_limits":"Proibida", "puzzles.on_the_house":"Por conta da casa", -"puzzles.one_backhoe_away_from_a_very":"A uma retroescavadeira de uma noite muito longa. Adicione um segundo caminho para ⭐⭐⭐.", +"puzzles.one_monkey_away_from_a_very":"A um macaco do caos de uma noite muito longa. Adicione uma segunda rota para ⭐⭐⭐.", "puzzles.one_ring_through_every_pop":"Um anel passando por todos os POPs", "puzzles.one_very_big_island_and_a":"Uma ilha enorme e muita fibra vazia.", "puzzles.open_a_pop_cost":"Abrir um POP · {cost}", @@ -3006,12 +3009,13 @@ "puzzles.same_cable_same_anchor":"Mesmo cabo de um link que você já tem: uma âncora leva os dois.", "puzzles.same_puzzle_for_everyone_this_week":"O mesmo puzzle para todo mundo nesta semana", "puzzles.same_trench_cheaper":"Mesma vala (mais barato)", -"puzzles.same_trench_cheaper_one_backhoe_cuts":"Mesma vala (mais barata, uma retroescavadeira corta as duas)", +"puzzles.same_trench_cheaper_one_snip_cuts":"Mesma vala (mais barata, um corte pega as duas)", "puzzles.sao_paulo_to_miami_before_the":"De São Paulo a Miami antes que a caipirinha esquente.", "puzzles.sea_to_shining_sea":"De costa a costa", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", "puzzles.six_cities_a_few_gigs_each":"Seis cidades, poucos gigas cada, e um router com oito portas. Conte antes de cavar.", "puzzles.size":"Tamanho", +"puzzles.skip_the_monkey":"Pular", "puzzles.small_networks_real_traffic":"Redes pequenas, tráfego de verdade", "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 c840b9f..4b9500e 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -81,7 +81,7 @@ const pzSig=()=>JSON.stringify([S.pops,S.links,S.pairMet||null,S.biz.map(b=>b.ro /* ⭐ every flow delivered in full (circuits within their latency cap), and the twists; ⭐⭐ the year's spend within budget; ⭐⭐⭐ N-1 under load: whichever single trench or cable is cut, every priority flow still gets all of its traffic (best-effort flows may drop). The cut is routed by compute() like the real thing. */ -function pzEval(){const sig=pzSig(),c0=UI.pzEv;if(c0&&c0.sig===sig)return c0.e; +function pzEval(){const sig=pzSig(),c0=UI.pzEv;if(c0&&(c0.sig===sig||UI.pzMk))return c0.e;// mid-scene the monkey's cuts are not the build const P=S.pz,hot=UI.hotMap;compute();const R0=R,got=pzGot(),spend=pzSpend(),peak={},pk=()=>{for(const c in R.nodeLoad)peak[c]=Math.max(peak[c]||0,R.nodeLoad[c]);};pk(); const flows=P.dem.map((f,i)=>({f,i,g:got[i].g,ms:got[i].ms,full:pzFull(f,got[i]),fast:pzFast(f,got[i])})); const tw=[];if(P.noSub)tw.push({k:'sub',ok:!S.links.some(l=>l.sub)}); @@ -118,7 +118,7 @@ const pzToastsClear=()=>{$('toasts').textContent='';}; // The running game gets its usual save first and is kept in memory, set aside: save() keeps writing it to its slot // (leaving the page mid-puzzle), and leaving the puzzle picks it up again. function pzFlush(){save(true);UI.pzKeep=S;} -function pzBegin(def){if(!def)return; +function pzBegin(def){if(!def)return;pzMkStop();mkStop(); const go=()=>{const cs=pzCities(def);newGame(pzName(def),cs[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null; S.pz={id:def.id,key:def.key||null,cities:cs,src:(def.src||[]).slice(),dem:def.dem.map(f=>({t:f.t,a:f.a,b:f.t==='l2'?f.b:null,g:f.g,ms:f.ms||0,be:!!f.be})), via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null,rev:def.rev||1}; @@ -130,7 +130,7 @@ function pzBegin(def){if(!def)return; if(pzOn()){go();return;} const live=!!(S&&UI.started&&!S.lost);UI.pzFrom=live?'game':'title'; if(live)pzFlush();go();} -function pzLeave(){const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; +function pzLeave(){pzMkStop();mkStop();const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null; if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} // It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told. @@ -142,14 +142,14 @@ function pzCam(){const cs=[...S.pz.cities,...S.pz.via].map(c=>CITY[c]),x0=cs[0]. const ph=isPhone(),side=ph&&CW>CH,pl=side?-Math.min(360,CW*0.52):ph?0:330,pb=ph&&!side?Math.min(230,CH*0.4):0,aw=Math.max(120,CW-Math.abs(pl)-90),ah=Math.max(120,CH-pb-150); cam.z=clamp(Math.min(aw/Math.max(40,b-a),ah/Math.max(40,d-c)),0.5,4);cam.x=(a+b)/2-pl/2/cam.z;cam.y=(c+d)/2+(pb/2-30)/cam.z;wrapCam();} // ---------- building ---------- -function pzSnap(){const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();} +function pzSnap(){pzMkStop();const h=UI.pzHist||(UI.pzHist=[]);h.push(JSON.stringify({p:S.pops,l:S.links,m:S.pairMet||{},r:S.biz.map(b=>b.route)}));if(h.length>60)h.shift();} function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI.sel.id))||(UI.sel.type==='city'&&!pzKind(UI.sel.id))))UI.sel=null; compute();renderAll();pzCheck();} // Stars count the moment they are earned. // Every solved state is recorded, so a cheaper build at the same stars counts too. // A new star below three is a cheer and a nudge, and play goes on; the results card opens at three stars, or when the // player says they are done (the card's Finish button). -function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}return e;} +function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;const show=()=>{if(e.stars>=3)pzResults(e,prev);else{pzCheer(e,prev);renderAll();}};if(pzMkCan())pzMonkey(show);else show();return e;} // The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend. function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null}; if(e.starsanimOn()&&!UI.mapHid&&performance.now()-(UI.drawnAt||-1e9)<2000; +function pzMonkey(then){pzMkStop();const units=[...new Set(S.links.map(pzUnit))];if(!units.length){if(then)then();return;} + const c=S.pz.src[0]||S.pz.cities[0];UI.pzMk={units,i:-1,t:0,then,bad:0};if(CITY[c])mkStart(c);sfx('alert');pzMkStep();} +// Off to the next one: the tube it last snipped is whole again, the next one stays whole until it gets there. +function pzMkStep(){const m=UI.pzMk;if(!m||!pzOn())return;for(const l of S.links)l.cut=0;m.i++;if(m.i>=m.units.length){pzMkDone();return;} + const u=m.units[m.i];compute();renderAll();mkRun(S.links.find(l=>pzUnit(l)===u),PZ_RUN/MK_RUN);m.t=setTimeout(pzMkHit,PZ_RUN);} +function pzMkHit(){const m=UI.pzMk;if(!m||!pzOn())return;const ls=S.links.filter(l=>pzUnit(l)===m.units[m.i]),l0=ls[0];for(const l of ls)l.cut=1;compute(); + const g=pzGot(),lost=[];S.pz.dem.forEach((f,i)=>{if(!f.be&&!pzFull(f,g[i]))lost.push({c:f.t==='l2'?f.b:f.a,g:Math.max(0,f.g-g[i].g)});}); + floater((CITY[l0.a].x+CITY[l0.a].x+wrapDx(CITY[l0.a].x,CITY[l0.b].x))/2,(CITY[l0.a].y+CITY[l0.b].y)/2-26,tr('puzzles.monkey_snip'),'#FF8A3D'); + for(const x of lost)floater(CITY[x.c].x,CITY[x.c].y-34,tr('puzzles.city_loses_g',{city:CITY[x.c].name,g:fmtG(x.g)}),'#FF4D5E'); + if(UI.mk)UI.mk.bad=lost.length>0;if(lost.length)m.bad++;sfx(lost.length?'err':'click');renderAll();m.t=setTimeout(pzMkStep,lost.length?PZ_HOLD*2:PZ_HOLD);} +// The end: a cheer if nothing broke, a tantrum if something did, then whatever was waiting (the stars). +function pzMkDone(bad){const m=UI.pzMk;if(!m)return;clearTimeout(m.t);UI.pzMk=null;for(const l of S.links)l.cut=0;compute(); + mkEnd(!(bad!=null?bad:m.bad),true);renderAll();if(m.then)m.then();} +// Skip: straight to the end; the verdict is already known. +function pzMkSkip(){if(UI.pzMk)pzMkDone(pzEval().n1?0:1);} +// Gone without a word: the build changed under it, or the puzzle closed. +function pzMkStop(){const m=UI.pzMk;if(!m)return;clearTimeout(m.t);UI.pzMk=null;for(const l of S.links)l.cut=0;mkStop();} diff --git a/src/game/90-actions/95-puzzles.js b/src/game/90-actions/95-puzzles.js index add3575..902e5cc 100644 --- a/src/game/90-actions/95-puzzles.js +++ b/src/game/90-actions/95-puzzles.js @@ -3,6 +3,9 @@ function pzWaveWhy(a,b,tier,r){if(r&&subWaveWhy(tier,r.km,r.sub))return tr('common.too_far_for_this_cable');if(!waveOk(a,b,tier))return tr('puzzles.needs_what',{what:waveNeed(tier)});return '';} const pzPortsFree=c=>!S.pops[c]||portsUsed(c)+1<=portsMax(c)+1e-9; Object.assign(ACT,{ + // The chaos monkey acts out the N-1 check, or is told to get on with it. + pzMonkey:()=>{if(pzOn()&&pzEval().goal)pzMonkey();}, + pzMkSkip:()=>{if(pzOn())pzMkSkip();}, // The puzzle list. The ruleset's title-screen door calls this. puzzleMenu:()=>{if(S&&UI.started&&!pzOn())UI.nm=S.name;pzMenu();}, pzStart:({id})=>{const d=pzDef(id);if(!d||!pzPackOpen(d.pack))return;pzBegin(d);}, diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index e0311fd..37ac637 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -29,6 +29,7 @@ function pzRender(){const el=$('pzBox');if(!pzOn()){el.hidden=true;return;}el.hi const w=e.worst; h+=!e.goal?`
🛡 ${tr('puzzles.n_1_deliver_everything_first')}
`:e.n1?`
🛡 ${tr('puzzles.survives_any_single_cut_under_load')}
` :`
⚠️ ${tr('puzzles.a_cut_on_where_drops_g',{where:pzUnitName(w.u),g:fmtG(w.g)})}
${w.lost.map(x=>esc(pzFlowName(P.dem[x.i]))).join(', ')}
`; + if(UI.pzMk)h+=`
${btn('⏩ '+tr('puzzles.skip_the_monkey'),'pzMkSkip',{},'big')}
`;else if(e.goal)h+=`
${btn(tr('puzzles.let_the_chaos_monkey_loose'),'pzMonkey',{},'sm')}
`; 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)}${(UI.pzTop||0)>0&&(UI.pzTop||0)<3?btn(tr('puzzles.finish_here'),'pzFinish',{},'sm'):''}${btn(UI.pzFrom==='game'?tr('puzzles.back_to_my_network'):tr('puzzles.back_to_the_title'),'pzLeave',{},'ghost sm')}
`; if(h!==UI._pzh){UI._pzh=h;morph(el,h);}} // Trenches on a pair get numbers, cables their names, so parallel links say where they run. @@ -91,13 +92,13 @@ function pzLinkModal(a,b,keep){const kb=pzKind(b); h+=`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost',P.noSub&&x.sub)).join('')}
`; if(P.noSub&&r.sub)h+=`

${tr('puzzles.the_sharks_say_no')}

`; if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}

`; - if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; + if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_the_monkey'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_snip_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; const full=[a,b].filter(c=>!pzPortsFree(c));if(full.length)h+=`

${tr('puzzles.no_free_ports_in_list',{list:full.map(c=>esc(CITY[c].name)).join(', ')})}

`; h+=`
${PZ_TIERS.map(i=>{const why=pzWaveWhy(a,b,i,r),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_chaos_monkey_walks_into_your_network'):!e.n1&&!e.cheap?tr('puzzles.it_works_finance_and_the_monkey'):!e.n1?tr('puzzles.one_monkey_away_from_a_very'):tr('puzzles.rock_solid_and_gold_plated_the');} // Stars still to win in this puzzle's pack, from the progress just saved. function pzPackLeft(P){const d=pzDef(P.id);if(!d)return null;const p=pzLoad(),xs=PZ.filter(x=>x.pack===d.pack);return xs.length*3-xs.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0);} function pzConfetti(){if(!animOn())return '';const cols=['#FF4F9A','#FFD23F','#22C47A','#2F8CFF','#FF8A3D','#7B61FF'];let h=''; diff --git a/src/i18n/en.js b/src/i18n/en.js index 15850a5..b1fbcda 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2883,8 +2883,8 @@ "progress.under_attack_now":"Under attack now", "progress.your_score_peak_traffic":"Your score: peak traffic", "progress.your_traffic_to_and_from_asia":"Your traffic to and from Asia", -"puzzles.a_backhoe_walks_into_your_network":"A backhoe walks into your network. Nothing happens.", "puzzles.a_bigger_boat":"A Bigger Boat", +"puzzles.a_chaos_monkey_walks_into_your_network":"A chaos monkey walks into your network. Nothing happens.", "puzzles.a_cut_on_where_drops_g":"A cut on {where} drops {g}", "puzzles.a_different_route":"A different route", "puzzles.a_diverse_route":"A diverse route (+40%)", @@ -2908,11 +2908,12 @@ "puzzles.carry_list":"Carry: {list}.", "puzzles.carrying":"Carrying", "puzzles.carrying_on_this_pair":"Carrying (all {n} links on this pair)", +"puzzles.city_loses_g":"{city} −{g}", "puzzles.content_lives_in_list":"Content lives in {list}: eyeballs pull from the nearest.", "puzzles.copied_paste_it_anywhere":"Copied! Paste it anywhere:
{t}", "puzzles.de_kicks_sales_has_your_number":"DE-KICKS sales has your number. Connect Germany without Frankfurt.", "puzzles.delivered":"Delivered", -"puzzles.diverse_route_40_survives_a_backhoe":"Diverse route (+40%, survives a backhoe)", +"puzzles.diverse_route_40_survives_the_monkey":"Diverse route (+40%, survives the chaos monkey)", "puzzles.down_under_up_and_running":"Down Under, Up and Running", "puzzles.drag_from_a_pink_pop_to":"Drag from a pink POP to another city to lease a wave", "puzzles.drag_from_this_pop_onto_another":"Drag from this POP onto another puzzle city, or pick one here.", @@ -2939,15 +2940,17 @@ "puzzles.hub_cap":"Hub Cap", "puzzles.includes_a_new_pop_in_city":"Includes a new POP in {city} ({price} for a year).", "puzzles.installed":"installed", -"puzzles.it_works_finance_and_the_backhoe":"It works! Finance and the backhoe would like a word.", +"puzzles.it_works_finance_and_the_monkey":"It works! Finance and the chaos monkey would like a word.", "puzzles.keep_building":"Keep building", "puzzles.kiwi_fruit_salad":"Kiwi Fruit Salad", "puzzles.latency":"Latency", "puzzles.latency_caps":"latency caps", "puzzles.lease_a_wave_to":"Lease a wave to", +"puzzles.let_the_chaos_monkey_loose":"🐒 Let the chaos monkey loose", "puzzles.loading_this_week_s_puzzle":"Loading this week's puzzle…", "puzzles.london_wants_half_a_terabit_your":"London wants half a terabit, and your routers came off eBuy.", "puzzles.model_facts":"{cap} · {ports} ports · waves up to {wave}", +"puzzles.monkey_snip":"🐒 Snip!", "puzzles.more_puzzles":"More puzzles", "puzzles.n_1_club":"N-1 Club", "puzzles.n_1_deliver_everything_first":"N-1: deliver everything first", @@ -2977,7 +2980,7 @@ "puzzles.not_through_frankfurt":"Not Through Frankfurt", "puzzles.off_limits":"Off limits", "puzzles.on_the_house":"On the house", -"puzzles.one_backhoe_away_from_a_very":"One backhoe away from a very long night. Add a second path for ⭐⭐⭐.", +"puzzles.one_monkey_away_from_a_very":"One chaos monkey away from a very long night. Add a second path for ⭐⭐⭐.", "puzzles.one_ring_through_every_pop":"One ring through every POP", "puzzles.one_very_big_island_and_a":"One very big island, and a lot of very empty fiber.", "puzzles.open_a_pop_cost":"Open a POP · {cost}", @@ -3007,12 +3010,13 @@ "puzzles.same_cable_same_anchor":"Same cable as a link you have: one anchor takes both.", "puzzles.same_puzzle_for_everyone_this_week":"Same puzzle for everyone this week", "puzzles.same_trench_cheaper":"Same trench (cheaper)", -"puzzles.same_trench_cheaper_one_backhoe_cuts":"Same trench (cheaper, one backhoe cuts both)", +"puzzles.same_trench_cheaper_one_snip_cuts":"Same trench (cheaper, one snip cuts both)", "puzzles.sao_paulo_to_miami_before_the":"São Paulo to Miami before the caipirinha gets warm.", "puzzles.sea_to_shining_sea":"Sea to Shining Sea", "puzzles.share_line":"Series of Tubes puzzle {what} {stars} {spend} · seriesoftub.es", "puzzles.six_cities_a_few_gigs_each":"Six cities, a few gigs each, and a router with eight ports. Count before you dig.", "puzzles.size":"Size", +"puzzles.skip_the_monkey":"Skip", "puzzles.small_networks_real_traffic":"Small networks, real traffic", "puzzles.spent_x":"Spent {x}", "puzzles.spent_x_of_y":"Spent {x} / {y}", diff --git a/tests/puzzle-monkey.test.js b/tests/puzzle-monkey.test.js new file mode 100644 index 0000000..ccfa6e5 --- /dev/null +++ b/tests/puzzle-monkey.test.js @@ -0,0 +1,42 @@ +// The chaos monkey in every puzzle: it acts out the N-1 star on the map, and the stars never wait on it in tests. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const lay = (ev, a, b, via, div = 1) => ev(`if(!S.pops['${a}'])ACT.pzPop({city:'${a}'});ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:${div}});ACT.pzLink({tier:1});closeModal()`); +const live = (ev) => ev('UI.drawnAt=performance.now()'); // as if the map were being drawn + +test('a new star sets the monkey loose, then the stars show; skipping goes straight to them', () => { + const { ev, errors } = load(); + ev("ACT.pzStart({id:'bigboat'})"); + live(ev); + lay(ev, 'fra', 'par', 'land'); lay(ev, 'fra', 'par', 'land'); + assert.ok(ev('pzEval().goal'), 'delivered'); + assert.ok(ev('!!UI.pzMk'), 'the monkey is reviewing the build'); + assert.ok(ev('!!UI.mk'), 'and it is on the map'); + assert.ok(ev("!!document.querySelector('#pzBox [data-act=pzMkSkip]')"), 'with a skip button'); + assert.equal(ev('pzEval().goal'), true, 'its cuts never change the stars'); + ev('ACT.pzMkSkip()'); + assert.equal(ev('UI.pzMk'), null); + assert.ok(ev('S.links.every(l=>!l.cut)'), 'every tube whole again'); + assert.match(ev("document.getElementById('toasts').textContent+document.getElementById('modalCard').textContent"), /⭐/); + assert.ok(ev("!!document.querySelector('#pzBox [data-act=pzMonkey]')"), 'and it can be let loose again'); + assert.deepEqual(errors, []); +}); + +test('the monkey snips each trench in turn, and an edit sends it away', () => { + const { ev, errors } = load(); + ev("ACT.pzStart({id:'bigboat'})"); + lay(ev, 'fra', 'par', 'land'); lay(ev, 'fra', 'par', 'land'); + ev("pzMonkey()"); + assert.equal(ev('UI.pzMk.units.length'), 2); + assert.equal(ev('S.links.some(l=>l.cut)'), false, 'nothing cut while it runs'); + ev('pzMkHit()'); + assert.equal(ev('S.links.filter(l=>l.cut).length'), 1, 'one trench cut when it arrives'); + ev('pzMkStep()'); + assert.equal(ev('S.links.some(l=>l.cut)'), false, 'and whole again when it runs on'); + lay(ev, 'fra', 'par', 'land'); + assert.equal(ev('UI.pzMk'), null, 'a change to the build stops the review'); + assert.equal(ev('UI.mk'), null); + assert.deepEqual(errors, []); +}); diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 5dfddd8..f4a45b8 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -315,18 +315,18 @@ test('results card: stars, the next puzzle, a retry, a share line and stars left ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('eurotrip'))"); build(ev, REF.eurotrip.one); assert.ok(ev("$('modal').hidden||!document.querySelector('#modalCard .pzres')"), 'two stars: no results card, play goes on'); - assert.match(ev("document.getElementById('toasts').textContent"), /One backhoe away/, 'a cheer with the next step instead'); + assert.match(ev("document.getElementById('toasts').textContent"), /One chaos monkey away/, 'a cheer with the next step instead'); assert.ok(ev("!!document.querySelector('[data-act=pzFinish]')"), 'and a Finish button on the card'); ev("document.querySelector('[data-act=pzFinish]').click()"); let card = ev("document.getElementById('modalCard').textContent"); assert.match(card, /Your stars so far/); assert.equal(evalP(ev).stars, 2, 'delivered, and the budget star is on the house'); - assert.match(card, /One backhoe away/); + assert.match(card, /One chaos monkey away/); assert.match(card, /13 ⭐ left in this pack/); assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')")); build(ev, [['ams', 'lon', 'concerto', 1], ['ams', 'fra', 'land', 1]]); card = ev("document.getElementById('modalCard').textContent"); - assert.match(card, /A backhoe walks into your network/); + assert.match(card, /A chaos monkey walks into your network/); assert.equal(ev("document.querySelectorAll('#modalCard .pzbig.on').length"), 3); assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')")); assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/); From dbc801169cd32576e1afe60edc24b9bf43f9b5d9 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 12:35:03 +0100 Subject: [PATCH 156/181] Architect runs: use the renamed same-trench and diverse-route labels --- src/game/95-modals/96-architect.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/game/95-modals/96-architect.js b/src/game/95-modals/96-architect.js index a150a98..3d9c6f4 100644 --- a/src/game/95-modals/96-architect.js +++ b/src/game/95-modals/96-architect.js @@ -56,7 +56,7 @@ function arLinkModal(a,b,keep){const kb=pzKind(b); if(pl.length)h+=`

${tr('puzzles.already_here_list',{list:[...new Set(pl.map(pzTrench))].join(', ')})}

`; h+=`

${tr('common.route')}

${rs.map(x=>btn(`${x.cab?esc(CAB[x.cab].name):tr('common.overland')} ${x.ms.toFixed(1)} ms · ${tr('architect.from_x',{x:fmt$(pzLinkCost(x,0,false))})}${pl.some(l=>(l.cable||'land')===x.via)?' · ✓':''}`,'pzVia',{v:x.via},x.via===r.via?'pink':'ghost')).join('')}
`; if(r.cab)h+=`

${esc(CAB[r.cab].blurb)}${pl.some(l=>l.cable===r.cab)?' '+tr('puzzles.same_cable_same_anchor'):''}

`; - if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_a_backhoe'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_backhoe_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; + if(land)h+=`
${btn(tr('puzzles.diverse_route_40_survives_the_monkey'),'pzDiv',{v:1},div?'pink':'ghost')}${btn(tr('puzzles.same_trench_cheaper_one_snip_cuts'),'pzDiv',{v:0},div?'ghost':'pink')}
`; if(pop)h+=`

${tr('puzzles.includes_a_new_pop_in_city',{city:esc(CITY[b].name),price:fmt$(pop)})}

`; const T=arTubes();if(T.max!=null&&T.u>=T.max)h+=`

${tr('architect.this_tube_is_over_the_plan')}

`; h+=`

${tr('architect.size')}

${AR_TIERS.map(i=>{const why=subWaveWhy(i,r.km,r.sub),rt=arRouterDelta(a,i)+(S.pops[b]?arRouterDelta(b,i):arRouterDelta(b,i)),c=pzLinkCost(r,i,div); From 7672db199280488623b64dd32f007eb264f96b4c Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 13:15:38 +0100 Subject: [PATCH 157/181] Puzzles: show one trench or separate paths on the map in every puzzle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two tubes between the same cities read as one line until clicked (reported by Thomas Kjær). Every puzzle now draws a shared trench as a bundle with a '2× one trench' tag and separate paths bowed apart with a '2 paths' tag, at any zoom. --- CHANGELOG.md | 1 + src/game/96-map/50-link-geometry.js | 4 ++-- src/game/96-map/60-draw.js | 5 +++-- tests/puzzles.test.js | 9 +++++++++ 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac04ead..ea5bd5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. - Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. - A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. - The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. diff --git a/src/game/96-map/50-link-geometry.js b/src/game/96-map/50-link-geometry.js index adb0642..7a9d024 100644 --- a/src/game/96-map/50-link-geometry.js +++ b/src/game/96-map/50-link-geometry.js @@ -37,8 +37,8 @@ function drawCables(ks){const z=cam.z,selC=UI.drag&&UI.drag.mode==='link'?UI.dra ctx.globalAlpha=1;}}} function bezGeom(l,at){const A=CITY[l.a],B=CITY[l.b];const i=at!==undefined?at:lineIdx(l);const key=l.id+'|b'+i;const hit=GEO.get(key);if(hit)return hit; const bx=A.x+wrapDx(A.x,B.x),by=B.y;const dx=bx-A.x,dy=by-A.y,len=Math.hypot(dx,dy)||1;let nx=-dy/len,ny=dx/len;if(ny>0){nx=-nx;ny=-ny;} - // Architect runs bow diverse paths well apart, so two routes never read as one. - const wide=S&&S.ar&&pzOn(),base=Math.max(4,Math.min(len*0.1,90)),step=wide?Math.min(30,len*.14):Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?(wide?0.9:0.2):1)+Math.ceil(i/2)*step); + // Puzzles bow diverse paths well apart, so two routes never read as one. + const wide=!!S&&pzOn(),base=Math.max(4,Math.min(len*0.1,90)),step=wide?Math.min(30,len*.14):Math.min(16,len*.06),off0=i<=0?base:(i%2?-1:1)*(base*(i%2?(wide?0.9:0.2):1)+Math.ceil(i/2)*step); const mx=(A.x+bx)/2,my=(A.y+by)/2; const sg=Math.sign(off0)||1,mag=Math.abs(off0); // Bend around cities in the way, but gently: short links need less room, no curve bows out more than about a diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 07df67a..d6370ae 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -43,7 +43,7 @@ function drawFrame(now){ ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(cut?[8,8]:vx?[2,7]:bld?[10,8]:idle?[4,6]:[]);path();ctx.stroke(); ctx.strokeStyle=bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':idle?'#9AA3BE':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]); // Architect runs: tubes sharing one trench are drawn as strands of one bundle (one snip takes them all). - if(arPz&&many&&!far){ctx.strokeStyle='#1E2640';ctx.lineWidth=1.3;for(let j=1;jpolyAtXY(SX,SY,gm.cum,t); @@ -53,8 +53,9 @@ function drawFrame(now){ const [mx2,my]=at(.5);const mxx=mx2; if(bld){if(far){ctx.fillStyle='#FF8A3D';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,4,0,7);ctx.fill();ctx.stroke();}else drawCone(mxx,my,now);} else if(cut&&!vx){if(far){ctx.fillStyle='#FF4D5E';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,5,0,7);ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',mxx,my+0.5);}else if(!arPz)drawBackhoe(mxx,my,now,l.sub);} - else if(arPz&&!sel&&!far&&(many||arPaths(l)>1)){const k=arPaths(l);if(many||lineIdx(l,PI.get(edgeKey(l)))===0){AR_PILLS.push([mxx,my,many?tr('architect.n_in_one_trench',{n:grp.length}):'✓ '+tr('architect.n_paths',{n:k}),many]);}} else if(sel||(pz?!S.ar:z>0.9&&!busy)){const t=lab||(lab=pz?pzLinkLab(grp,up||[l],load,cap):many?groupLabel(grp,up):capName(l));ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);} + // Every puzzle: say whether the tubes between two cities share one trench or take separate paths. + if(pz&&!cut&&!bld&&(many||arPaths(l)>1)&&(many||lineIdx(l,PI.get(edgeKey(l)))===0))AR_PILLS.push([mxx,my+(sel||!S.ar?19:0),many?tr('architect.n_in_one_trench',{n:grp.length}):'✓ '+tr('architect.n_paths',{n:arPaths(l)}),many]); } } // drag preview diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index f4a45b8..32b180e 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -545,3 +545,12 @@ test('each pack\'s idea is needed: three stars without it fail, and the one-star } assert.deepEqual(errors, []); }); + +test('every puzzle tells two tubes in one trench from two separate paths, zoomed out too', () => { + const { ev, errors } = load(); + ev("ACT.pzStart({id:'eurotrip'});closeModal()"); + build(ev, [['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1, 1], ['ams', 'lon', 'nshuttle', 1], ['ams', 'lon', 'concerto', 1]]); + ev("cam.z=0.6;drawFrame(performance.now())"); + assert.deepEqual(JSON.parse(ev("JSON.stringify(AR_PILLS.map(p=>p[2]).sort())")), ['2× one trench', '✓ 2 paths']); + assert.deepEqual(errors, []); +}); From 601f7028bd56468bbc2701c32392fb5890eb2541 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 13:24:08 +0100 Subject: [PATCH 158/181] Puzzles: city markers move to the top left, clear of the IX badge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The eyeballs, content and circuit markers sat on the IX badge of cities without a POP yet (reported by Thomas Kjær). Architect's mission-critical marker is now the siren like everywhere else. --- src/game/96-map/85-puzzle-cities.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/game/96-map/85-puzzle-cities.js b/src/game/96-map/85-puzzle-cities.js index 19041d1..baddeb7 100644 --- a/src/game/96-map/85-puzzle-cities.js +++ b/src/game/96-map/85-puzzle-cities.js @@ -1,7 +1,7 @@ /* Puzzle map: the puzzle's cities stand out (goals with a pulsing ring and a badge for what they send or ask for, stepping stones with a dashed one, cities to avoid crossed out); every other city is on the map as usual, open to build in but not emphasised. */ -function pzBadge(c){const P=S.pz;if(S.ar)return c===S.ar.hq?'🏠':S.ar.gold.includes(c)?'🥇':'';return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';} +function pzBadge(c){const P=S.pz;if(S.ar)return c===S.ar.hq?'🏠':S.ar.gold.includes(c)?'🚨':'';return P.src.includes(c)?'🗄️':P.dem.some(f=>f.t==='eye'&&f.a===c)?'👀':P.dem.some(f=>f.t==='l2'&&(f.a===c||f.b===c))?'🔗':'';} function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); if(!k||k==='off'){drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly);return;} const r=(CM.far?16:34)*sc,y=v.sy-(CM.far?0:6*sc),p=S.pops[v.C.id]; @@ -10,7 +10,7 @@ function pzDrawCity(v,sc,now){const k=pzKind(v.C.id); else{const a=animOn()?.55+.35*Math.sin(now/300):.8,gold=S.ar&&S.ar.gold.includes(v.C.id),dk=S.ar&&arDarkNow(v.C.id);ctx.strokeStyle=dk?`rgba(255,77,94,${a})`:gold?`rgba(224,160,0,${p?1:a})`:k==='goal'?`rgba(255,79,154,${p?1:a})`:'rgba(30,38,64,.7)';if(gold||dk)ctx.lineWidth=5;if(k==='via')ctx.setLineDash([5,5]); ctx.fillStyle=k==='goal'&&!p?'rgba(255,210,63,.35)':'rgba(255,255,255,.25)';ctx.beginPath();ctx.arc(v.sx,y,r,0,7);ctx.fill();ctx.stroke();ctx.setLineDash([]);} ctx.restore();drawCity(v.C,v.sx,v.sy,sc,now,v.ly===null?undefined:v.ly); - const b=k==='goal'&&!CM.far?pzBadge(v.C.id):'';if(b){ctx.font=`${Math.round(15*sc)}px sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(b,v.sx+r*.75,y-r*.75);}} + const b=k==='goal'&&!CM.far?pzBadge(v.C.id):'';if(b){ctx.font=`${Math.round(15*sc)}px sans-serif`;ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(b,v.sx-r*.75,y-r*.75);}} // top left: the IX badge has the top right // In a puzzle every line says what it is ("2×100G · 70%"), and a selected POP lights up every pair it has links on. function pzLinkLab(grp,up,load,cap){if(S.ar)return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');return groupLabel(grp,up)+(cap?` · ${Math.round(load/cap*100)}%`:'');} const pzLinkHot=grp=>!!(UI.sel&&UI.sel.type==='city'&&grp.some(x=>x.a===UI.sel.id||x.b===UI.sel.id)); From 4e6e8294d29c62c6ade1390ba6a0e3eb62f7c1ad Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 13:44:04 +0100 Subject: [PATCH 159/181] Architect runs: a generated run every week scripts/weekly-architect.js picks an HQ in a region the last weeks did not have and designs each brief against the network a reference architect has built so far, so every brief asks for something new; the game's own checklist and chaos monkey review judge it, and the whole run is replayed from the file for three stars. The game fetches architect/weekly/.json when Puzzles opens, checks it field by field and writes the briefs' text itself. The Sunday job and the release deploy carry it like the weekly puzzles and scenarios. Later briefs' cities no longer show early. --- .claude/skills/gameplay-rules/SKILL.md | 1 + .github/workflows/release.yml | 5 +- .github/workflows/weekly-puzzle.yml | 13 +- CHANGELOG.md | 1 + scripts/weekly-architect.js | 217 ++++++++++++++++++++ site/architect/weekly/2026-W44.json | 1 + site/architect/weekly/2026-W45.json | 1 + site/architect/weekly/2026-W46.json | 1 + site/architect/weekly/index.json | 1 + site/i18n/de.js | 14 ++ site/i18n/es.js | 14 ++ site/i18n/fr.js | 14 ++ site/i18n/it.js | 14 ++ site/i18n/pt.js | 14 ++ site/sw.js | 4 +- src/game/60-features/96-architect.js | 11 +- src/game/60-features/98-architect-weekly.js | 59 ++++++ src/game/95-modals/96-architect.js | 4 +- src/i18n/en.js | 14 ++ tests/architect.test.js | 2 +- tests/weekly-architect.test.js | 73 +++++++ 21 files changed, 461 insertions(+), 17 deletions(-) create mode 100644 scripts/weekly-architect.js create mode 100644 site/architect/weekly/2026-W44.json create mode 100644 site/architect/weekly/2026-W45.json create mode 100644 site/architect/weekly/2026-W46.json create mode 100644 site/architect/weekly/index.json create mode 100644 src/game/60-features/98-architect-weekly.js create mode 100644 tests/weekly-architect.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 6e691fb..99ea7eb 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -55,6 +55,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. | | C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. | | C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. | +| C4 | Every Architect run, handmade (`REF` in `tests/architect.test.js`) or weekly (`ref` in its file, `scripts/weekly-architect.js --check`), has a reference build that passes every brief's chaos monkey review and earns three stars; every weekly brief takes at least one tube, and later briefs' cities stay hidden until they come. | A run you cannot finish, or a brief that asks for nothing, is not a puzzle; knowing the next brief makes it a chore. | ## Fun and fairness diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0d1ad7a..c9e813f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -74,7 +74,7 @@ jobs: run: | set -euo pipefail git fetch --no-tags --depth=1 origin main - for d in site/puzzles/weekly site/scenarios/weekly; do + for d in site/puzzles/weekly site/scenarios/weekly site/architect/weekly; do if git cat-file -e "FETCH_HEAD:$d" 2>/dev/null; then rm -rf "$d" git checkout FETCH_HEAD -- "$d" @@ -92,11 +92,12 @@ jobs: 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 if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi + if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi - run: npm test if: ${{ !inputs.weekly }} - name: Test the weekly puzzles against this release if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }} - run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js 2>/dev/null) + run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null) - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build - uses: actions/upload-pages-artifact@v5 diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml index 9ac5cfa..fdff934 100644 --- a/.github/workflows/weekly-puzzle.yml +++ b/.github/workflows/weekly-puzzle.yml @@ -1,6 +1,7 @@ name: Weekly puzzle -# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js) and scenario (scripts/weekly-scenario.js), +# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), scenario (scripts/weekly-scenario.js) and +# Architect run (scripts/weekly-architect.js), # commit them to main as a data-only change, and redeploy the live release with them, once. Weeks start Sunday # 06:00 Berlin time; 03:37 UTC is 04:37 in winter and 05:37 in summer, so the files are live before the week starts. # @@ -47,7 +48,7 @@ jobs: - run: npm ci # Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current. - name: Fit the published weeks to main - run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check - name: Make the puzzle and the scenario run: | set -euo pipefail @@ -55,18 +56,20 @@ jobs: [[ "$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" node scripts/weekly-scenario.js --key "$KEY" + node scripts/weekly-architect.js --key "$KEY" else node scripts/weekly-puzzle.js node scripts/weekly-scenario.js + node scripts/weekly-architect.js fi - name: Check every weekly puzzle - run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js tests/weekly-architect.test.js - name: Commit it to main run: | set -euo pipefail - git add site/puzzles/weekly site/scenarios/weekly + git add site/puzzles/weekly site/scenarios/weekly site/architect/weekly # Data only: anything else changed means something is wrong. - if git status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi + if git status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' -e ' site/architect/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 and scenario $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')" diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5bd5d..4d59bb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Later briefs stay a surprise in every Architect run: their cities only appear when they come. - In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. - Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. - A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. diff --git a/scripts/weekly-architect.js b/scripts/weekly-architect.js new file mode 100644 index 0000000..e3dd253 --- /dev/null +++ b/scripts/weekly-architect.js @@ -0,0 +1,217 @@ +#!/usr/bin/env node +// The weekly Architect run generator, the twin of scripts/weekly-puzzle.js. Every Sunday .github/workflows/weekly-puzzle.yml +// runs it to publish site/architect/weekly/.json, which the game fetches when Puzzles opens +// (src/game/60-features/98-architect-weekly.js). It plays the real game headless, so the briefs are judged by the game's +// own checklist and chaos monkey review. +// +// node scripts/weekly-architect.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing +// node scripts/weekly-architect.js --key 2026-W45 that week (--force replaces an existing file) +// node scripts/weekly-architect.js --next 3 this week and the next two +// node scripts/weekly-architect.js --check re-play every week not over yet; one whose reference no longer +// earns three stars is regenerated with rev + 1; then validate every file +// --page FILE / --dir DIR another build of the game / where the files live +// +// How a run is made: an HQ in a region the last weeks did not have, and its nearest cities as the sites to come. Then a +// reference architect plays it brief by brief, and each brief is designed against the network it has built so far, so +// every brief asks for something new: a site to connect, a site that one cut would strand made mission-critical, a ring +// it does not have yet, a latency cap its paths miss, a site that closes. The reference builds the cheapest fix it finds +// (connect to the nearest POP; for a site a cut strands, the cheapest tube from the stranded side to the rest on another +// trench or cable) until the game's review passes. Its tube count is the brief's plan, its spend plus a little the +// budget, and the whole run is then replayed from the file and must earn three stars. +const fs = require('node:fs'); +const path = require('node:path'); +const { game, world } = require('./weekly-puzzle'); + +const ROOT = path.join(__dirname, '..'); +const SCHEMA = 1, HISTORY = 4, ATTEMPTS = 40, DEM_MAX = 100; +const NAMES = ['architect_weekly.name_all_roads_lead_to_hq', 'architect_weekly.name_the_hq_job', 'architect_weekly.name_hq_and_friends']; +const JOKES = ['architect_weekly.joke_hq_signed_the_lease', 'architect_weekly.joke_one_network_a_handful']; + +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; +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() : []); +const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`)); + +// ---------- playing the game ---------- +// Load a run definition into the page as this week's, with the briefs known so far. +function stage(ev, key, hq, briefs) { + ev(`UI.arWk={key:'${key}',def:{id:arWkId('${key}'),key:'${key}',wk:true,n:'',j:'',hq:'${hq}',via:[],budget:2e7,briefs:${JSON.stringify(briefs)},rev:1},at:Date.now()}`); +} +// Lay one tube the way a player does: a diverse trench when the pair already has one overland. +function lay(ev, a, b, via) { + if (!ev(`!!S.pops['${a}']`)) [a, b] = [b, a]; + const n = ev('S.links.length'); + ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:AR_TIER});closeModal()`); + if (ev('S.links.length') !== n + 1) throw new Error(`could not lay ${a}-${b} ${via}`); + return [a, b, via]; +} +// What the review would say: the first cut that strands a mission-critical site or leaves a site short. +const reviewFail = (ev) => J(ev, `(()=>{let f=null;for(const u of [...new Set(S.links.map(pzUnit))]){const x=arCut(u);for(const l of x.ls)l.cut=0;if(x.gold.length||x.short.length){f={u,gold:x.gold,short:x.short,dark:x.dark};break;}}compute();return f;})()`); +const passes = (ev) => ev('arShowStart();arShowSkip();S.ar.passed===pzSig()'); + +// The reference architect: fix what the checklist and the review find, cheapest first, until the brief passes. +function solveBrief(ev, W, steps) { + for (let guard = 0; guard < 24; guard++) { + for (const c of J(ev, 'S.pz.avoid.filter(c=>S.pops[c])')) { ev(`ACT.pzRmPop({city:'${c}'})`); steps.push(['@rm', c]); } + const e = J(ev, '(()=>{const e=arEval(),r=[...arReach(S.ar.hq,arAdj())];return {conn:e.conn,lat:e.lat,rings:e.rings,ready:e.ready,why:e.why,r,miss:e.sites.filter(s=>!s.ok).map(s=>s.c)};})()'); + const best = (from, to, skip) => { let o = null; for (const a of from) for (const b of to) if (a !== b) for (const x of W.opts(a, b)) if (!x.second && x.unit !== skip && (!o || x.cost < o.cost)) o = x; return o; }; + if (!e.conn) { const c = e.miss[0], o = best([c], e.r); if (!o) throw new Error(`no way to ${c}`); steps.push(lay(ev, o.a, o.b, o.via)); continue; } + if (e.lat && !e.lat.ok) { const os = W.opts(e.lat.a, e.lat.b).filter((x) => !x.second && x.ms <= e.lat.cap).sort((x, y) => x.cost - y.cost); if (!os.length) throw new Error('latency cap out of reach'); steps.push(lay(ev, os[0].a, os[0].b, os[0].via)); continue; } + const rg = e.rings.find((x) => !x.ok); + if (rg) { const cs = rg.cs, has = J(ev, 'S.links.map(l=>edgeKey(l))'); let done = false; + for (let i = 0; i < cs.length && !done; i++) { const a = cs[i], b = cs[(i + 1) % cs.length]; if (has.includes(ev(`edgeKey({a:'${a}',b:'${b}'})`))) continue; const o = best([a], [b]); if (o) { steps.push(lay(ev, o.a, o.b, o.via)); done = true; } } + if (!done) throw new Error('ring out of reach'); continue; } + if (!e.ready) throw new Error(`not ready: ${e.why}`); + const f = reviewFail(ev); if (!f) return; + if (f.short.length) throw new Error('short of capacity'); + // A cut strands a mission-critical site: join the stranded side to the rest another way. + const rest = J(ev, `Object.keys(S.pops).filter(c=>!${JSON.stringify(f.dark)}.includes(c))`), o = best(f.dark, rest, f.u); + if (!o) throw new Error('no second way'); steps.push(lay(ev, o.a, o.b, o.via)); + } + throw new Error('the brief would not pass'); +} + +// ---------- designing a run ---------- +// The brief kinds after the first two. Each is designed against the reference network as it stands, or refused (null). +function design(kind, ev, W, r, s) { + const pops = J(ev, 'S.pz.cities'), gold = J(ev, 'S.ar.gold'), hq = s.hq, next = () => s.todo.shift(), dem = (c) => { const g = Math.min(s.room, pick(r, [10, 20, 20, 30])); s.room -= g; return { [c]: g }; }; + const weak = J(ev, `S.pz.cities.filter(c=>c!==S.ar.hq&&!S.ar.gold.includes(c)&&[...new Set(S.links.map(pzUnit))].some(u=>arDark(u).includes(c)))`); + if (kind === 'gold') { if (!weak.length) return null; const c = weak.sort((a, b) => W.km(hq, b) - W.km(hq, a))[0]; return { gold: [c] }; } + if (kind === 'addgold') { if (!s.todo.length || s.room < 10) return null; const c = next(); return { add: [c], dem: dem(c), gold: [c] }; } + if (kind === 'move') { const c = pops.filter((x) => x !== hq && !gold.includes(x) && !(s.lat || []).includes(x)).sort((a, b) => W.km(hq, b) - W.km(hq, a))[0]; + if (!c || !s.todo.length || s.room < 10) return null; const n = next(); return { drop: [c], add: [n], dem: dem(n), gold: [n] }; } + if (kind === 'lat') { let bestP = null; + for (const a of pops) for (const b of pops) { if (a >= b) continue; const cur = J(ev, `arLat('${a}','${b}')`), os = W.opts(a, b).filter((x) => !x.second); if (cur == null || !os.length) continue; + const ms = Math.min(...os.map((x) => x.ms)), cap = Math.ceil(ms * 1.12 * 10) / 10; if (cap < 2 || cap >= cur * 0.85) continue; + if (!bestP || cur / cap > bestP.k) bestP = { a, b, cap, k: cur / cap }; } + if (!bestP) return null; s.lat = [bestP.a, bestP.b]; return { lat: [bestP.a, bestP.b, bestP.cap] }; } + if (kind === 'ring') { const cs = pops.filter((c) => c !== hq).sort((a, b) => W.km(hq, a) - W.km(hq, b)).slice(0, 2); if (cs.length < 2) return null; + const ring = [hq, ...cs]; if (ev(`arRingOk(${JSON.stringify(ring)})`)) return null; return { ring }; } + return null; +} + +// Play a run from scratch: stage, start, then brief by brief design (when designing) or follow the file, solve, review, next. +function play(g, W, key, hq, plan, r, sites) { + const { ev } = g, briefs = [], steps = [], s = { hq, todo: sites.slice(), room: DEM_MAX, lat: null }; + const first = () => { const c = s.todo.shift(), g0 = Math.min(s.room, pick(r, [20, 30, 40])); s.room -= g0; return { add: [c], dem: { [c]: g0 } }; }; + for (let i = 0; i < plan.length; i++) { + let b = null; + if (plan[i] === 'add1') b = first(); + else if (plan[i] === 'add2') { if (s.todo.length < 2) throw new Error('not enough sites'); const a = s.todo.shift(), c = s.todo.shift(), ga = Math.min(s.room, 20); s.room -= ga; const gc = Math.min(s.room, pick(r, [10, 20])); s.room -= gc; b = { add: [a, c], dem: { [a]: ga, [c]: gc } }; } + // A kind that cannot be made here gives way to one the run has not had yet, then to a new mission-critical site. + else for (const k of [plan[i], ...['lat', 'ring', 'move', 'gold'].filter((x) => !plan.slice(0, i).includes(x) && x !== plan[i]), 'addgold']) { b = design(k, ev, W, r, s); if (b) { plan[i] = k; break; } } + if (!b) throw new Error(`brief ${i + 1}: nothing left to ask`); + b.tubes = 9; briefs.push(b); stage(ev, key, hq, briefs.map((x) => Object.assign({ t: '' }, x))); + if (i === 0) ev(`ACT.pzArStart({id:arWkId('${key}')})`); else ev('ACT.pzArNext()'); + if (ev('S.ar.bi') !== i) throw new Error(`brief ${i + 1} did not start`); + const st = []; solveBrief(ev, W, st); steps.push(st); + b.tubes = ev('S.links.filter(l=>(l.br|0)===S.ar.bi).length'); + if (!b.tubes) throw new Error(`brief ${i + 1} needs no tube`); + ev(`UI.arWk.def.briefs[${i}].tubes=${b.tubes}`); + if (!passes(ev)) throw new Error(`brief ${i + 1}: the review does not pass`); + } + return { briefs, steps, spend: ev('arSpend()') }; +} + +// Replay a file the way a player would, from its own reference: it must pass every brief and earn three stars. +function verify(g, j, key) { + const { ev } = g, def = J(ev, `arWkValid(${JSON.stringify(j)},'${key}')`); + if (!def) return { ok: false, why: 'the game rejects it' }; + if (!j.ref || !Array.isArray(j.ref.steps) || j.ref.steps.length !== def.briefs.length) return { ok: false, why: 'no reference' }; + try { + ev(`UI.arWk={key:'${key}',def:arWkValid(${JSON.stringify(j)},'${key}'),at:Date.now()}`); + ev(`ACT.pzArStart({id:arWkId('${key}')})`); + for (let i = 0; i < def.briefs.length; i++) { + for (const st of j.ref.steps[i]) if (st[0] === '@rm') ev(`ACT.pzRmPop({city:'${st[1]}'})`); else lay(ev, st[0], st[1], st[2]); + if (!passes(ev)) return { ok: false, why: `brief ${i + 1} does not pass` }; + if (i < def.briefs.length - 1) ev('ACT.pzArNext()'); + } + const sp = ev('arSpend()'), stars = ev(`arStars(${sp})`); + ev('arStop(true)'); + return stars === 3 ? { ok: true, spend: sp } : { ok: false, why: `the reference earns ${stars} stars (spend ${sp}, budget ${j.budget})` }; + } catch (e) { return { ok: false, why: e.message }; } +} + +function generate(g, key, dir) { + const { ev } = g, W = world(ev); + // The regions of the last weeks, so the HQ moves around the world. + const past = list(dir).filter((k) => k < key).map((k) => { try { return JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')).hq; } catch (e) { return null; } }); + const recent = past.slice(-HISTORY).map((c) => W.C[c] && W.C[c].reg), used = past.slice(-12); + for (let attempt = 0; attempt < ATTEMPTS; attempt++) { + const r = rng(hash(`architect|${key}|${attempt}`)); + const hqs = W.cities.filter((c) => !used.includes(c.id) && (!recent.includes(c.reg) || attempt >= ATTEMPTS / 2)); + const hq = pick(r, hqs).id; + const near = W.cities.filter((c) => c.id !== hq && c.reg === W.C[hq].reg && W.km(hq, c.id) < 2500).sort((a, b) => W.km(hq, a.id) - W.km(hq, b.id)).slice(0, 8).map((c) => c.id); + if (near.length < 6) continue; + const mid = shuffle(r, ['lat', 'ring', 'move', 'addgold']).slice(0, r() < 0.5 ? 2 : 3); + const plan = ['add1', 'add2', 'gold', ...mid, 'gold']; + const sites = [...near.slice(0, 3), ...shuffle(r, near.slice(3))]; + try { + const run = play(g, W, key, hq, plan, r, sites); + const jk = pick(r, JOKES), j = { v: SCHEMA, key, hq, budget: ceil10k(run.spend * 1.06), name: { l: pick(r, NAMES), p: { hq } }, joke: { l: jk, p: jk === JOKES[0] ? { hq } : {} }, briefs: run.briefs, ref: { spend: run.spend, steps: run.steps } }; + const v = verify(g, j, key); + if (!v.ok) { if (process.env.DEBUG) console.warn(`${key} #${attempt}: ${v.why}`); continue; } + return j; + } catch (e) { if (process.env.DEBUG) console.warn(`${key} #${attempt} (${hq}): ${e.message}`); } + } + throw new Error(`${key}: no run survived verification`); +} + +// --check: every file is what the game accepts, under its own name, and the weeks still to come earn three stars. +function check(g, dir, now = Date.now()) { + const { ev } = g, 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(`!!arWkValid(${JSON.stringify(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; } + if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); } + } + if (keys.length) { + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), '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; +} +// A release can change prices under weeks already out: a week not over yet whose reference no longer earns three stars +// is regenerated with its rev up, so players' stars for that week (only that week) start again. Past weeks stay. +function refresh(g, dir, now = Date.now()) { + const { ev } = g, fixed = [], bad = []; + for (const k of list(dir)) { + let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated below */ } + const valid = !!j && ev(`!!arWkValid(${JSON.stringify(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now; + if (valid && (!live || verify(g, j, k).ok)) continue; + const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1; + try { writeWeek(dir, Object.assign(generate(g, k, dir), { rev })); fixed.push(`${k}: regenerated as rev ${rev}`); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); } + } + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ } + if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); } + return { fixed, 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); }; +const say = (j) => `${j.key}: HQ ${j.hq}, ${j.briefs.length} briefs (${j.briefs.map((b) => Object.keys(b).filter((k) => k !== 'tubes' && k !== 'dem').join('+')).join(', ')}), budget ${j.budget}, reference ${j.ref.spend}`; + +module.exports = { generate, verify, check, refresh, writeWeek, writeIndex, list, say }; + +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/architect/weekly')), g = game(opt('--page') && path.resolve(opt('--page'))); + if (!g.ev("typeof arWkValid==='function'")) { console.log('This game has no weekly Architect runs yet.'); process.exit(0); } + if (args.includes('--check')) { + const r = refresh(g, dir); + for (const x of r.fixed) console.log(`fixed: ${x}`); + const bad = [...r.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 Architect run(s) OK`); + process.exit(bad.length ? 1 : 0); + } + 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(say(j)); + } +} diff --git a/site/architect/weekly/2026-W44.json b/site/architect/weekly/2026-W44.json new file mode 100644 index 0000000..fd5f6ed --- /dev/null +++ b/site/architect/weekly/2026-W44.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W44","hq":"cor","budget":1160000,"name":{"l":"architect_weekly.name_all_roads_lead_to_hq","p":{"hq":"cor"}},"joke":{"l":"architect_weekly.joke_hq_signed_the_lease","p":{"hq":"cor"}},"briefs":[{"add":["bue"],"dem":{"bue":20},"tubes":1},{"add":["scl","mvd"],"dem":{"scl":20,"mvd":20},"tubes":2},{"gold":["mvd"],"tubes":2},{"ring":["cor","bue","scl"],"tubes":1},{"add":["cgr"],"dem":{"cgr":20},"gold":["cgr"],"tubes":2},{"lat":["cgr","cor",11.3],"tubes":1}],"ref":{"spend":1090844,"steps":[[["cor","bue","land"]],[["cor","scl","land"],["bue","mvd","land"]],[["bue","cor","land"],["mvd","bue","land"]],[["scl","bue","land"]],[["bue","cgr","land"],["cgr","bue","land"]],[["cgr","cor","land"]]]}} diff --git a/site/architect/weekly/2026-W45.json b/site/architect/weekly/2026-W45.json new file mode 100644 index 0000000..ea2b841 --- /dev/null +++ b/site/architect/weekly/2026-W45.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W45","hq":"maa","budget":920000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"maa"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["blr"],"dem":{"blr":20},"tubes":1},{"add":["hyd","cbo"],"dem":{"hyd":20,"cbo":20},"tubes":2},{"gold":["cbo"],"tubes":1},{"ring":["maa","blr","hyd"],"tubes":1},{"drop":["hyd"],"add":["mle"],"dem":{"mle":30},"gold":["mle"],"tubes":2},{"gold":["blr"],"tubes":1}],"ref":{"spend":860936,"steps":[[["maa","blr","land"]],[["blr","hyd","land"],["maa","cbo","smw6"]],[["cbo","maa","smw4"]],[["hyd","maa","land"]],[["@rm","hyd"],["cbo","mle","smw6"],["mle","maa","iax"]],[["blr","maa","land"]]]}} diff --git a/site/architect/weekly/2026-W46.json b/site/architect/weekly/2026-W46.json new file mode 100644 index 0000000..a047c0e --- /dev/null +++ b/site/architect/weekly/2026-W46.json @@ -0,0 +1 @@ +{"v":1,"key":"2026-W46","hq":"svg","budget":570000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"svg"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["krs"],"dem":{"krs":40},"tubes":1},{"add":["osl","ebj"],"dem":{"osl":20,"ebj":10},"tubes":2},{"gold":["ebj"],"tubes":2},{"lat":["osl","svg",2.2],"tubes":1},{"drop":["krs"],"add":["ams"],"dem":{"ams":20},"gold":["ams"],"tubes":4},{"ring":["svg","osl","ebj"],"tubes":1},{"add":["edi"],"dem":{"edi":10},"gold":["edi"],"tubes":2}],"ref":{"spend":534112,"steps":[[["svg","krs","land"]],[["krs","osl","land"],["krs","ebj","land"]],[["krs","svg","land"],["ebj","krs","land"]],[["osl","svg","land"]],[["@rm","krs"],["ebj","svg","land"],["ebj","ams","land"],["ebj","svg","land"],["ams","ebj","land"]],[["ebj","osl","land"]],[["svg","edi","nouk"],["edi","ebj","havh"]]]}} diff --git a/site/architect/weekly/index.json b/site/architect/weekly/index.json new file mode 100644 index 0000000..8955841 --- /dev/null +++ b/site/architect/weekly/index.json @@ -0,0 +1 @@ +{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]} diff --git a/site/i18n/de.js b/site/i18n/de.js index 9715f99..e2c5eae 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -123,6 +123,20 @@ "architect.usa_6":"Ein Cloud-Deal im Silicon Valley. Er ist geschäftskritisch.", "architect.x_paid_for_and_gone":"{x} davon für Dinge, die du wieder entfernt hast", "architect.your_shape":"Deine Form", +"architect_weekly.joke_hq_signed_the_lease":"{hq} hat den Mietvertrag unterschrieben. Alles Weitere ist dein Problem.", +"architect_weekly.joke_one_network_a_handful":"Ein Netz, eine Handvoll Briefings und ein Affe mit Schere.", +"architect_weekly.name_all_roads_lead_to_hq":"Alle Wege führen nach {hq}", +"architect_weekly.name_hq_and_friends":"{hq} und Freunde", +"architect_weekly.name_the_hq_job":"Der {hq}-Job", +"architect_weekly.t_add_gold":"{a} ist neu dabei und von Tag eins an geschäftskritisch: muss jeden einzelnen Schnitt überstehen.", +"architect_weekly.t_add_one":"{a} ist neu dabei: anschließen.", +"architect_weekly.t_add_two":"{a} und {b} sind neu dabei: anschließen.", +"architect_weekly.t_drop":"{a} schließt: zieh aus und bau dort nicht wieder.", +"architect_weekly.t_gold_one":"{a} ist jetzt geschäftskritisch: muss jeden einzelnen Schnitt überstehen.", +"architect_weekly.t_gold_two":"{a} und {b} sind jetzt geschäftskritisch: müssen jeden einzelnen Schnitt überstehen.", +"architect_weekly.t_lat":"{a} ⇄ {b} muss unter {ms} ms bleiben.", +"architect_weekly.t_ring":"{list} wollen auf einem Ring liegen.", +"architect_weekly.weekly_run":"Architect-Run der Woche", "badges.a_petabit_a_second":"Ein Petabit pro Sekunde", "badges.a_secret_badge":"Ein geheimes Abzeichen", "badges.attend_a_conference":"Besuche eine Konferenz.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 605bade..5376911 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -121,6 +121,20 @@ "architect.usa_6":"Un trato de nube en Silicon Valley. Es crítico.", "architect.x_paid_for_and_gone":"{x} de eso pagó cosas que quitaste", "architect.your_shape":"Tu forma", +"architect_weekly.joke_hq_signed_the_lease":"{hq} firmó el contrato. Todo lo demás es problema tuyo.", +"architect_weekly.joke_one_network_a_handful":"Una red, un puñado de encargos y un mono con tijeras.", +"architect_weekly.name_all_roads_lead_to_hq":"Todos los caminos llevan a {hq}", +"architect_weekly.name_hq_and_friends":"{hq} y amigos", +"architect_weekly.name_the_hq_job":"El golpe de {hq}", +"architect_weekly.t_add_gold":"{a} se apunta, crítico desde el primer día: debe sobrevivir a cualquier corte.", +"architect_weekly.t_add_one":"{a} se apunta: conéctalo.", +"architect_weekly.t_add_two":"{a} y {b} se apuntan: conéctalos.", +"architect_weekly.t_drop":"{a} cierra: múdate y no vuelvas a construir allí.", +"architect_weekly.t_gold_one":"{a} es ahora crítico: debe sobrevivir a cualquier corte.", +"architect_weekly.t_gold_two":"{a} y {b} son ahora críticos: deben sobrevivir a cualquier corte.", +"architect_weekly.t_lat":"{a} ⇄ {b} debe quedarse por debajo de {ms} ms.", +"architect_weekly.t_ring":"{list} quieren estar en un mismo anillo.", +"architect_weekly.weekly_run":"La ronda de Arquitecto de la semana", "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 8ba1aeb..4fbd868 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -121,6 +121,20 @@ "architect.usa_6":"Un contrat cloud dans la Silicon Valley. Il est critique.", "architect.x_paid_for_and_gone":"dont {x} pour des choses que tu as retirées", "architect.your_shape":"Ta forme", +"architect_weekly.joke_hq_signed_the_lease":"{hq} a signé le bail. Tout le reste, c’est ton problème.", +"architect_weekly.joke_one_network_a_handful":"Un réseau, une poignée de briefs et un singe avec des ciseaux.", +"architect_weekly.name_all_roads_lead_to_hq":"Tous les chemins mènent à {hq}", +"architect_weekly.name_hq_and_friends":"{hq} et ses amis", +"architect_weekly.name_the_hq_job":"Le coup de {hq}", +"architect_weekly.t_add_gold":"{a} signe, critique dès le premier jour : il doit survivre à n’importe quelle coupure.", +"architect_weekly.t_add_one":"{a} signe : raccorde-le.", +"architect_weekly.t_add_two":"{a} et {b} signent : raccorde-les.", +"architect_weekly.t_drop":"{a} ferme : déménage et ne construis plus là-bas.", +"architect_weekly.t_gold_one":"{a} est désormais critique : il doit survivre à n’importe quelle coupure.", +"architect_weekly.t_gold_two":"{a} et {b} sont désormais critiques : ils doivent survivre à n’importe quelle coupure.", +"architect_weekly.t_lat":"{a} ⇄ {b} doit rester sous {ms} ms.", +"architect_weekly.t_ring":"{list} veulent être sur un même anneau.", +"architect_weekly.weekly_run":"Le parcours d’architecte de la semaine", "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 69b9299..c21f57c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -121,6 +121,20 @@ "architect.usa_6":"Un accordo cloud nella Silicon Valley. È critico.", "architect.x_paid_for_and_gone":"{x} di questi per cose che hai tolto", "architect.your_shape":"La tua forma", +"architect_weekly.joke_hq_signed_the_lease":"{hq} ha firmato il contratto. Tutto il resto è un problema tuo.", +"architect_weekly.joke_one_network_a_handful":"Una rete, una manciata di brief e una scimmia con le forbici.", +"architect_weekly.name_all_roads_lead_to_hq":"Tutte le strade portano a {hq}", +"architect_weekly.name_hq_and_friends":"{hq} e amici", +"architect_weekly.name_the_hq_job":"Il colpo di {hq}", +"architect_weekly.t_add_gold":"{a} si iscrive, critico dal primo giorno: deve sopravvivere a qualsiasi taglio.", +"architect_weekly.t_add_one":"{a} si iscrive: collegalo.", +"architect_weekly.t_add_two":"{a} e {b} si iscrivono: collegali.", +"architect_weekly.t_drop":"{a} chiude: trasloca e non costruire più lì.", +"architect_weekly.t_gold_one":"{a} ora è critico: deve sopravvivere a qualsiasi taglio.", +"architect_weekly.t_gold_two":"{a} e {b} ora sono critici: devono sopravvivere a qualsiasi taglio.", +"architect_weekly.t_lat":"{a} ⇄ {b} deve restare sotto {ms} ms.", +"architect_weekly.t_ring":"{list} vogliono stare su un unico anello.", +"architect_weekly.weekly_run":"Il percorso da architetto della settimana", "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 00c2e32..3782ca0 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -121,6 +121,20 @@ "architect.usa_6":"Um contrato de nuvem no Vale do Silício. É crítico.", "architect.x_paid_for_and_gone":"{x} disso pagou coisas que você removeu", "architect.your_shape":"Seu formato", +"architect_weekly.joke_hq_signed_the_lease":"{hq} assinou o contrato. Todo o resto é problema seu.", +"architect_weekly.joke_one_network_a_handful":"Uma rede, um punhado de briefings e um macaco com uma tesoura.", +"architect_weekly.name_all_roads_lead_to_hq":"Todos os caminhos levam a {hq}", +"architect_weekly.name_hq_and_friends":"{hq} e amigos", +"architect_weekly.name_the_hq_job":"O golpe de {hq}", +"architect_weekly.t_add_gold":"{a} entrou, crítico desde o primeiro dia: precisa sobreviver a qualquer corte.", +"architect_weekly.t_add_one":"{a} entrou: conecte-o.", +"architect_weekly.t_add_two":"{a} e {b} entraram: conecte-os.", +"architect_weekly.t_drop":"{a} vai fechar: saia de lá e não construa lá de novo.", +"architect_weekly.t_gold_one":"{a} agora é crítico: precisa sobreviver a qualquer corte.", +"architect_weekly.t_gold_two":"{a} e {b} agora são críticos: precisam sobreviver a qualquer corte.", +"architect_weekly.t_lat":"{a} ⇄ {b} precisa ficar abaixo de {ms} ms.", +"architect_weekly.t_ring":"{list} querem ficar no mesmo anel.", +"architect_weekly.weekly_run":"A rodada de Arquiteto da semana", "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/site/sw.js b/site/sw.js index 2e0924c..745bafa 100644 --- a/site/sw.js +++ b/site/sw.js @@ -25,8 +25,8 @@ self.addEventListener('fetch', (e) => { } const local = url.origin === location.origin, fonts = /fonts\.(googleapis|gstatic)\.com$/.test(url.hostname); if (!local && !fonts) return; - // Weekly puzzles and scenarios are published between releases: ask the network first, and keep a copy for offline. - if (local && (url.pathname.startsWith('/puzzles/weekly/') || url.pathname.startsWith('/scenarios/weekly/'))) { + // Weekly puzzles, scenarios and Architect runs are published between releases: ask the network first, and keep a copy for offline. + if (local && (url.pathname.startsWith('/puzzles/weekly/') || url.pathname.startsWith('/scenarios/weekly/') || url.pathname.startsWith('/architect/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; diff --git a/src/game/60-features/96-architect.js b/src/game/60-features/96-architect.js index 14ef3f3..ed69701 100644 --- a/src/game/60-features/96-architect.js +++ b/src/game/60-features/96-architect.js @@ -41,17 +41,17 @@ const AR_RUNS=[ ]}, ]; const arOn=()=>pzOn()&&!!S.ar; -const arRunDef=id=>AR_RUNS.find(r=>r.id===id)||null; +const arRunDef=id=>AR_RUNS.find(r=>r.id===id)||arWkRun(id); const arRun=()=>arRunDef(S.ar.id); const arBrief=()=>arRun().briefs[S.ar.bi]; const arLast=()=>S.ar.bi>=arRun().briefs.length-1; // ---------- progress: best stars, spend and briefs cleared per run, under its own key ---------- function arLoad(){let j=null;try{j=JSON.parse(localStorage.getItem(AR_KEY)||'{}');}catch(e){}const o={runs:{}}; - if(j&&j.runs&&typeof j.runs==='object')for(const k of Object.keys(j.runs)){const r=j.runs[k];if(!arRunDef(k)||!r||typeof r!=='object')continue; - o.runs[k]={st:int(r.st,0,3,0),br:int(r.br,0,99,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)};} + if(j&&j.runs&&typeof j.runs==='object')for(const k of Object.keys(j.runs)){const r=j.runs[k];if((!arRunDef(k)&&!AR_WK_ID.test(k))||!r||typeof r!=='object')continue; + o.runs[k]={st:int(r.st,0,3,0),br:int(r.br,0,99,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)};if(AR_WK_ID.test(k))o.runs[k].rv=int(r.rv,1,999,1);} return o;} function arStore(p){try{localStorage.setItem(AR_KEY,JSON.stringify(p));}catch(e){}} -function arRecord(st,br,sp){const p=arLoad(),r=p.runs[S.ar.id]||{st:0,br:0,sp:null}; +function arRecord(st,br,sp){const p=arLoad(),run=arRun(),old=p.runs[S.ar.id],r=old&&(!run.wk||(old.rv||1)===run.rev)?old:{st:0,br:0,sp:null};if(run.wk)r.rv=run.rev; if(st>r.st||(st===r.st&&st>0&&(r.sp==null||sp[...(x.add||[]),...(x.gold||[]),...(x.ring||[])]))].filter(c=>!P.cities.includes(c)&&!P.avoid.includes(c)); + // Later briefs stay a surprise: their cities do not show until they come (Show all cities shows everything). + P.via=(arRun().via||[]).filter(c=>!P.cities.includes(c)&&!P.avoid.includes(c)); arDemand();A.start=arSnapStr();UI.pzHist=[];UI.sel=null;UI.arFail=null; compute();pzCam();renderAll(); toast(`${tr('architect.brief_n_of_m',{n:i+1,m:arRun().briefs.length})}
${esc(b.t)}`,'goal');sfx('click');} diff --git a/src/game/60-features/98-architect-weekly.js b/src/game/60-features/98-architect-weekly.js new file mode 100644 index 0000000..f345fdd --- /dev/null +++ b/src/game/60-features/98-architect-weekly.js @@ -0,0 +1,59 @@ +/* ---------- the published weekly Architect run ---------- + Every Sunday scripts/weekly-architect.js publishes architect/weekly/.json next to the page: an HQ, a budget and + the briefs, as data. Fetched only when Puzzles opens, checked field by field, and played like the handmade runs + (AR_RUNS) under the id 'wk-'. A brief's text is written here from what it asks for, in the player's language, so + the file can never say one thing and want another. When the file is missing, offline or wrong there is simply no + weekly run that week. */ +const AR_WK_V=1,AR_WK_FIELDS=['v','key','hq','budget','name','joke','briefs','ref','rev'],AR_WK_BRIEF=['add','gold','ring','drop','dem','lat','tubes']; +// The labels a file may name (N_: kept whole in the shipped page); their only placeholder is {hq}, a city. +const AR_WK_NAMES=[N_('architect_weekly.name_all_roads_lead_to_hq'),N_('architect_weekly.name_the_hq_job'),N_('architect_weekly.name_hq_and_friends')]; +const AR_WK_JOKES=[N_('architect_weekly.joke_hq_signed_the_lease'),N_('architect_weekly.joke_one_network_a_handful')]; +const arWkId=key=>'wk-'+key,AR_WK_ID=/^wk-\d{4}-W\d{2}$/; +function arWkTxt(o,list){if(!pzObj(o)||!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]))]; + if(Object.keys(p).length!==need.length||!need.every(k=>k==='hq'&&pzCityOk(p[k])))return null;return {l:o.l,p:Object.assign({},p)};} +const arWkSay1=o=>tr(o.l,o.p.hq?{hq:CITY[o.p.hq].name}:{}); +// What a brief says, built from what it wants. +function arWkSay(b){const n=c=>CITY[c].name,t=[]; + if(b.drop)t.push(tr('architect_weekly.t_drop',{a:n(b.drop[0])})); + const ag=b.add&&b.gold&&b.add.length===1&&b.gold.length===1&&b.add[0]===b.gold[0]; + if(ag)t.push(tr('architect_weekly.t_add_gold',{a:n(b.add[0])})); + else if(b.add)t.push(b.add.length>1?tr('architect_weekly.t_add_two',{a:n(b.add[0]),b:n(b.add[1])}):tr('architect_weekly.t_add_one',{a:n(b.add[0])})); + if(b.gold&&!ag)t.push(b.gold.length>1?tr('architect_weekly.t_gold_two',{a:n(b.gold[0]),b:n(b.gold[1])}):tr('architect_weekly.t_gold_one',{a:n(b.gold[0])})); + if(b.ring)t.push(tr('architect_weekly.t_ring',{list:b.ring.map(n).join(', ')})); + if(b.lat)t.push(tr('architect_weekly.t_lat',{a:n(b.lat[0]),b:n(b.lat[1]),ms:+b.lat[2].toFixed(1)})); + return t.join(' ');} +// The briefs, in order: a site exists from the brief that adds it until one drops it; every brief asks for something. +function arWkBriefs(a,hq){if(!Array.isArray(a)||a.length<3||a.length>7)return null;const sites=new Set([hq]),gone=new Set(),out=[]; + const ids=(x,lo,hi)=>x==null?[]:Array.isArray(x)&&x.length>=lo&&x.length<=hi&&x.every(pzCityOk)&&new Set(x).size===x.length?x.slice():null; + for(const b of a){if(!pzObj(b)||Object.keys(b).some(k=>!AR_WK_BRIEF.includes(k)))return null; + const drop=ids(b.drop,1,1),add=ids(b.add,1,2),gold=ids(b.gold,1,2),ring=b.ring==null?[]:ids(b.ring,3,4);if(!drop||!add||!gold||!ring)return null; + for(const c of drop){if(c===hq||!sites.has(c))return null;sites.delete(c);gone.add(c);} + for(const c of add){if(sites.has(c)||gone.has(c))return null;sites.add(c);} + if(![...gold,...ring].every(c=>sites.has(c))||gold.includes(hq))return null; + const dem={};if(b.dem!=null){if(!pzObj(b.dem))return null;for(const c of Object.keys(b.dem)){const g=b.dem[c];if(!sites.has(c)||c===hq||!Number.isInteger(g)||g<10||g>400)return null;dem[c]=g;}} + let lat=null;if(b.lat!=null){const l=b.lat;if(!Array.isArray(l)||l.length!==3||!sites.has(l[0])||!sites.has(l[1])||l[0]===l[1]||typeof l[2]!=='number'||!isFinite(l[2])||l[2]<1||l[2]>300)return null;lat=l.slice();} + if(!Number.isInteger(b.tubes)||b.tubes<0||b.tubes>9)return null; + if(!add.length&&!gold.length&&!ring.length&&!lat)return null; + const o={tubes:b.tubes};if(add.length)o.add=add;if(gold.length)o.gold=gold;if(ring.length)o.ring=ring;if(drop.length)o.drop=drop;if(Object.keys(dem).length)o.dem=dem;if(lat)o.lat=lat; + o.t=arWkSay(o);out.push(o);} + return out[0].add?out:null;} +// The file, never trusted: a run definition like AR_RUNS's, or null. +function arWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!AR_WK_FIELDS.includes(k))||j.v!==AR_WK_V||j.key!==key||pzWeekStart(key)==null||!pzCityOk(j.hq))return null; + if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>2e7)return null; + if(j.rev!==undefined&&!(Number.isInteger(j.rev)&&j.rev>=2&&j.rev<=999))return null;if(j.ref!==undefined&&!pzObj(j.ref))return null; + const name=arWkTxt(j.name,AR_WK_NAMES),joke=arWkTxt(j.joke,AR_WK_JOKES),briefs=arWkBriefs(j.briefs,j.hq);if(!name||!joke||!briefs)return null; + return {id:arWkId(key),key,wk:true,n:arWkSay1(name),j:arWkSay1(joke),hq:j.hq,via:[],budget:j.budget,briefs,rev:j.rev||1};} +// The run behind an id, when it is this week's. +function arWkRun(id){const w=UI.arWk;return w&&w.def&&w.def.id===id?w.def:null;} +// ---------- fetching it: when Puzzles opens, never on page load ---------- +function arWkEnsure(){const key=pzWeekKey(new Date()),w=UI.arWk;if(w&&w.key===key&&(w.def||Date.now()-w.at<5*60e3))return; + const st=UI.arWk={key,def:null,at:Date.now()};let done=false; + const fin=def=>{if(done)return;done=true;clearTimeout(to);if(UI.arWk!==st)return;st.def=def;st.at=Date.now();const el=$('arWk');if(el)el.outerHTML=arWkRow();}; + 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;} + try{fetch(`architect/weekly/${key}.json`,ac?{signal:ac.signal}:{}).then(r=>r.ok?r.json():null).then(j=>arWkValid(j,key),()=>null).then(fin,()=>fin(null));}catch(e){fin(null);}} +// Its row in the Puzzles menu, above the handmade runs; nothing while there is none. +function arWkRow(){const w=UI.arWk,r=w&&w.key===pzWeekKey(new Date())?w.def:null;if(!r)return '
'; + const x=arLoad().runs[r.id],ok=x&&(x.rv||1)===r.rev?x:null; + return `
🗓️ ${tr('architect_weekly.weekly_run')}
${esc(r.n)} ${pzStarStr(ok?ok.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)} · ${tr('puzzles.budget_x',{x:fmt$(r.budget)})}${ok&&ok.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(ok.sp)}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},ok&&ok.st>=3?'ghost':'pink')}
`;} diff --git a/src/game/95-modals/96-architect.js b/src/game/95-modals/96-architect.js index 3d9c6f4..1eb9c7c 100644 --- a/src/game/95-modals/96-architect.js +++ b/src/game/95-modals/96-architect.js @@ -65,7 +65,7 @@ function arLinkModal(a,b,keep){const kb=pzKind(b); // ---------- results ---------- const arLine=st=>st>=3?tr('architect.line_3'):st===2?tr('architect.line_2'):tr('architect.line_1'); function arResults(done){const A=S.ar,run=arRun(),sp=arSpend(),br=done?run.briefs.length:A.bi,st=done?arStars(sp):0,sh=arShape();arRecord(st,br,sp); - const nx=AR_RUNS[AR_RUNS.indexOf(run)+1]||null,stars=[0,1,2].map(i=>`⭐`).join(''); + const ri=AR_RUNS.indexOf(run),nx=ri>=0?AR_RUNS[ri+1]||null:null,stars=[0,1,2].map(i=>`⭐`).join(''); openModal(`
${st>=3?pzConfetti():''}
🏗️ ${done?tr('architect.run_complete'):tr('architect.run_over')}

${esc(run.n)}

${stars}

${done?arLine(st):tr('architect.the_cfo_pulled_the_plug')}

${done?'⭐':'☆'} ${tr('architect.briefs_done')}${br} / ${run.briefs.length}
@@ -75,7 +75,7 @@ function arResults(done){const A=S.ar,run=arRun(),sp=arSpend(),br=done?run.brief
${nx&&done?btn(tr('architect.next_run')+' →','pzArStart',{id:nx.id},'pink big'):btn(tr('puzzles.more_puzzles'),'puzzleMenu',{},'pink big')}${btn(tr('architect.try_again'),'pzRetry',{},'')}${done?btn(tr('common.share_2cd9'),'pzShare',{},'ghost'):btn(tr('architect.keep_going'),'closeModal',{},'ghost')}
`); for(let i=0;i{sfx('star');haptic(15);},i*450+150);if(st>=3)setTimeout(()=>sfx('fanfare'),3*450+250);} // ---------- the list ---------- -function arMenuRows(){const p=arLoad();let h=`

🏗️ ${tr('architect.architect_runs')} ${tr('architect.new')}

${tr('architect.runs_lead')}

`; +function arMenuRows(){const p=arLoad();let h=`

🏗️ ${tr('architect.architect_runs')} ${tr('architect.new')}

${tr('architect.runs_lead')}

`;arWkEnsure();h+=arWkRow(); for(const r of AR_RUNS){const x=p.runs[r.id]; h+=`
${esc(r.n)} ${pzStarStr(x?x.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)}${' · '+tr('puzzles.budget_x',{x:fmt$(r.budget)})}${x&&x.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(x.sp)}):x&&x.br?' · '+tr('architect.best_n_briefs',{n:x.br}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},x&&x.st>=3?'ghost':'pink')}
`;} return h;} diff --git a/src/i18n/en.js b/src/i18n/en.js index 3429679..e0a4100 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -122,6 +122,20 @@ "architect.usa_6":"A cloud deal in Silicon Valley. It's mission-critical.", "architect.x_paid_for_and_gone":"{x} of that paid for things you removed", "architect.your_shape":"Your shape", +"architect_weekly.joke_hq_signed_the_lease":"{hq} signed the lease. Everything after that is your problem.", +"architect_weekly.joke_one_network_a_handful":"One network, a handful of briefs and a monkey with scissors.", +"architect_weekly.name_all_roads_lead_to_hq":"All Roads Lead to {hq}", +"architect_weekly.name_hq_and_friends":"{hq} and Friends", +"architect_weekly.name_the_hq_job":"The {hq} Job", +"architect_weekly.t_add_gold":"{a} signs up, mission-critical from day one: it must survive any single cut.", +"architect_weekly.t_add_one":"{a} signs up: connect it.", +"architect_weekly.t_add_two":"{a} and {b} sign up: connect them.", +"architect_weekly.t_drop":"{a} is closing: move out, and don’t build there again.", +"architect_weekly.t_gold_one":"{a} is now mission-critical: it must survive any single cut.", +"architect_weekly.t_gold_two":"{a} and {b} are now mission-critical: they must survive any single cut.", +"architect_weekly.t_lat":"{a} ⇄ {b} must stay under {ms} ms.", +"architect_weekly.t_ring":"{list} want to sit on one ring.", +"architect_weekly.weekly_run":"This week’s Architect run", "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/architect.test.js b/tests/architect.test.js index a245070..40d4498 100644 --- a/tests/architect.test.js +++ b/tests/architect.test.js @@ -39,7 +39,7 @@ test('architect runs: the chaos monkey finds a shared trench, edits clear the cu const { ev, errors } = load(); ev("ACT.pzArStart({id:'euro'})"); assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden'); - assert.equal(ev("arHide('dus')"), false); + assert.equal(ev("arHide('dus')"), true, 'a city a later brief adds stays hidden until then'); // Later briefs stay a surprise: nothing on the map or a city card says where the run goes next. assert.equal(ev("typeof arTags"), 'undefined'); ev("UI.sel={type:'city',id:'fra'};renderPanel()"); diff --git a/tests/weekly-architect.test.js b/tests/weekly-architect.test.js new file mode 100644 index 0000000..42aca52 --- /dev/null +++ b/tests/weekly-architect.test.js @@ -0,0 +1,73 @@ +// The weekly Architect run: generated every Sunday (scripts/weekly-architect.js), checked by the game field by field, +// and played like the handmade runs. +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 { game } = require('../scripts/weekly-puzzle'); +const AW = require('../scripts/weekly-architect'); + +const DIR = path.join(__dirname, '..', 'site', 'architect', 'weekly'); +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'sot-arwk-')); + +test('the generator makes the same run for the same week, and its reference earns three stars', () => { + const g = game(), a = AW.generate(g, '2026-W50', tmp()), b = AW.generate(g, '2026-W50', tmp()); + assert.deepEqual(a, b, 'deterministic'); + assert.ok(a.briefs.length >= 6 && a.briefs.length <= 7); + assert.ok(a.briefs.every((x) => x.tubes >= 1), 'every brief asks for at least one tube'); + assert.ok(a.briefs.some((x) => x.gold), 'something is mission-critical'); + assert.ok(a.budget >= a.ref.spend && a.budget <= a.ref.spend * 1.1 + 10000, 'the budget sits just above the reference'); + assert.equal(AW.verify(g, a, '2026-W50').ok, true); +}); + +test('every published week is accepted and its reference still earns three stars', () => { + const keys = AW.list(DIR); + assert.ok(keys.length >= 3); + assert.deepEqual(AW.check(game(), DIR, 0), []); +}); + +test('the game refuses a file that does not add up', () => { + const { ev } = load(); + const j = JSON.parse(fs.readFileSync(path.join(DIR, AW.list(DIR)[0] + '.json'), 'utf8')), k = j.key; + const ok = (o) => ev(`!!arWkValid(${JSON.stringify(o)},'${k}')`); + assert.equal(ok(j), true); + const bad = (f) => { const o = JSON.parse(JSON.stringify(j)); f(o); return ok(o); }; + assert.equal(ev(`!!arWkValid(${JSON.stringify(j)},'2030-W01')`), false, 'under another week'); + assert.equal(bad((o) => { o.extra = 1; }), false, 'an unknown field'); + assert.equal(bad((o) => { o.hq = 'atlantis'; }), false, 'an unknown HQ'); + assert.equal(bad((o) => { o.name.l = 'common.play'; }), false, 'a label it may not name'); + assert.equal(bad((o) => { o.briefs[0] = { tubes: 1 }; }), false, 'a brief that asks for nothing'); + assert.equal(bad((o) => { o.briefs[1].gold = [o.hq]; }), false, 'HQ made mission-critical'); + assert.equal(bad((o) => { o.briefs[1].gold = ['tok']; }), false, 'a site that is not in the run yet'); + assert.equal(bad((o) => { o.briefs.push({ lat: [o.hq, o.briefs[0].add[0], 0.5], tubes: 1 }); }), false, 'a latency cap below 1 ms'); + assert.equal(bad((o) => { o.budget = 1e9; }), false, 'a silly budget'); +}); + +test('this week\'s run shows in Puzzles, plays like a handmade one and keeps its own stars', () => { + const { ev, errors, dom } = load(); + const key = ev('pzWeekKey(new Date())'), j = AW.generate(game(), key, tmp()); + ev(`UI.arWk={key:'${key}',def:arWkValid(${JSON.stringify(j)},'${key}'),at:Date.now()}`); + ev('ACT.puzzleMenu()'); + const row = dom.window.document.getElementById('arWk'); + assert.ok(row && row.querySelector('[data-act=pzArStart]'), 'a row with a Play button'); + assert.match(row.textContent, /This week’s Architect run/); + row.querySelector('[data-act=pzArStart]').click(); + assert.equal(ev('S.ar.id'), 'wk-' + key); + assert.match(ev('arBrief().t'), /signs up: connect it\./, 'the brief is written from what it asks'); + assert.equal(ev(`arHide('${j.briefs[1].add[0]}')`), true, 'the next brief\'s cities stay hidden'); + // The reference, played through: three stars, stored under the week, and no handmade run offered as "next". + j.ref.steps.forEach((st, i) => { + for (const s of st) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else ev(`ACT.pzLinkTo({a:'${s[0]}',b:'${s[1]}'});ACT.pzVia({v:'${s[2]}'});ACT.pzDiv({v:1});ACT.pzLink({tier:AR_TIER});closeModal()`); + ev('arShowStart();arShowSkip()'); + assert.ok(ev('S.ar.passed===pzSig()'), `brief ${i + 1} passes`); + ev('ACT.pzArNext()'); + }); + assert.equal(ev(`arLoad().runs['wk-${key}'].st`), 3); + assert.equal(ev("document.querySelector('#modalCard [data-act=pzArStart]')"), null, 'no "next run" after a weekly one'); + // A regenerated week (rev 2) starts its stars again. + ev(`UI.arWk.def.rev=2;ACT.puzzleMenu()`); + assert.match(dom.window.document.getElementById('arWk').textContent, /⬜⬜⬜/); + assert.deepEqual(errors, []); +}); From 5f478dd318b930626375a5ae1eca1a6f820fa698 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 14:07:45 +0100 Subject: [PATCH 160/181] Weekly Architect runs: sites outgrow their tubes, and a countdown A grow brief raises a site's traffic past what its tubes carry; the reference makes room by upsizing the busiest tube, or laying a second one where a long cable cannot grow. Traffic may now reach 380G. The weekly row says when the next run comes out. --- .claude/skills/gameplay-rules/SKILL.md | 2 +- CHANGELOG.md | 2 +- scripts/weekly-architect.js | 52 +++++++++++++++------ site/architect/weekly/2026-W44.json | 2 +- site/architect/weekly/2026-W45.json | 2 +- site/architect/weekly/2026-W46.json | 2 +- 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/98-architect-weekly.js | 8 +++- src/i18n/en.js | 3 ++ tests/weekly-architect.test.js | 20 +++++++- 14 files changed, 85 insertions(+), 23 deletions(-) diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 99ea7eb..ad7c362 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -55,7 +55,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. | | C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. | | C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. | -| C4 | Every Architect run, handmade (`REF` in `tests/architect.test.js`) or weekly (`ref` in its file, `scripts/weekly-architect.js --check`), has a reference build that passes every brief's chaos monkey review and earns three stars; every weekly brief takes at least one tube, and later briefs' cities stay hidden until they come. | A run you cannot finish, or a brief that asks for nothing, is not a puzzle; knowing the next brief makes it a chore. | +| C4 | Every Architect run, handmade (`REF` in `tests/architect.test.js`) or weekly (`ref` in its file, `scripts/weekly-architect.js --check`), has a reference build that passes every brief's chaos monkey review and earns three stars; every weekly brief takes at least one change (a tube, a bigger tube, a move), and later briefs' cities stay hidden until they come. | A run you cannot finish, or a brief that asks for nothing, is not a puzzle; knowing the next brief makes it a chore. | ## Fun and fairness diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d59bb4..cb1bb2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 -- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Later briefs stay a surprise in every Architect run: their cities only appear when they come. +- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come. - In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. - Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. - A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. diff --git a/scripts/weekly-architect.js b/scripts/weekly-architect.js index e3dd253..1e916be 100644 --- a/scripts/weekly-architect.js +++ b/scripts/weekly-architect.js @@ -23,7 +23,7 @@ const path = require('node:path'); const { game, world } = require('./weekly-puzzle'); const ROOT = path.join(__dirname, '..'); -const SCHEMA = 1, HISTORY = 4, ATTEMPTS = 40, DEM_MAX = 100; +const SCHEMA = 1, HISTORY = 4, ATTEMPTS = 40, DEM_MAX = 380; const NAMES = ['architect_weekly.name_all_roads_lead_to_hq', 'architect_weekly.name_the_hq_job', 'architect_weekly.name_hq_and_friends']; const JOKES = ['architect_weekly.joke_hq_signed_the_lease', 'architect_weekly.joke_one_network_a_handful']; @@ -40,13 +40,35 @@ const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`)); function stage(ev, key, hq, briefs) { ev(`UI.arWk={key:'${key}',def:{id:arWkId('${key}'),key:'${key}',wk:true,n:'',j:'',hq:'${hq}',via:[],budget:2e7,briefs:${JSON.stringify(briefs)},rev:1},at:Date.now()}`); } -// Lay one tube the way a player does: a diverse trench when the pair already has one overland. -function lay(ev, a, b, via) { +// Lay one tube the way a player does: a diverse trench when the pair already has one overland. The size is what all +// the traffic needs (100G, or 400G once there is more than 100G), smaller where a long cable cannot take it. +const tierFor = (ev) => (ev('S.pz.cities.reduce((a,c)=>a+(c===S.ar.hq?0:arDem(c)),0)') > 100 ? 2 : 1); +function lay(ev, a, b, via, tier) { if (!ev(`!!S.pops['${a}']`)) [a, b] = [b, a]; const n = ev('S.links.length'); - ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:AR_TIER});closeModal()`); - if (ev('S.links.length') !== n + 1) throw new Error(`could not lay ${a}-${b} ${via}`); - return [a, b, via]; + for (let t = tier == null ? tierFor(ev) : tier; t >= 0; t--) { + ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:${t}});closeModal()`); + if (ev('S.links.length') === n + 1) return [a, b, via, t]; + if (tier != null) break; + } + throw new Error(`could not lay ${a}-${b} ${via}`); +} +// One step of a reference, as the file keeps it: a tube [a, b, route, size], ['@rm', city] closing a POP, or +// ['@tier', n, size] resizing the n-th tube. +function step(ev, s) { + if (s[0] === '@rm') { ev(`ACT.pzRmPop({city:'${s[1]}'})`); return; } + if (s[0] === '@tier') { const n = ev(`(()=>{const l=S.links[${s[1]}];ACT.pzTier({id:l.id,tier:${s[2]}});return S.links[${s[1]}].tier;})()`); if (n !== s[2]) throw new Error(`could not resize tube ${s[1]}`); return; } + lay(ev, s[0], s[1], s[2], s[3]); +} +// Room for the traffic: upsize the busiest tube that is not cut (or, when it cannot grow, lay a second one beside it). +function makeRoom(ev, W, steps, cut) { + const ls = J(ev, `(()=>{${cut ? `for(const l of S.links)if(pzUnit(l)===${JSON.stringify(cut)})l.cut=1;` : ''}compute();const o=S.links.map((l,i)=>({i,a:l.a,b:l.b,cut:!!l.cut,tier:l.tier,u:(R.load[l.id]||0)/capOf(l)})).filter(x=>!x.cut).sort((x,y)=>y.u-x.u);for(const l of S.links)l.cut=0;compute();return o;})()`); + for (const l of ls.slice(0, 3)) { + if (l.tier < 2) { const t = ev(`(()=>{const l=S.links[${l.i}];ACT.pzTier({id:l.id,tier:${l.tier + 1}});return S.links[${l.i}].tier;})()`); if (t === l.tier + 1) { steps.push(['@tier', l.i, t]); return; } } + const o = W.opts(l.a, l.b).filter((x) => !x.second).sort((x, y) => x.cost - y.cost)[0]; + if (o) { try { steps.push(lay(ev, o.a, o.b, o.via)); return; } catch (e) { /* try the next tube */ } } + } + throw new Error('no room to be made'); } // What the review would say: the first cut that strands a mission-critical site or leaves a site short. const reviewFail = (ev) => J(ev, `(()=>{let f=null;for(const u of [...new Set(S.links.map(pzUnit))]){const x=arCut(u);for(const l of x.ls)l.cut=0;if(x.gold.length||x.short.length){f={u,gold:x.gold,short:x.short,dark:x.dark};break;}}compute();return f;})()`); @@ -64,9 +86,9 @@ function solveBrief(ev, W, steps) { if (rg) { const cs = rg.cs, has = J(ev, 'S.links.map(l=>edgeKey(l))'); let done = false; for (let i = 0; i < cs.length && !done; i++) { const a = cs[i], b = cs[(i + 1) % cs.length]; if (has.includes(ev(`edgeKey({a:'${a}',b:'${b}'})`))) continue; const o = best([a], [b]); if (o) { steps.push(lay(ev, o.a, o.b, o.via)); done = true; } } if (!done) throw new Error('ring out of reach'); continue; } - if (!e.ready) throw new Error(`not ready: ${e.why}`); + if (!e.ready) { if (/thin/i.test(e.why) || J(ev, 'arEval().sites.some(s=>!s.full)')) { makeRoom(ev, W, steps, null); continue; } throw new Error(`not ready: ${e.why}`); } const f = reviewFail(ev); if (!f) return; - if (f.short.length) throw new Error('short of capacity'); + if (f.short.length && !f.gold.length) { makeRoom(ev, W, steps, f.u); continue; } // A cut strands a mission-critical site: join the stranded side to the rest another way. const rest = J(ev, `Object.keys(S.pops).filter(c=>!${JSON.stringify(f.dark)}.includes(c))`), o = best(f.dark, rest, f.u); if (!o) throw new Error('no second way'); steps.push(lay(ev, o.a, o.b, o.via)); @@ -88,6 +110,8 @@ function design(kind, ev, W, r, s) { const ms = Math.min(...os.map((x) => x.ms)), cap = Math.ceil(ms * 1.12 * 10) / 10; if (cap < 2 || cap >= cur * 0.85) continue; if (!bestP || cur / cap > bestP.k) bestP = { a, b, cap, k: cur / cap }; } if (!bestP) return null; s.lat = [bestP.a, bestP.b]; return { lat: [bestP.a, bestP.b, bestP.cap] }; } + if (kind === 'grow') { const cs = pops.filter((c) => c !== hq).map((c) => [c, ev(`arDem('${c}')`)]).sort((x, y) => y[1] - x[1]); if (!cs.length || s.room < 60) return null; + const [c, d] = cs[0], g = d + Math.min(s.room, pick(r, [60, 90, 120])); s.room -= g - d; return { dem: { [c]: g } }; } if (kind === 'ring') { const cs = pops.filter((c) => c !== hq).sort((a, b) => W.km(hq, a) - W.km(hq, b)).slice(0, 2); if (cs.length < 2) return null; const ring = [hq, ...cs]; if (ev(`arRingOk(${JSON.stringify(ring)})`)) return null; return { ring }; } return null; @@ -102,14 +126,14 @@ function play(g, W, key, hq, plan, r, sites) { if (plan[i] === 'add1') b = first(); else if (plan[i] === 'add2') { if (s.todo.length < 2) throw new Error('not enough sites'); const a = s.todo.shift(), c = s.todo.shift(), ga = Math.min(s.room, 20); s.room -= ga; const gc = Math.min(s.room, pick(r, [10, 20])); s.room -= gc; b = { add: [a, c], dem: { [a]: ga, [c]: gc } }; } // A kind that cannot be made here gives way to one the run has not had yet, then to a new mission-critical site. - else for (const k of [plan[i], ...['lat', 'ring', 'move', 'gold'].filter((x) => !plan.slice(0, i).includes(x) && x !== plan[i]), 'addgold']) { b = design(k, ev, W, r, s); if (b) { plan[i] = k; break; } } + else for (const k of [plan[i], ...['lat', 'ring', 'move', 'grow', 'gold'].filter((x) => !plan.slice(0, i).includes(x) && x !== plan[i]), 'addgold']) { b = design(k, ev, W, r, s); if (b) { plan[i] = k; break; } } if (!b) throw new Error(`brief ${i + 1}: nothing left to ask`); b.tubes = 9; briefs.push(b); stage(ev, key, hq, briefs.map((x) => Object.assign({ t: '' }, x))); if (i === 0) ev(`ACT.pzArStart({id:arWkId('${key}')})`); else ev('ACT.pzArNext()'); if (ev('S.ar.bi') !== i) throw new Error(`brief ${i + 1} did not start`); const st = []; solveBrief(ev, W, st); steps.push(st); b.tubes = ev('S.links.filter(l=>(l.br|0)===S.ar.bi).length'); - if (!b.tubes) throw new Error(`brief ${i + 1} needs no tube`); + if (!st.length) throw new Error(`brief ${i + 1} asks for nothing new`); ev(`UI.arWk.def.briefs[${i}].tubes=${b.tubes}`); if (!passes(ev)) throw new Error(`brief ${i + 1}: the review does not pass`); } @@ -125,7 +149,7 @@ function verify(g, j, key) { ev(`UI.arWk={key:'${key}',def:arWkValid(${JSON.stringify(j)},'${key}'),at:Date.now()}`); ev(`ACT.pzArStart({id:arWkId('${key}')})`); for (let i = 0; i < def.briefs.length; i++) { - for (const st of j.ref.steps[i]) if (st[0] === '@rm') ev(`ACT.pzRmPop({city:'${st[1]}'})`); else lay(ev, st[0], st[1], st[2]); + for (const st of j.ref.steps[i]) step(ev, st); if (!passes(ev)) return { ok: false, why: `brief ${i + 1} does not pass` }; if (i < def.briefs.length - 1) ev('ACT.pzArNext()'); } @@ -146,7 +170,7 @@ function generate(g, key, dir) { const hq = pick(r, hqs).id; const near = W.cities.filter((c) => c.id !== hq && c.reg === W.C[hq].reg && W.km(hq, c.id) < 2500).sort((a, b) => W.km(hq, a.id) - W.km(hq, b.id)).slice(0, 8).map((c) => c.id); if (near.length < 6) continue; - const mid = shuffle(r, ['lat', 'ring', 'move', 'addgold']).slice(0, r() < 0.5 ? 2 : 3); + const mid = shuffle(r, ['lat', 'ring', 'move', 'addgold', 'grow']).slice(0, r() < 0.5 ? 2 : 3); const plan = ['add1', 'add2', 'gold', ...mid, 'gold']; const sites = [...near.slice(0, 3), ...shuffle(r, near.slice(3))]; try { @@ -191,9 +215,9 @@ function refresh(g, dir, now = Date.now()) { } 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); }; -const say = (j) => `${j.key}: HQ ${j.hq}, ${j.briefs.length} briefs (${j.briefs.map((b) => Object.keys(b).filter((k) => k !== 'tubes' && k !== 'dem').join('+')).join(', ')}), budget ${j.budget}, reference ${j.ref.spend}`; +const say = (j) => `${j.key}: HQ ${j.hq}, ${j.briefs.length} briefs (${j.briefs.map((b) => Object.keys(b).filter((k) => k !== 'tubes' && (k !== 'dem' || !b.add)).map((k) => (k === 'dem' ? 'grow' : k)).join('+')).join(', ')}), budget ${j.budget}, reference ${j.ref.spend}`; -module.exports = { generate, verify, check, refresh, writeWeek, writeIndex, list, say }; +module.exports = { generate, verify, check, refresh, writeWeek, writeIndex, list, say, step }; 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; }; diff --git a/site/architect/weekly/2026-W44.json b/site/architect/weekly/2026-W44.json index fd5f6ed..18ecb43 100644 --- a/site/architect/weekly/2026-W44.json +++ b/site/architect/weekly/2026-W44.json @@ -1 +1 @@ -{"v":1,"key":"2026-W44","hq":"cor","budget":1160000,"name":{"l":"architect_weekly.name_all_roads_lead_to_hq","p":{"hq":"cor"}},"joke":{"l":"architect_weekly.joke_hq_signed_the_lease","p":{"hq":"cor"}},"briefs":[{"add":["bue"],"dem":{"bue":20},"tubes":1},{"add":["scl","mvd"],"dem":{"scl":20,"mvd":20},"tubes":2},{"gold":["mvd"],"tubes":2},{"ring":["cor","bue","scl"],"tubes":1},{"add":["cgr"],"dem":{"cgr":20},"gold":["cgr"],"tubes":2},{"lat":["cgr","cor",11.3],"tubes":1}],"ref":{"spend":1090844,"steps":[[["cor","bue","land"]],[["cor","scl","land"],["bue","mvd","land"]],[["bue","cor","land"],["mvd","bue","land"]],[["scl","bue","land"]],[["bue","cgr","land"],["cgr","bue","land"]],[["cgr","cor","land"]]]}} +{"v":1,"key":"2026-W44","hq":"cor","budget":1580000,"name":{"l":"architect_weekly.name_all_roads_lead_to_hq","p":{"hq":"cor"}},"joke":{"l":"architect_weekly.joke_hq_signed_the_lease","p":{"hq":"cor"}},"briefs":[{"add":["bue"],"dem":{"bue":40},"tubes":1},{"add":["scl","mvd"],"dem":{"scl":20,"mvd":20},"tubes":2},{"gold":["mvd"],"tubes":2},{"drop":["scl"],"add":["ldb"],"dem":{"ldb":10},"gold":["ldb"],"tubes":2},{"lat":["ldb","mvd",10.1],"tubes":1},{"dem":{"bue":100},"tubes":0},{"add":["cgr"],"dem":{"cgr":10},"gold":["cgr"],"tubes":2}],"ref":{"spend":1489176,"steps":[[["cor","bue","land",1]],[["cor","scl","land",1],["bue","mvd","land",1]],[["bue","cor","land",1],["mvd","bue","land",1]],[["@rm","scl"],["cor","ldb","land",1],["ldb","cor","land",1]],[["ldb","mvd","land",1]],[["@tier",2,2],["@tier",0,2]],[["ldb","cgr","land",2],["cgr","ldb","land",2]]]}} diff --git a/site/architect/weekly/2026-W45.json b/site/architect/weekly/2026-W45.json index ea2b841..0ebd073 100644 --- a/site/architect/weekly/2026-W45.json +++ b/site/architect/weekly/2026-W45.json @@ -1 +1 @@ -{"v":1,"key":"2026-W45","hq":"maa","budget":920000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"maa"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["blr"],"dem":{"blr":20},"tubes":1},{"add":["hyd","cbo"],"dem":{"hyd":20,"cbo":20},"tubes":2},{"gold":["cbo"],"tubes":1},{"ring":["maa","blr","hyd"],"tubes":1},{"drop":["hyd"],"add":["mle"],"dem":{"mle":30},"gold":["mle"],"tubes":2},{"gold":["blr"],"tubes":1}],"ref":{"spend":860936,"steps":[[["maa","blr","land"]],[["blr","hyd","land"],["maa","cbo","smw6"]],[["cbo","maa","smw4"]],[["hyd","maa","land"]],[["@rm","hyd"],["cbo","mle","smw6"],["mle","maa","iax"]],[["blr","maa","land"]]]}} +{"v":1,"key":"2026-W45","hq":"maa","budget":930000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"maa"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["blr"],"dem":{"blr":30},"tubes":1},{"add":["hyd","cbo"],"dem":{"hyd":20,"cbo":20},"tubes":2},{"gold":["cbo"],"tubes":1},{"ring":["maa","blr","hyd"],"tubes":1},{"drop":["hyd"],"add":["dac"],"dem":{"dac":20},"gold":["dac"],"tubes":2},{"gold":["blr"],"tubes":1}],"ref":{"spend":869628,"steps":[[["maa","blr","land",1]],[["blr","hyd","land",1],["maa","cbo","smw6",1]],[["cbo","maa","smw4",1]],[["hyd","maa","land",1]],[["@rm","hyd"],["maa","dac","land",1],["dac","maa","land",1]],[["blr","maa","land",1]]]}} diff --git a/site/architect/weekly/2026-W46.json b/site/architect/weekly/2026-W46.json index a047c0e..446e87a 100644 --- a/site/architect/weekly/2026-W46.json +++ b/site/architect/weekly/2026-W46.json @@ -1 +1 @@ -{"v":1,"key":"2026-W46","hq":"svg","budget":570000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"svg"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["krs"],"dem":{"krs":40},"tubes":1},{"add":["osl","ebj"],"dem":{"osl":20,"ebj":10},"tubes":2},{"gold":["ebj"],"tubes":2},{"lat":["osl","svg",2.2],"tubes":1},{"drop":["krs"],"add":["ams"],"dem":{"ams":20},"gold":["ams"],"tubes":4},{"ring":["svg","osl","ebj"],"tubes":1},{"add":["edi"],"dem":{"edi":10},"gold":["edi"],"tubes":2}],"ref":{"spend":534112,"steps":[[["svg","krs","land"]],[["krs","osl","land"],["krs","ebj","land"]],[["krs","svg","land"],["ebj","krs","land"]],[["osl","svg","land"]],[["@rm","krs"],["ebj","svg","land"],["ebj","ams","land"],["ebj","svg","land"],["ams","ebj","land"]],[["ebj","osl","land"]],[["svg","edi","nouk"],["edi","ebj","havh"]]]}} +{"v":1,"key":"2026-W46","hq":"svg","budget":610000,"name":{"l":"architect_weekly.name_the_hq_job","p":{"hq":"svg"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["krs"],"dem":{"krs":30},"tubes":1},{"add":["osl","ebj"],"dem":{"osl":20,"ebj":20},"tubes":2},{"gold":["ebj"],"tubes":2},{"lat":["osl","svg",2.2],"tubes":1},{"drop":["krs"],"add":["cph"],"dem":{"cph":20},"gold":["cph"],"tubes":3},{"dem":{"osl":140},"tubes":0}],"ref":{"spend":567292,"steps":[[["svg","krs","land",1]],[["krs","osl","land",1],["krs","ebj","land",1]],[["krs","svg","land",1],["ebj","krs","land",1]],[["osl","svg","land",1]],[["@rm","krs"],["ebj","svg","land",1],["ebj","cph","land",1],["cph","osl","land",1]],[["@tier",0,2],["@tier",1,2],["@tier",2,2],["@tier",3,2]]]}} diff --git a/site/i18n/de.js b/site/i18n/de.js index e2c5eae..102b491 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -128,12 +128,15 @@ "architect_weekly.name_all_roads_lead_to_hq":"Alle Wege führen nach {hq}", "architect_weekly.name_hq_and_friends":"{hq} und Freunde", "architect_weekly.name_the_hq_job":"Der {hq}-Job", +"architect_weekly.next_run_in_d_h":"neuer Run in {d} T {h} Std.", +"architect_weekly.next_run_in_h_m":"neuer Run in {h} Std. {m} Min.", "architect_weekly.t_add_gold":"{a} ist neu dabei und von Tag eins an geschäftskritisch: muss jeden einzelnen Schnitt überstehen.", "architect_weekly.t_add_one":"{a} ist neu dabei: anschließen.", "architect_weekly.t_add_two":"{a} und {b} sind neu dabei: anschließen.", "architect_weekly.t_drop":"{a} schließt: zieh aus und bau dort nicht wieder.", "architect_weekly.t_gold_one":"{a} ist jetzt geschäftskritisch: muss jeden einzelnen Schnitt überstehen.", "architect_weekly.t_gold_two":"{a} und {b} sind jetzt geschäftskritisch: müssen jeden einzelnen Schnitt überstehen.", +"architect_weekly.t_grow":"{a} wächst auf {g}: schaff Platz.", "architect_weekly.t_lat":"{a} ⇄ {b} muss unter {ms} ms bleiben.", "architect_weekly.t_ring":"{list} wollen auf einem Ring liegen.", "architect_weekly.weekly_run":"Architect-Run der Woche", diff --git a/site/i18n/es.js b/site/i18n/es.js index 5376911..a7a695c 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -126,12 +126,15 @@ "architect_weekly.name_all_roads_lead_to_hq":"Todos los caminos llevan a {hq}", "architect_weekly.name_hq_and_friends":"{hq} y amigos", "architect_weekly.name_the_hq_job":"El golpe de {hq}", +"architect_weekly.next_run_in_d_h":"nueva ronda en {d} d {h} h", +"architect_weekly.next_run_in_h_m":"nueva ronda en {h} h {m} min", "architect_weekly.t_add_gold":"{a} se apunta, crítico desde el primer día: debe sobrevivir a cualquier corte.", "architect_weekly.t_add_one":"{a} se apunta: conéctalo.", "architect_weekly.t_add_two":"{a} y {b} se apuntan: conéctalos.", "architect_weekly.t_drop":"{a} cierra: múdate y no vuelvas a construir allí.", "architect_weekly.t_gold_one":"{a} es ahora crítico: debe sobrevivir a cualquier corte.", "architect_weekly.t_gold_two":"{a} y {b} son ahora críticos: deben sobrevivir a cualquier corte.", +"architect_weekly.t_grow":"{a} crece hasta {g}: haz sitio.", "architect_weekly.t_lat":"{a} ⇄ {b} debe quedarse por debajo de {ms} ms.", "architect_weekly.t_ring":"{list} quieren estar en un mismo anillo.", "architect_weekly.weekly_run":"La ronda de Arquitecto de la semana", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4fbd868..5f2e28a 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -126,12 +126,15 @@ "architect_weekly.name_all_roads_lead_to_hq":"Tous les chemins mènent à {hq}", "architect_weekly.name_hq_and_friends":"{hq} et ses amis", "architect_weekly.name_the_hq_job":"Le coup de {hq}", +"architect_weekly.next_run_in_d_h":"nouveau parcours dans {d} j {h} h", +"architect_weekly.next_run_in_h_m":"nouveau parcours dans {h} h {m} min", "architect_weekly.t_add_gold":"{a} signe, critique dès le premier jour : il doit survivre à n’importe quelle coupure.", "architect_weekly.t_add_one":"{a} signe : raccorde-le.", "architect_weekly.t_add_two":"{a} et {b} signent : raccorde-les.", "architect_weekly.t_drop":"{a} ferme : déménage et ne construis plus là-bas.", "architect_weekly.t_gold_one":"{a} est désormais critique : il doit survivre à n’importe quelle coupure.", "architect_weekly.t_gold_two":"{a} et {b} sont désormais critiques : ils doivent survivre à n’importe quelle coupure.", +"architect_weekly.t_grow":"{a} passe à {g} : fais de la place.", "architect_weekly.t_lat":"{a} ⇄ {b} doit rester sous {ms} ms.", "architect_weekly.t_ring":"{list} veulent être sur un même anneau.", "architect_weekly.weekly_run":"Le parcours d’architecte de la semaine", diff --git a/site/i18n/it.js b/site/i18n/it.js index c21f57c..cc4b4fe 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -126,12 +126,15 @@ "architect_weekly.name_all_roads_lead_to_hq":"Tutte le strade portano a {hq}", "architect_weekly.name_hq_and_friends":"{hq} e amici", "architect_weekly.name_the_hq_job":"Il colpo di {hq}", +"architect_weekly.next_run_in_d_h":"nuovo percorso tra {d} g {h} h", +"architect_weekly.next_run_in_h_m":"nuovo percorso tra {h} h {m} min", "architect_weekly.t_add_gold":"{a} si iscrive, critico dal primo giorno: deve sopravvivere a qualsiasi taglio.", "architect_weekly.t_add_one":"{a} si iscrive: collegalo.", "architect_weekly.t_add_two":"{a} e {b} si iscrivono: collegali.", "architect_weekly.t_drop":"{a} chiude: trasloca e non costruire più lì.", "architect_weekly.t_gold_one":"{a} ora è critico: deve sopravvivere a qualsiasi taglio.", "architect_weekly.t_gold_two":"{a} e {b} ora sono critici: devono sopravvivere a qualsiasi taglio.", +"architect_weekly.t_grow":"{a} cresce fino a {g}: fai spazio.", "architect_weekly.t_lat":"{a} ⇄ {b} deve restare sotto {ms} ms.", "architect_weekly.t_ring":"{list} vogliono stare su un unico anello.", "architect_weekly.weekly_run":"Il percorso da architetto della settimana", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 3782ca0..bc3cd3a 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -126,12 +126,15 @@ "architect_weekly.name_all_roads_lead_to_hq":"Todos os caminhos levam a {hq}", "architect_weekly.name_hq_and_friends":"{hq} e amigos", "architect_weekly.name_the_hq_job":"O golpe de {hq}", +"architect_weekly.next_run_in_d_h":"nova rodada em {d} d {h} h", +"architect_weekly.next_run_in_h_m":"nova rodada em {h} h {m} min", "architect_weekly.t_add_gold":"{a} entrou, crítico desde o primeiro dia: precisa sobreviver a qualquer corte.", "architect_weekly.t_add_one":"{a} entrou: conecte-o.", "architect_weekly.t_add_two":"{a} e {b} entraram: conecte-os.", "architect_weekly.t_drop":"{a} vai fechar: saia de lá e não construa lá de novo.", "architect_weekly.t_gold_one":"{a} agora é crítico: precisa sobreviver a qualquer corte.", "architect_weekly.t_gold_two":"{a} e {b} agora são críticos: precisam sobreviver a qualquer corte.", +"architect_weekly.t_grow":"{a} cresce para {g}: abra espaço.", "architect_weekly.t_lat":"{a} ⇄ {b} precisa ficar abaixo de {ms} ms.", "architect_weekly.t_ring":"{list} querem ficar no mesmo anel.", "architect_weekly.weekly_run":"A rodada de Arquiteto da semana", diff --git a/src/game/60-features/98-architect-weekly.js b/src/game/60-features/98-architect-weekly.js index f345fdd..d7a00d0 100644 --- a/src/game/60-features/98-architect-weekly.js +++ b/src/game/60-features/98-architect-weekly.js @@ -20,6 +20,7 @@ function arWkSay(b){const n=c=>CITY[c].name,t=[]; if(ag)t.push(tr('architect_weekly.t_add_gold',{a:n(b.add[0])})); else if(b.add)t.push(b.add.length>1?tr('architect_weekly.t_add_two',{a:n(b.add[0]),b:n(b.add[1])}):tr('architect_weekly.t_add_one',{a:n(b.add[0])})); if(b.gold&&!ag)t.push(b.gold.length>1?tr('architect_weekly.t_gold_two',{a:n(b.gold[0]),b:n(b.gold[1])}):tr('architect_weekly.t_gold_one',{a:n(b.gold[0])})); + for(const c of Object.keys(b.dem||{}))if(!(b.add||[]).includes(c))t.push(tr('architect_weekly.t_grow',{a:n(c),g:arG(b.dem[c])})); if(b.ring)t.push(tr('architect_weekly.t_ring',{list:b.ring.map(n).join(', ')})); if(b.lat)t.push(tr('architect_weekly.t_lat',{a:n(b.lat[0]),b:n(b.lat[1]),ms:+b.lat[2].toFixed(1)})); return t.join(' ');} @@ -34,7 +35,7 @@ function arWkBriefs(a,hq){if(!Array.isArray(a)||a.length<3||a.length>7)return nu const dem={};if(b.dem!=null){if(!pzObj(b.dem))return null;for(const c of Object.keys(b.dem)){const g=b.dem[c];if(!sites.has(c)||c===hq||!Number.isInteger(g)||g<10||g>400)return null;dem[c]=g;}} let lat=null;if(b.lat!=null){const l=b.lat;if(!Array.isArray(l)||l.length!==3||!sites.has(l[0])||!sites.has(l[1])||l[0]===l[1]||typeof l[2]!=='number'||!isFinite(l[2])||l[2]<1||l[2]>300)return null;lat=l.slice();} if(!Number.isInteger(b.tubes)||b.tubes<0||b.tubes>9)return null; - if(!add.length&&!gold.length&&!ring.length&&!lat)return null; + if(!add.length&&!gold.length&&!ring.length&&!lat&&!Object.keys(dem).length)return null; const o={tubes:b.tubes};if(add.length)o.add=add;if(gold.length)o.gold=gold;if(ring.length)o.ring=ring;if(drop.length)o.drop=drop;if(Object.keys(dem).length)o.dem=dem;if(lat)o.lat=lat; o.t=arWkSay(o);out.push(o);} return out[0].add?out:null;} @@ -56,4 +57,7 @@ function arWkEnsure(){const key=pzWeekKey(new Date()),w=UI.arWk;if(w&&w.key===ke // Its row in the Puzzles menu, above the handmade runs; nothing while there is none. function arWkRow(){const w=UI.arWk,r=w&&w.key===pzWeekKey(new Date())?w.def:null;if(!r)return '
'; const x=arLoad().runs[r.id],ok=x&&(x.rv||1)===r.rev?x:null; - return `
🗓️ ${tr('architect_weekly.weekly_run')}
${esc(r.n)} ${pzStarStr(ok?ok.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)} · ${tr('puzzles.budget_x',{x:fmt$(r.budget)})}${ok&&ok.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(ok.sp)}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},ok&&ok.st>=3?'ghost':'pink')}
`;} + return `
🗓️ ${tr('architect_weekly.weekly_run')} · ${arWkNext(new Date())}
${esc(r.n)} ${pzStarStr(ok?ok.st:0)}
${esc(r.j)}
${tr('architect.n_briefs',{n:r.briefs.length})} · 🏠 ${esc(CITY[r.hq].name)} · ${tr('puzzles.budget_x',{x:fmt$(r.budget)})}${ok&&ok.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(ok.sp)}):''}
${btn(tr('common.play'),'pzArStart',{id:r.id},ok&&ok.st>=3?'ghost':'pink')}
`;} +// "New run in 2 d 14 h": when next week's run comes out. +function arWkNext(now){const t=pzWeekStart(pzKeyAdd(pzWeekKey(now),1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60); + return d?tr('architect_weekly.next_run_in_d_h',{d,h}):tr('architect_weekly.next_run_in_h_m',{h,m:m%60});} diff --git a/src/i18n/en.js b/src/i18n/en.js index e0a4100..4df1db5 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -127,12 +127,15 @@ "architect_weekly.name_all_roads_lead_to_hq":"All Roads Lead to {hq}", "architect_weekly.name_hq_and_friends":"{hq} and Friends", "architect_weekly.name_the_hq_job":"The {hq} Job", +"architect_weekly.next_run_in_d_h":"new run in {d} d {h} h", +"architect_weekly.next_run_in_h_m":"new run in {h} h {m} min", "architect_weekly.t_add_gold":"{a} signs up, mission-critical from day one: it must survive any single cut.", "architect_weekly.t_add_one":"{a} signs up: connect it.", "architect_weekly.t_add_two":"{a} and {b} sign up: connect them.", "architect_weekly.t_drop":"{a} is closing: move out, and don’t build there again.", "architect_weekly.t_gold_one":"{a} is now mission-critical: it must survive any single cut.", "architect_weekly.t_gold_two":"{a} and {b} are now mission-critical: they must survive any single cut.", +"architect_weekly.t_grow":"{a} grows to {g}: make room.", "architect_weekly.t_lat":"{a} ⇄ {b} must stay under {ms} ms.", "architect_weekly.t_ring":"{list} want to sit on one ring.", "architect_weekly.weekly_run":"This week’s Architect run", diff --git a/tests/weekly-architect.test.js b/tests/weekly-architect.test.js index 42aca52..916ba41 100644 --- a/tests/weekly-architect.test.js +++ b/tests/weekly-architect.test.js @@ -16,12 +16,28 @@ test('the generator makes the same run for the same week, and its reference earn const g = game(), a = AW.generate(g, '2026-W50', tmp()), b = AW.generate(g, '2026-W50', tmp()); assert.deepEqual(a, b, 'deterministic'); assert.ok(a.briefs.length >= 6 && a.briefs.length <= 7); - assert.ok(a.briefs.every((x) => x.tubes >= 1), 'every brief asks for at least one tube'); + assert.ok(a.ref.steps.every((st) => st.length >= 1), 'every brief asks for a change: a tube, a bigger tube or a move'); assert.ok(a.briefs.some((x) => x.gold), 'something is mission-critical'); assert.ok(a.budget >= a.ref.spend && a.budget <= a.ref.spend * 1.1 + 10000, 'the budget sits just above the reference'); assert.equal(AW.verify(g, a, '2026-W50').ok, true); }); +test('a grow brief makes the reference make room: a bigger tube or a second one', () => { + const g = game(), d = tmp(), runs = ['2026-W47', '2026-W49', '2026-W53'].map((k) => AW.generate(g, k, d)); + const grows = runs.flatMap((j) => j.briefs.map((b, i) => [j, b, i]).filter(([, b]) => b.dem && !b.add)); + assert.ok(grows.length >= 1, 'some weeks grow a site'); + for (const [j, b, i] of grows) { + const [c, gb] = Object.entries(b.dem)[0]; + assert.ok(gb > 100 || j.briefs.slice(0, i).some((x) => x.dem && x.dem[c] && x.dem[c] < gb), 'the site really grows'); + assert.ok(j.ref.steps[i].length >= 1, 'and that brief takes a change'); + } + const { ev } = load(); + const [j, b] = grows[0]; + ev(`UI.arWk={key:'${j.key}',def:arWkValid(${JSON.stringify(j)},'${j.key}'),at:Date.now()}`); + const c = Object.keys(b.dem)[0]; + assert.ok(ev(`UI.arWk.def.briefs.some(x=>x.t.includes(CITY['${c}'].name+' grows to'))`), 'the brief says so'); +}); + test('every published week is accepted and its reference still earns three stars', () => { const keys = AW.list(DIR); assert.ok(keys.length >= 3); @@ -59,7 +75,7 @@ test('this week\'s run shows in Puzzles, plays like a handmade one and keeps its assert.equal(ev(`arHide('${j.briefs[1].add[0]}')`), true, 'the next brief\'s cities stay hidden'); // The reference, played through: three stars, stored under the week, and no handmade run offered as "next". j.ref.steps.forEach((st, i) => { - for (const s of st) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else ev(`ACT.pzLinkTo({a:'${s[0]}',b:'${s[1]}'});ACT.pzVia({v:'${s[2]}'});ACT.pzDiv({v:1});ACT.pzLink({tier:AR_TIER});closeModal()`); + for (const s of st) AW.step(ev, s); ev('arShowStart();arShowSkip()'); assert.ok(ev('S.ar.passed===pzSig()'), `brief ${i + 1} passes`); ev('ACT.pzArNext()'); From 73e11349dce76093c0dd8835e6cf0b79e4889ea0 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 14:54:10 +0100 Subject: [PATCH 161/181] Routers: a picture for every model Seventeen cartoons in the map's style, one per router model (the ones picked from the Router Rogues sketches), drawn as inline SVG from a small kit in its own scope and built only when a panel shows them. A POP's router section shows its model big; the list of other models shows each one small. --- CHANGELOG.md | 1 + src/game/10-catalog/25-router-art.js | 159 ++++++++++++++++++ .../80-simulation/90-sites-and-service.js | 2 +- src/game/93-ui/50-city-panel.js | 2 +- src/styles/37-router-art.css | 5 + tests/router-art.test.js | 27 +++ 6 files changed, 194 insertions(+), 2 deletions(-) create mode 100644 src/game/10-catalog/25-router-art.js create mode 100644 src/styles/37-router-art.css create mode 100644 tests/router-art.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index cb1bb2c..6741d16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- Every router model has its own picture: open a POP's routers to meet the one you have, and the others when you compare models. - A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come. - In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. - Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. diff --git a/src/game/10-catalog/25-router-art.js b/src/game/10-catalog/25-router-art.js new file mode 100644 index 0000000..124d4f4 --- /dev/null +++ b/src/game/10-catalog/25-router-art.js @@ -0,0 +1,159 @@ +/* ---------- router pictures: one cartoon per model in RG, same order ---------- + Drawn as SVG from a small kit in the map's style (navy outlines, candy colours), each with its model's joke. Built + only when a panel shows one, then cached; the kit lives in its own scope. */ +const RG_ART=(()=>{ +const O='#1E2640',W=4; +const st=(f,w=W)=>`fill="${f}" stroke="${O}" stroke-width="${w}" stroke-linejoin="round" stroke-linecap="round"`; +const P=(d,f='none',w=W)=>``; +const R=(x,y,w,h,f,r=10,sw=W)=>``; +const C=(x,y,r,f,sw=W)=>``; +const E=(x,y,rx,ry,f,sw=W,rot=0)=>``; +const T=(x,y,t,s=10,f=O)=>`${t}`; +const sh=(w=70,x=100,y=146)=>``; +const bob=s=>`${s}`; +const ports=(x,y,w,n,c='#7FD8EE')=>{let s=R(x,y,w,16,O,4,2);const g=(w-8)/n;for(let i=0;i`;return s;}; +const leds=(x,y,cs,r=4)=>cs.map((c,i)=>C(x+i*(r*3),y,r,c,2)).join(''); +// faces: eyes at (x,y), d apart from the middle +const glint=(x,y)=>``; +const EY={ + happy:(x,y,d=14)=>P(`M${x-d-6} ${y} q6 -8 12 0 M${x+d-6} ${y} q6 -8 12 0`), + sleepy:(x,y,d=14)=>P(`M${x-d-6} ${y} q6 6 12 0 M${x+d-6} ${y} q6 6 12 0`), + dots:(x,y,d=14)=>``, + angry:(x,y,d=14)=>P(`M${x-d-9} ${y-8} L${x-d+7} ${y-3} M${x+d+9} ${y-8} L${x+d-7} ${y-3}`,'none',5)+``, + shades:(x,y,d=14)=>``+P(`M${x-d+11} ${y-3} H${x+d-11}`,'none',3)+glint(x-d,y)+glint(x+d,y), + sad:(x,y,d=14)=>EY.dots(x,y+2,d)+P(`M${x-d-7} ${y-9} L${x-d+5} ${y-6} M${x+d+7} ${y-9} L${x+d-5} ${y-6}`,'none',3), + dizzy:(x,y,d=14)=>P(`M${x-d-5} ${y-5} l10 10 m0 -10 l-10 10 M${x+d-5} ${y-5} l10 10 m0 -10 l-10 10`,'none',3.5), + worried:(x,y,d=14)=>EY.dots(x,y,d)+P(`M${x-d-6} ${y-10} L${x-d+6} ${y-12} M${x+d+6} ${y-10} L${x+d-6} ${y-12}`,'none',3), +}; +EY.wink=(x,y,d=14)=>``+P(`M${x+d-6} ${y} q6 -8 12 0`); +const MO={ + smile:(x,y,w=9)=>P(`M${x-w} ${y} q${w} ${w*.8} ${2*w} 0`), + grin:(x,y,w=10)=>P(`M${x-w} ${y} q${w} ${w*1.2} ${2*w} 0z`,'#7A2633',3), + flat:(x,y,w=8)=>P(`M${x-w} ${y} h${2*w}`), + frown:(x,y,w=8)=>P(`M${x-w} ${y+4} q${w} ${-w*.8} ${2*w} 0`), + o:(x,y)=>E(x,y+2,4,5,'#7A2633',3), + smirk:(x,y,w=9)=>P(`M${x-w} ${y+1} q${w*1.2} ${w*.5} ${2*w} -4`), + w:(x,y)=>P(`M${x-8} ${y} q4 5 8 0 q4 5 8 0`), + teeth:(x,y,w=12)=>R(x-w,y-4,2*w,9,'#fff',3,3)+P(`M${x-w/3} ${y-4} v9 M${x+w/3} ${y-4} v9`,'none',2), +}; +const face=(x,y,e,m,d=14,my=14)=>EY[e](x,y,d)+(m?MO[m](x,y+my):''); +const cheeks=(x,y,d=26)=>``; +// props +const antenna=(x,y,dx,dy,tip='#FFD23F')=>P(`M${x} ${y} l${dx} ${dy}`)+C(x+dx,y+dy,5,tip,3); +const bent=(x,y)=>P(`M${x} ${y} q4 -14 18 -22 q6 4 2 10`); +const tapeX=(x,y,w,h)=>P(`M${x} ${y} L${x+w} ${y+h} M${x+w} ${y} L${x} ${y+h}`,'none',13).replace(`stroke="${O}"`,'stroke="#C9D1E6"')+P(`M${x} ${y} L${x+w} ${y+h} M${x+w} ${y} L${x} ${y+h}`,'none',2).replace('stroke-linecap','stroke-dasharray="2 5" stroke-linecap'); +const cobweb=(x,y)=>P(`M${x} ${y} q10 -10 20 0 M${x+6} ${y} q4 -6 8 0 M${x+10} ${y} v-9`,'none',1.5); +const sticker=(x,y,w,h,t,f='#fff',s=8)=>P(`M${x} ${y} h${w} l3 ${h} h${-w}z`,f,2.5)+T(x+w/2+1.5,y+h/2+3,t,s); +const spots=(a)=>a.map(([x,y,s])=>P(`M${x} ${y} q${s} ${-s*.6} ${s*1.8} ${s*.2} q${-s*.2} ${s} ${-s*1.2} ${s*.8}z`,'#9A5226',3)).join(''); +const flames=(x,y,s=1)=>P(`M${x} ${y} q${-14*s} ${-6*s} ${-6*s} ${-24*s} q${4*s} ${8*s} ${10*s} ${8*s} q${-2*s} ${-12*s} ${8*s} ${-20*s} q${2*s} ${14*s} ${10*s} ${16*s} q${2*s} ${-6*s} ${-2*s} ${-12*s} q${14*s} ${8*s} ${8*s} ${32*s}z`,'#FF8A3D',3)+P(`M${x+2*s} ${y-2*s} q${-6*s} ${-4*s} ${-1*s} ${-12*s} q${4*s} ${6*s} ${8*s} ${4*s} q${2*s} ${6*s} ${-1*s} ${8*s}z`,'#FFD23F',2); +const feet=(xs,y,f)=>xs.map(x=>P(`M${x-8} ${y} q-2 10 8 10 h6 q8 0 4 -10`,f)).join(''); +const legs=(xs,y,f='#1E2640',h=12)=>xs.map(x=>P(`M${x} ${y} v${h} h8`,'none',5)).join(''); +const cloud=(x,y,s=1,f='#fff')=>P(`M${x-22*s} ${y} q-8 -14 8 -14 q4 -12 18 -6 q12 -8 18 6 q14 0 8 14z`,f,3); +const rain=(x,y)=>P(`M${x-14} ${y+6} l-3 8 M${x} ${y+6} l-3 8 M${x+14} ${y+6} l-3 8`,'none',3).replace(`stroke="${O}"`,'stroke="#2F8CFF"'); +const sun=(x,y,r=10)=>C(x,y,r,'#FFD23F',3)+P(`M${x} ${y-r-4} v-6 M${x} ${y+r+4} v6 M${x-r-4} ${y} h-6 M${x+r+4} ${y} h6 M${x-r} ${y-r} l-4 -4 M${x+r} ${y+r} l4 4 M${x+r} ${y-r} l4 -4 M${x-r} ${y+r} l-4 4`,'none',3); +const bolt=(x,y,s=1,f='#FFD23F')=>P(`M${x} ${y} l${-10*s} ${18*s} h${8*s} l${-6*s} ${18*s} l${18*s} ${-24*s} h${-9*s} l${7*s} ${-12*s}z`,f,3); +const smoke=(x,y)=>C(x,y,6,'#C9D1E6',2.5)+C(x+8,y-10,8,'#C9D1E6',2.5)+C(x+2,y-24,10,'#E8EDF7',2.5); +const steam=(x,y)=>P(`M${x} ${y} q-6 -8 0 -16 q6 -8 0 -16 M${x+12} ${y} q-6 -8 0 -16 q6 -8 0 -16`,'none',3).replace(`stroke="${O}"`,'stroke="#fff"').replace('stroke-width="3"','stroke-width="4"'); +const speed=(x,y)=>P(`M${x} ${y} h-26 M${x-6} ${y+14} h-30 M${x} ${y+28} h-22`,'none',4).replace(`stroke="${O}"`,'stroke="#fff"'); +const tag=(x,y,l1,l2)=>P(`M${x-24} ${y-20} q-12 2 -12 14`,'none',2.5)+R(x-12,y-6,30,26,'#FFD23F',4,3)+T(x+3,y+5,l1,8)+(l2?T(x+3,y+15,l2,8):''); +const disco=(x,y,r=16)=>P(`M${x} ${y-r-12} v12`)+C(x,y,r,'#C9D1E6')+P(`M${x-r+2} ${y-6} h${2*r-4} M${x-r} ${y+2} h${2*r} M${x-r+3} ${y+9} h${2*r-6} M${x} ${y-r} v${2*r} M${x-9} ${y-r+3} q-4 ${r-3} 0 ${2*r-6} M${x+9} ${y-r+3} q4 ${r-3} 0 ${2*r-6}`,'none',2); +const beams=(x,y)=>``; +const coinslot=(x,y)=>R(x,y,24,10,'#FFD23F',3,3)+R(x+6,y+3,12,3,O,1,1); +const coins=(x,y,n)=>Array.from({length:n},(_,i)=>E(x,y-i*6,12,5,'#FFD23F',3)).join(''); +const eyepatch=(x,y)=>C(x,y,8,O,2)+P(`M${x-24} ${y-16} L${x+30} ${y+6}`,'none',2.5); +const beanie=(x,y,w,f='#FF8A3D')=>P(`M${x-w/2} ${y} q0 ${-w*.5} ${w/2} ${-w*.5} q${w/2} 0 ${w/2} ${w*.5}z`,f)+R(x-w/2-3,y-6,w+6,12,f,5,3)+C(x,y-w*.5-5,6,f,3); +const beard=(x,y,w=30,f='#8A4B22')=>P(`M${x-w/2} ${y} q${w/2} ${w*.9} ${w} 0 q-6 6 ${-w/2} 6 q${-w/2+6} 0 ${-w/2} -6z`,f,3); +const capHat=(x,y,w=70)=>P(`M${x-w/2} ${y} q${w/2} -40 ${w} 0 q${-w/2} 12 ${-w} 0z`,'#1E2640',3)+C(x,y-14,5,'#FFD23F',2)+P(`M${x-5} ${y-14} l10 0`,'none',2).replace(`stroke="${O}"`,'stroke="#FFF"'); +const bandana=(x,y,w)=>P(`M${x-w/2} ${y} q${w/2} -26 ${w} 0z`,'#FF4D5E',3)+P(`M${x+w/2} ${y-2} l14 4 l-6 8z`,'#FF4D5E',3)+``; +const parrot=(x,y)=>E(x,y,10,14,'#22C47A',3)+C(x+2,y-14,8,'#22C47A',3)+P(`M${x+9} ${y-15} q8 2 2 8z`,'#FFD23F',2.5)+``+P(`M${x-6} ${y+10} l-8 10 M${x+2} ${y+12} l2 8`,'none',3).replace(`stroke="${O}"`,'stroke="#FF4D5E"'); +const chest=(x,y)=>R(x,y,40,26,'#C9B27C',4,3)+P(`M${x} ${y} q20 -18 40 0`,'#C9B27C',3)+R(x+16,y-2,8,8,'#FFD23F',2,2)+coins(x+20,y-12,1); +const mast=(x,y,h=70)=>P(`M${x} ${y} v${-h}`)+P(`M${x} ${y-h+4} l34 10 l-34 14z`,'#1E2640',3)+C(x+14,y-h+15,4,'#fff',1.5); +const wheel=(x,y,r=16)=>C(x,y,r,'#C9B27C',3)+C(x,y,5,'#FFD23F',2.5)+P(`M${x-r-6} ${y} h${2*r+12} M${x} ${y-r-6} v${2*r+12} M${x-r} ${y-r} l${2*r} ${2*r} M${x+r} ${y-r} l${-2*r} ${2*r}`,'none',3); +const anchor=(x,y)=>P(`M${x} ${y} v26 M${x-12} ${y+18} q12 16 24 0 M${x-6} ${y+6} h12`,'none',4)+C(x,y-4,4,'#fff',3); +const rivets=(x,y,w,h)=>[[x+8,y+8],[x+w-8,y+8],[x+8,y+h-8],[x+w-8,y+h-8]].map(([a,b])=>C(a,b,3,'#E8EDF7',2)).join(''); +const pine=(x,y,w,h)=>{let s='';for(let i=1;i<6;i++)s+=P(`M${x+i*w/6} ${y+4} v${h-8}`,'none',2);return s;}; +const thermo=(x,y,f='#FF4D5E')=>R(x-4,y-26,8,30,'#fff',4,2.5)+C(x,y+6,7,f,2.5)+``; +const stars=(pts)=>pts.map(([x,y,r])=>``).join(''); +const planet=(x,y,r,f,ring)=>C(x,y,r,f,3)+(ring?E(x,y,r+8,4,'none',3,-20):''); +const towel=(x,y)=>P(`M${x} ${y} q22 -6 20 26 l-8 36 q-4 -28 -12 -40z`,'#FFD23F',3)+P(`M${x+8} ${y+6} l6 40 M${x+16} ${y+10} l2 20`,'none',3).replace(`stroke="${O}"`,'stroke="#FF4F9A"'); +const screen=(x,y,w,h,t,s=20)=>R(x,y,w,h,'#0B0F1C',4,3).replace(`stroke="${O}"`,'stroke="#7FD8EE"')+T(x+w/2,y+h/2+s*.35,t,s,'#7FD8EE'); +const bricks=(x,y,n)=>Array.from({length:n},(_,i)=>R(x+i*36,y,34,16,'#E07A5F',2,3)).join(''); +const bandaid=(x,y,rot=-30)=>`${R(x-14,y-5,28,10,'#F4CFA0',4,2.5)}`; +const knob=(x,y)=>C(x,y,8,'#C9B27C',3)+P(`M${x} ${y} l4 -5`,'none',3); +const mustache=(x,y)=>P(`M${x} ${y} q-8 -6 -18 2 q8 2 18 -2 q8 -6 18 2 q-8 2 -18 -2z`,'#8A4B22',2.5); +const hood=(x,y,w,h)=>P(`M${x} ${y+h} V${y+24} q0 -30 ${w/2} -30 q${w/2} 0 ${w/2} 30 V${y+h}`,'#3A4266'); +const katana=(x1,y1,x2,y2)=>P(`M${x1} ${y1} L${x2} ${y2}`,'none',7).replace(`stroke="${O}"`,'stroke="#C9D1E6"')+P(`M${x1} ${y1} L${x2} ${y2}`,'none',2)+P(`M${x2} ${y2} l10 -10`,'none',6).replace(`stroke="${O}"`,'stroke="#7A2633"'); +const ears=(x,y,d,f)=>P(`M${x-d-14} ${y} l8 -22 l16 16z M${x+d+14} ${y} l-8 -22 l-16 16z`,f); +const tail=(x,y,f)=>P(`M${x} ${y} q30 -6 22 -34 q-2 -8 -8 -4`,'none',9).replace(`stroke="${O}"`,`stroke="${O}"`)+P(`M${x} ${y} q30 -6 22 -34 q-2 -8 -8 -4`,'none',5).replace(`stroke="${O}"`,`stroke="${f}"`); +const sweat=(x,y)=>P(`M${x} ${y} q-6 8 0 10 q6 -2 0 -10z`,'#7FD8EE',2.5); +const arm=(x,y,s)=>P(`M${x} ${y} q${s*22} 4 ${s*26} -18 q${s*-2} -10 ${s*-12} -6`,'none',10)+P(`M${x} ${y} q${s*22} 4 ${s*26} -18 q${s*-2} -10 ${s*-12} -6`,'none',6).replace(`stroke="${O}"`,'stroke="#FF8FBE"')+C(x+s*22,y-8,7,'#FF8FBE',3); +const dumbbell=(y)=>P(`M30 ${y} H170`,'none',5)+R(18,y-14,12,28,'#5D6788',3,3)+R(170,y-14,12,28,'#5D6788',3,3)+R(8,y-10,10,20,'#5D6788',3,3)+R(182,y-10,10,20,'#5D6788',3,3); +const headband=(x,y,w)=>R(x,y,w,10,'#FF4D5E',3,3); +const notes=(x,y)=>P(`M${x} ${y} v-14 l10 -3 v14`,'none',3)+C(x-3,y,3.5,O,0)+C(x+7,y-3,3.5,O,0); +const tiles=(y)=>{const cs=['#FF4F9A','#FFD23F','#22C47A','#7FD8EE','#7B61FF'];let s='';for(let i=0;i<8;i++)s+=P(`M${20+i*20} ${y} h20 l-4 14 h-20z`,cs[i%5],2.5);return s;}; +const headphones=(x,y,w)=>P(`M${x-w/2} ${y} q0 ${-w*.55} ${w/2} ${-w*.55} q${w/2} 0 ${w/2} ${w*.55}`,'none',5)+R(x-w/2-8,y-6,12,18,'#FF4F9A',4,3)+R(x+w/2-4,y-6,12,18,'#FF4F9A',4,3); +const afro=(x,y,w)=>{let s='';for(let i=0;i<7;i++){const a=Math.PI*(i/6),r=w/2;s+=C(x-Math.cos(a)*r*.9,y-Math.sin(a)*r*.6,14,'#3A2A20',3);}return s+E(x,y-10,w/2,18,'#3A2A20',0);}; +const bells=(xs,y)=>xs.map(x=>P(`M${x-5} ${y} l-6 18 h18 l-6 -18z`,'#FF8A3D',3)).join(''); +const hammer=(x,y)=>P(`M${x} ${y} l26 -8`,'none',6).replace(`stroke="${O}"`,'stroke="#C9B27C"')+P(`M${x} ${y} l26 -8`,'none',2)+R(x+32,y-30,12,22,'#9AA3BE',2,3)+P(`M${x+30} ${y-6} l4 -4 M${x+28} ${y-12} l4 2`,'none',2); +const anvil=(x,y)=>P(`M${x-24} ${y} h48 l-6 8 h-10 l4 12 h-24 l4 -12 h-10z M${x-24} ${y} q-14 0 -16 -6 h16z`,'#5D6788',3); +const dizzyStars=(x,y)=>stars([[x-12,y,3],[x,y-6,3.5],[x+12,y,3]])+P(`M${x-18} ${y+4} q18 -14 36 0`,'none',2); +const icicles=(x,y,w)=>{let s='';for(let i=0;i<5;i++)s+=P(`M${x+i*w/5+4} ${y} l4 ${10+(i%2)*6} l4 ${-10-(i%2)*6}`,'#E8F6FF',2);return s;}; +const snowcap=(x,y,w)=>P(`M${x-4} ${y+4} q${w/4} -14 ${w/2} -4 q${w/4} -12 ${w/2+8} 4 q-6 8 -14 2 q-10 8 -20 0 q-12 8 -24 0 q-10 8 ${-w/2+22} -2z`,'#fff',3); +const racing=(x,y,w)=>``; +const roundel=(x,y,t)=>C(x,y,15,'#fff',3)+T(x,y+6,t,16); +const fire=(x,y)=>flames(x,y,.55); +const extinguisher=(x,y)=>R(x,y,14,34,'#FF4D5E',6,3)+P(`M${x+4} ${y} v-6 h10 l6 6`,'none',3)+P(`M${x-2} ${y+12} h18`,'none',6).replace(`stroke="${O}"`,'stroke="#C9D1E6"'); +const rope=(x1,x2,y)=>R(x1-4,y-34,8,40,'#FFD23F',3,3)+R(x2-4,y-34,8,40,'#FFD23F',3,3)+P(`M${x1} ${y-26} q${(x2-x1)/2} 18 ${x2-x1} 0`,'none',6).replace(`stroke="${O}"`,'stroke="#C0154F"'); +const receipt=(x,y)=>P(`M${x} ${y} h18 v34 q-2 10 14 12 h40 v10 h-56 q-16 0 -16 -14z`,'#fff',3)+P(`M${x+4} ${y+8} h10 M${x+4} ${y+16} h10 M${x+4} ${y+24} h10 M${x+26} ${y+52} h30`,'none',2)+T(x+9,y+-2,'€',10); +const piglet=(x,y)=>C(x,y,10,'#FF8FBE',3)+E(x,y+3,5,3.5,'#FF4F9A',2)+``+P(`M${x-9} ${y-7} l-3 -6 l6 3 M${x+9} ${y-7} l3 -6 l-6 3`,'#FF8FBE',2); +const ladder=(x,y,h)=>P(`M${x} ${y} l10 ${-h} M${x+16} ${y} l10 ${-h}`,'none',3)+Array.from({length:Math.floor(h/12)},(_,i)=>P(`M${x+2+i*1.2*10/h*12} ${y-8-i*12} h16`,'none',2.5)).join(''); +const rainbow=(x,y,r)=>['#FF4D5E','#FF8A3D','#FFD23F','#22C47A','#2F8CFF'].map((c,i)=>``).join(''); +const nest=(x,y)=>P(`M${x-18} ${y} h36 l-4 14 h-28z`,'#C9B27C',3)+P(`M${x} ${y+14} v24`,'none',4); +const scope=(x,y)=>P(`M${x} ${y} l26 -10`,'none',8)+P(`M${x} ${y} l26 -10`,'none',4).replace(`stroke="${O}"`,'stroke="#FFD23F"'); +const bench=(y)=>R(24,y,152,12,'#C9B27C',3,3)+P(`M40 ${y+12} v14 M160 ${y+12} v14`,'none',5); +const vihta=(x,y)=>P(`M${x} ${y} l-6 30`,'none',4).replace(`stroke="${O}"`,'stroke="#8A4B22"')+[[0,0],[-8,6],[8,6],[-4,14],[6,14],[0,-8]].map(([a,b])=>E(x+a,y+b-6,6,9,'#22C47A',2,a*4)).join(''); +const bucket=(x,y)=>P(`M${x-16} ${y-22} h32 l-4 26 h-24z`,'#C9B27C',3)+P(`M${x-16} ${y-14} h32 M${x-16} ${y-4} h32`,'none',2)+P(`M${x+10} ${y-24} q12 -24 28 -18`,'none',4)+E(x+40,y-40,7,4,'#C9B27C',2.5); +const rocks=(x,y)=>[[0,0,9],[14,2,8],[-14,3,7],[6,-9,7],[-6,-8,6]].map(([a,b,r])=>C(x+a,y+b,r,'#9AA3BE',2.5)).join(''); +const springs=(x,y,dir)=>P(`M${x} ${y} l${8*dir} -6 l${-6*dir} -6 l${8*dir} -6 l${-6*dir} -6 l${8*dir} -6`,'none',3)+R(x+dir*6-5,y-38,10,8,'#FFD23F',2,2.5); +const propeller=(x,y)=>beanie(x,y,40,'#22C47A')+P(`M${x} ${y-26} v-8`,'none',3)+E(x-14,y-36,14,4,'#FF4F9A',2.5)+E(x+14,y-36,14,4,'#FFD23F',2.5); +const band=(x,y,w,h)=>P(`M${x+w*.3} ${y-2} v${h+4}`,'none',6).replace(`stroke="${O}"`,'stroke="#C0154F"'); +const awning=(x,y,w)=>{let s='';const n=6,g=w/n;for(let i=0;iE(x,y,18,5,'#fff',3)+P(`M${x} ${y+4} v20 M${x-10} ${y+24} h20`,'none',3)+R(x-2,y-14,4,10,'#fff',1,2)+P(`M${x} ${y-14} q-3 -4 0 -8 q3 4 0 8z`,'#FFD23F',1.5)+P(`M${x-34} ${y+24} v-26 h10 v10 M${x+34} ${y+24} v-26 h-10 v10`,'none',3); +const swirl=(x,y)=>`${[56,42,28,14].map((r,i)=>``).join('')}`; +const box=(x,y,w,h,f,r=10)=>R(x,y,w,h,f,r); +const tower=(x,y,w,h,f)=>R(x,y,w,h,f,10); +const raft=(y)=>{let s='';for(let i=0;i<6;i++)s+=R(28+i*24,y,24,12,'#C9B27C',3,3);return s+P(`M14 ${y+18} q14 -8 28 0 q14 8 28 0 q14 -8 28 0 q14 8 28 0 q14 -8 28 0 q14 8 28 0`,'none',4).replace(`stroke="${O}"`,'stroke="#2F8CFF"');}; +const sail=(x,y)=>P(`M${x} ${y} v-62`)+P(`M${x+3} ${y-58} q30 20 2 48z`,'#fff',3); +const hook=(x,y)=>P(`M${x} ${y} h14`,'none',6)+P(`M${x+14} ${y} q14 2 10 16 q-4 8 -12 2`,'none',4).replace(`stroke="${O}"`,'stroke="#C9D1E6"'); +const glasses=(x,y)=>C(x,y,9,'rgba(255,255,255,.4)',3); +const mug=(x,y)=>R(x,y,20,22,'#fff',4,3)+P(`M${x+20} ${y+6} q10 0 10 6 q0 6 -10 6`,'none',3)+P(`M${x+5} ${y-4} q-3 -6 0 -10 M${x+13} ${y-4} q-3 -6 0 -10`,'none',2).replace(`stroke="${O}"`,'stroke="#9AA3BE"'); +const skates=(xs,y)=>xs.map(x=>R(x-14,y,30,10,'#FF4F9A',4,3)+C(x-6,y+14,5,'#FFD23F',2.5)+C(x+8,y+14,5,'#FFD23F',2.5)).join(''); +const tray=(y)=>R(18,y,164,12,'#C9D1E6',4,3); +const juice=(x,y)=>R(x,y,18,28,'#FFD23F',2,3)+P(`M${x+12} ${y} l6 -14`,'none',3)+T(x+9,y+18,'OJ',8); +const apple=(x,y)=>C(x,y,10,'#FF4D5E',3)+P(`M${x} ${y-10} q2 -6 6 -6`,'none',3)+E(x+6,y-12,4,2,'#22C47A',1.5,-20); +const sandwich=(x,y)=>P(`M${x} ${y} h50 l-10 -24 q-15 -10 -30 0z`,'#F4CFA0',4)+P(`M${x+4} ${y-12} q10 -6 20 0 q10 6 22 0`,'none',5).replace(`stroke="${O}"`,'stroke="#22C47A"')+P(`M${x+8} ${y-4} h36`,'none',5).replace(`stroke="${O}"`,'stroke="#FF4D5E"'); +const handle=(x,y,w)=>P(`M${x} ${y} q0 -22 ${w/2} -22 q${w/2} 0 ${w/2} 22`,'none',7); +const stickers=(pts)=>pts.map(([x,y,f,k])=>k?R(x-8,y-6,16,12,f,3,2):C(x,y,7,f,2)).join(''); +const wood=(x,y,w,h)=>{let s='';for(let i=1;i<4;i++)s+=P(`M${x+6} ${y+i*h/4} q${w/2} -4 ${w-12} 0`,'none',1.5);return s;}; + return [ + /* rusty: Vintage set */ ()=>sh()+bob(P('M84 58 L62 18 M116 58 L138 18')+C(62,18,5,'#C9D1E6',3)+C(138,18,5,'#C9D1E6',3)+box(32,56,136,78,'#E8D9B0',14)+wood(32,56,136,78)+R(46,68,72,46,'#5D6788',8,3)+face(82,86,'dots',null,12)+mustache(82,104)+knob(140,78)+knob(140,106)+cobweb(146,56)), + /* edgelord: All spikes */ ()=>sh(72)+bob(P('M26 128 L40 52 L58 36 L70 50 L86 30 L100 48 L114 28 L130 48 L144 34 L160 52 L174 128Z','#2E3550')+face(100,80,'angry',null,22)+ports(54,100,92,6,'#FF4D5E')+legs([46,146],128)), + /* chonk: Round and content */ ()=>sh(76)+bob(feet([68,128],132,'#FF8FBE')+E(100,82,78,56,'#FF8FBE')+P('M30 92 Q100 116 170 92 L168 108 Q100 128 32 108Z','#1E2640',3)+leds(56,106,['#FFD23F','#FFD23F','#FFD23F','#FFD23F','#FFD23F','#FFD23F','#FFD23F'],3)+face(100,62,'happy','smile',18,14)+cheeks(100,76,34)+C(164,40,3,'#C9B27C',2)+C(172,50,2,'#C9B27C',2)), + /* unit16: Flexing */ ()=>sh(78)+bob(arm(46,88,-1)+arm(154,88,1)+box(46,46,108,88,'#FF8FBE',12)+face(100,72,'dots','grin',18,16)+ports(58,108,84,6)+cloud(150,26,.8,'#E8EDF7')+rain(146,26)), + /* mikro: Lunchbox */ ()=>sh(74)+bob(handle(64,72,44)+box(40,70,92,64,'#22C47A')+ports(50,104,72,6)+leds(58,86,['#FFD23F'])+T(96,92,'CCR',11)+sandwich(136,128)), + /* wb32: Roller skates */ ()=>sh(66)+speed(36,74)+bob(box(46,56,108,64,'#F4F6FB')+face(100,80,'wink','grin',16,14)+ports(58,98,84,7)+skates([70,130],120)), + /* ar7280: Flat white */ ()=>sh()+bob(box(40,54,108,80,'#2F8CFF')+beanie(94,56,84,'#22C47A')+eyepatch(78,84)+glasses(112,84)+``+MO.smirk(94,104)+ports(50,116,88,7)+mug(150,96)), + /* ar7800: The captain */ ()=>sh(70)+bob(box(46,46,108,90,'#2F8CFF',8)+capHat(100,48,96)+face(100,66,'dots','smirk',16,10)+[86,100,114].map(y=>R(56,y,88,10,'#1E2640',3,2)+[0,1,2,3,4].map(i=>C(68+i*16,y+5,3,'#FFD23F',0)).join('')).join('')), + /* disco8k: Disco ball */ ()=>sh()+beams(100,38)+bob(disco(100,38)+box(34,60,132,74,'#7B61FF')+leds(54,80,['#FF4F9A','#FFD23F','#22C47A','#7FD8EE','#FF8A3D'],5)+ports(46,98,108,8,'#fff')+tag(178,104,'€/mo','∞')), + /* knockia7750: Minus forty */ ()=>sh()+bob(box(38,58,124,76,'#9AA3BE',6)+snowcap(38,58,124)+icicles(44,134,112)+face(96,86,'dots','smile',14,12)+thermo(144,108,'#2F8CFF')+ports(48,108,80,6))+R(140,30,42,18,'#fff',5,2.5)+T(161,43,'−40°',11,'#2F8CFF'), + /* wb64: Race car */ ()=>sh(84)+bob(box(26,62,148,62,'#F4F6FB',14)+racing(26,70,148)+roundel(60,104,'64')+face(124,100,'shades',null,14)+ports(88,108,30,2)+smoke(178,96)), + /* disco8ku: Double disco */ ()=>sh()+beams(70,36)+bob(disco(70,36,13)+disco(130,36,13)+box(30,56,140,78,'#7B61FF')+coinslot(88,72)+ports(42,102,116,9,'#fff')+tag(180,108,'€/mo','∞∞')), + /* unit32: Litter of pigs */ ()=>sh(84)+bob(box(24,36,152,100,'#FF8FBE',14)+face(100,64,'happy','smile',22,14)+R(38,90,124,30,'#1E2640',6,3)+piglet(58,105)+piglet(100,105)+piglet(142,105)), + /* ar7800r5: Ship of the line */ ()=>sh(84)+bob(mast(100,72,62)+P('M20 72 H180 L164 132 H36Z','#2F8CFF')+[0,1,2,3,4,5,6,7].map(i=>C(44+i*16,92,5,'#1E2640',2)+``).join('')+ports(48,108,104,8)), + /* knockia7950: Sauna door */ ()=>sh()+steam(70,46)+bob(box(40,50,120,86,'#E6C48E',8)+pine(40,50,120,86)+thermo(68,98)+R(132,78,8,26,'#8A4B22',3,2.5)+face(100,74,'sleepy',null,12))+ports(52,116,96,7), + /* mikro32: Propeller hat */ ()=>sh(66)+bob(propeller(100,64)+box(50,66,100,66,'#22C47A')+face(100,88,'happy','grin',16,14)+sweat(154,78)+ports(60,112,80,6,'#FF4F9A')), + /* universe: 42 and a towel */ ()=>bob(tower(62,12,76,132,'#1E2640')+stars([[76,28,1.8],[122,40,1.5],[90,112,1.6],[126,96,2],[72,88,1.3],[110,128,1.4]])+screen(74,44,52,30,'42',20)+P('M74 84 H126 M74 92 H126 M74 100 H126','none',2).replace(`stroke="${O}"`,'stroke="#7FD8EE"')+towel(138,30))+``+planet(22,100,11,'#FF8A3D',1)+planet(178,52,7,'#22C47A') + ];})(); +const RG_ART_C=[]; +// The picture for model g, as inline SVG ('' for a model without one). +function rgArt(g){const f=RG_ART[g];if(!f)return '';return RG_ART_C[g]||(RG_ART_C[g]=``);} diff --git a/src/game/80-simulation/90-sites-and-service.js b/src/game/80-simulation/90-sites-and-service.js index a586f34..0dfa450 100644 --- a/src/game/80-simulation/90-sites-and-service.js +++ b/src/game/80-simulation/90-sites-and-service.js @@ -16,7 +16,7 @@ function waveOk(a,b,i){return [a,b].every(c=>i<=RG[S.pops[c]?(S.pops[c].rgen||0) function waveNeed(i){const g=RG.find(r=>r.maxLT>=i);return g?tr('sites_and_service.pn_routers',{pn:g.pn}):'?';} function routerModels(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1; return `
${RG.map((M,i)=>{if(i===g)return '';const why=modelFits(c,i),lk=!techOk('rg',i,M.lvl); - return `
${esc(M.n)} ${M.pn} · ${tr('sites_and_service.n_ports',{n:M.ports})} · ${fmtG(M.cap)} · ${tr('sites_and_service.boots_in_n_min',{n:M.boot})}${M.flaky?' · '+tr('common.crashes_more'):''}
${esc(M.blurb)}
${why?`
${esc(why)}
`:''}
${lk?demoBtn('rg',i,M.lvl,tr('sites_and_service.level_n',{n:M.lvl}),'sm'):btn(tr('sites_and_service.swap_cost_mo_mo',{cost:fmt$(swapCost(c,i)),mo:fmt$(M.mo*rt)}),'upRouter',{city:c,g:i},'sm',!!why||S.cash`;}).join('')}
`;} + return `
${rgArt(i)?`${rgArt(i)}`:``}
${esc(M.n)} ${M.pn} · ${tr('sites_and_service.n_ports',{n:M.ports})} · ${fmtG(M.cap)} · ${tr('sites_and_service.boots_in_n_min',{n:M.boot})}${M.flaky?' · '+tr('common.crashes_more'):''}
${esc(M.blurb)}
${why?`
${esc(why)}
`:''}
${lk?demoBtn('rg',i,M.lvl,tr('sites_and_service.level_n',{n:M.lvl}),'sm'):btn(tr('sites_and_service.swap_cost_mo_mo',{cost:fmt$(swapCost(c,i)),mo:fmt$(M.mo*rt)}),'upRouter',{city:c,g:i},'sm',!!why||S.cash`;}).join('')}
`;} function portNote(c){const p=S.pops[c];if(!p)return '';const g=p.rgen||0;return RG[g].maxP${tr('sites_and_service.your_model_here_tops_out_at',{model:esc(RG[g].n),pn:RG[g].pn})}

`:'';} // Service: what you deliver, times how it feels. Traffic backhauled far to transit is slow, and users notice. const latSlow=c=>!!(R&&R.latF&&R.latF[c]<0.97&&R.latFar[c]); diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 7a57efb..9af838b 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -65,7 +65,7 @@ function cityPanel(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')}

-
${rt} × ${esc(G.n)}
${tr('city_panel.up_to_pn_interfaces_ports_ports',{pn:G.pn,ports:G.ports,cap:fmtG(G.cap)})} · ${esc(G.blurb)}
+
${rgArt(g)?`${rgArt(g)}`:``}
${rt} × ${esc(G.n)}
${tr('city_panel.up_to_pn_interfaces_ports_ports',{pn:G.pn,ports:G.ports,cap:fmtG(G.cap)})} · ${esc(G.blurb)}
${tr('common.router_ports')}${tr('city_panel.used_max_in_use',{used:fmtPorts(pu),max:pm})}
${pu>=pm?`

${tr('city_panel.every_port_is_taken_add_a')}

`:''}
${tr('common.forwarding_chip')}${esc(G.chip)}
${tr('common.boot_time')}${slowBoot(c)?`${tr('city_panel.n_min_a_slow_one',{n:bootMin(c)})}`:tr('city_panel.n_min',{n:bootMin(c)})}
${slowBoot(c)?`

${tr('city_panel.this_chassis_takes_forever_to_boot')}

`:''}
${tr('common.forwarding_load')}${fmtG(nl)} / ${fmtG(nc)}
diff --git a/src/styles/37-router-art.css b/src/styles/37-router-art.css new file mode 100644 index 0000000..18dc6aa --- /dev/null +++ b/src/styles/37-router-art.css @@ -0,0 +1,5 @@ +/* Router pictures (src/game/10-catalog/25-router-art.js): each on a small map-green stage, the same in both themes. */ +.rgpic{flex:0 0 auto;display:block;width:58px;height:46px;border:2px solid #1E2640;border-radius:10px;background:radial-gradient(circle at 50% 125%,#94D168 0 55%,#A8DE7C 56%);overflow:hidden} +.rgpic.big{width:96px;height:77px;border-width:3px;border-radius:14px} +.rgpic .rgart{display:block;width:100%;height:100%} +.row.rgrow{align-items:center} diff --git a/tests/router-art.test.js b/tests/router-art.test.js new file mode 100644 index 0000000..05b21f5 --- /dev/null +++ b/tests/router-art.test.js @@ -0,0 +1,27 @@ +// Every router model has its own picture, shown where you pick and compare models. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('every router model has a picture, and each one is valid SVG', () => { + const { ev, dom } = load(); + assert.equal(ev('RG_ART.length'), ev('RG.length'), 'one picture per model, in RG order'); + const n = ev('RG.length'); + for (let g = 0; g < n; g++) { + const s = ev(`rgArt(${g})`); + const doc = new dom.window.DOMParser().parseFromString(s.replace(' 8, `model ${g} draws something`); + } + assert.equal(new Set(Array.from({ length: n }, (_, g) => ev(`rgArt(${g})`))).size, n, 'no two models look the same'); + assert.equal(ev('rgArt(99)'), ''); +}); + +test('the POP panel shows the model\'s picture, and the other models show theirs', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;selectCity(S.home);UI.tab='links';UI.models=true;renderAll()"); + const pics = dom.window.document.querySelectorAll('#panel .rgpic'); + assert.equal(pics.length, ev('RG.length'), 'the model in use plus every other one'); + assert.ok(dom.window.document.querySelector('#panel .rgpic.big svg.rgart'), 'the one in use, big'); + assert.deepEqual(errors, []); +}); From 78d2b7c8c91a21be9cb2d156356f1152dcf64f22 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 15:47:37 +0100 Subject: [PATCH 162/181] Routers: the picture only in the POP overview The list of other models goes back to its badges; only the model a POP runs shows its picture. --- CHANGELOG.md | 2 +- src/game/80-simulation/90-sites-and-service.js | 2 +- tests/router-art.test.js | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6741d16..43127be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 -- Every router model has its own picture: open a POP's routers to meet the one you have, and the others when you compare models. +- Every router model has its own picture: open a POP's routers to meet the one it runs. - A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come. - In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. - Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. diff --git a/src/game/80-simulation/90-sites-and-service.js b/src/game/80-simulation/90-sites-and-service.js index 0dfa450..a586f34 100644 --- a/src/game/80-simulation/90-sites-and-service.js +++ b/src/game/80-simulation/90-sites-and-service.js @@ -16,7 +16,7 @@ function waveOk(a,b,i){return [a,b].every(c=>i<=RG[S.pops[c]?(S.pops[c].rgen||0) function waveNeed(i){const g=RG.find(r=>r.maxLT>=i);return g?tr('sites_and_service.pn_routers',{pn:g.pn}):'?';} function routerModels(c){const p=S.pops[c],g=p.rgen||0,rt=p.routers||1; return `
${RG.map((M,i)=>{if(i===g)return '';const why=modelFits(c,i),lk=!techOk('rg',i,M.lvl); - return `
${rgArt(i)?`${rgArt(i)}`:``}
${esc(M.n)} ${M.pn} · ${tr('sites_and_service.n_ports',{n:M.ports})} · ${fmtG(M.cap)} · ${tr('sites_and_service.boots_in_n_min',{n:M.boot})}${M.flaky?' · '+tr('common.crashes_more'):''}
${esc(M.blurb)}
${why?`
${esc(why)}
`:''}
${lk?demoBtn('rg',i,M.lvl,tr('sites_and_service.level_n',{n:M.lvl}),'sm'):btn(tr('sites_and_service.swap_cost_mo_mo',{cost:fmt$(swapCost(c,i)),mo:fmt$(M.mo*rt)}),'upRouter',{city:c,g:i},'sm',!!why||S.cash`;}).join('')}
`;} + return `
${esc(M.n)} ${M.pn} · ${tr('sites_and_service.n_ports',{n:M.ports})} · ${fmtG(M.cap)} · ${tr('sites_and_service.boots_in_n_min',{n:M.boot})}${M.flaky?' · '+tr('common.crashes_more'):''}
${esc(M.blurb)}
${why?`
${esc(why)}
`:''}
${lk?demoBtn('rg',i,M.lvl,tr('sites_and_service.level_n',{n:M.lvl}),'sm'):btn(tr('sites_and_service.swap_cost_mo_mo',{cost:fmt$(swapCost(c,i)),mo:fmt$(M.mo*rt)}),'upRouter',{city:c,g:i},'sm',!!why||S.cash`;}).join('')}
`;} function portNote(c){const p=S.pops[c];if(!p)return '';const g=p.rgen||0;return RG[g].maxP${tr('sites_and_service.your_model_here_tops_out_at',{model:esc(RG[g].n),pn:RG[g].pn})}

`:'';} // Service: what you deliver, times how it feels. Traffic backhauled far to transit is slow, and users notice. const latSlow=c=>!!(R&&R.latF&&R.latF[c]<0.97&&R.latFar[c]); diff --git a/tests/router-art.test.js b/tests/router-art.test.js index 05b21f5..eb90cde 100644 --- a/tests/router-art.test.js +++ b/tests/router-art.test.js @@ -17,11 +17,11 @@ test('every router model has a picture, and each one is valid SVG', () => { assert.equal(ev('rgArt(99)'), ''); }); -test('the POP panel shows the model\'s picture, and the other models show theirs', () => { +test('only the POP overview shows a picture: the model in use', () => { const { ev, errors, dom } = load(); ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;selectCity(S.home);UI.tab='links';UI.models=true;renderAll()"); const pics = dom.window.document.querySelectorAll('#panel .rgpic'); - assert.equal(pics.length, ev('RG.length'), 'the model in use plus every other one'); + assert.equal(pics.length, 1, 'the model in use only, not the list of other models'); assert.ok(dom.window.document.querySelector('#panel .rgpic.big svg.rgart'), 'the one in use, big'); assert.deepEqual(errors, []); }); From dbd2fa7b55ded4759eb8c21a1f49cf91c2a23e0f Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 15:48:49 +0100 Subject: [PATCH 163/181] Routers: the picture in the POP overview's header, left of the city name --- CHANGELOG.md | 2 +- src/game/93-ui/50-city-panel.js | 6 ++++-- src/styles/37-router-art.css | 6 ++++-- tests/router-art.test.js | 8 ++++++-- 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 43127be..a6882e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 -- Every router model has its own picture: open a POP's routers to meet the one it runs. +- Every router model has its own picture: open one of your POPs and its router sits next to the city's name. - A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come. - In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. - Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 9af838b..2b34ea2 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -1,6 +1,8 @@ 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(siteName(c,'a'))}

${C.name}

+ // Your POP's router model, as a picture left of the name (10-catalog/25-router-art.js). + const art=p?rgArt(p.rgen||0):''; + let h=`
${art?`${art}`:''}
${REG[C.reg]} · ${esc(siteName(c,'a'))}

${C.name}

${tr('city_panel.g_of_eyeballs',{g:fmtG(eyeP(c))})}${grantFact(c)}${latSlow(c)?`🐢 ${tr('city_panel.ms_ms_to_transit',{ms:Math.round(R.latFar[c].ms)})}`:''}${regionMult(c)>1?`${tr('city_panel.transit_x_pricier',{x:regionMult(c)})}`:''}${C.kr&&scnRule('sender')?`${tr('city_panel.sender_pays_fee_per_gbps',{fee:fmt$(KR_FEE)})}`:''}${colo(c)>1?`${tr('city_panel.few_data_centers_pops_x',{x:colo(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('city_panel.underserved_users_grow_60_faster')+'':''}${ix?`${tr('city_panel.ix_ix',{ix:esc(ix)})}`:''}${p?`${tr('common.your_pop')}`:''}${down?`DOWN`:''}
`; if(!p){ @@ -65,7 +67,7 @@ function cityPanel(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')}

-
${rgArt(g)?`${rgArt(g)}`:``}
${rt} × ${esc(G.n)}
${tr('city_panel.up_to_pn_interfaces_ports_ports',{pn:G.pn,ports:G.ports,cap:fmtG(G.cap)})} · ${esc(G.blurb)}
+
${rt} × ${esc(G.n)}
${tr('city_panel.up_to_pn_interfaces_ports_ports',{pn:G.pn,ports:G.ports,cap:fmtG(G.cap)})} · ${esc(G.blurb)}
${tr('common.router_ports')}${tr('city_panel.used_max_in_use',{used:fmtPorts(pu),max:pm})}
${pu>=pm?`

${tr('city_panel.every_port_is_taken_add_a')}

`:''}
${tr('common.forwarding_chip')}${esc(G.chip)}
${tr('common.boot_time')}${slowBoot(c)?`${tr('city_panel.n_min_a_slow_one',{n:bootMin(c)})}`:tr('city_panel.n_min',{n:bootMin(c)})}
${slowBoot(c)?`

${tr('city_panel.this_chassis_takes_forever_to_boot')}

`:''}
${tr('common.forwarding_load')}${fmtG(nl)} / ${fmtG(nc)}
diff --git a/src/styles/37-router-art.css b/src/styles/37-router-art.css index 18dc6aa..f78ef52 100644 --- a/src/styles/37-router-art.css +++ b/src/styles/37-router-art.css @@ -1,5 +1,7 @@ -/* Router pictures (src/game/10-catalog/25-router-art.js): each on a small map-green stage, the same in both themes. */ +/* Router pictures (src/game/10-catalog/25-router-art.js): your POP's model in the city panel's header, left of the + name, on a small map-green stage that looks the same in both themes. */ .rgpic{flex:0 0 auto;display:block;width:58px;height:46px;border:2px solid #1E2640;border-radius:10px;background:radial-gradient(circle at 50% 125%,#94D168 0 55%,#A8DE7C 56%);overflow:hidden} .rgpic.big{width:96px;height:77px;border-width:3px;border-radius:14px} .rgpic .rgart{display:block;width:100%;height:100%} -.row.rgrow{align-items:center} +.ph .phpic{align-self:center} +@media (max-width:420px){.rgpic.big{width:76px;height:61px}} diff --git a/tests/router-art.test.js b/tests/router-art.test.js index eb90cde..7c289e3 100644 --- a/tests/router-art.test.js +++ b/tests/router-art.test.js @@ -17,11 +17,15 @@ test('every router model has a picture, and each one is valid SVG', () => { assert.equal(ev('rgArt(99)'), ''); }); -test('only the POP overview shows a picture: the model in use', () => { +test('only the POP overview shows a picture: its model, left of the city name', () => { const { ev, errors, dom } = load(); ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;selectCity(S.home);UI.tab='links';UI.models=true;renderAll()"); const pics = dom.window.document.querySelectorAll('#panel .rgpic'); assert.equal(pics.length, 1, 'the model in use only, not the list of other models'); - assert.ok(dom.window.document.querySelector('#panel .rgpic.big svg.rgart'), 'the one in use, big'); + assert.ok(dom.window.document.querySelector('#panel .ph > .rgpic.big svg.rgart'), 'in the header, beside the name'); + ev("UI.tab='cust';renderAll()"); + assert.equal(dom.window.document.querySelectorAll('#panel .rgpic').length, 1, 'on every tab'); + ev("selectCity(Object.keys(CITY).find(c=>!S.pops[c]&&!CITY[c].off));renderAll()"); + assert.equal(dom.window.document.querySelectorAll('#panel .rgpic').length, 0, 'no POP, no router'); assert.deepEqual(errors, []); }); From abd55c084683351b2e3478b0304869aff2d1865b Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Fri, 30 Oct 2026 16:28:19 +0100 Subject: [PATCH 164/181] Release notes: a story for big releases, and the 2.0 story A CHANGELOG section may open with prose before its first bullet. The build bakes it into the page and version.json, and "What's new" tells it in full with a link to every change on GitHub instead of the first sentences of five bullets. The 2.0.0 section gets its story and every change grouped under headings, Architect runs included. --- CHANGELOG.md | 128 +++++++++++++++++-------- scripts/build.js | 7 +- scripts/release-notes.js | 17 +++- src/game/00-core/20-analytics.js | 2 + src/game/95-modals/40-title.js | 4 +- src/game/95-modals/50-release-notes.js | 4 +- src/styles/40-modal.css | 3 + tests/release-story.test.js | 34 +++++++ 8 files changed, 150 insertions(+), 49 deletions(-) create mode 100644 tests/release-story.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a6882e1..b499d7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,64 +6,108 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Architect runs (preview), under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, mission-critical sites must survive any single trench or cable cut with room on the detour, and a chaos monkey runs round the map snipping tubes before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. +## [2.0.0] — 2026-10-30 -## [2.0.0] — 2026-10-29 +**Series of Tubes 2.0: one game, four doors.** Some of you wanted a calmer game, some a harder one, some a quick puzzle over coffee and some a playground where nothing can go wrong. So now every network starts behind a door, and the rules you pick stay with that network for good. Your saved games carry on exactly as they were. -- Every router model has its own picture: open one of your POPs and its router sits next to the city's name. -- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come. -- In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. +**Normal** comes in three flavours. Change Freeze is the calm one: a third of the outages, no DDoS floods, and deliveries in days instead of months. On-call is the game you know. BGP at 3 a.m. is for people whose pager is a personality: more outages, longer ones, more attacks, and fiery badges to prove you survived. In your first month you also pick a charter: a global backbone, or a low-latency boutique racing the speed of light. + +**Sandbox** is a real sandbox now: everything unlocked from day one, money that never runs out, and a chaos dial from nothing ever breaks to spicy. + +**Puzzles** are small networks that carry real traffic, routed exactly like the big game. Deliver every flow for the first star, stay on budget for the second, and survive any single cut for the third. When your build earns a star, the chaos monkey runs round the map snipping every trench and cable to prove it. A new puzzle arrives every Sunday morning, the same for everyone. + +**Architect runs** grow one network brief by brief. New sites sign up, some become mission-critical, a city closes, traffic outgrows its tubes, and the chaos monkey reviews every brief before the next customer signs. Three handmade runs to start, and a fresh one every Sunday with its HQ somewhere new. + +**Scenarios** are themed crises against the clock: a cut cable, a peering spat, a flood week, a race for low latency. A new one comes out every Sunday too. + +And in On-call and BGP at 3 a.m., a **chaos monkey** sometimes moves into your network for a few months and snips tubes on purpose, the ones without a backup path first. Outlast it without a customer noticing and it pays; throw it a banana if you have had enough. + +**Also new:** Tier 1 works like the real thing, so peering with the big club brings their customers along. A NOC intern carries out your standing orders. Customers call when your network can serve them, not only when your level says so. You can buy a seat on a consortium subsea cable, see at a glance whether a PNI is worth it, keep several networks and play two side by side, and every router model has its own face. + +### One game, four doors + +- 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 hardware shortages, sold-out routes and de-peering at exchanges. 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. +- Pick a charter in your first month of a Normal game: Global backbone (the game as you know it, and the default) or Low-latency boutique (#187). The boutique gets more trading firms, pays them 40% more and has its own win, Speed of Light: beat the fastest leased latency on three finance routes with your own glass while two latency customers pay you. It comes with a badge and shows on your share card. +- 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. +- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. +- A tidier start screen: language first, then your network's name, the doors, three compact difficulty buttons with the chosen one explained below, and one drop-down for your home city with the five suggested homes at the top. +- Pick your own AS number next to your network's name when you start (#135). Leave it empty and the game picks one, and the round green arrow in the name box suggests another name. + +### Puzzles + +- Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. +- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, 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. - Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. -- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. -- The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. +- In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. +- When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. + +### Architect runs + +- Architect runs, under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, mission-critical sites must survive any single trench or cable cut with room on the detour, and a chaos monkey runs round the map snipping tubes before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. +- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come. + +### Scenarios + +- A new weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands in. - Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. + +### The chaos monkey + +- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. + +### Build your network your way + - Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. - Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price. - Take a seat on a new consortium subsea cable (#173). Capacity conferences offer them, and now and then a consortium calls from level 2: pay your share of the build, wait for the ship, then own one, two or four fiber pairs and light them with your own optics, your way onto your own subsea glass before Tier 1. A cut on that cable cuts your pairs too. -- Pick a charter in your first month of a Normal game: Global backbone (the game as you know it, and the default) or Low-latency boutique (#187). The boutique gets more trading firms, pays them 40% more and has its own win, Speed of Light: beat the fastest leased latency on three finance routes with your own glass while two latency customers pay you. It comes with a badge and shows on your share card. -- 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. -- Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. -- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, 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 weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands 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, 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). +- 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). +- 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). +- 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. +- 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. +- 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. +- Every router model has its own picture: open one of your POPs and its router sits next to the city's name. + +### Peering and Tier 1 + - 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. -- 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 hardware shortages, sold-out routes and de-peering at exchanges. 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. -- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. -- 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. -- Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days. -- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside. -- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner. -- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. +- The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. +- Every network in a POP's PNI list now shows how you reach it today and whether a PNI there is worth the cross-connect (#175, #172). A chip says PNI here (with size and load), PNI elsewhere, which exchanges you peer at, whose customer cone carries it, transit only or not reached; a value line shows how much of its traffic leaves from that POP over transit, exchanges or other PNIs, and what a PNI there would save or cost a month. The best candidates get a ⭐ Worth it tag, the list sorts them first, filters to All, Via transit, Worth it or Already PNI, and groups networks by type, with idle groups folded. The same chip shows in the Networks tab and in the bulk PNI preview. - 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). -- 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. +- Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days. +- Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. + +### Prices, routing and money + - 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. +- Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. +- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. +- 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. +- Check a selected link’s redundancy against current demand: see disconnected endpoints, additional service loss and full fallback links without changing the live network. + +### Attacks + - Attacks are more varied: sizes and lengths change from one attack to the next, and several can hit at once, each with its own controls in the NOC. Hosting game servers or cloud gaming makes attacks more frequent, as it does in real life (#153). -- 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 (#153). -- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency (#153). -- 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 (#153). -- Live attacks now show how much traffic Flowspec actually drops. Routers without TCAM no longer claim to filter attacks, and Flowspec drops are counted separately from other edge filters (#153). - Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec and require dedicated mitigation (#153). -- Flood Season keeps sending ever larger attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off (#153). -- Flood Season escalates again: ordinary floods mixed with terabit monsters, all growing through the year, and floods go for the POPs that serve customers, so empty POPs no longer hold them for free. -- The China licence follows quick lead times: about 5 days instead of 45 under Change Freeze and in Sandbox. -- Imported saves can no longer change a network's rules or slip HTML into a Flood Season attacker's name. +- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation (#153). +- 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 (#153). - Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through (#153). - 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 (#153). -- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation (#153). -- 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 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. A POP's Infra tab shows the redundancy kit as one line with its price, above the rows it fills in. -- 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). -- Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. -- 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). -- Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. -- When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. +- Live attacks now show how much traffic Flowspec actually drops. Routers without TCAM no longer claim to filter attacks, and Flowspec drops are counted separately from other edge filters (#153). +- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency (#153). +- 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 (#153). +- Flood Season keeps sending ever larger attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off (#153). +- Flood Season escalates again: ordinary floods mixed with terabit monsters, all growing through the year, and floods go for the POPs that serve customers, so empty POPs no longer hold them for free. + +### Smoother and safer + +- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner. - The Networks list shows 100 networks at a time, with a button for the rest, so it opens quickly now that every country has its own networks. -- A tidier start screen: language first, then your network's name, the doors, three compact difficulty buttons with the chosen one explained below, and one drop-down for your home city with the five suggested homes at the top. -- Pick your own AS number next to your network's name when you start (#135). Leave it empty and the game picks one, and the round green arrow in the name box suggests another name. -- Every network in a POP's PNI list now shows how you reach it today and whether a PNI there is worth the cross-connect (#175, #172). A chip says PNI here (with size and load), PNI elsewhere, which exchanges you peer at, whose customer cone carries it, transit only or not reached; a value line shows how much of its traffic leaves from that POP over transit, exchanges or other PNIs, and what a PNI there would save or cost a month. The best candidates get a ⭐ Worth it tag, the list sorts them first, filters to All, Via transit, Worth it or Already PNI, and groups networks by type, with idle groups folded. The same chip shows in the Networks tab and in the bulk PNI preview. +- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside. +- The China licence follows quick lead times: about 5 days instead of 45 under Change Freeze and in Sandbox. +- Imported saves can no longer change a network's rules or slip HTML into a Flood Season attacker's name. ## [1.37.0] — 2026-10-28 diff --git a/scripts/build.js b/scripts/build.js index 38e597b..6c8971a 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -41,8 +41,11 @@ if (process.env.REQUIRE_NOTES === '1' && notes === '[]') die(`CHANGELOG.md has n const page = path.join(OUT, 'index.html'), PH = '/*__RELEASE_NOTES__*/[]', html = fs.readFileSync(page, 'utf8'); if (!html.includes(PH)) die('release-notes placeholder missing from the page'); // Function replacer: no $& / $$ expansion. Escape "<" so a note can never close the